<template>
  <div class="h-full flex flex-col">
    <!-- Masthead: AI Brief branding -->
    <header
      class="shrink-0 px-4 py-2 flex items-center justify-between gap-2"
      :style="isDark
        ? 'border-bottom: 1px solid rgba(255, 255, 255, 0.08)'
        : 'border-bottom: 1px solid rgba(0, 0, 0, 0.06)'"
    >
      <p class="text-[10px] uppercase tracking-[0.2em] font-semibold shrink-0"
         :class="isDark ? 'text-white/50' : 'text-gray-500'">
        AI Brief
      </p>
      <div class="flex-1" />
      <div class="shrink-0">
        <slot name="header-actions" />
      </div>
    </header>

    <div class="flex-1 overflow-y-auto custom-scrollbar pb-16">
      <!-- Headline banner: edge-to-edge, tech style -->
      <div
        v-if="headlineText"
        class="relative w-full pt-4 overflow-hidden"
        :class="isDark ? 'bg-white/[0.02]' : 'bg-black/[0.02]'"
      >
        <!-- Tech lines decoration -->
        <div class="absolute inset-0 pointer-events-none overflow-hidden">
          <div
            class="absolute left-0 top-0 bottom-0 w-px"
            :class="isDark ? 'bg-gradient-to-b from-transparent via-white/20 to-transparent' : 'bg-gradient-to-b from-transparent via-black/10 to-transparent'"
          />
          <div
            class="absolute left-12 top-0 bottom-0 w-px"
            :class="isDark ? 'bg-white/5' : 'bg-black/5'"
          />
          <div
            class="absolute right-0 top-0 bottom-0 w-px"
            :class="isDark ? 'bg-gradient-to-b from-transparent via-white/20 to-transparent' : 'bg-gradient-to-b from-transparent via-black/10 to-transparent'"
          />
          <div
            class="absolute left-0 right-0 bottom-0 h-px"
            :class="isDark ? 'bg-gradient-to-r from-transparent via-white/15 to-transparent' : 'bg-gradient-to-r from-transparent via-black/10 to-transparent'"
          />
          <!-- Scan line accent -->
          <div
            class="absolute left-0 right-0 top-1/2 h-px"
            :class="isDark ? 'bg-white/5' : 'bg-black/5'"
          />
        </div>

        <div class="relative flex items-start gap-3 px-4 py-5 sm:py-6">
          <!-- News icon -->
          <div
            class="shrink-0 w-10 h-10 sm:w-12 sm:h-12 rounded-lg flex items-center justify-center"
            :class="isDark ? 'bg-white/10' : 'bg-black/5'"
          >
            <svg class="w-5 h-5 sm:w-6 sm:h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
                 :class="isDark ? 'text-white/70' : 'text-gray-600'">
              <path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2" />
              <path d="M18 14h-8" />
              <path d="M15 18h-5" />
              <path d="M10 6h8v4h-8V6Z" />
            </svg>
          </div>

          <div class="min-w-0 flex-1">
            <span
              class="text-[9px] uppercase tracking-[0.25em] font-bold block mb-1"
              :class="isDark ? 'text-white/40' : 'text-gray-500'"
            >
              What you asked
            </span>
            <h1
              class="text-xl sm:text-2xl font-bold leading-snug"
              :class="isDark ? 'text-white/95' : 'text-gray-900'"
            >
              {{ headlineText }}
            </h1>
          </div>
        </div>
      </div>

      <!-- News homepage body -->
      <div
        class="space-y-4 px-4 pt-5"
      >
        <!-- Lead story: first section -->
        <article
          v-if="sections[0]"
          class="path-glass-bubble rounded-2xl p-4 sm:p-5 border-l relative"
          :class="isDark ? 'border-white/10' : 'border-black/5'"
        >
          <div class="flex items-start justify-between gap-2">
            <div class="min-w-0 flex-1">
              <span
                class="text-[9px] uppercase tracking-widest font-bold block mb-1.5"
                :class="isDark ? 'text-white/40' : 'text-gray-500'"
              >
                Lead
              </span>
              <h2 class="text-base font-bold mb-2"
                  :class="isDark ? 'text-white/90' : 'text-gray-900'">
                {{ sections[0].title }}
              </h2>
              <p v-if="sections[0].author"
                 class="text-[10px] mb-2"
                 :class="isDark ? 'text-white/50' : 'text-gray-500'">
                {{ sections[0].author }}
              </p>
              <p class="text-sm leading-relaxed"
                 :class="isDark ? 'text-white/80' : 'text-gray-700'"
                 v-html="formatContent(sections[0].content)"
              />
            </div>
            <button
              v-if="sections[0].url"
              class="shrink-0 p-2 rounded-lg transition-colors"
              :class="isDark ? 'text-white/50 hover:bg-white/10 hover:text-white/70' : 'text-gray-500 hover:bg-black/5 hover:text-gray-700'"
              title="Open in new window"
              aria-label="Open link"
              @click.stop="openLink(sections[0].url!)"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
            </button>
          </div>
        </article>

        <!-- Secondary stories grid (single col when many sections for readability) -->
        <div
          class="gap-4"
          :class="sections.length > 4 ? 'flex flex-col' : 'grid sm:grid-cols-2'"
        >
          <article
            v-for="(section, i) in sections.slice(1)"
            :key="i"
            class="path-glass-bubble rounded-2xl p-3 sm:p-4 relative"
          >
            <div class="flex items-start justify-between gap-2">
              <div class="min-w-0 flex-1">
                <h3 class="text-sm font-bold mb-1"
                    :class="isDark ? 'text-white/85' : 'text-gray-800'">
                  {{ section.title }}
                </h3>
                <p v-if="section.author"
                   class="text-[10px] mb-2"
                   :class="isDark ? 'text-white/45' : 'text-gray-500'">
                  {{ section.author }}
                </p>
                <p class="text-xs leading-relaxed"
                   :class="isDark ? 'text-white/75' : 'text-gray-600'"
                   v-html="formatContent(section.content)"
                />
              </div>
              <button
                v-if="section.url"
                class="shrink-0 p-1.5 rounded-lg transition-colors"
                :class="isDark ? 'text-white/40 hover:bg-white/10 hover:text-white/60' : 'text-gray-400 hover:bg-black/5 hover:text-gray-600'"
                title="Open in new window"
                aria-label="Open link"
                @click.stop="openLink(section.url!)"
              >
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                </svg>
              </button>
            </div>
          </article>
        </div>
      </div>

      <div v-if="sections.length === 0" class="flex items-center justify-center py-12 px-4 pt-5">
        <p class="text-sm" :class="isDark ? 'text-white/30' : 'text-gray-400'">
          No sections to display
        </p>
      </div>

      <!-- Images below content: equally sized containers -->
      <div class="px-4 pt-6 grid grid-cols-2 gap-4">
        <div
          class="path-glass-bubble rounded-2xl overflow-hidden aspect-[4/3]"
        >
          <div class="relative w-full h-full overflow-hidden">
            <img
              :src="heroImageDisplay"
              alt=""
              class="absolute inset-0 w-full h-full object-cover"
              loading="lazy"
            />
            <div class="absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none" />
          </div>
        </div>
        <div
          class="path-glass-bubble rounded-2xl overflow-hidden aspect-[4/3]"
        >
          <div class="relative w-full h-full overflow-hidden">
            <img
              :src="memeImageUrl"
              alt=""
              class="absolute inset-0 w-full h-full object-cover"
              loading="lazy"
            />
            <div class="absolute bottom-0 left-0 right-0 p-2 text-center"
                 :class="isDark ? 'bg-black/70' : 'bg-black/50'">
              <p class="text-[11px] font-bold"
                 :class="isDark ? 'text-white/95' : 'text-white'">
                {{ memeCaption }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useTheme } from '@/composables/useTheme'
import { useArticleOverlayStore } from '@/stores/articleOverlay'
import type { MagazineSection } from '@/composables/useContentPanel'

const props = withDefaults(defineProps<{
  sections: MagazineSection[]
  /** Hero image URL (from response or web results) */
  heroImageUrl?: string | null
  title?: string
  /** User's prompt for headline banner */
  query?: string
}>(), {
  heroImageUrl: null,
  title: 'Brief',
  query: '',
})

const { isDark } = useTheme()
const overlayStore = useArticleOverlayStore()

function isSafeImgUrl(u: string | undefined | null): u is string {
  return !!u && typeof u === 'string' && /^https?:\/\//i.test(u.trim())
}

/** Hero image: use extracted/web result, or picsum fallback seeded by query */
const heroImageDisplay = computed(() => {
  if (props.heroImageUrl && isSafeImgUrl(props.heroImageUrl)) return props.heroImageUrl
  const seed = (props.query || 'magazine').toLowerCase().replace(/\s+/g, '-').slice(0, 30) || 'brief'
  return `https://picsum.photos/seed/${seed}/800/450`
})

/** Meme image: contextual meme templates (imgflip) */
const memeImageUrl = computed(() => {
  const text = props.sections.map((s) => s.title + ' ' + s.content).join(' ').toLowerCase()
  const q = (props.query || '').toLowerCase()
  const combined = text + ' ' + q
  if (/\bbearish|bear|fear|dump|crash|extreme fear\b/.test(combined)) return 'https://i.imgflip.com/wxica.jpg' // This is Fine
  if (/\bbull|rally|moon|pump|buy the dip\b/.test(combined)) return 'https://i.imgflip.com/1bhk.jpg' // Success Kid
  if (/\bbitcoin|btc\b/.test(combined)) return 'https://i.imgflip.com/30b1gx.jpg' // Drake
  if (/\bmacro|fed|rate|inflation\b/.test(combined)) return 'https://i.imgflip.com/1ur9b0.jpg' // Distracted Boyfriend
  return 'https://i.imgflip.com/1bij.jpg' // One does not simply
})

/** Meme caption: short contextual phrase */
const memeCaption = computed(() => {
  const text = props.sections.map((s) => s.title + ' ' + s.content).join(' ').toLowerCase()
  if (/\bbearish|fear|extreme fear\b/.test(text)) return 'Me checking my portfolio'
  if (/\bbull|rally|moon\b/.test(text)) return 'Buying the dip'
  if (/\bmacro|fed|inflation\b/.test(text)) return 'The economy rn'
  if (/\bbitcoin|btc\b/.test(text)) return 'Bitcoin holders'
  return 'Markets be like'
})

function openLink(url: string) {
  overlayStore.open(url, '', undefined, undefined)
}

const headlineText = computed(() => {
  const q = (props.query ?? '').trim()
  if (!q) return props.title
  return q.length > 100 ? q.slice(0, 97) + '…' : q
})

/** Render content with **bold** preserved and newlines as paragraphs (sanitized). */
function formatContent(text: string): string {
  const safe = text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
  const withParas = safe.replace(/\n\n+/g, '</p><p class="mt-2">').replace(/\n/g, '<br/>')
  return `<p>${withParas}</p>`
}
</script>
