import { useMemo } from 'react'
import { motion } from 'framer-motion'
import {
  ArrowLeft, Landmark, Globe, BarChart3, Activity, Database,
  Newspaper, Building2, TrendingUp, Coins, type LucideIcon,
} from 'lucide-react'
import { Link } from 'react-router-dom'
import { useLang } from '@/context/LangContext'
import { INTEGRATIONS, INTEGRATIONS_META, type IntegrationIcon } from '@/content/integrations'

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

const ICONS: Record<IntegrationIcon, LucideIcon> = {
  exchange: Landmark, globe: Globe, chart: BarChart3, activity: Activity,
  database: Database, newspaper: Newspaper, building: Building2, trending: TrendingUp, coins: Coins,
}

export default function IntegrationsSection() {
  const { lang } = useLang()
  const isFa = lang === 'fa'
  const m = INTEGRATIONS_META[lang]
  // Built at render time so it reflects the post-bootstrap INTEGRATIONS array.
  const CELL = useMemo(() => new Map(INTEGRATIONS.map((it) => [`${it.col}-${it.row}`, it])), [])

  return (
    <section style={{ background: NAVY, padding: '64px 0', overflow: 'hidden', position: 'relative' }} dir={isFa ? 'rtl' : 'ltr'}>
      {/* drifting gold glow */}
      <motion.div
        animate={{ x: [0, 26, 0], y: [0, -18, 0], opacity: [0.8, 1, 0.8] }}
        transition={{ repeat: Infinity, duration: 9, ease: 'easeInOut' }}
        style={{
          position: 'absolute', top: '50%', insetInlineEnd: '8%', transform: 'translateY(-50%)',
          width: 460, height: 460, borderRadius: '50%',
          background: `radial-gradient(circle, ${GOLD}22 0%, transparent 70%)`, pointerEvents: 'none',
        }}
      />

      <div className="max-w-7xl mx-auto px-12 max-md:px-5" style={{ position: 'relative' }}>
        <div style={{ display: 'flex', flexDirection: isFa ? 'row' : 'row-reverse', alignItems: 'center', gap: 48 }} className="max-lg:!flex-col max-lg:!gap-12">

          {/* ── TEXT side ── */}
          <div style={{ flex: 1, minWidth: 0 }} className="max-lg:!w-full max-lg:!text-center">
            <motion.div
              initial={{ opacity: 0, y: 24 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true, amount: 0.4 }}
              transition={{ duration: 0.6, ease: EASE }}
            >
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '3px', color: GOLD, marginBottom: 18 }}>{m.overline}</div>
              <h2 style={{ fontSize: 'clamp(30px, 4vw, 56px)', fontWeight: 900, color: '#fff', letterSpacing: '-1px', lineHeight: 1.1, margin: '0 0 22px' }}>
                {m.heading}
              </h2>
              <p style={{ fontSize: 'clamp(14px, 1.3vw, 18px)', lineHeight: 1.9, color: 'rgba(255,255,255,0.62)', maxWidth: 460, margin: '0 0 34px' }} className="max-lg:!mx-auto">
                {m.sub}
              </p>
              <Link
                to="/pulse"
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 10,
                  background: GOLD, color: NAVY, borderRadius: 999,
                  padding: '13px 28px', fontSize: 14, fontWeight: 800, textDecoration: 'none',
                  transition: 'transform 180ms, opacity 180ms',
                }}
                onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.opacity = '0.88'; (e.currentTarget as HTMLElement).style.transform = 'translateX(-3px)' }}
                onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.opacity = '1'; (e.currentTarget as HTMLElement).style.transform = 'translateX(0)' }}
              >
                {m.cta}
                <ArrowLeft size={16} style={{ transform: isFa ? 'none' : 'rotate(180deg)' }} />
              </Link>
            </motion.div>
          </div>

          {/* ── GRID side ── */}
          <div style={{ flexShrink: 0 }} className="max-lg:!w-full max-lg:!flex max-lg:!justify-center">
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${COLS}, 78px)`, gridTemplateRows: `repeat(${ROWS}, 78px)`, gap: 14 }}
              className="max-sm:![grid-template-columns:repeat(6,52px)] max-sm:![grid-template-rows:repeat(5,52px)] max-sm:!gap-2">
              {Array.from({ length: COLS * ROWS }).map((_, idx) => {
                const col = (idx % COLS) + 1
                const row = Math.floor(idx / COLS) + 1
                const it = CELL.get(`${col}-${row}`)

                if (!it) {
                  // empty placeholder cell — faint outline, soft breathing
                  return (
                    <motion.div
                      key={idx}
                      animate={{ opacity: [0.4, 0.7, 0.4] }}
                      transition={{ repeat: Infinity, duration: 4 + (idx % 5) * 0.4, ease: 'easeInOut' }}
                      style={{ borderRadius: 16, border: '1px solid rgba(255,255,255,0.06)', background: 'rgba(255,255,255,0.015)' }}
                    />
                  )
                }

                const Icon = ICONS[it.icon]
                const delay = (col + row) * 0.07
                return (
                  <motion.div
                    key={idx}
                    initial={{ opacity: 0, scale: 0.3, rotate: -8 }}
                    whileInView={{ opacity: 1, scale: 1, rotate: 0 }}
                    viewport={{ once: true }}
                    transition={{ type: 'spring', stiffness: 220, damping: 16, delay }}
                    whileHover={{ scale: 1.12, y: -4 }}
                    title={it.name}
                    aria-label={it.name}
                    style={{
                      position: 'relative',
                      borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.12)',
                      boxShadow: `0 12px 34px -16px ${it.accent ?? GOLD}cc`,
                      cursor: 'pointer',
                    }}
                  >
                    {/* accent glow halo */}
                    <motion.div
                      animate={{ opacity: [0.25, 0.55, 0.25] }}
                      transition={{ repeat: Infinity, duration: 3 + (delay % 2), ease: 'easeInOut' }}
                      style={{
                        position: 'absolute', inset: 0, borderRadius: 16, pointerEvents: 'none',
                        background: `radial-gradient(circle at 50% 50%, ${it.accent ?? GOLD}26 0%, transparent 70%)`,
                      }}
                    />
                    {/* gentle float of the icon itself */}
                    <motion.div
                      animate={{ y: [0, -5, 0] }}
                      transition={{ repeat: Infinity, duration: 3.2 + (delay % 1.5), ease: 'easeInOut' }}
                      style={{ position: 'relative' }}
                    >
                      {it.logo ? (
                        <img src={it.logo} alt={it.name} className="max-sm:!w-6 max-sm:!h-6" style={{ width: 34, height: 34, objectFit: 'contain', display: 'block' }} />
                      ) : (
                        <Icon className="max-sm:!w-[18px] max-sm:!h-[18px]" size={26} color={it.accent ?? '#fff'} strokeWidth={1.9} />
                      )}
                    </motion.div>
                  </motion.div>
                )
              })}
            </div>
          </div>

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