// Landing.jsx — CLASIA institutional landing page
// Design tokens
const C = {
  navy: '#0A1E3A',
  terracotta: '#B25C3A',
  bone: '#F7F4EE',
  white: '#FFFFFF',
  body: '#2A2622',
  muted: '#5A5247',
  rule: '#D9D2C3',
  warmGray: '#CFC8B8',
  sage: '#5A9173',
  amber: '#CF9420',
  oxidized: '#9A3526',
};

const FONT_SERIF = '"Newsreader", "Tiempos Text", "Cormorant Garamond", Georgia, serif';
const FONT_SANS = '"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
const FONT_MONO = '"JetBrains Mono", ui-monospace, monospace';

// ─── Stellated asterisk mark ───
function AsteriskMark({ size = 28, color = C.terracotta }) {
  // 8-pointed stellated asterisk
  const pts = [];
  const outer = size / 2;
  const inner = outer * 0.32;
  for (let i = 0; i < 16; i++) {
    const a = (i * Math.PI) / 8 - Math.PI / 2;
    const r = i % 2 === 0 ? outer : inner;
    pts.push(`${(r * Math.cos(a) + size / 2).toFixed(2)},${(r * Math.sin(a) + size / 2).toFixed(2)}`);
  }
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block' }}>
      <polygon points={pts.join(' ')} fill={color} />
    </svg>
  );
}

// ─── Logo (mark + wordmark) ───
function Logo({ small = false, color = C.navy, markColor = C.terracotta, showTagline = false }) {
  const ms = small ? 20 : 28;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: small ? 10 : 14 }}>
      <AsteriskMark size={ms} color={markColor} />
      <div style={{ lineHeight: 1 }}>
        <div style={{
          fontFamily: FONT_SERIF, fontWeight: 500,
          fontSize: small ? 20 : 28, color, letterSpacing: '0.02em',
        }}>CLASIA</div>
        {showTagline && (
          <div style={{
            fontFamily: FONT_SANS, fontSize: 9.5, color: C.muted,
            letterSpacing: '0.08em', textTransform: 'uppercase',
            marginTop: 4, maxWidth: 260, lineHeight: 1.4,
          }}>
            Centro Latinoamericano de Adaptación<br/>a la Super Inteligencia Artificial
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Header ───
function Header({ compact = false }) {
  const navItems = [
    { label: 'Inicio', href: '#inicio' },
    { label: 'Programa', href: '#programa' },
    { label: 'Manifiesto', href: '/manifiesto/' },
    { label: 'Fundadores', href: '#fundadores' },
    { label: 'El Vigía', href: '#vigia' },
    { label: 'Publicaciones', href: '/publicaciones/' },
    { label: 'Contacto', href: '#contacto' },
  ];
  if (compact) {
    return (
      <header style={{
        position: 'sticky', top: 0, zIndex: 10,
        background: 'rgba(247,244,238,0.92)',
        backdropFilter: 'blur(8px)',
        borderBottom: `1px solid ${C.rule}`,
        padding: '14px 20px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <Logo small color={C.navy} />
        <div style={{
          display: 'flex', flexDirection: 'column', gap: 4,
          width: 22, cursor: 'pointer',
        }}>
          <div style={{ height: 1.5, background: C.navy }} />
          <div style={{ height: 1.5, background: C.navy }} />
        </div>
      </header>
    );
  }
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 10,
      background: 'rgba(247,244,238,0.88)',
      backdropFilter: 'blur(10px)',
      borderBottom: `1px solid ${C.rule}`,
      padding: '18px 56px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    }}>
      <Logo small color={C.navy} />
      <nav style={{ display: 'flex', gap: 28 }}>
        {navItems.map((n, i) => (
          <a key={i} href={n.href} style={{
            fontFamily: FONT_SANS, fontSize: 13.5, color: C.body,
            textDecoration: 'none', fontWeight: 400,
          }}>{n.label}</a>
        ))}
      </nav>
    </header>
  );
}

// ─── HERO ───
function Hero({ compact = false }) {
  return (
    <section id="inicio" style={{
      padding: compact ? '56px 24px 72px' : '120px 56px 100px',
      minHeight: compact ? 'auto' : '85vh',
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
      maxWidth: compact ? 'none' : 1200, margin: '0 auto',
      scrollMarginTop: 80,
    }}>
      {/* Big wordmark */}
      <div style={{ display: 'flex', alignItems: 'center', gap: compact ? 14 : 24, marginBottom: compact ? 24 : 40 }}>
        <AsteriskMark size={compact ? 40 : 64} color={C.terracotta} />
        <div style={{
          fontFamily: FONT_SERIF, fontWeight: 500,
          fontSize: compact ? 52 : 108, color: C.navy,
          letterSpacing: '0.01em', lineHeight: 1,
        }}>CLASIA</div>
      </div>

      {/* Tagline italic */}
      <div style={{
        fontFamily: FONT_SERIF, fontStyle: 'italic',
        fontSize: compact ? 40 : 84, color: C.navy,
        lineHeight: 1.02, marginBottom: compact ? 20 : 28,
        letterSpacing: '-0.02em', fontWeight: 400,
      }}>Aprender sin parar.</div>

      {/* Subhead sans */}
      <div style={{
        fontFamily: FONT_SANS, fontSize: compact ? 14 : 17,
        color: C.muted, letterSpacing: '0.02em',
        marginBottom: compact ? 28 : 40, maxWidth: 640,
        lineHeight: 1.5,
      }}>
        Centro Latinoamericano de Adaptación a la Super Inteligencia Artificial
      </div>

      {/* Lead paragraph */}
      <div style={{
        fontFamily: FONT_SERIF, fontSize: compact ? 18 : 24,
        color: C.body, lineHeight: 1.5,
        maxWidth: compact ? '100%' : 760, fontWeight: 400,
        marginBottom: compact ? 36 : 52,
      }}>
        Si el siglo XX fue el siglo de la alfabetización manuscrita —la conquista de la lectoescritura como derecho universal—, el siglo XXI es el siglo de la alfabetización digital en inteligencia artificial. <span style={{ color: C.terracotta, fontStyle: 'italic' }}>América Latina está llegando tarde.</span>
      </div>

      {/* CTA */}
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginBottom: compact ? 36 : 48 }}>
        <a href="#programa" style={{
          background: C.terracotta, color: C.bone,
          padding: compact ? '14px 22px' : '16px 28px',
          fontFamily: FONT_SANS, fontSize: compact ? 14 : 15,
          fontWeight: 500, textDecoration: 'none',
          letterSpacing: '0.01em',
        }}>Leer el programa</a>
      </div>

      {/* Thin rule + monospace date */}
      <div style={{ borderTop: `1px solid ${C.rule}`, paddingTop: 16 }}>
        <div style={{
          fontFamily: FONT_MONO, fontSize: 11,
          color: C.muted, letterSpacing: '0.15em',
        }}>ABRIL 2026 · CIUDAD DE MÉXICO</div>
      </div>
    </section>
  );
}

// ─── Category label ───
function CatLabel({ children, color = C.terracotta }) {
  return (
    <div style={{
      fontFamily: FONT_SANS, fontSize: 11, color,
      letterSpacing: '0.22em', textTransform: 'uppercase',
      fontWeight: 600, marginBottom: 20,
    }}>{children}</div>
  );
}

// ─── Diagnóstico ───
function Diagnostico({ compact = false }) {
  const stats = [
    { n: '26–38 %', c: 'de los empleos formales de América Latina enfrentarán transformación o desplazamiento por IA generativa' },
    { n: '1.12 %', c: 'de la inversión mundial en IA es lo que recibe una región que genera el 6.6 % del PIB global' },
    { n: '20×', c: 'menos que EE. UU. y China invierte LATAM en investigación y desarrollo de IA' },
  ];

  return (
    <section style={{
      background: C.bone,
      padding: compact ? '72px 24px 88px' : '140px 56px 160px',
      borderTop: `1px solid ${C.rule}`,
    }}>
      <div style={{ maxWidth: compact ? 'none' : 1200, margin: '0 auto' }}>
        <CatLabel>Diagnóstico</CatLabel>
        <h2 style={{
          fontFamily: FONT_SERIF, fontWeight: 500,
          fontSize: compact ? 36 : 64, color: C.navy,
          lineHeight: 1.05, letterSpacing: '-0.015em',
          margin: 0, marginBottom: compact ? 48 : 96,
          maxWidth: compact ? '100%' : 900,
        }}>Lo que está en juego en los próximos 36 meses</h2>

        {/* Stat blocks */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: compact ? '1fr' : 'repeat(3, 1fr)',
          gap: compact ? 40 : 40,
          borderTop: `1px solid ${C.rule}`,
          paddingTop: compact ? 32 : 48,
          marginBottom: compact ? 72 : 120,
        }}>
          {stats.map((s, i) => (
            <div key={i} style={{
              borderLeft: i > 0 && !compact ? `1px solid ${C.rule}` : 'none',
              paddingLeft: i > 0 && !compact ? 40 : 0,
              borderTop: compact && i > 0 ? `1px solid ${C.rule}` : 'none',
              paddingTop: compact && i > 0 ? 32 : 0,
            }}>
              <div style={{
                fontFamily: FONT_SERIF, fontWeight: 400,
                fontSize: compact ? 76 : 112, color: C.terracotta,
                lineHeight: 1, letterSpacing: '-0.03em',
                marginBottom: 20,
              }}>{s.n}</div>
              <div style={{
                fontFamily: FONT_SERIF, fontSize: compact ? 17 : 19,
                color: C.body, lineHeight: 1.45,
                maxWidth: 340, fontWeight: 400,
              }}>{s.c}</div>
            </div>
          ))}
        </div>

        {/* Dot grid heading */}
        <div style={{ textAlign: 'center', marginBottom: compact ? 28 : 40 }}>
          <CatLabel>Adopción global</CatLabel>
          <div style={{
            fontFamily: FONT_SERIF, fontStyle: 'italic',
            fontSize: compact ? 22 : 28, color: C.navy,
            fontWeight: 400, maxWidth: 640, margin: '0 auto',
            lineHeight: 1.3,
          }}>La conversación sobre IA no la tienen los 2 500 millones.</div>
        </div>

        {/* The 2500-dot grid */}
        <DotGrid compact={compact} />

        <div style={{
          fontFamily: FONT_MONO, fontSize: compact ? 10 : 11,
          color: C.muted, letterSpacing: '0.15em',
          textAlign: 'center', marginTop: 24,
          textTransform: 'uppercase',
        }}>
          Cada punto ≈ 3.2 millones de personas · Distribución global de adopción de IA · Febrero 2026
        </div>

        {/* Legend */}
        <div style={{
          display: 'flex', justifyContent: 'center', gap: compact ? 18 : 40,
          flexWrap: 'wrap', marginTop: 32, paddingTop: 24,
          borderTop: `1px solid ${C.rule}`,
        }}>
          {[
            { c: C.oxidized, lbl: 'Usuarios intensivos', sub: '≈ 0.04 %' },
            { c: C.amber, lbl: 'Usuarios de pago', sub: '≈ 0.3 %' },
            { c: C.sage, lbl: 'Usuarios gratuitos', sub: '≈ 16 %' },
            { c: C.warmGray, lbl: 'Sin acceso o sin uso', sub: '≈ 84 %' },
          ].map((l, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
              <div style={{ width: 8, height: 8, background: l.c, marginTop: 5 }} />
              <div>
                <div style={{ fontFamily: FONT_SANS, fontSize: 12.5, color: C.body, fontWeight: 500 }}>{l.lbl}</div>
                <div style={{ fontFamily: FONT_MONO, fontSize: 10.5, color: C.muted, letterSpacing: '0.1em', marginTop: 2 }}>{l.sub}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// The functional 50×50 = 2500 dot grid
function DotGrid({ compact = false }) {
  // Correct orientation (matches original "AI adoption" visualization):
  // - Gray mass (~84%, never used AI) occupies the TOP rows
  // - Sage green (~16%, free chatbot users) occupies the BOTTOM 8 rows
  // - Amber (~0.3%, paid users) = 8 dots in the bottom-right of last row
  // - Oxidized red (~0.04%, uses coding scaffold) = 1 single dot at bottom-right corner
  // The single red dot is the visual "we are here" for CLASIA's thesis.
  const cols = 50, rows = 50;
  const total = cols * rows;
  const colors = new Array(total);

  // Fill top-down, left-to-right with categories in order: gray → sage → amber → oxidized
  // Counts chosen so rows align: 42 rows of gray (2100) + 8 rows of sage/amber/oxidized (400)
  // In bottom row: 41 sage + 8 amber + 1 oxidized = 50
  // Total sage across 8 bottom rows: 7*50 + 41 = 391. Then 8 amber + 1 oxidized = 400 non-gray.
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      let color;
      if (r < rows - 8) {
        color = C.warmGray;
      } else if (r < rows - 1) {
        color = C.sage;
      } else {
        // Last row: sage in first 41 cells, amber in next 8, oxidized in last
        if (c < cols - 9) color = C.sage;
        else if (c < cols - 1) color = C.amber;
        else color = C.oxidized;
      }
      colors[r * cols + c] = color;
    }
  }

  const gridMax = compact ? 320 : 560;
  const dotSize = compact ? 4 : 8;
  const gap = compact ? 1.5 : 3;

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: `repeat(${cols}, ${dotSize}px)`,
      gap: gap,
      justifyContent: 'center',
      margin: '0 auto',
      maxWidth: gridMax,
    }}>
      {colors.map((col, i) => (
        <div key={i} style={{
          width: dotSize, height: dotSize,
          background: col,
        }} />
      ))}
    </div>
  );
}

Object.assign(window, {
  Logo, AsteriskMark, Header, Hero, Diagnostico, CatLabel, DotGrid,
  C, FONT_SERIF, FONT_SANS, FONT_MONO,
});
