import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { BarChart3, Cpu, Leaf, Globe, Zap, ChevronLeft, ChevronRight, X, LogIn, UserPlus, Calendar, User } from 'lucide-react'
import { useLang } from '@/context/LangContext'
import { useAuth } from '@/context/AuthContext'
import { type RadarItem, type RadarCategory } from '@/content/radar'
import { RADAR_FUTURE_ITEMS as RADAR_ITEMS } from '@/content/radarFuture'

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

const CATEGORY_ICON: Record<RadarCategory, typeof BarChart3> = {
  market: BarChart3,
  tech: Cpu,
  commodity: Leaf,
  geo: Globe,
  energy: Zap,
}

const CATEGORY_LABEL: Record<RadarCategory, { fa: string; en: string }> = {
  market: { fa: 'بازار', en: 'Market' },
  tech: { fa: 'فناوری', en: 'Technology' },
  commodity: { fa: 'کامودیتی', en: 'Commodity' },
  geo: { fa: 'ژئوپلیتیک', en: 'Geopolitics' },
  energy: { fa: 'انرژی', en: 'Energy' },
}

const T = {
  fa: {
    overline: 'FORESIGHT & INTELLIGENCE', heading: 'رادار آینده',
    sub: 'رصد سیگنال‌های راهبردی و روندهای نوظهور صنعت فولاد جهان',
    readMore: 'ادامه مطلب',
    analysis: 'تحلیل راهبردی',
    disclaimer: 'این تحلیل توسط هوش مصنوعی تولید شده و جنبه راهنمایی دارد.',
    blurTitle: 'برای مطالعه کامل این تحلیل، عضو شوید',
    blurSub: 'دسترسی کامل به تمام گزارش‌ها و تحلیل‌های رادار آینده',
    login: 'ورود', signup: 'عضویت',
    author: 'نویسنده',
  },
  en: {
    overline: 'FORESIGHT & INTELLIGENCE', heading: 'Future Radar',
    sub: 'Monitoring strategic signals and emerging trends in the global steel industry',
    readMore: 'Read more',
    analysis: 'Strategic Analysis',
    disclaimer: 'This analysis was generated with AI assistance and is for guidance purposes.',
    blurTitle: 'Become a member to read the full analysis',
    blurSub: 'Full access to all Future Radar reports and analyses',
    login: 'Login', signup: 'Sign Up',
    author: 'Author',
  },
}

/* ─── membership gate (blur overlay) ─── */
function MembershipGate({ lang }: { lang: 'fa' | 'en' }) {
  const t = T[lang]
  return (
    <div style={{
      position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', gap: 16,
      background: 'linear-gradient(to bottom, rgba(250,247,244,0) 0%, rgba(250,247,244,0.85) 30%, rgba(250,247,244,0.97) 60%)',
      padding: '0 32px 32px',
    }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 16, fontWeight: 800, color: NAVY, marginBottom: 8 }}>{t.blurTitle}</div>
        <div style={{ fontSize: 13, color: 'rgba(7,29,73,0.6)', lineHeight: 1.7 }}>{t.blurSub}</div>
      </div>
      <div style={{ display: 'flex', gap: 10, direction: 'ltr' }}>
        <a
          href="/membership"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 7,
            padding: '10px 22px', borderRadius: 10, fontSize: 13, fontWeight: 700,
            background: NAVY, color: '#fff', textDecoration: 'none',
          }}
        >
          <LogIn size={15} />
          {t.login}
        </a>
        <a
          href="/membership"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 7,
            padding: '10px 22px', borderRadius: 10, fontSize: 13, fontWeight: 700,
            background: GOLD, color: NAVY, textDecoration: 'none',
          }}
        >
          <UserPlus size={15} />
          {t.signup}
        </a>
      </div>
    </div>
  )
}

/* ─── radar item modal ─── */
export function RadarItemModal({ item, lang, onClose }: { item: RadarItem; lang: 'fa' | 'en'; onClose: () => void }) {
  const t = T[lang]
  const content = item[lang]
  const { member } = useAuth()
  const isLoggedIn = member !== null
  const Icon = CATEGORY_ICON[item.category]
  const catLabel = CATEGORY_LABEL[item.category][lang]
  const dir = lang === 'fa' ? 'rtl' : 'ltr'

  const bodyParagraphs = content.body ?? []

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        onClick={onClose}
        style={{
          position: 'fixed', inset: 0, zIndex: 1000,
          background: 'rgba(3,35,64,0.65)', backdropFilter: 'blur(4px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '20px 16px',
        }}
      >
        <motion.div
          initial={{ opacity: 0, y: 32, scale: 0.96 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 32, scale: 0.96 }}
          transition={{ duration: 0.38, ease: [0.22, 1, 0.36, 1] }}
          onClick={e => e.stopPropagation()}
          dir={dir}
          style={{
            background: '#faf7f4', borderRadius: 20, width: '100%', maxWidth: 720,
            maxHeight: '90vh', overflowY: 'auto', position: 'relative',
            boxShadow: '0 40px 100px -20px rgba(3,35,64,0.5)',
          }}
        >
          {/* cover image */}
          <div style={{ position: 'relative', width: '100%', height: 280 }}>
            <img
              src={item.img}
              alt={content.title}
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', borderRadius: '20px 20px 0 0' }}
            />
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(3,35,64,0.6) 0%, transparent 50%)', borderRadius: '20px 20px 0 0' }} />
            {/* category tag on the image */}
            <div style={{
              position: 'absolute', bottom: 16,
              ...(lang === 'fa' ? { right: 20 } : { left: 20 }),
              display: 'flex', alignItems: 'center', gap: 6,
              background: GOLD, borderRadius: 8, padding: '5px 12px',
              direction: 'ltr',
            }}>
              <Icon size={13} color={NAVY} />
              <span style={{ fontSize: 11, fontWeight: 800, color: NAVY }}>{catLabel}</span>
            </div>
          </div>

          {/* close button */}
          <button
            onClick={onClose}
            style={{
              position: 'absolute', top: 16,
              ...(lang === 'fa' ? { left: 16 } : { right: 16 }),
              width: 36, height: 36, borderRadius: '50%', border: 'none',
              background: 'rgba(3,35,64,0.7)', color: '#fff', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              backdropFilter: 'blur(4px)',
            }}
          >
            <X size={18} />
          </button>

          {/* content area */}
          <div style={{ padding: '28px 32px 36px' }}>
            {/* title */}
            <h2 style={{ fontSize: 'clamp(18px,2.2vw,24px)', fontWeight: 900, color: NAVY, lineHeight: 1.4, margin: '0 0 16px' }}>
              {content.title}
            </h2>

            {/* meta row: author + date — direction:ltr so icon is physically before text */}
            <div style={{ display: 'flex', gap: 20, marginBottom: 24, flexWrap: 'wrap', direction: 'ltr', justifyContent: lang === 'fa' ? 'flex-end' : 'flex-start' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'rgba(7,29,73,0.55)', fontSize: 12, fontWeight: 600 }}>
                <User size={14} color={GOLD} />
                <span>{item.author.name}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'rgba(7,29,73,0.55)', fontSize: 12, fontWeight: 600 }}>
                <Calendar size={14} color={GOLD} />
                <span>{content.date}</span>
              </div>
            </div>

            {/* body paragraphs */}
            <div style={{ position: 'relative' }}>
              {bodyParagraphs.length > 0 ? (
                <>
                  {/* first paragraph always visible */}
                  <p style={{ fontSize: 14, lineHeight: 2, color: 'rgba(7,29,73,0.8)', margin: '0 0 16px' }}>
                    {bodyParagraphs[0]}
                  </p>

                  {/* rest: visible if logged in, blurred if not */}
                  {bodyParagraphs.length > 1 && (
                    <div style={{ position: 'relative' }}>
                      <div style={{
                        filter: isLoggedIn ? 'none' : 'blur(7px)',
                        opacity: isLoggedIn ? 1 : 0.55,
                        maxHeight: isLoggedIn ? 'none' : 340,
                        overflow: isLoggedIn ? 'visible' : 'hidden',
                        WebkitMaskImage: isLoggedIn ? 'none' : 'linear-gradient(to bottom, black 0%, transparent 90%)',
                        maskImage: isLoggedIn ? 'none' : 'linear-gradient(to bottom, black 0%, transparent 90%)',
                        userSelect: isLoggedIn ? 'auto' : 'none',
                        transition: 'filter 0.3s',
                      }}>
                        {bodyParagraphs.slice(1).map((p, i) => (
                          <p key={i} style={{ fontSize: 14, lineHeight: 2, color: 'rgba(7,29,73,0.8)', margin: '0 0 16px' }}>{p}</p>
                        ))}
                      </div>
                      {!isLoggedIn && <MembershipGate lang={lang} />}
                    </div>
                  )}
                </>
              ) : (
                <p style={{ fontSize: 14, lineHeight: 2, color: 'rgba(7,29,73,0.8)', margin: '0 0 16px' }}>
                  {content.excerpt}
                </p>
              )}
            </div>

            {/* strategic analysis box (only if logged in) */}
            {isLoggedIn && content.analysis && (
              <div style={{
                marginTop: 28, borderRadius: 14, padding: '20px 22px',
                background: `${NAVY}08`, border: `1.5px solid ${NAVY}15`,
              }}>
                <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '2px', color: GOLD, marginBottom: 10 }}>{t.analysis}</div>
                <p style={{ fontSize: 13, lineHeight: 1.9, color: NAVY, margin: 0 }}>{content.analysis}</p>
              </div>
            )}

            {/* AI disclaimer */}

            {/* close button at bottom */}
            {isLoggedIn && (
              <div style={{ marginTop: 28, display: 'flex', justifyContent: 'center' }}>
                <button
                  onClick={onClose}
                  style={{
                    padding: '10px 32px', borderRadius: 10, border: 'none', cursor: 'pointer',
                    background: NAVY, color: '#fff', fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
                    display: 'flex', alignItems: 'center', gap: 8, direction: 'ltr',
                  }}
                >
                  <X size={14} />
                  {lang === 'fa' ? 'بستن' : 'Close'}
                </button>
              </div>
            )}
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  )
}

/* ─── one card: gold bar (default) → navy author panel (hover) ─── */
export function RadarCard({ item, lang, onClick }: { item: RadarItem; lang: 'fa' | 'en'; onClick?: (item: RadarItem) => void }) {
  const [hover, setHover] = useState(false)
  const navigate = useNavigate()
  const t = item[lang]
  const Icon = CATEGORY_ICON[item.category]

  return (
    <motion.article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => onClick ? onClick(item) : navigate(`/radar/post/${item.id}`)}
      style={{
        position: 'relative', borderRadius: 16, overflow: 'hidden', cursor: 'pointer',
        aspectRatio: '3 / 2.4', background: NAVY,
        boxShadow: hover ? '0 30px 70px -30px rgba(7,29,73,0.45)' : '0 16px 40px -24px rgba(7,29,73,0.30)',
      }}
      animate={{ y: hover ? -4 : 0 }}
      transition={{ duration: 0.35, ease: [0.22, 1, 0.36, 1] }}
    >
      {/* background image */}
      <motion.img
        src={item.img}
        alt=""
        animate={{ scale: hover ? 1.06 : 1 }}
        transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
      />
      {/* hover dim so the navy panel reads */}
      <motion.div
        animate={{ opacity: hover ? 0.55 : 0 }}
        transition={{ duration: 0.35 }}
        style={{ position: 'absolute', inset: 0, background: NAVY }}
      />

      {/* ── DEFAULT: gold bar at the bottom ── */}
      <AnimatePresence>
        {!hover && (
          <motion.div
            initial={{ y: 0, opacity: 1 }}
            exit={{ y: 16, opacity: 0 }}
            transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
            style={{
              position: 'absolute', left: 12, right: 12, bottom: 12,
              background: GOLD, borderRadius: 12, padding: '14px 16px',
              display: 'flex', alignItems: 'center', gap: 12, direction: lang === 'fa' ? 'rtl' : 'ltr',
            }}
          >
            <div style={{ flexShrink: 0, width: 40, height: 40, borderRadius: '50%', background: 'rgba(7,29,73,0.10)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon size={20} color={NAVY} strokeWidth={2} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 800, color: NAVY, lineHeight: 1.4, marginBottom: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                {t.title}
              </div>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'rgba(7,29,73,0.65)' }}>{t.date}</div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* ── HOVER: navy author panel slides up ── */}
      <AnimatePresence>
        {hover && (
          <motion.div
            initial={{ y: 24, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 24, opacity: 0 }}
            transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
            style={{
              position: 'absolute', left: 12, right: 12, bottom: 12,
              background: 'rgba(7,29,73,0.92)', backdropFilter: 'blur(6px)',
              borderRadius: 12, padding: '16px 18px',
              direction: lang === 'fa' ? 'rtl' : 'ltr',
            }}
          >
            <div style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 13, fontWeight: 800, color: '#fff', lineHeight: 1.4, marginBottom: 4 }}>{t.title}</div>
              <div style={{ fontSize: 10, color: GOLD, fontWeight: 600 }}>{t.date}</div>
            </div>
            <p style={{ fontSize: 12, lineHeight: 1.8, color: 'rgba(255,255,255,0.78)', margin: 0 }}>
              {t.excerpt}
            </p>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.article>
  )
}

/* ─── pagination ─── */
function Pagination({ page, pages, onGo }: { page: number; pages: number; onGo: (p: number) => void }) {
  if (pages <= 1) return null
  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: 38, height: 38, borderRadius: 10, border: 'none', padding: '0 10px',
        fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: disabled ? 'default' : 'pointer',
        background: active ? NAVY : '#eee9e3', color: active ? '#fff' : NAVY,
        opacity: disabled ? 0.4 : 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        transition: 'background 160ms, color 160ms',
      }}
    >
      {children}
    </button>
  )

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 44, direction: 'ltr' }}>
      <Btn onClick={() => onGo(page - 1)} disabled={page === 1}><ChevronLeft 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)}>{n}</Btn>
      )}
      <Btn onClick={() => onGo(page + 1)} disabled={page === pages}><ChevronRight size={18} /></Btn>
    </div>
  )
}

export default function Radar() {
  const { lang } = useLang()
  const t = T[lang]
  const [page, setPage] = useState(1)
  const [selectedItem, setSelectedItem] = useState<RadarItem | null>(null)

  const pages = Math.ceil(RADAR_ITEMS.length / PER_PAGE)
  const start = (page - 1) * PER_PAGE
  const visible = RADAR_ITEMS.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: '#faf7f4', minHeight: '80vh' }}>
      <div className="max-w-7xl mx-auto px-12 max-md:px-5" style={{ paddingTop: 56, paddingBottom: 72 }}>

        {/* heading with gold rule on the leading side */}
        <div style={{ display: 'flex', alignItems: 'stretch', justifyContent: 'flex-start', marginBottom: 40 }}>
          <div style={{
            borderRight: lang === 'fa' ? `4px solid ${GOLD}` : undefined,
            borderLeft: lang === 'fa' ? undefined : `4px solid ${GOLD}`,
            paddingRight: lang === 'fa' ? 18 : 0,
            paddingLeft: lang === 'fa' ? 0 : 18,
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '3px', color: GOLD, marginBottom: 8 }}>{t.overline}</div>
            <h1 style={{ fontSize: 'clamp(26px, 2.8vw, 40px)', fontWeight: 900, color: NAVY, letterSpacing: '-0.5px', margin: 0 }}>{t.heading}</h1>
            <p style={{ fontSize: 'clamp(13px, 1.1vw, 15px)', color: 'rgba(7,29,73,0.6)', margin: '10px 0 0', maxWidth: 560, lineHeight: 1.8 }}>{t.sub}</p>
          </div>
        </div>

        {/* card grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 22 }} className="max-lg:!grid-cols-2 max-sm:!grid-cols-1">
          {visible.map((item) => (
            <RadarCard key={item.id} item={item} lang={lang} onClick={setSelectedItem} />
          ))}
        </div>

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

      {/* modal */}
      {selectedItem && (
        <RadarItemModal item={selectedItem} lang={lang} onClose={() => setSelectedItem(null)} />
      )}
    </div>
  )
}
