import { useState, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { ExternalLink, ChevronLeft, ChevronRight } from 'lucide-react'
import { useLang } from '@/context/LangContext'
import { bootstrapEvents, events } from '@/data/events'

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

const TYPE_LABEL: Record<string, { fa: string; en: string; color: string; bg: string }> = {
  conference:    { fa: 'کنفرانس',    en: 'Conference',    color: '#2471a3', bg: '#EAF2FB' },
  exhibition:    { fa: 'نمایشگاه',   en: 'Exhibition',    color: '#1e8449', bg: '#EAFAF1' },
  seminar:       { fa: 'نشست تخصصی', en: 'Seminar',       color: '#7d3c98', bg: '#F5EEF8' },
  international: { fa: 'بین‌الملل',  en: 'International', color: '#c0392b', bg: '#FDEDEC' },
}

const EVENT_IMGS: Record<string, string> = {
  'smu-steel-summit-2026':         '/news/photo-1566873535350-6586b0b7a1f2.jpg',
  'china-international-steel-congress-2026': '/news/photo-1504307651254-35680f356dfd.jpg',
  'future-green-steel-2026':       '/news/photo-1611273426858-450d8e3c9fce.jpg',
  'iran-steel-congress-1403':      '/news/photo-1611273426858-450d8e3c9fce.jpg',
  'middle-east-steel-metals-2024': '/news/photo-1570168007204-dfb528c6958f.jpg',
  'steel-policy-seminar-1404':     '/news/photo-1567789884554-0b844b597180.jpg',
  'world-steel-forum-2025':        '/news/photo-1504307651254-35680f356dfd.jpg',
  'iran-metallurgy-expo-1404':     '/news/photo-1518770660439-4636190af475.jpg',
  'oecd-steel-summit-2025':        '/news/photo-1581092160607-ee22731c9b4e.jpg',
}

/* ── Countdown ─────────────────────────────────────────── */
function useCountdown(targetTime: number) {
  const calc = () => {
    const diff = Math.max(0, targetTime - Date.now())
    return {
      days:  Math.floor(diff / 86400000),
      hours: Math.floor((diff % 86400000) / 3600000),
      mins:  Math.floor((diff % 3600000) / 60000),
      secs:  Math.floor((diff % 60000) / 1000),
    }
  }
  const [t, setT] = useState(calc)
  useEffect(() => {
    setT(calc())
    const id = setInterval(() => setT(calc()), 1000)
    return () => clearInterval(id)
  }, [targetTime])
  return t
}

/* ── Jalali calendar helpers ────────────────────────────── */
const WEEKDAYS = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنج‌شنبه', 'جمعه']
const J_MONTHS = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند']
const faNum = (n: number) => n.toLocaleString('fa-IR', { useGrouping: false })

type CalendarEventDate = { day: number; month: number; year: number }

function jalaliMonthNumber(value: string) {
  const normalized = String(value ?? '')
    .replace(/ماه/g, '')
    .replace(/[\s\u200c]/g, '')
    .replace(/ي/g, 'ی')
    .replace(/ك/g, 'ک')
  return J_MONTHS.findIndex(month => month === normalized) + 1
}

function calendarDateKey(date: CalendarEventDate) {
  return date.year * 10000 + date.month * 100 + date.day
}

function gregorianDateForJalali(target: CalendarEventDate) {
  const cursor = new Date(target.year + 621, 2, 15, 12)
  for (let index = 0; index < 380; index += 1) {
    const current = jParts(cursor)
    if (current.day === target.day && current.month === target.month && current.year === target.year) {
      return new Date(cursor)
    }
    cursor.setDate(cursor.getDate() + 1)
  }
  return null
}

function initialCalendarAnchor(sourceEvents = events) {
  const today = new Date()
  const todayJ = jParts(today)
  const todayKey = calendarDateKey(todayJ)
  const nearestHomeEvent = sourceEvents
    .slice(0, 3)
    .map(event => ({
      day: Number(event.date),
      month: jalaliMonthNumber(event.month),
      year: Number(event.year),
    }))
    .filter(date => date.day >= 1 && date.month >= 1 && date.year > 0 && calendarDateKey(date) >= todayKey)
    .sort((a, b) => calendarDateKey(a) - calendarDateKey(b))[0]

  return nearestHomeEvent ? gregorianDateForJalali(nearestHomeEvent) ?? today : today
}

function nearestUpcomingEvent(sourceEvents: typeof events) {
  const todayJ = jParts(new Date())
  const todayKey = calendarDateKey(todayJ)
  return [...sourceEvents]
    .filter(event => {
      const date = { day: Number(event.date), month: jalaliMonthNumber(event.month), year: Number(event.year) }
      return date.day >= 1 && date.month >= 1 && date.year > 0 && calendarDateKey(date) >= todayKey
    })
    .sort((a, b) => {
      const aKey = calendarDateKey({ day: Number(a.date), month: jalaliMonthNumber(a.month), year: Number(a.year) })
      const bKey = calendarDateKey({ day: Number(b.date), month: jalaliMonthNumber(b.month), year: Number(b.year) })
      return aKey - bKey
    })[0]
}

function eventStartTimestamp(event: (typeof events)[number] | undefined) {
  if (!event) return Date.now()
  const date = gregorianDateForJalali({
    day: Number(event.date),
    month: jalaliMonthNumber(event.month),
    year: Number(event.year),
  })
  if (!date) return Date.now()
  date.setHours(9, 0, 0, 0)
  return date.getTime()
}

function jParts(d: Date) {
  if (!(d instanceof Date) || !Number.isFinite(d.getTime())) {
    return { day: 0, month: 0, year: 0 }
  }
  const p = new Intl.DateTimeFormat('en-US-u-ca-persian', { day:'numeric', month:'numeric', year:'numeric' }).formatToParts(d)
  const get = (t: string) => Number(p.find(x => x.type === t)?.value)
  return { day: get('day'), month: get('month'), year: get('year') }
}
function buildMonth(anchor: Date) {
  const { month, year } = jParts(anchor)
  const first = new Date(anchor)
  while (jParts(first).day !== 1) first.setDate(first.getDate() - 1)
  const days: Date[] = []
  const cur = new Date(first)
  while (jParts(cur).month === month && jParts(cur).year === year) {
    days.push(new Date(cur)); cur.setDate(cur.getDate() + 1)
  }
  // Persian week starts Saturday → JS getDay(): Sat=6, Sun=0, Mon=1 … Fri=5
  const dowMap = [1, 2, 3, 4, 5, 6, 0] // Sun→1, Mon→2 … Sat→0
  const firstDow = dowMap[first.getDay()]
  return { days, firstDow, month, year }
}

function MiniCalendar({ anchor, onNav, eventDates, onSelect }: {
  anchor: Date; onNav: (d: 1|-1) => void
  eventDates: CalendarEventDate[]; onSelect: (d: Date) => void
}) {
  const { days, firstDow, month, year } = buildMonth(anchor)
  const today = new Date(); const todayJ = jParts(today)

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 12,
      background: '#fff', border: '1px solid #E7E7E7', borderRadius: 8,
      padding: 12, height: '100%', boxSizing: 'border-box',
    }}>
      {/* تقویم label row */}
      <div style={{ width: '100%', padding: '0 8px', boxSizing: 'border-box' }}>
        <span style={{ display: 'block', width: '100%', fontSize: 18, fontWeight: 700, color: '#262626', textAlign: 'right' }}>تقویم</span>
      </div>

      {/* month nav */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 8px', direction: 'ltr' }}>
        <button type="button" aria-label="ماه بعد" title="ماه بعد" onClick={() => onNav(1)} style={{
          width: 24, height: 24, borderRadius: 24, border: 'none',
          background: '#FBEED9', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <ChevronRight size={12} color={GOLD} />
        </button>
        <span dir="rtl" style={{ fontSize: 18, fontWeight: 500, color: '#262626', textAlign: 'center', flex: 1 }}>
          {J_MONTHS[month - 1]} ماه {faNum(year)}
        </span>
        <button type="button" aria-label="ماه قبل" title="ماه قبل" onClick={() => onNav(-1)} style={{
          width: 24, height: 24, borderRadius: 24, border: 'none',
          background: '#FBEED9', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <ChevronLeft size={12} color={GOLD} />
        </button>
      </div>

      {/* weekday headers — pill bg #F7F7F7 */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', direction: 'rtl',
        background: '#F7F7F7', borderRadius: 25, padding: '6px 4px', gap: 3,
      }}>
        {WEEKDAYS.map(d => (
          <div key={d} style={{ textAlign: 'center', fontSize: 10, fontWeight: 500, color: '#5D5D5D', lineHeight: '16px' }}>{d}</div>
        ))}
      </div>

      {/* day cells — bg #F7F7F7 */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, minmax(0, 1fr))', direction: 'rtl',
        background: '#F7F7F7', borderRadius: 16, padding: 8, gap: 4,
        alignContent: 'start', width: '100%', boxSizing: 'border-box', overflow: 'hidden',
      }}>
        {Array.from({ length: firstDow }, (_, i) => <div key={`e${i}`} />)}
        {days.map(d => {
          const jp = jParts(d)
          const isToday = jp.day === todayJ.day && jp.month === todayJ.month && jp.year === todayJ.year
          const hasEv = eventDates.some(ed => ed.day === jp.day && ed.month === jp.month && ed.year === jp.year)
          return (
            <button key={jp.day} onClick={() => onSelect(d)} style={{
              aspectRatio: '1', border: hasEv && !isToday ? `1px solid ${GOLD}` : 'none',
              width: '100%', minWidth: 0, padding: 0,
              borderRadius: isToday ? 99 : hasEv ? 60 : '50%',
              fontSize: isToday ? 14 : 12, fontWeight: hasEv || isToday ? 800 : 500,
              background: isToday ? GOLD : hasEv ? '#FFF6E6' : '#fff',
              color: isToday ? '#fff' : hasEv ? NAVY : '#888888',
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'background .15s', position: 'relative',
            }}>
              {faNum(jp.day)}
              {hasEv && (
                <span aria-hidden style={{
                  position: 'absolute', bottom: '12%', left: '50%', transform: 'translateX(-50%)',
                  width: 4, height: 4, borderRadius: '50%', background: isToday ? '#fff' : GOLD,
                }} />
              )}
            </button>
          )
        })}
      </div>
    </div>
  )
}

/* ── Countdown box ─────────────────────────────────────── */
function CBox({ v, label }: { v: number; label: string }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
      <div style={{
        width: 80, height: 80, borderRadius: 14,
        background: 'rgba(255,255,255,0.09)', border: '1px solid rgba(255,255,255,0.14)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 32, fontWeight: 900, color: '#fff', fontVariantNumeric: 'tabular-nums',
      }}>{faNum(v)}</div>
      <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', fontWeight: 600 }}>{label}</span>
    </div>
  )
}

/* ── Main component ────────────────────────────────────── */
export default function Events() {
  const { lang } = useLang()
  const isFa = lang === 'fa'

  const [calAnchor, setCalAnchor] = useState(initialCalendarAnchor)
  const [eventList, setEventList] = useState(() => [...events])
  const [selEvt, setSelEvt] = useState(events[0])
  const [showAll, setShowAll] = useState(false)
  const nextEvent = nearestUpcomingEvent(eventList) ?? eventList[0]
  const nextEventTarget = eventStartTimestamp(nextEvent)
  const cd = useCountdown(nextEventTarget)

  useEffect(() => {
    let active = true
    bootstrapEvents().then(() => {
      if (!active) return
      const latestEvents = [...events]
      setEventList(latestEvents)
      if (latestEvents[0]) setSelEvt(latestEvents[0])
      setCalAnchor(initialCalendarAnchor(latestEvents))
    })
    return () => { active = false }
  }, [])

  const handleCalNav = (dir: 1 | -1) => {
    const firstDay = new Date(calAnchor)
    while (jParts(firstDay).day !== 1) firstDay.setDate(firstDay.getDate() - 1)
    firstDay.setDate(firstDay.getDate() + (dir === 1 ? 32 : -1))
    setCalAnchor(firstDay)
  }

  // scroll to the calendar when arriving via the «تقویم اندیشکده» nav link (/events#calendar)
  const { hash } = useLocation()
  useEffect(() => {
    if (hash !== '#calendar') return
    const el = document.getElementById('calendar')
    if (!el) return
    const timer = setTimeout(() => window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 90, behavior: 'smooth' }), 120)
    return () => clearTimeout(timer)
  }, [hash])

  const eventDates = eventList
    .flatMap(ev => {
      const start = Number(ev.date)
      const end = Number(ev.dateEnd ?? ev.date)
      return Array.from({ length: Math.max(1, end - start + 1) }, (_, index) => ({
        day: start + index,
        month: jalaliMonthNumber(ev.month),
        year: Number(ev.year),
      }))
    })
    .filter(date => date.day >= 1 && date.day <= 31 && date.month >= 1 && date.year > 0)

  const featured = eventList[0]
  const others = eventList.slice(1)
  const visibleOthers = showAll ? others : others.slice(0, 4)

  const selType = TYPE_LABEL[selEvt.type] ?? { fa: selEvt.type, en: selEvt.type, color: GOLD, bg: '#f5f5f5' }
  const featType = TYPE_LABEL[featured.type] ?? { fa: featured.type, en: featured.type, color: GOLD, bg: '#f5f5f5' }

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

      {/* ═══════════════════════════════════════════════
          HERO BANNER
      ═══════════════════════════════════════════════ */}
      <section style={{ position: 'relative', background: NAVY, overflow: 'hidden' }}>
        {/* world map background */}
        <img src="/world-map.webp" alt="" style={{ width: '100%', display: 'block' }} />
        {/* overlay + content absolutely on top of the image */}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to left, rgba(3,35,64,0.92) 30%, rgba(3,35,64,0.55) 65%, rgba(3,35,64,0.35) 100%)' }} />

        {/* text + countdown — right side, vertically centered */}
        <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, width: '52%', zIndex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '48px 5vw 48px 24px', direction: 'rtl' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 14 }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: GOLD }}>{nextEvent.location || nextEvent.city}</span>
            <img src="/icons/vuesax/linear/location.svg" alt="" style={{ width: 16, height: 16, filter: 'invert(73%) sepia(50%) saturate(500%) hue-rotate(5deg)' }} />
          </div>
          <h1 style={{ fontSize: 'clamp(22px,3vw,42px)', fontWeight: 900, color: GOLD, margin: '0 0 14px', lineHeight: 1.2 }}>
            {nextEvent.title}
          </h1>
          <p style={{ fontSize: 14, lineHeight: 2, color: 'rgba(255,255,255,0.72)', margin: '0 0 24px' }}>
            {nextEvent.description}
          </p>
          {/* countdown — inline below description */}
          <div style={{ display: 'flex', gap: 12, marginBottom: 24, direction: 'ltr', justifyContent: 'flex-end' }}>
            <CBox v={cd.days}  label={isFa ? 'روز'   : 'Days'} />
            <CBox v={cd.hours} label={isFa ? 'ساعت'  : 'Hrs'}  />
            <CBox v={cd.mins}  label={isFa ? 'دقیقه' : 'Min'}  />
            <CBox v={cd.secs}  label={isFa ? 'ثانیه' : 'Sec'}  />
          </div>
          <div>
            <a href="#calendar" onClick={() => {
              setSelEvt(nextEvent)
              const eventDate = gregorianDateForJalali({
                day: Number(nextEvent.date),
                month: jalaliMonthNumber(nextEvent.month),
                year: Number(nextEvent.year),
              })
              if (eventDate) setCalAnchor(eventDate)
            }} style={{
              display: 'inline-flex', alignItems: 'center', gap: 8, direction: 'ltr',
              background: GOLD, color: NAVY, borderRadius: 10, padding: '12px 28px',
              fontSize: 14, fontWeight: 800, textDecoration: 'none',
            }}>
              <ExternalLink size={14} strokeWidth={2.5} />
              <span style={{ direction: 'rtl' }}>{isFa ? 'اطلاعات بیشتر' : 'Learn More'}</span>
            </a>
          </div>
        </div>
      </section>

      {/* ═══════════════════════════════════════════════
          CALENDAR  |  SELECTED EVENT DETAIL
          LTR grid so physical column order: calendar=LEFT, event=RIGHT
      ═══════════════════════════════════════════════ */}
      <div className="max-w-7xl mx-auto px-12 max-md:px-5" style={{ paddingTop: 48, paddingBottom: 0 }}>
        {/* Figma: Calendar 409px | gap 37 | Card rest — LTR so calendar LEFT */}
        <div style={{ display: 'grid', gridTemplateColumns: '409px 1fr', gap: 37, direction: 'ltr', alignItems: 'stretch' }} className="max-lg:!grid-cols-1">

          {/* LEFT — calendar */}
          <div id="calendar" dir={isFa ? 'rtl' : 'ltr'} style={{ scrollMarginTop: 90 }}>
            <MiniCalendar anchor={calAnchor} onNav={handleCalNav} eventDates={eventDates}
              onSelect={d => {
                const jp = jParts(d)
                const hit = eventList.find(ev => {
                  return jp.day >= Number(ev.date)
                    && jp.day <= Number(ev.dateEnd ?? ev.date)
                    && jalaliMonthNumber(ev.month) === jp.month
                    && Number(ev.year) === jp.year
                })
                if (hit) setSelEvt(hit)
              }}
            />
          </div>

          {/* RIGHT — event card (Figma: white, border #E7E7E7, radius 16, padding 20, gap 20) */}
          <div style={{
            background: '#fff', border: '1px solid #E7E7E7', borderRadius: 16,
            padding: 20, display: 'flex', flexDirection: 'column', gap: 20,
          }}>
            {/* content row: text LEFT (flex 1) | image RIGHT (251px) — forced LTR */}
            <div style={{ display: 'flex', gap: 18, direction: 'ltr', flex: 1, minHeight: 0 }}>
              {/* text section */}
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 9, direction: isFa ? 'rtl' : 'ltr', minWidth: 0 }}>
                {/* date + category row */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end', direction: 'ltr' }}>
                  {/* category tag — GOLD bg white text */}
                  <span style={{ fontSize: 12, fontWeight: 400, padding: '2px 10px', borderRadius: 4, background: GOLD, color: '#fff' }}>
                    {isFa ? selType.fa : selEvt.type}
                  </span>
                  {/* date */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                    <span style={{ fontSize: 12, color: '#262626', direction: 'rtl' }}>
                      {selEvt.dateEnd && selEvt.dateEnd !== selEvt.date ? `${selEvt.date} تا ${selEvt.dateEnd}` : selEvt.date} {selEvt.month} {selEvt.year}
                    </span>
                    <img src="/icons/vuesax/linear/calendar-tick.svg" alt="" style={{ width: 22, height: 22, filter: 'invert(40%) sepia(90%) saturate(400%) hue-rotate(190deg)' }} />
                  </div>
                </div>
                {/* title */}
                <h3 style={{ fontSize: 18, fontWeight: 400, color: '#183354', margin: 0, lineHeight: 1.7, textAlign: 'right' }}>{selEvt.title}</h3>
                {/* description lines */}
                <p style={{ fontSize: 14, lineHeight: 1.7, color: '#4D4635', margin: 0, textAlign: 'right' }}>{selEvt.description}</p>
                {/* CTA — full width */}
                <a href="#" style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  background: GOLD, color: '#fff', borderRadius: 8, padding: '8px 16px',
                  fontSize: 16, fontWeight: 500, textDecoration: 'none', marginTop: 'auto',
                  direction: 'ltr',
                }}>
                  <img src="/icons/vuesax/linear/export.svg" alt="" style={{ width: 18, height: 18, filter: 'brightness(0) invert(1)' }} />
                  <span style={{ direction: 'rtl' }}>{isFa ? 'اطلاعات بیشتر' : 'Learn More'}</span>
                </a>
              </div>
              {/* image RIGHT — 251px, full height */}
              <div style={{ flexShrink: 0, width: 251, borderRadius: 8, overflow: 'hidden' }}>
                <img src={EVENT_IMGS[selEvt.id] ?? '/news/photo-1567789884554-0b844b597180.jpg'} alt=""
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ═══════════════════════════════════════════════
          FEATURED UPCOMING EVENT
      ═══════════════════════════════════════════════ */}
      <div className="max-w-7xl mx-auto px-12 max-md:px-5" style={{ paddingTop: 56 }}>
        {/* heading — gold right border (Figma: border-right 5px solid #CD9E53) */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'flex-start',
          borderInlineStart: `5px solid ${GOLD}`, paddingInlineStart: 10, marginBottom: 24,
          direction: isFa ? 'rtl' : 'ltr', width: '100%',
        }}>
          <h2 style={{ fontSize: 24, fontWeight: 500, color: NAVY, margin: 0, lineHeight: '41px' }}>
            {isFa ? 'رویداد برجسته پیش رو' : 'Featured Upcoming Event'}
          </h2>
        </div>

        {/* card: image LEFT (1fr) | navy RIGHT (2fr) */}
        <div style={{ display: 'grid', gridTemplateColumns: '354fr 714fr', borderRadius: 16, overflow: 'hidden', boxShadow: '0 4px 40px rgba(3,35,64,0.13)', direction: 'ltr', minHeight: 287 }} className="max-lg:!grid-cols-1">

          {/* IMAGE — gradient overlay + CTA at bottom */}
          <div style={{ position: 'relative', minHeight: 287, overflow: 'hidden' }}>
            <img src={EVENT_IMGS[featured.id] ?? '/news/photo-1611273426858-450d8e3c9fce.jpg'} alt=""
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
            {/* bottom gradient overlay */}
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(0deg, #000000 29%, rgba(0,0,0,0) 100%)' }} />
            {/* bottom: date badge + CTA */}
            <div style={{ position: 'absolute', bottom: 19, left: 17, right: 17, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                width: 40, height: 40, borderRadius: 8,
                background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(4px)',
              }}>
                <img src="/icons/vuesax/linear/calendar-tick.svg" alt="" style={{ width: 22, height: 22, filter: 'invert(73%) sepia(50%) saturate(500%) hue-rotate(5deg)' }} />
              </div>
              <a href="#" style={{
                display: 'inline-flex', alignItems: 'center', gap: 8, direction: 'ltr',
                background: GOLD, color: '#fff', borderRadius: 8, padding: '8px 16px',
                fontSize: 14, fontWeight: 500, textDecoration: 'none', flex: 1, justifyContent: 'center',
              }}>
                <img src="/icons/vuesax/linear/export.svg" alt="" style={{ width: 18, height: 18, filter: 'brightness(0) invert(1)' }} />
                <span style={{ direction: 'rtl' }}>{isFa ? 'اطلاعات بیشتر' : 'Learn More'}</span>
              </a>
            </div>
          </div>

          {/* NAVY PANEL */}
          <div style={{ background: NAVY, padding: '24px 36px 32px', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'center', gap: 10, direction: isFa ? 'rtl' : 'ltr', boxSizing: 'border-box' }}>
            {/* gold decorative bar */}
            <div style={{ width: 108, height: 14, background: GOLD, borderRadius: 7, alignSelf: 'flex-end' }} />

            {/* content */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, width: '100%' }}>
              {/* ── top block: title + meta + tag | gold bottom border ── */}
              <div style={{ borderBottom: `1px solid ${GOLD}`, paddingBottom: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {/* title */}
                <h3 style={{ fontSize: 18, fontWeight: 500, color: GOLD, margin: 0, lineHeight: 1.5, textAlign: 'right' }}>{featured.title}</h3>
                {/* meta row: location | date | category tag — all right-aligned */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'flex-end', direction: 'ltr', flexWrap: 'wrap' }}>
                  {/* location */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                    <img src="/icons/vuesax/linear/location.svg" alt="" style={{ width: 22, height: 22, filter: 'invert(73%) sepia(50%) saturate(500%) hue-rotate(5deg)' }} />
                    <span style={{ fontSize: 15, color: '#ADADAD', direction: 'rtl' }}>{featured.city}</span>
                  </div>
                  {/* date */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                    <img src="/icons/vuesax/linear/calendar-tick.svg" alt="" style={{ width: 22, height: 22, filter: 'invert(73%) sepia(50%) saturate(500%) hue-rotate(5deg)' }} />
                    <span style={{ fontSize: 15, color: '#ADADAD', direction: 'rtl' }}>{featured.date} {featured.month} {featured.year}</span>
                  </div>
                  {/* category tag */}
                  <span style={{ fontSize: 12, fontWeight: 400, padding: '4px 14px', borderRadius: 8, background: '#E53935', color: '#fff' }}>
                    {isFa ? featType.fa : featured.type}
                  </span>
                </div>
              </div>

              {/* ── bottom block: why + description ── */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '0 16px' }}>
                <p style={{ fontSize: 18, fontWeight: 500, color: GOLD, margin: 0, textAlign: 'right' }}>
                  {isFa ? 'چرا این رویداد اهمیت دارد؟' : 'Why this event matters?'}
                </p>
                <p style={{ fontSize: 16, lineHeight: 1.75, color: '#F9F9F9', margin: 0, textAlign: 'right' }}>{featured.description}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ═══════════════════════════════════════════════
          OTHER EVENTS GRID
      ═══════════════════════════════════════════════ */}
      <div className="max-w-7xl mx-auto px-12 max-md:px-5" style={{ paddingTop: 56, paddingBottom: 80 }}>
        {/* heading — gold right border */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-start', borderInlineStart: `5px solid ${GOLD}`, paddingInlineStart: 10, marginBottom: 24, direction: isFa ? 'rtl' : 'ltr', width: '100%' }}>
          <h2 style={{ fontSize: 24, fontWeight: 500, color: NAVY, margin: 0, lineHeight: '41px' }}>
            {isFa ? 'سایر رویدادها' : 'Other Events'}
          </h2>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', columnGap: 18, rowGap: 32 }} className="max-lg:!grid-cols-1">
          {visibleOthers.map(ev => {
            const t = TYPE_LABEL[ev.type] ?? { fa: ev.type, en: ev.type, color: GOLD, bg: '#f5f5f5' }
            return (
              <div key={ev.id} style={{
                background: '#F9F9F9', borderBottom: `3px solid ${GOLD}`, borderRadius: 21,
                padding: '11px 12px', display: 'flex', direction: 'ltr', gap: 10, minHeight: 207,
                transition: 'box-shadow .2s, transform .2s',
              }}
                onMouseEnter={e => { const el = e.currentTarget as HTMLElement; el.style.boxShadow='0 8px 28px rgba(3,35,64,0.13)'; el.style.transform='translateY(-2px)' }}
                onMouseLeave={e => { const el = e.currentTarget as HTMLElement; el.style.boxShadow=''; el.style.transform='' }}
              >
                {/* IMAGE — left side */}
                <div style={{ flexShrink: 0, width: 138, height: 175, borderRadius: 16, overflow: 'hidden', alignSelf: 'center' }} className="max-md:hidden">
                  <img src={EVENT_IMGS[ev.id] ?? '/news/photo-1567789884554-0b844b597180.jpg'} alt=""
                    style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                </div>

                {/* TEXT — right side */}
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: 8, direction: isFa ? 'rtl' : 'ltr', minWidth: 0 }}>
                  {/* meta: location + date + category */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 13, justifyContent: 'flex-end', direction: 'ltr', flexWrap: 'wrap' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                      <img src="/icons/vuesax/linear/location.svg" alt="" style={{ width: 24, height: 24, filter: 'invert(73%) sepia(50%) saturate(500%) hue-rotate(5deg)' }} />
                      <span style={{ fontSize: 16, color: '#ADADAD', direction: 'rtl' }}>{ev.city}</span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                      <img src="/icons/vuesax/linear/calendar-tick.svg" alt="" style={{ width: 24, height: 24, filter: 'invert(73%) sepia(50%) saturate(500%) hue-rotate(5deg)' }} />
                      <span style={{ fontSize: 16, color: '#ADADAD', direction: 'rtl' }}>{ev.date} {ev.month} {ev.year}</span>
                    </div>
                    <span style={{ fontSize: 12, fontWeight: 400, padding: '4px 14px', borderRadius: 8, background: '#E53935', color: '#fff', flexShrink: 0 }}>
                      {isFa ? t.fa : ev.type}
                    </span>
                  </div>

                  {/* content: title + desc + cta */}
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                    <h3 style={{ fontSize: 18, fontWeight: 400, color: '#111415', margin: 0, lineHeight: 1.5, textAlign: 'right' }}>{ev.title}</h3>
                    <p style={{ fontSize: 14, lineHeight: 1.7, color: '#4D4635', margin: 0, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', textAlign: 'right' }}>{ev.description}</p>
                    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                      <a href="#" style={{
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, direction: 'ltr',
                        background: GOLD, color: '#fff', borderRadius: 8, width: 169, height: 40,
                        fontSize: 16, fontWeight: 500, textDecoration: 'none', flexShrink: 0,
                      }}>
                        <img src="/icons/vuesax/linear/export.svg" alt="" style={{ width: 18, height: 18, filter: 'brightness(0) invert(1)' }} />
                        <span style={{ direction: 'rtl' }}>{isFa ? 'اطلاعات بیشتر' : 'Learn More'}</span>
                      </a>
                    </div>
                  </div>
                </div>
              </div>
            )
          })}
        </div>

        {/* show all / less */}
        {others.length > 4 && (
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 36 }}>
            <button onClick={() => setShowAll(v => !v)} style={{
              display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 700, color: NAVY,
              background: 'none', border: 'none', cursor: 'pointer', direction: 'rtl',
            }}>
              <img src="/icons/vuesax/linear/arrow-down.svg" alt="" style={{ width: 18, height: 18, opacity: 0.6, transform: showAll ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }} />
              <span>{showAll ? (isFa ? 'نمایش کمتر' : 'Show less') : (isFa ? 'مشاهده همه' : 'Show all')}</span>
            </button>
          </div>
        )}
      </div>
    </div>
  )
}
