import { useState } from 'react'
import { Link, useParams, Navigate, useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { ArrowLeft, Download, Calendar, ChevronLeft, ChevronRight } from 'lucide-react'
import { useLang } from '@/context/LangContext'
import { RADAR_FUTURE, RADAR_SLUG_LABEL } from '@/content/radarFuture'
import { bannerFor } from '@/data/banners'
import {
  RADAR_CATEGORY_PAGES,
  BOOK_IMG,
  type RadarSlug,
} from '@/content/radarCategories'

const NAVY = '#032340'
const GOLD = '#CD9E53'
const PAPER = '#faf7f4'
const PER_PAGE = 12
const EASE = [0.22, 1, 0.36, 1] as const

/* ─── small reveal wrapper (animates in once on mount, never hides content) ─── */
function Reveal({ children, delay = 0 }: { children: React.ReactNode; delay?: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 18 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5, ease: EASE, delay }}
    >
      {children}
    </motion.div>
  )
}

/* ─── breadcrumb ─── */
function Breadcrumb({ label, lang }: { label: string; lang: 'fa' | 'en' }) {
  const home = lang === 'fa' ? 'خانه' : 'Home'
  const radar = lang === 'fa' ? 'رادار آینده' : 'Future Radar'
  const Sep = () => (
    <ChevronLeft size={15} color="rgba(7,29,73,0.4)" style={{ transform: lang === 'fa' ? 'none' : 'rotate(180deg)' }} className="no-rtl-flip" />
  )
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 24, direction: lang === 'fa' ? 'rtl' : 'ltr', flexWrap: 'wrap' }}>
      {/* gold tick */}
      <span style={{ width: 4, height: 18, background: GOLD, borderRadius: 2, display: 'inline-block', marginInlineEnd: 6 }} />
      <Link to="/" style={{ fontSize: 14, fontWeight: 700, color: NAVY, textDecoration: 'none' }}>{home}</Link>
      <Sep />
      <Link to="/radar" style={{ fontSize: 14, fontWeight: 700, color: NAVY, textDecoration: 'none' }}>{radar}</Link>
      <Sep />
      <span style={{ fontSize: 14, fontWeight: 800, color: GOLD }}>{label}</span>
    </div>
  )
}

/* ─── a "latest" mini-card (image on the trailing side, text + CTA) ─── */
function MiniCard({ img, title, excerpt, date, lang, onClick }: { img: string; title: string; excerpt: string; date: string; lang: 'fa' | 'en'; onClick?: () => void }) {
  const cta = lang === 'fa' ? 'مشاهده تحلیل' : 'View analysis'
  return (
    <article style={{ display: 'flex', gap: 16, direction: lang === 'fa' ? 'rtl' : 'ltr', alignItems: 'stretch' }}>
      {/* image (first in RTL → right side) */}
      <div style={{ flexShrink: 0, width: 180, minHeight: 150, borderRadius: 12, overflow: 'hidden' }} className="max-sm:!w-[130px]">
        <img src={img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </div>
      {/* text */}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', textAlign: lang === 'fa' ? 'right' : 'left' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'rgba(7,29,73,0.5)', fontWeight: 600, marginBottom: 8, justifyContent: lang === 'fa' ? 'flex-start' : 'flex-start' }}>
          <Calendar size={13} color={GOLD} />
          <span>{date}</span>
        </div>
        <h3 style={{ fontSize: 15, fontWeight: 800, color: NAVY, lineHeight: 1.55, margin: '0 0 8px' }}>{title}</h3>
        <p style={{ fontSize: 12, lineHeight: 1.9, color: 'rgba(7,29,73,0.55)', margin: '0 0 14px', overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
          {excerpt}
        </p>
        <div style={{ marginTop: 'auto', display: 'flex', justifyContent: lang === 'fa' ? 'flex-start' : 'flex-start' }}>
          <button onClick={onClick} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, direction: 'ltr',
            background: GOLD, color: NAVY, border: 'none', borderRadius: 8,
            padding: '8px 16px', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, cursor: 'pointer',
          }}>
            <ArrowLeft size={14} strokeWidth={2.5} className="no-rtl-flip" />
            <span>{cta}</span>
          </button>
        </div>
      </div>
    </article>
  )
}

/* ─── big featured card (right column of the hero) ─── */
function FeaturedCard({ img, title, date, lang, onClick }: { img: string; title: string; date: string; lang: 'fa' | 'en'; onClick?: () => void }) {
  return (
    <article onClick={onClick} style={{ position: 'relative', borderRadius: 16, overflow: 'hidden', height: '100%', minHeight: 360, cursor: 'pointer' }} className="max-md:!min-h-[260px]">
      <img src={img} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(3,35,64,0.92) 0%, rgba(3,35,64,0.45) 45%, transparent 75%)' }} />
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: 28, direction: lang === 'fa' ? 'rtl' : 'ltr', textAlign: lang === 'fa' ? 'right' : 'left' }} className="max-md:!p-5">
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: GOLD, color: NAVY, borderRadius: 8, padding: '5px 12px', fontSize: 11, fontWeight: 700, marginBottom: 14 }}>
          <Calendar size={13} />
          <span>{date}</span>
        </div>
        <h2 style={{ fontSize: 'clamp(18px, 1.8vw, 24px)', fontWeight: 900, color: '#fff', lineHeight: 1.5, margin: 0 }}>{title}</h2>
      </div>
    </article>
  )
}

/* ─── grid card (gold framed) ─── */
function GridCard({ img, title, excerpt, date, lang, onClick }: { img: string; title: string; excerpt: string; date: string; lang: 'fa' | 'en'; onClick?: () => void }) {
  const [hover, setHover] = useState(false)
  return (
    <motion.article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick}
      animate={{ y: hover ? -4 : 0 }}
      transition={{ duration: 0.3, ease: EASE }}
      style={{
        background: '#fff', borderRadius: 14, overflow: 'hidden', cursor: 'pointer',
        borderTop: `1px solid rgba(205,158,83,0.35)`,
        borderInlineStart: `1px solid rgba(205,158,83,0.35)`,
        borderInlineEnd: `1px solid rgba(205,158,83,0.35)`,
        borderBottom: `3px solid ${GOLD}`,
        boxShadow: hover ? '0 22px 50px -26px rgba(7,29,73,0.40)' : '0 10px 30px -22px rgba(7,29,73,0.28)',
        display: 'flex', flexDirection: 'column',
        direction: lang === 'fa' ? 'rtl' : 'ltr',
      }}
    >
      <div style={{ overflow: 'hidden' }}>
        <motion.img
          src={img} alt=""
          animate={{ scale: hover ? 1.06 : 1 }}
          transition={{ duration: 0.6, ease: EASE }}
          style={{ width: '100%', aspectRatio: '16 / 8', objectFit: 'cover', display: 'block' }}
        />
      </div>
      <div style={{ padding: '10px 14px 10px', display: 'flex', flexDirection: 'column', flex: 1, textAlign: lang === 'fa' ? 'right' : 'left' }}>
        <h3 style={{ fontSize: 13, fontWeight: 800, color: NAVY, lineHeight: 1.5, margin: '0 0 4px', overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical' }}>{title}</h3>
        <p style={{ fontSize: 11.5, lineHeight: 1.7, color: 'rgba(7,29,73,0.55)', margin: '0 0 8px', overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical' }}>{excerpt}</p>
        {/* footer: date (trailing/right) + arrow (physical left) */}
        <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'rgba(7,29,73,0.5)', fontWeight: 600 }}>
            <Calendar size={12} color={GOLD} />
            {date}
          </span>
          <span style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(205,158,83,0.15)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <ArrowLeft size={15} color={GOLD} strokeWidth={2.5} className="no-rtl-flip" />
          </span>
        </div>
      </div>
    </motion.article>
  )
}

/* ─── special-analysis banner — reuses the home FeaturedReportBanner design
   (book mockup spills outside the frame; navy gradient + angled gold band) ─── */
function SpecialBanner({ kicker, title, desc, lang, img, ctaUrl, ctaLabel }: { kicker: string; title: string; desc: string; lang: 'fa' | 'en'; img?: string; ctaUrl?: string; ctaLabel?: string }) {
  const isFa = lang === 'fa'
  const dl = ctaLabel || (isFa ? 'دانلود گزارش' : 'Download report')
  return (
    <div style={{ margin: '52px 0 60px' }} className="max-md:!my-8">
      {/* wrapper allows the book to spill outside the frame */}
      <div style={{ position: 'relative', overflow: 'visible' }} className="max-md:!overflow-hidden max-md:!rounded-2xl">

        {/* clipped background (navy gradient + angled gold band) */}
        <div style={{
          position: 'absolute', inset: 0, borderRadius: 20, overflow: 'hidden',
          background: `linear-gradient(110deg, ${NAVY} 0%, #06335c 55%, ${NAVY} 100%)`,
          boxShadow: '0 30px 70px -34px rgba(3,35,64,0.5)',
        }}>
          <div style={{
            position: 'absolute', insetInlineStart: 0, insetInlineEnd: 0, bottom: -6, height: 88,
            background: GOLD, transform: 'skewY(-2.4deg)', transformOrigin: isFa ? 'right' : 'left',
          }} className="max-md:hidden" />
        </div>

        {/* DESKTOP: row. MOBILE: column */}
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center', minHeight: 240, direction: 'ltr' }}
          className="max-md:!flex-col">

          {/* TEXT */}
          <div style={{ width: '52%', padding: '40px 48px', direction: isFa ? 'rtl' : 'ltr' }}
            className="max-md:!w-full max-md:!px-6 max-md:!pb-7 max-md:!pt-5 max-md:!order-2">
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
              <span style={{ background: GOLD, color: NAVY, borderRadius: 6, padding: '4px 12px', fontSize: 12, fontWeight: 800 }}>{kicker}</span>
            </div>
            <h2 style={{ fontSize: 'clamp(18px, 2.3vw, 30px)', fontWeight: 900, color: '#fff', lineHeight: 1.4, letterSpacing: '-0.5px', margin: '0 0 12px' }}>
              {title}
            </h2>
            <div style={{ fontSize: 'clamp(12px, 1.1vw, 15px)', lineHeight: 1.9, color: 'rgba(255,255,255,0.6)', marginBottom: 22, textAlign: isFa ? 'right' : 'left' }}>
              {desc}
            </div>
            <div style={{ display: 'flex', justifyContent: isFa ? 'flex-start' : 'flex-end' }}>
              <button
                onClick={() => { if (ctaUrl) window.open(ctaUrl, '_blank', 'noopener') }}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 10, direction: 'ltr',
                  background: '#f4ede0', color: NAVY, border: 'none', borderRadius: 10,
                  padding: '13px 28px', fontSize: 14, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit',
                  transition: 'transform 180ms, box-shadow 180ms',
                }}
                onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.transform = 'translateY(-2px)'; (e.currentTarget as HTMLElement).style.boxShadow = '0 12px 26px -10px rgba(0,0,0,0.4)' }}
                onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.transform = 'translateY(0)'; (e.currentTarget as HTMLElement).style.boxShadow = 'none' }}
              >
                <Download size={17} strokeWidth={2.4} />
                {dl}
              </button>
            </div>
          </div>

          {/* RIGHT SIDE — CMS cover image or fallback mockup, keeping background and tilt */}
          <div style={{ width: '48%', position: 'relative', minHeight: 240 }} className="max-md:!w-full max-md:!min-height-none max-md:!order-1">
            <div style={{
              position: 'absolute', top: -38, right: 30, width: '92%', height: 'auto', zIndex: 10,
              transform: 'rotate(-4deg)', transformOrigin: 'bottom right',
              filter: 'drop-shadow(0 20px 40px rgba(0,0,0,0.35))',
            }} className="max-md:!static max-md:!w-full max-md:!rotate-0 max-md:!p-6">
              <img src={img || BOOK_IMG} alt="" style={{ width: '100%', height: 'auto', display: 'block' }} />
            </div>
          </div>

        </div>
      </div>
    </div>
  )
}

/* ─── pagination ─── */
function Pagination({ page, pages, onGo, lang }: { page: number; pages: number; onGo: (p: number) => void; lang: 'fa' | 'en' }) {
  if (pages <= 1) return null
  const fa = (n: number) => lang === 'fa' ? n.toLocaleString('fa-IR') : String(n)
  const nums: (number | '…')[] = []
  for (let i = 1; i <= pages; i++) {
    if (i === 1 || i === pages || Math.abs(i - page) <= 1) nums.push(i)
    else if (nums[nums.length - 1] !== '…') nums.push('…')
  }
  const Btn = ({ children, active, onClick, disabled }: { children: React.ReactNode; active?: boolean; onClick?: () => void; disabled?: boolean }) => (
    <button onClick={onClick} disabled={disabled} style={{
      minWidth: 40, height: 40, borderRadius: 10, border: 'none', padding: '0 10px',
      fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: disabled ? 'default' : 'pointer',
      background: active ? GOLD : '#eee9e3', color: active ? NAVY : NAVY,
      opacity: disabled ? 0.4 : 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      transition: 'background 160ms',
    }}>{children}</button>
  )
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 44, direction: lang === 'fa' ? 'rtl' : 'ltr' }}>
      <Btn onClick={() => onGo(page - 1)} disabled={page === 1}>{lang === 'fa' ? <ChevronLeft size={18} /> : <ChevronRight size={18} />}</Btn>
      {nums.map((n, i) =>
        n === '…'
          ? <span key={`e${i}`} style={{ color: NAVY, opacity: 0.5, padding: '0 4px' }}>…</span>
          : <Btn key={n} active={n === page} onClick={() => onGo(n)}>{fa(n)}</Btn>
      )}
      <Btn onClick={() => onGo(page + 1)} disabled={page === pages}>{lang === 'fa' ? <ChevronRight size={18} /> : <ChevronLeft size={18} />}</Btn>
    </div>
  )
}

/* ════════════════════════════════════════════════════════════ */
export default function RadarCategory() {
  const { lang } = useLang()
  const { category } = useParams<{ category: string }>()
  const [page, setPage] = useState(1)
  const navigate = useNavigate()

  const cfg = category ? RADAR_CATEGORY_PAGES[category as RadarSlug] : undefined
  if (!cfg) return <Navigate to="/radar" replace />

  const c = cfg[lang]

  // card pool = رادار آینده block articles whose category == this sub-menu label
  const base = RADAR_FUTURE.filter((r) => r.category === RADAR_SLUG_LABEL[category as string])

  if (!base.length) {
    return (
      <div dir={lang === 'fa' ? 'rtl' : 'ltr'} style={{ background: PAPER, minHeight: '80vh' }}>
        <div className="max-w-7xl mx-auto px-12 max-md:!px-4" style={{ paddingTop: 40, paddingBottom: 72 }}>
          <Breadcrumb label={c.label} lang={lang} />
          <p style={{ color: NAVY, fontSize: 15, opacity: 0.7, padding: '40px 0' }}>
            {lang === 'fa' ? 'هنوز مطلبی برای این بخش منتشر نشده است.' : 'No articles published in this section yet.'}
          </p>
        </div>
      </div>
    )
  }
  const seed = base
  const cards = seed

  // latest 2 mini-cards
  const latest = cards.slice(0, 2)

  const pages = Math.max(1, Math.ceil(cards.length / PER_PAGE))
  const start = (page - 1) * PER_PAGE
  const visible = cards.slice(start, start + PER_PAGE)

  const go = (p: number) => {
    if (p < 1 || p > pages) return
    setPage(p)
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  return (
    <div dir={lang === 'fa' ? 'rtl' : 'ltr'} style={{ background: PAPER, minHeight: '80vh', overflowX: 'hidden' }}>
      <div className="max-w-7xl mx-auto px-12 max-md:!px-4" style={{ paddingTop: 40, paddingBottom: 72 }}>

        {/* breadcrumb */}
        <Breadcrumb label={c.label} lang={lang} />

        {/* ── HERO ROW ── */}
        <Reveal>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 40 }} className="max-lg:!grid-cols-1 max-md:!gap-4 max-md:!mb-7">
            {/* RIGHT (first in RTL): big featured */}
            <FeaturedCard img={c.featured.img} title={c.featured.title} date={c.featured.date} lang={lang} onClick={() => navigate(`/radar/post/${seed[0]?.id ?? 'r1'}`)} />
            {/* LEFT (second in RTL): latest box */}
            <div style={{ background: '#efe9e1', borderRadius: 16, padding: 24, display: 'flex', flexDirection: 'column' }} className="max-md:!p-4">
              <h2 style={{ fontSize: 16, fontWeight: 900, color: GOLD, margin: '0 0 18px', textAlign: lang === 'fa' ? 'right' : 'left' }}>{c.latestHeading}</h2>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 20, flex: 1, justifyContent: 'space-around' }}>
                {latest.map((item, idx) => (
                  <MiniCard key={item.id} img={item.img} title={item[lang].title} excerpt={item[lang].excerpt} date={item[lang].date} lang={lang} onClick={() => navigate(`/radar/post/${seed[idx]?.id ?? seed[0]?.id ?? 'r1'}`)} />
                ))}
              </div>
            </div>
          </div>
        </Reveal>

        {/* ── FIRST GRID (4) ── */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18 }} className="max-lg:!grid-cols-2 max-sm:!grid-cols-1">
          {visible.slice(0, 4).map((item, idx) => (
            <Reveal key={item.id}>
              <GridCard img={item.img} title={item[lang].title} excerpt={item[lang].excerpt} date={item[lang].date} lang={lang} onClick={() => navigate(`/radar/post/${seed[idx % seed.length].id}`)} />
            </Reveal>
          ))}
        </div>

        {/* ── SPECIAL BANNER (CMS banner for this radar page, else page default) ── */}
        <Reveal>
          {(() => {
            const cms = bannerFor('radar-' + category)
            const bk = cms
              ? { kicker: cms[lang].overline || c.banner.kicker, title: cms[lang].title || c.banner.title, desc: cms[lang].subtitle || c.banner.desc, img: cms.image, ctaUrl: cms.ctaUrl, ctaLabel: cms[lang].cta }
              : { kicker: c.banner.kicker, title: c.banner.title, desc: c.banner.desc }
            return <SpecialBanner {...bk} lang={lang} />
          })()}
        </Reveal>

        {/* ── SECOND GRID (rest) ── */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18 }} className="max-lg:!grid-cols-2 max-sm:!grid-cols-1">
          {visible.slice(4).map((item, idx) => (
            <Reveal key={item.id}>
              <GridCard img={item.img} title={item[lang].title} excerpt={item[lang].excerpt} date={item[lang].date} lang={lang} onClick={() => navigate(`/radar/post/${seed[(idx + 4) % seed.length].id}`)} />
            </Reveal>
          ))}
        </div>

        <Pagination page={page} pages={pages} onGo={go} lang={lang} />
      </div>
    </div>
  )
}
