import { useMemo } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useLang } from '@/context/LangContext'
import { reports } from '@/data/reports'
import { POSTS } from '@/content/posts'
import { RADAR_ITEMS, RADAR_CATEGORY_LABEL } from '@/content/radar'
import { RADAR_FUTURE } from '@/content/radarFuture'
import { videos, podcasts } from '@/data/media'
import { events } from '@/data/events'

const GOLD = '#CD9E53'
const NAVY = '#032340'

type Result = { id: string; title: string; summary: string; meta: string; badge: string; color: string; url: string }

/* Aggregate every searchable content source into one flat, normalized list.
   All of these are already bootstrapped from the panel into memory at startup,
   so this is a pure client-side search — no extra API call. */
function buildIndex(isFa: boolean): Result[] {
  const out: Result[] = []
  const L = (o: { fa: string; en: string }) => (isFa ? o.fa : o.en)

  for (const r of reports) {
    out.push({ id: `report-${r.id}`, title: r.title, summary: r.summary || '', meta: r.category || '', badge: 'گزارش', color: '#1d4ed8', url: `/reports/${r.id}` })
  }
  for (const p of POSTS) {
    const t = isFa ? p.fa : p.en
    out.push({ id: `post-${p.id}`, title: t.title, summary: t.lead || '', meta: L(p.category), badge: 'مطلب', color: '#9b1c1c', url: `/posts/${p.id}` })
  }
  for (const it of RADAR_ITEMS) {
    const t = isFa ? it.fa : it.en
    out.push({ id: `glance-${it.id}`, title: t.title, summary: t.excerpt || '', meta: L(RADAR_CATEGORY_LABEL[it.category]), badge: 'در یک نگاه', color: GOLD, url: `/radar/post/${it.id}` })
  }
  for (const it of RADAR_FUTURE) {
    const t = isFa ? it.fa : it.en
    out.push({ id: `radar-${it.id}`, title: t.title, summary: t.excerpt || '', meta: it.category || '', badge: 'رادار آینده', color: '#166534', url: `/radar/post/${it.id}` })
  }
  for (const v of videos) {
    const t = isFa ? v.fa : v.en
    out.push({ id: `video-${v.id}`, title: t.title, summary: t.body || '', meta: t.guest || '', badge: 'ویدیوکست', color: '#4a1d96', url: '/podcast' })
  }
  for (const p of podcasts) {
    const t = isFa ? p.fa : p.en
    out.push({ id: `podcast-${p.id}`, title: t.title, summary: t.body || '', meta: t.ep || '', badge: 'پادکست', color: '#7c2d12', url: '/podcast' })
  }
  for (const e of events) {
    out.push({ id: `event-${e.id}`, title: e.title, summary: '', meta: '', badge: 'رویداد', color: '#0f766e', url: '/events' })
  }
  return out
}

export default function SearchResults() {
  const { lang } = useLang()
  const isFa = lang === 'fa'
  const [params] = useSearchParams()
  const q = (params.get('q') || '').trim()

  const results = useMemo(() => {
    if (!q) return []
    const needle = q.toLowerCase()
    const has = (v: unknown) => String(v ?? '').toLowerCase().includes(needle)
    return buildIndex(isFa).filter((r) => has(r.title) || has(r.summary) || has(r.meta))
  }, [q, isFa])

  return (
    <div dir={isFa ? 'rtl' : 'ltr'} style={{ maxWidth: 1000, margin: '0 auto', padding: 'clamp(24px,5vw,56px) clamp(16px,4vw,40px)', minHeight: '60vh' }}>
      <div style={{ borderBottom: `3px solid ${NAVY}`, paddingBottom: 14, marginBottom: 28 }}>
        <h1 style={{ fontSize: 24, fontWeight: 900, color: NAVY, margin: 0 }}>
          {isFa ? 'نتایج جستجو' : 'Search results'}
        </h1>
        {q && (
          <p style={{ fontSize: 14, color: 'var(--ink-4)', margin: '8px 0 0' }}>
            {isFa
              ? `${results.length.toLocaleString('fa-IR')} نتیجه برای «${q}»`
              : `${results.length} results for “${q}”`}
          </p>
        )}
      </div>

      {!q ? (
        <p style={{ color: 'var(--ink-5)', fontSize: 15 }}>{isFa ? 'عبارتی برای جستجو وارد کنید.' : 'Enter a search term.'}</p>
      ) : results.length === 0 ? (
        <div style={{ padding: '64px 0', textAlign: 'center', color: 'var(--ink-5)' }}>
          <p style={{ fontSize: 15 }}>{isFa ? 'نتیجه‌ای یافت نشد' : 'No results found'}</p>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {results.map((r) => (
            <Link
              key={r.id}
              to={r.url}
              style={{
                display: 'block', textDecoration: 'none', border: '1px solid var(--rule-thin)',
                borderRadius: 12, padding: '16px 18px', background: '#fff', transition: 'box-shadow 150ms, transform 150ms',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.boxShadow = '0 8px 24px rgba(3,35,64,0.10)'; e.currentTarget.style.transform = 'translateY(-2px)' }}
              onMouseLeave={(e) => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none' }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 11, fontWeight: 700, color: '#fff', background: r.color, borderRadius: 6, padding: '2px 8px' }}>{r.badge}</span>
                {r.meta && <span style={{ fontSize: 11, color: 'var(--ink-5)' }}>{r.meta}</span>}
              </div>
              <h3 style={{ fontSize: 16, fontWeight: 800, color: NAVY, margin: '0 0 4px' }}>{r.title}</h3>
              {r.summary && (
                <p style={{ fontSize: 13, color: 'var(--ink-4)', margin: 0, lineHeight: 1.7, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                  {r.summary}
                </p>
              )}
            </Link>
          ))}
        </div>
      )}
    </div>
  )
}
