import { useState, type ReactElement } from 'react'
import { useParams, Navigate, Link } from 'react-router-dom'
import AuthPage from '@/pages/Auth/AuthPage'
import { motion } from 'framer-motion'
import { Calendar, Tag, UserPlus, LogIn, Send, Share2, Globe, Mail, ArrowLeft, ExternalLink } from 'lucide-react'
import { useLang } from '@/context/LangContext'
import { useAuth } from '@/context/AuthContext'
import { RADAR_FUTURE, type RadarFutureArticle, type RFBlock } from '@/content/radarFuture'
import { MagicTextGroup } from '@/components/ui/magic-text'

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

/* ─── one content block (text paragraph or image/chart) ─── */
function Block({ b }: { b: RFBlock }) {
  if (b.type === 'image' && b.url) {
    return (
      <figure style={{ margin: '24px 0' }}>
        <img src={b.url} alt={b.caption || ''} style={{ width: '100%', borderRadius: 14, display: 'block', boxShadow: '0 18px 44px -26px rgba(7,29,73,0.4)' }} />
        {b.caption && (
          <figcaption style={{ fontSize: 12.5, color: 'rgba(7,29,73,0.55)', textAlign: 'center', marginTop: 10 }}>{b.caption}</figcaption>
        )}
      </figure>
    )
  }
  if (!b.value) return null
  return <p style={{ fontSize: 15.5, lineHeight: 2.2, color: NAVY, margin: '0 0 18px', textAlign: 'justify', fontWeight: 500 }}>{b.value}</p>
}

/* ─── sources / citations list ─── */
function Sources({ sources, lang }: { sources: { title: string; url: string }[]; lang: 'fa' | 'en' }) {
  if (!sources.length) return null
  return (
    <div style={{ margin: '28px 0 0', borderTop: '1px solid rgba(7,29,73,0.1)', paddingTop: 18 }}>
      <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '2.5px', color: GOLD, marginBottom: 12 }}>
        {lang === 'fa' ? 'منابع' : 'SOURCES'}
      </div>
      <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {sources.map((s, i) => (
          <li key={i} style={{ fontSize: 13, color: NAVY, display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ color: GOLD, flexShrink: 0 }}>•</span>
            {s.url ? (
              <a href={s.url} target="_blank" rel="noopener noreferrer" style={{ color: NAVY, fontWeight: 700, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 5, direction: 'ltr' }}>
                {s.title || s.url}<ExternalLink size={12} color={GOLD} />
              </a>
            ) : (
              <span style={{ fontWeight: 700 }}>{s.title}</span>
            )}
          </li>
        ))}
      </ul>
    </div>
  )
}

/* ─── membership gate ─── */
function MembershipGate({ lang, onLogin }: { lang: 'fa' | 'en'; onLogin: () => void }) {
  const isFa = lang === 'fa'
  const copy = isFa
    ? 'تحلیل‌های راهبردی، آمارهای تخصصی و گزارش‌های اختصاصی اندیشکده فولاد آینده تنها در اختیار اعضای شبکه قرار می‌گیرد. برای دسترسی به این محتوا، وارد حساب کاربری خود شوید یا به جمع اعضای اندیشکده بپیوندید.'
    : 'At the Future Steel Institute we craft our strategic outputs for members of our expert network. Membership unlocks full reports, foresight scenarios and high-level analysis.'
  return (
    <div style={{
      position: 'relative', background: '#fff', borderRadius: 18, padding: 'clamp(20px,3vw,34px)',
      boxShadow: '0 30px 70px -30px rgba(7,29,73,0.35)', border: '1px solid rgba(7,29,73,0.06)',
      maxWidth: 720, margin: '0 auto', direction: isFa ? 'rtl' : 'ltr',
    }}>
      <p style={{ fontSize: 14.5, lineHeight: 2.1, color: 'rgba(7,29,73,0.78)', margin: '0 0 22px', textAlign: 'justify' }}>{copy}</p>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 10, direction: 'ltr' }}>
          {[Send, Share2, Globe, Mail].map((Icon, i) => (
            <a key={i} href="#" aria-label="social" style={{ width: 36, height: 36, borderRadius: '50%', background: NAVY, color: GOLD, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon size={16} />
            </a>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button onClick={onLogin} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, direction: 'ltr',
            background: 'transparent', color: NAVY, border: `1.5px solid ${NAVY}`, borderRadius: 10,
            padding: '12px 26px', fontFamily: 'inherit', fontSize: 14, fontWeight: 800, cursor: 'pointer',
          }}>
            <LogIn size={16} strokeWidth={2.5} />
            <span>{isFa ? 'ورود' : 'Log in'}</span>
          </button>
          <button onClick={onLogin} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, direction: 'ltr',
            background: GOLD, color: NAVY, border: 'none', borderRadius: 10, padding: '12px 26px',
            fontFamily: 'inherit', fontSize: 14, fontWeight: 800, cursor: 'pointer',
          }}>
            <UserPlus size={16} strokeWidth={2.5} />
            <span>{isFa ? 'ثبت نام' : 'Sign up'}</span>
          </button>
        </div>
      </div>
    </div>
  )
}

/* ─── related sidebar ─── */
function RelatedSidebar({ items, currentId, lang }: { items: RadarFutureArticle[]; currentId: string; lang: 'fa' | 'en' }) {
  const related = items.filter(r => r.id !== currentId).slice(0, 3)
  if (!related.length) return null
  return (
    <aside style={{ position: 'sticky', top: 88, alignSelf: 'flex-start' }} className="max-lg:!static">
      <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '2px', color: GOLD, marginBottom: 16 }}>
        {lang === 'fa' ? 'سیگنال‌های مرتبط' : 'RELATED SIGNALS'}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {related.map(r => (
          <Link key={r.id} to={`/radar/post/${r.id}`} style={{ textDecoration: 'none' }}>
            <article style={{
              background: '#fff', borderRadius: 14, overflow: 'hidden', cursor: 'pointer',
              border: '1px solid rgba(205,158,83,0.3)', borderBottom: `3px solid ${GOLD}`,
              transition: 'transform 180ms, box-shadow 180ms',
            }}
              onMouseEnter={e => { const d = e.currentTarget; d.style.transform = 'translateY(-3px)'; d.style.boxShadow = '0 16px 34px -22px rgba(7,29,73,0.42)' }}
              onMouseLeave={e => { const d = e.currentTarget; d.style.transform = 'translateY(0)'; d.style.boxShadow = 'none' }}
            >
              {r.img && <img src={r.img} alt="" style={{ width: '100%', aspectRatio: '16/10', objectFit: 'cover', display: 'block' }} />}
              <div style={{ padding: '12px 14px', textAlign: lang === 'fa' ? 'right' : 'left' }}>
                <h4 style={{ fontSize: 13, fontWeight: 800, color: NAVY, lineHeight: 1.6, margin: '0 0 6px' }}>{r[lang].title}</h4>
                <p style={{ fontSize: 11.5, color: 'rgba(7,29,73,0.55)', lineHeight: 1.7, margin: '0 0 10px' }}>{r[lang].excerpt}</p>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span style={{ width: 28, height: 28, borderRadius: '50%', background: 'rgba(205,158,83,0.15)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                    <ArrowLeft size={14} color={GOLD} strokeWidth={2.5} className="no-rtl-flip" />
                  </span>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: 'rgba(7,29,73,0.5)', fontWeight: 600 }}>
                    <Calendar size={11} color={GOLD} />{r[lang].date}
                  </span>
                </div>
              </div>
            </article>
          </Link>
        ))}
      </div>
    </aside>
  )
}

/* ─── main ─── */
export default function RadarPost() {
  const { lang } = useLang()
  const { id } = useParams<{ id: string }>()
  const isFa = lang === 'fa'

  const item = RADAR_FUTURE.find(r => r.id === id)
  const { member } = useAuth()
  const loggedIn = member !== null
  const [showAuth, setShowAuth] = useState(false)
  const handleAuthSuccess = () => setShowAuth(false)

  if (!item) return <Navigate to="/radar" replace />

  const content = item[lang]
  // drop a leading cover-image block (already shown big at the top)
  const blocks = item.blocks.filter((b, i) => !(i === 0 && b.type === 'image' && b.url === item.img))
  const textTeaser = blocks.filter(b => b.type !== 'image' && b.value).map(b => b.value || '').join(' ')

  return (
    <div dir={isFa ? 'rtl' : 'ltr'} style={{ background: '#fff', minHeight: '80vh' }}>

      {/* ── COVER ── */}
      {item.img && (
        <div style={{
          position: 'relative', width: '100vw',
          marginInline: 'calc(50% - 50vw)',
          height: 'clamp(420px, 92vh, 1000px)',
          borderRadius: 40, overflow: 'hidden',
        }} className="max-md:!rounded-3xl">
          <img src={item.img} alt={content.title} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(3,35,64,0.6) 0%, transparent 50%)' }} />
        </div>
      )}

      {showAuth && (
        <AuthPage defaultMode="register" onSuccess={handleAuthSuccess} onClose={() => setShowAuth(false)} />
      )}

      <div className="max-w-7xl mx-auto px-12 max-md:px-5" style={{ paddingTop: 28, paddingBottom: 72 }}>

        {/* ── BODY GRID ── */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 40 }} className="max-lg:!grid-cols-1 max-lg:!gap-8">

          {/* MAIN ARTICLE */}
          <article style={{ minWidth: 0 }}>

            {/* date */}
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'rgba(7,29,73,0.55)', fontWeight: 600, marginBottom: 12 }}>
              <Calendar size={14} color={GOLD} /> {content.date}
            </div>

            {/* title */}
            <h1 style={{ fontSize: 'clamp(22px,2.6vw,34px)', fontWeight: 900, color: NAVY, lineHeight: 1.5, letterSpacing: '-0.5px', margin: '0 0 12px' }}>
              {content.title}
            </h1>

            {/* category + tags + author */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 26, flexWrap: 'wrap' }}>
              {item.category && (
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 700, color: GOLD }}>
                  <Tag size={15} /> {item.category}
                </div>
              )}
              {item.tags.slice(0, 4).map(t => (
                <span key={t} style={{ fontSize: 11, fontWeight: 700, color: NAVY, background: `${GOLD}25`, borderRadius: 6, padding: '3px 10px' }}>{t}</span>
              ))}
              {item.author.name && (
                <span style={{ fontSize: 13, fontWeight: 700, color: NAVY }}>{item.author.name}</span>
              )}
            </div>

            {/* body */}
            {loggedIn ? (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.4, ease: EASE }}>
                {/* consecutive text blocks reveal word-by-word on scroll; images/charts render as-is */}
                {(() => {
                  const out: ReactElement[] = []
                  let run: string[] = []
                  const flush = (k: string) => {
                    if (!run.length) return
                    out.push(<MagicTextGroup key={k} paragraphs={run} dir={lang === 'fa' ? 'rtl' : 'ltr'} style={{ fontSize: 15.5, lineHeight: 2.2, color: NAVY, margin: '0 0 18px', fontWeight: 500 }} />)
                    run = []
                  }
                  blocks.forEach((b, i) => {
                    if (b.type !== 'image' && b.value) { run.push(b.value); return }
                    flush(`g${i}`)
                    out.push(<Block key={i} b={b} />)
                  })
                  flush('g-end')
                  return out
                })()}
                <Sources sources={item.sources} lang={lang} />
              </motion.div>
            ) : (
              <>
                {/* logged-out: at most 5 lines, faded out at the bottom, then the gate */}
                {textTeaser && (
                  <p style={{
                    fontSize: 15.5, lineHeight: 2.2, color: NAVY, margin: '0 0 12px', textAlign: 'justify', fontWeight: 500,
                    display: '-webkit-box', WebkitLineClamp: 5, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                    WebkitMaskImage: 'linear-gradient(to bottom, #000 56%, transparent 100%)',
                    maskImage: 'linear-gradient(to bottom, #000 56%, transparent 100%)',
                  }}>{textTeaser}</p>
                )}
                <MembershipGate lang={lang} onLogin={() => setShowAuth(true)} />
              </>
            )}
          </article>

          {/* RELATED SIDEBAR */}
          <RelatedSidebar items={RADAR_FUTURE} currentId={item.id} lang={lang} />
        </div>
      </div>
    </div>
  )
}
