import { useState, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { greenSteelProjects, type GreenSteelProject } from '../data/greenSteelProjects'

const faNum = (n: number) => n.toLocaleString('fa-IR')

// ─── Persian label maps ─────────────────────────────────────────────────────────
const TECH_FA: Record<string, string> = {
  'Complementing conventional steelmaking': 'مکمل فولادسازی متعارف',
  'Phasing out BF': 'حذف کوره بلند',
}
const SCALE_FA: Record<string, string> = { Pilot: 'پایلوت', Demo: 'نمایشی', 'Full scale': 'مقیاس کامل' }
const STATUS_FA: Record<string, string> = {
  Operating: 'در حال بهره‌برداری',
  Construction: 'در حال ساخت',
  Announced: 'اعلام‌شده',
  'Finalized (research & testing)': 'تحقیق و آزمایش',
  'Paused or postponed': 'متوقف / به‌تعویق',
  Cancelled: 'لغوشده',
}
const STATUS_COLOR: Record<string, string> = {
  Operating: '#16a34a',
  Construction: '#2563eb',
  Announced: '#d97706',
  'Finalized (research & testing)': '#0891b2',
  'Paused or postponed': '#64748b',
  Cancelled: '#dc2626',
}
const REGION_FA: Record<string, string> = {
  Europe: 'اروپا', Asia: 'آسیا', 'North America': 'آمریکای شمالی',
  'South America': 'آمریکای جنوبی', Africa: 'آفریقا', 'Australia & Oceania': 'اقیانوسیه',
}
const REGION_COLOR: Record<string, string> = {
  Africa: '#065f46', Asia: '#059669', Europe: '#10b981',
  'North America': '#34d399', 'South America': '#6ee7b7', 'Australia & Oceania': '#a7f3d0',
}
const REGION_ORDER = ['Africa', 'Asia', 'Europe', 'North America', 'South America', 'Australia & Oceania']
const COUNTRY_FA: Record<string, string> = {
  Netherlands: 'هلند', Austria: 'اتریش', France: 'فرانسه', Germany: 'آلمان', Belgium: 'بلژیک',
  Australia: 'استرالیا', Namibia: 'نامیبیا', 'United States': 'آمریکا', 'United Arab Emirates': 'امارات',
  Finland: 'فنلاند', Sweden: 'سوئد', Chile: 'شیلی', China: 'چین', India: 'هند', Spain: 'اسپانیا',
  Thailand: 'تایلند', Oman: 'عمان', Canada: 'کانادا', 'South Korea': 'کره جنوبی', Italy: 'ایتالیا',
}

const NAVY = '#0f172a'
const uniq = (k: keyof GreenSteelProject) => [...new Set(greenSteelProjects.map((p) => p[k]).filter(Boolean) as string[])]

const selectStyle: React.CSSProperties = {
  fontFamily: 'Vazir, sans-serif', fontSize: 12, fontWeight: 600, color: '#334155',
  padding: '6px 10px', borderRadius: 8, border: '1px solid #cbd5e1', background: '#fff',
  cursor: 'pointer', minWidth: 150, direction: 'rtl',
}

function Stat({ value, label, color, i }: { value: string; label: string; color: string; i: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: -8, scale: 0.9 }}
      whileInView={{ opacity: 1, y: 0, scale: 1 }}
      viewport={{ once: true }}
      transition={{ duration: 0.4, delay: i * 0.07, ease: [0.22, 1, 0.36, 1] }}
      style={{ flex: 1, minWidth: 110, background: '#fff', border: '1px solid #e2e8f0', borderTop: `3px solid ${color}`, borderRadius: 10, padding: '12px 14px', textAlign: 'center', boxShadow: '0 4px 12px rgba(3,35,64,0.05)' }}
    >
      <div style={{ fontSize: 22, fontWeight: 800, color, fontFamily: 'Vazir, sans-serif', lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 10, color: '#94a3b8', marginTop: 4 }}>{label}</div>
    </motion.div>
  )
}

export default function GreenSteelTracker() {
  const [tech, setTech] = useState('all')
  const [scale, setScale] = useState('all')
  const [status, setStatus] = useState('all')
  const [activeCountry, setActiveCountry] = useState<string | null>(null)
  const [hoverBar, setHoverBar] = useState<{ year: number; region: string; n: number } | null>(null)
  const [showAllProjects, setShowAllProjects] = useState(false)

  const techs = useMemo(() => uniq('tech'), [])
  const scales = ['Pilot', 'Demo', 'Full scale']
  const statuses = useMemo(() => uniq('status'), [])

  const filtered = useMemo(() => greenSteelProjects.filter((p) =>
    (tech === 'all' || p.tech === tech) &&
    (scale === 'all' || p.scale === scale) &&
    (status === 'all' || p.status === status) &&
    (!activeCountry || p.country === activeCountry),
  ), [tech, scale, status, activeCountry])

  // country ranking (respects tech/scale/status, NOT activeCountry so the list stays full)
  const forRanking = useMemo(() => greenSteelProjects.filter((p) =>
    (tech === 'all' || p.tech === tech) && (scale === 'all' || p.scale === scale) && (status === 'all' || p.status === status),
  ), [tech, scale, status])

  const countryCounts = useMemo(() => {
    const m: Record<string, number> = {}
    forRanking.forEach((p) => { m[p.country] = (m[p.country] || 0) + 1 })
    return Object.entries(m).sort((a, b) => b[1] - a[1])
  }, [forRanking])
  const maxCountry = countryCounts.length ? countryCounts[0][1] : 1

  // announcements over time, stacked by region
  const years = useMemo(() => [...new Set(greenSteelProjects.map((p) => p.announceYear).filter(Boolean) as number[])].sort((a, b) => a - b), [])
  const byYear = useMemo(() => {
    const m: Record<number, Record<string, number>> = {}
    years.forEach((y) => { m[y] = {} })
    forRanking.forEach((p) => {
      if (p.announceYear == null) return
      m[p.announceYear][p.region] = (m[p.announceYear][p.region] || 0) + 1
    })
    return m
  }, [forRanking, years])
  const maxYearTotal = useMemo(() => Math.max(1, ...years.map((y) => Object.values(byYear[y]).reduce((a, b) => a + b, 0))), [byYear, years])

  const totalInvest = useMemo(() => forRanking.reduce((a, p) => a + (p.investMUSD || 0), 0), [forRanking])
  const fullScaleCount = useMemo(() => forRanking.filter((p) => p.scale === 'Full scale').length, [forRanking])

  const CHART_H = 220

  return (
    <div style={{ background: '#fff', border: '1px solid #e2e6eb', borderRadius: 8, marginBottom: 16, overflow: 'hidden' }}>
      {/* header */}
      <div style={{ borderLeft: '3px solid #16a34a', padding: '12px 16px', background: '#f8fafc', borderBottom: '1px solid #e2e6eb', display: 'flex', alignItems: 'center', gap: 10, direction: 'rtl', flexWrap: 'wrap' }}>
        <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '1.5px', textTransform: 'uppercase' as const, color: '#16a34a' }}>ردیاب جهانی فولاد سبز</span>
        <span style={{ fontSize: 11, color: '#94a3b8' }}>پروژه‌های گذار صنعت فولاد · LeadIT Green Steel Tracker · ۲۰۲۶ Q۱</span>
        <a href="https://www.industrytransition.org/trackers/green-steel-tracker/" target="_blank" rel="noopener noreferrer" style={{ marginRight: 'auto', fontSize: 10, fontWeight: 700, color: '#1e40af', textDecoration: 'none' }}>منبع داده ↗</a>
      </div>

      <div style={{ padding: 16, direction: 'rtl' }}>
        {/* summary stats */}
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 14 }}>
          <Stat i={0} value={faNum(filtered.length)} label="پروژه فولاد سبز" color="#16a34a" />
          <Stat i={1} value={faNum(countryCounts.length)} label="کشور دارای پروژه" color="#059669" />
          <Stat i={2} value={`$${faNum(Math.round(totalInvest / 1000))}B`} label="مجموع سرمایه‌گذاری" color="#0891b2" />
          <Stat i={3} value={faNum(fullScaleCount)} label="پروژه مقیاس کامل" color="#CD9E53" />
        </div>

        {/* filters */}
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center', marginBottom: 16, padding: '10px 12px', background: '#f8fafc', borderRadius: 8, border: '1px solid #eef2f6' }}>
          <Filter label="فناوری" value={tech} onChange={setTech} options={techs} fa={TECH_FA} />
          <Filter label="مقیاس پروژه" value={scale} onChange={setScale} options={scales} fa={SCALE_FA} />
          <Filter label="وضعیت پروژه" value={status} onChange={setStatus} options={statuses} fa={STATUS_FA} />
          {activeCountry && (
            <button onClick={() => setActiveCountry(null)} style={{ ...selectStyle, minWidth: 0, color: '#dc2626', borderColor: '#fecaca', cursor: 'pointer', fontWeight: 700 }}>
              ✕ حذف فیلتر {COUNTRY_FA[activeCountry] || activeCountry}
            </button>
          )}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.7fr) minmax(0,1fr)', gap: 16 }} className="gst-grid">
          {/* Announcements over time */}
          <div style={{ border: '1px solid #eef2f6', borderRadius: 10, padding: 14, background: '#fff' }}>
            <div style={{ fontSize: 13, fontWeight: 800, color: NAVY, marginBottom: 2 }}>اعلام پروژه‌ها در طول زمان</div>
            <div style={{ fontSize: 10, color: '#94a3b8', marginBottom: 12 }}>تعداد اعلام پروژه به تفکیک قاره</div>

            {/* legend */}
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 10, fontSize: 10, color: '#64748b' }}>
              {REGION_ORDER.map((r) => (
                <span key={r} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ width: 9, height: 9, borderRadius: '50%', background: REGION_COLOR[r] }} />{REGION_FA[r]}
                </span>
              ))}
            </div>

            {/* chart */}
            <div style={{ position: 'relative', display: 'flex', alignItems: 'flex-end', gap: 6, height: CHART_H, direction: 'ltr', borderBottom: '1px solid #cbd5e1', paddingBottom: 0 }}>
              {years.map((y) => {
                const segs = byYear[y]
                const total = Object.values(segs).reduce((a, b) => a + b, 0)
                return (
                  <div key={y} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'center', height: '100%' }}>
                    <div style={{ width: '100%', maxWidth: 34, display: 'flex', flexDirection: 'column-reverse', borderRadius: '4px 4px 0 0', overflow: 'hidden' }}>
                      {REGION_ORDER.filter((r) => segs[r]).map((r) => {
                        const h = (segs[r] / maxYearTotal) * (CHART_H - 22)
                        return (
                          <motion.div
                            key={r}
                            initial={{ height: 0 }}
                            whileInView={{ height: h }}
                            viewport={{ once: true }}
                            transition={{ duration: 0.7, ease: [0.22, 1, 0.36, 1] }}
                            onMouseEnter={() => setHoverBar({ year: y, region: r, n: segs[r] })}
                            onMouseLeave={() => setHoverBar(null)}
                            style={{ background: REGION_COLOR[r], minHeight: segs[r] ? 3 : 0, cursor: 'pointer' }}
                          />
                        )
                      })}
                    </div>
                    <div style={{ fontSize: 9, color: total ? '#475569' : '#cbd5e1', fontWeight: 700, fontFamily: 'Vazir, sans-serif', marginTop: 4 }}>{total ? faNum(total) : ''}</div>
                    <div style={{ fontSize: 9, color: '#94a3b8', fontFamily: 'Vazir, sans-serif' }}>{faNum(y)}</div>
                  </div>
                )
              })}
              {hoverBar && (
                <div style={{ position: 'absolute', top: 0, right: 0, background: NAVY, color: '#fff', padding: '6px 10px', borderRadius: 8, fontSize: 11, direction: 'rtl', boxShadow: '0 8px 20px rgba(0,0,0,0.25)' }}>
                  {faNum(hoverBar.year)} · {REGION_FA[hoverBar.region]}: <b style={{ color: REGION_COLOR[hoverBar.region] }}>{faNum(hoverBar.n)}</b> پروژه
                </div>
              )}
            </div>
          </div>

          {/* Country ranking */}
          <div style={{ border: '1px solid #eef2f6', borderRadius: 10, padding: 14, background: NAVY }}>
            <div style={{ fontSize: 13, fontWeight: 800, color: '#fff', marginBottom: 12 }}>
              کشورهای دارای پروژه — {faNum(countryCounts.length)}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 280, overflowY: 'auto' }}>
              {countryCounts.map(([c, n], i) => {
                const isActive = activeCountry === c
                return (
                  <motion.div
                    key={c}
                    initial={{ opacity: 0, x: 16 }}
                    whileInView={{ opacity: 1, x: 0 }}
                    viewport={{ once: true }}
                    transition={{ duration: 0.35, delay: Math.min(i, 16) * 0.03 }}
                    onClick={() => setActiveCountry(isActive ? null : c)}
                    style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 10px', borderRadius: 6, cursor: 'pointer', background: isActive ? '#16a34a' : 'rgba(255,255,255,0.04)', overflow: 'hidden' }}
                  >
                    <motion.div
                      initial={{ width: 0 }}
                      whileInView={{ width: `${(n / maxCountry) * 100}%` }}
                      viewport={{ once: true }}
                      transition={{ duration: 0.8, delay: 0.1 + Math.min(i, 16) * 0.03, ease: [0.22, 1, 0.36, 1] }}
                      style={{ position: 'absolute', top: 0, right: 0, bottom: 0, background: isActive ? 'rgba(255,255,255,0.18)' : '#16a34a33' }}
                    />
                    <span style={{ position: 'relative', fontSize: 12, fontWeight: 700, color: '#fff' }}>{COUNTRY_FA[c] || c}</span>
                    <span style={{ position: 'relative', fontSize: 11, fontWeight: 800, color: '#fff', background: '#16a34a', borderRadius: 99, minWidth: 22, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Vazir, sans-serif' }}>{faNum(n)}</span>
                  </motion.div>
                )
              })}
            </div>
          </div>
        </div>

        {/* filtered project list */}
        <div style={{ fontSize: 12, fontWeight: 800, color: NAVY, margin: '18px 0 10px' }}>
          فهرست پروژه‌ها ({faNum(filtered.length)})
        </div>
        <div style={{ position: 'relative' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 10 }}>
          <AnimatePresence mode="popLayout">
            {(showAllProjects ? filtered : filtered.slice(0, 9)).map((p, i) => (
              <motion.div
                key={p.name}
                layout
                initial={{ opacity: 0, y: 14 }}
                whileInView={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.96 }}
                viewport={{ once: true, margin: '-20px' }}
                transition={{ duration: 0.35, delay: Math.min(i, 18) * 0.02, ease: [0.22, 1, 0.36, 1] }}
                style={{ background: '#fff', border: '1px solid #e2e6eb', borderRight: `3px solid ${STATUS_COLOR[p.status] || '#64748b'}`, borderRadius: 8, padding: 12, ...(!showAllProjects && i >= 6 ? { filter: 'blur(4px)', opacity: 0.5, pointerEvents: 'none' as const } : {}) }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8, marginBottom: 6 }}>
                  <div style={{ fontSize: 12, fontWeight: 800, color: NAVY, lineHeight: 1.5 }}>{p.name}</div>
                  <span style={{ flexShrink: 0, fontSize: 9, fontWeight: 700, color: STATUS_COLOR[p.status] || '#64748b', background: `${STATUS_COLOR[p.status] || '#64748b'}18`, padding: '2px 7px', borderRadius: 99, whiteSpace: 'nowrap' as const }}>
                    {STATUS_FA[p.status] || p.status}
                  </span>
                </div>
                <div style={{ fontSize: 10, color: '#64748b', marginBottom: 8 }}>{p.company} · {COUNTRY_FA[p.country] || p.country}</div>
                <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 9, fontWeight: 700, color: REGION_COLOR[p.region], background: `${REGION_COLOR[p.region]}1f`, padding: '2px 7px', borderRadius: 99 }}>{REGION_FA[p.region] || p.region}</span>
                  <span style={{ fontSize: 9, fontWeight: 700, color: '#475569', background: '#f1f5f9', padding: '2px 7px', borderRadius: 99 }}>{SCALE_FA[p.scale] || p.scale}</span>
                  {p.investMUSD != null && <span style={{ fontSize: 9, fontWeight: 700, color: '#0891b2', background: '#ecfeff', padding: '2px 7px', borderRadius: 99, fontFamily: 'Vazir, sans-serif' }}>${faNum(p.investMUSD)}M</span>}
                  {p.commYear != null && <span style={{ fontSize: 9, fontWeight: 700, color: '#854d0e', background: '#fef9c3', padding: '2px 7px', borderRadius: 99, fontFamily: 'Vazir, sans-serif' }}>بهره‌برداری {faNum(p.commYear)}</span>}
                </div>
                <div style={{ fontSize: 10, color: '#94a3b8', marginTop: 8 }}>{p.techUsed}</div>
              </motion.div>
            ))}
          </AnimatePresence>
        </div>
        {!showAllProjects && filtered.length > 6 && (
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 170, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 4, background: 'linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 60%, #fff 100%)', pointerEvents: 'none' }}>
            <button onClick={() => setShowAllProjects(true)} style={{ pointerEvents: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6, background: NAVY, color: '#fff', border: 'none', borderRadius: 99, padding: '10px 24px', fontSize: 12, fontWeight: 800, cursor: 'pointer', fontFamily: 'Vazir, sans-serif', boxShadow: '0 8px 24px rgba(3,35,64,0.28)' }}>
              مشاهده بیشتر ({faNum(filtered.length - 6)} پروژه دیگر)
            </button>
          </div>
        )}
        </div>
      </div>
    </div>
  )
}

function Filter({ label, value, onChange, options, fa }: { label: string; value: string; onChange: (v: string) => void; options: string[]; fa: Record<string, string> }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#64748b', fontWeight: 700 }}>
      {label}:
      <select value={value} onChange={(e) => onChange(e.target.value)} style={selectStyle}>
        <option value="all">همه</option>
        {options.map((o) => <option key={o} value={o}>{fa[o] || o}</option>)}
      </select>
    </label>
  )
}
