// ══════════════════════════════════════════════════════════════════════
// screens.jsx — Pantallas de inicio y attract screen
//
// Contiene:
//   · ArcadeBG     — fondo con grid y glow (compartido con otros archivos)
//   · UnnicLogo    — logo Unnic AI
//   · CornerMarks  — marcas de esquina decorativas
//   · ScreenInicio — pantalla de presentación con botón EMPEZAR
//   · ScreenAttract — pantalla idle: leaderboard animado + CTA
//
// Resolución de diseño: 1080×1920 px (9:16 portrait kiosk)
// Todos los valores de px son para esa resolución — el escalado
// a la pantalla real lo hace App() en kiosco.html con CSS transform.
// ══════════════════════════════════════════════════════════════════════

const UNNIC_YELLOW = '#dddb26';
const PRIMARY = '#031d40';                       // deep navy (brand)
const PRIMARY_SOFT = '#0a3160';                  // accent tint
const PRIMARY_DARK = '#02132c';
const PRIMARY_GLOW = '#2a5aa8';                  // for glows/gradients on dark bg
const BG = '#020914';                            // deeper navy-black
const SURFACE = '#081730';
const SURFACE_2 = '#0d2348';
const BORDER = 'rgba(255,255,255,0.08)';
const TEXT = '#f5f5fa';
const TEXT_DIM = 'rgba(245,245,250,0.55)';
const OK = 'oklch(0.78 0.19 150)';
const ERR = 'oklch(0.66 0.25 22)';

// ─── Shared chrome: subtle grid bg + corner marks ───
function ArcadeBG({ children, accent = PRIMARY }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, background: BG, color: TEXT,
      fontFamily: '"Inter", system-ui, sans-serif',
      overflow: 'hidden',
    }}>
      {/* radial glow */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse at 50% 30%, ${PRIMARY_GLOW} 0%, transparent 55%)`,
        opacity: 0.45, pointerEvents: 'none',
      }} />
      {/* grid */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.25, pointerEvents: 'none' }}>
        <defs>
          <pattern id="grid" width="80" height="80" patternUnits="userSpaceOnUse">
            <path d="M 80 0 L 0 0 0 80" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="1"/>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#grid)" />
      </svg>
      {/* scanline */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'repeating-linear-gradient(0deg, rgba(255,255,255,0.012) 0px, rgba(255,255,255,0.012) 2px, transparent 2px, transparent 4px)',
        pointerEvents: 'none',
      }} />
      {children}
    </div>
  );
}

// Unnic AI wordmark — official asset provided by the client.
// `size` is height in px. Original PNG is 750×300 (aspect 2.5:1).
function UnnicLogo({ size = 22, style }) {
  return (
    <img
      src="assets/unnic-logo.png"
      alt="Unnic AI"
      style={{ height: size, width: 'auto', display: 'block', ...style }}
    />
  );
}

function CornerMarks() {
  const m = (pos) => ({
    position: 'absolute', width: 32, height: 32,
    borderColor: 'rgba(255,255,255,0.15)',
    ...pos,
  });
  return (
    <>
      <div style={{ ...m({ top: 32, left: 32 }), borderTop: '2px solid', borderLeft: '2px solid' }}/>
      <div style={{ ...m({ top: 32, right: 32 }), borderTop: '2px solid', borderRight: '2px solid' }}/>
      <div style={{ ...m({ bottom: 32, left: 32 }), borderBottom: '2px solid', borderLeft: '2px solid' }}/>
      <div style={{ ...m({ bottom: 32, right: 32 }), borderBottom: '2px solid', borderRight: '2px solid' }}/>
    </>
  );
}

// ══════════════════════════════════════════════════════════════
// 1. INICIO
// ══════════════════════════════════════════════════════════════
function ScreenInicio({ onStart, active = true, liveTotal = 0 }) {
  const [pulse, setPulse] = React.useState(0);
  React.useEffect(() => {
    if (!active) return;
    const t = setInterval(() => setPulse(p => p + 1), 1400);
    return () => clearInterval(t);
  }, [active]);
  return (
    <ArcadeBG>
      <CornerMarks />
      {/* top header — stacked for vertical */}
      <div style={{ position: 'absolute', top: 80, left: 60, right: 60, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 28 }}>
        <UnnicLogo size={150}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 22, color: TEXT_DIM, letterSpacing: '0.18em', textAlign: 'center' }}>
          <span style={{ width: 12, height: 12, borderRadius: 6, background: UNNIC_YELLOW, boxShadow: `0 0 14px ${UNNIC_YELLOW}` }}/>
          {window.t('event_label')}
        </div>
      </div>

      {/* Language switcher — top-right corner */}
      <LangSwitcher/>

      {/* big centered block: hero + button grouped around vertical center */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: '50%', transform: 'translateY(-50%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '0 60px',
      }}>
        <div style={{ fontSize: 26, letterSpacing: '0.45em', color: UNNIC_YELLOW, marginBottom: 44, fontWeight: 500 }}>
          {window.t('el_reto')}
        </div>
        <h1 style={{
          fontFamily: '"Space Grotesk", system-ui, sans-serif',
          fontSize: 170, fontWeight: 700, lineHeight: 0.98,
          margin: 0, letterSpacing: '-0.04em',
        }}>
          {window.t('hero_line1')}<br/>
          {window.t('hero_pre_word') ? window.t('hero_pre_word') + ' ' : ''}<span style={{
            fontStyle: 'italic', fontWeight: 600,
            color: UNNIC_YELLOW,
            display: 'inline-block',
            padding: '0 0.12em 0.08em 0.02em',
            textShadow: `0 0 40px ${UNNIC_YELLOW}55`,
          }}>{window.t('hero_word')}</span><br/>
          {window.t('hero_line3')} <span style={{
            color: UNNIC_YELLOW,
            fontWeight: 700,
            display: 'inline-block',
            padding: '0 0.04em',
          }}>{window.t('hero_ai')}</span>?
        </h1>
        <div style={{ marginTop: 48, fontSize: 28, color: TEXT_DIM, maxWidth: 880, lineHeight: 1.35, textWrap: 'pretty' }}>
          {window.t('hero_subtitle')}<br/>
          {window.t('hero_subtitle2')}
        </div>

        <div style={{ marginTop: 80 }}/>
        <button onClick={onStart}
          style={{
            position: 'relative',
            padding: '48px 120px',
            fontFamily: '"Space Grotesk", system-ui, sans-serif',
            fontSize: 64, fontWeight: 600,
            color: BG, background: UNNIC_YELLOW,
            border: 'none', borderRadius: 24,
            cursor: 'pointer', letterSpacing: '-0.01em',
            boxShadow: `0 0 0 0 ${UNNIC_YELLOW}55, 0 28px 70px rgba(0,0,0,0.55), inset 0 -8px 0 rgba(0,0,0,0.15)`,
            transform: `scale(${1 + (pulse % 2) * 0.02})`,
            transition: 'transform 700ms cubic-bezier(.4,1.6,.5,1), box-shadow 300ms',
          }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
            {window.t('start_btn')}
            <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14M13 5l7 7-7 7"/>
            </svg>
          </span>
          <div style={{
            position: 'absolute', inset: -10, borderRadius: 28,
            border: `2px solid ${UNNIC_YELLOW}`,
            opacity: 0.5 - (pulse % 2) * 0.3,
            pointerEvents: 'none',
            transform: `scale(${1 + (pulse % 2) * 0.08})`,
            transition: 'transform 700ms ease-out, opacity 700ms',
          }}/>
        </button>

        <div style={{ marginTop: 40, fontSize: 22, color: TEXT_DIM, letterSpacing: '0.25em' }}>
          {window.t('tap_to_play')}
        </div>
      </div>

      {/* minimal footer strip — kept inside visible zone */}
      <div style={{
        position: 'absolute', bottom: 100, left: 60, right: 60,
        display: 'flex', justifyContent: 'center', gap: 48,
        fontSize: 18, color: TEXT_DIM, letterSpacing: '0.18em',
      }}>
        <span>{window.t('participants', { n: liveTotal > 0 ? liveTotal : '—' })}</span>
        <span style={{ color: 'rgba(255,255,255,0.2)' }}>·</span>
        <span>{window.t('prize_label')} <span style={{ color: UNNIC_YELLOW, fontWeight: 600 }}>{window.t('prize_amount')}</span></span>
      </div>
    </ArcadeBG>
  );
}

// ══════════════════════════════════════════════════════════════
// ATTRACT SCREEN — idle / sin uso
// Combina hero llamativo + leaderboard animado en vivo
// ══════════════════════════════════════════════════════════════
function ScreenAttract({ onStart, liveScores = [], liveTotal = 0 }) {
  const [pulse, setPulse] = React.useState(0);
  const [scrollY, setScrollY] = React.useState(0);

  // Refs for scroll state — shared between raf loop and touch handlers
  const posRef        = React.useRef(0);
  const dirRef        = React.useRef(1);
  const rafRef        = React.useRef(null);
  const isTouchingRef = React.useRef(false);
  const touchStartYRef     = React.useRef(0);
  const touchStartScrollRef = React.useRef(0);

  // Button pulse
  React.useEffect(() => {
    const t = setInterval(() => setPulse(p => p + 1), 1400);
    return () => clearInterval(t);
  }, []);

  const STATIC_MODELS = [
    { name: 'Claude Opus',   brand: 'anthropic', kind: 'ai', score: 93 },
    { name: 'GPT-5',         brand: 'openai',    kind: 'ai', score: 91 },
    { name: 'Claude Sonnet', brand: 'anthropic', kind: 'ai', score: 89 },
    { name: 'GPT-4',         brand: 'openai',    kind: 'ai', score: 81 },
  ];

  const ATTRACT_ROWS = React.useMemo(() => {
    const humanRows = liveScores.length > 0
      ? liveScores.map(e => ({ name: e.name, kind: 'human', score: e.score }))
      : [
          'MARTA G.','DAVID Ñ.','ANA P.','LEO B.','CARLA S.',
          'JAVIER R.','SOFIA M.','MARC T.','ELENA B.','PABLO R.',
          'LUCIA G.','OMAR S.','RITA V.','DIEGO C.','ALBA N.',
        ].map((name, i) => ({ name, kind: 'human', score: Math.max(12, 88 - i * 4.2) }));

    return [...STATIC_MODELS, ...humanRows].sort((a, b) => b.score - a.score);
  }, [liveScores]);

  const ROW_H = 76;
  const ROW_GAP = 8;
  const ROW_STRIDE = ROW_H + ROW_GAP;
  const VISIBLE = 8;
  const maxPos = Math.max(0, (ATTRACT_ROWS.length - VISIBLE) * ROW_STRIDE);

  // Auto-scroll: slow pan down/up — pauses while user is touching
  React.useEffect(() => {
    const tick = () => {
      if (!isTouchingRef.current) {
        posRef.current += dirRef.current * 0.4;
        if (posRef.current >= maxPos) { posRef.current = maxPos; dirRef.current = -1; }
        if (posRef.current <= 0)      { posRef.current = 0;      dirRef.current =  1; }
        setScrollY(posRef.current);
      }
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [maxPos]);

  // Touch scroll handlers
  const handleTouchStart = React.useCallback((e) => {
    isTouchingRef.current = true;
    touchStartYRef.current = e.touches[0].clientY;
    touchStartScrollRef.current = posRef.current;
  }, []);

  const handleTouchMove = React.useCallback((e) => {
    if (!isTouchingRef.current) return;
    // Compensate for CSS scale: kiosk is 1080px wide, screen may be narrower
    const scale = window.innerWidth / 1080;
    const dy = touchStartYRef.current - e.touches[0].clientY;
    const newPos = Math.max(0, Math.min(maxPos, touchStartScrollRef.current + dy / scale));
    posRef.current = newPos;
    setScrollY(newPos);
  }, [maxPos]);

  const handleTouchEnd = React.useCallback(() => {
    isTouchingRef.current = false;
    // Resume auto-scroll in the direction that makes sense from current position
    dirRef.current = posRef.current >= maxPos ? -1 : 1;
  }, [maxPos]);

  const UNNIC_YELLOW = '#dddb26';
  const BG = '#020914';

  return (
    <div style={{ position: 'absolute', inset: 0, background: BG, color: '#f5f5fa', overflow: 'hidden', fontFamily: '"Inter", system-ui, sans-serif' }}>
      {/* Language switcher */}
      <LangSwitcher/>

      {/* Animated background grid */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.18, pointerEvents: 'none' }}>
        <defs>
          <pattern id="ag" width="80" height="80" patternUnits="userSpaceOnUse">
            <path d="M 80 0 L 0 0 0 80" fill="none" stroke="rgba(255,255,255,0.07)" strokeWidth="1"/>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#ag)"/>
      </svg>

      {/* Top radial glow — yellow-tinted */}
      <div style={{
        position: 'absolute', top: -200, left: '50%', transform: 'translateX(-50%)',
        width: 1400, height: 1400, borderRadius: '50%',
        background: `radial-gradient(circle, ${UNNIC_YELLOW}22 0%, transparent 65%)`,
        pointerEvents: 'none',
      }}/>

      {/* Blue radial glow — matches ArcadeBG */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 50% 30%, #2a5aa8 0%, transparent 55%)',
        opacity: 0.45, pointerEvents: 'none',
      }}/>

      {/* Scanlines */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'repeating-linear-gradient(0deg, rgba(255,255,255,0.012) 0px, rgba(255,255,255,0.012) 2px, transparent 2px, transparent 4px)',
        pointerEvents: 'none',
      }}/>

      {/* ── HERO ZONE (top 55%) ── */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: '55%',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        textAlign: 'center', padding: '0 60px',
      }}>
        {/* Logo */}
        <UnnicLogo size={120} style={{ marginBottom: 60 }}/>

        {/* Headline */}
        <div style={{ fontSize: 24, letterSpacing: '0.4em', color: UNNIC_YELLOW, marginBottom: 36, fontWeight: 500 }}>
          {window.t('el_reto')}
        </div>
        <h1 style={{
          fontFamily: '"Space Grotesk", system-ui, sans-serif',
          fontSize: 130, fontWeight: 700, lineHeight: 0.98,
          margin: 0, letterSpacing: '-0.04em',
        }}>
          {window.t('hero_line1')}{window.t('hero_pre_word') ? ' ' + window.t('hero_pre_word') : ''}<br/>
          <span style={{
            fontStyle: 'italic', color: UNNIC_YELLOW,
            textShadow: `0 0 60px ${UNNIC_YELLOW}66`,
          }}>{window.t('hero_word')}</span><br/>
          {window.t('hero_line3')} <span style={{ color: UNNIC_YELLOW }}>{window.t('hero_ai')}</span>?
        </h1>

        {/* Pulsing CTA */}
        <button onClick={onStart} style={{
          marginTop: 56, position: 'relative',
          padding: '36px 96px',
          fontFamily: '"Space Grotesk", system-ui, sans-serif',
          fontSize: 48, fontWeight: 600,
          color: BG, background: UNNIC_YELLOW,
          border: 'none', borderRadius: 20, cursor: 'pointer',
          boxShadow: `0 0 60px ${UNNIC_YELLOW}55, inset 0 -6px 0 rgba(0,0,0,0.15)`,
          transform: `scale(${1 + (pulse % 2) * 0.025})`,
          transition: 'transform 700ms cubic-bezier(.4,1.6,.5,1)',
          letterSpacing: '-0.01em',
        }}>
          {window.t('toca_jugar')}
          <div style={{
            position: 'absolute', inset: -10, borderRadius: 24,
            border: `2px solid ${UNNIC_YELLOW}`,
            opacity: 0.4 - (pulse % 2) * 0.3,
            transform: `scale(${1 + (pulse % 2) * 0.06})`,
            transition: 'transform 700ms ease-out, opacity 700ms',
            pointerEvents: 'none',
          }}/>
        </button>
      </div>

      {/* Divider */}
      <div style={{
        position: 'absolute', top: '55%', left: 60, right: 60, height: 1,
        background: `linear-gradient(90deg, transparent, ${UNNIC_YELLOW}55, transparent)`,
      }}/>

      {/* ── LEADERBOARD ZONE (bottom 45%) ── */}
      <div style={{ position: 'absolute', top: 'calc(55% + 1px)', left: 0, right: 0, bottom: 0 }}>
        {/* Header */}
        <div style={{
          padding: '28px 60px 16px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div style={{ fontSize: 18, letterSpacing: '0.3em', color: UNNIC_YELLOW, fontWeight: 600 }}>
            {window.t('clasif_directo')}
          </div>
          <div style={{ fontSize: 16, color: 'rgba(245,245,250,0.4)', letterSpacing: '0.15em' }}>
            {window.t('participants', { n: liveTotal || ATTRACT_ROWS.length })}
          </div>
        </div>

        {/* Scrolling list — touch-draggable + auto-scroll when idle */}
        <div
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
          style={{ position: 'absolute', top: 88, left: 60, right: 60, bottom: 40, overflow: 'hidden', touchAction: 'none' }}
        >
          {/* Top fade */}
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: 40,
            background: `linear-gradient(to bottom, ${BG}, transparent)`,
            zIndex: 10, pointerEvents: 'none',
          }}/>
          {/* Bottom fade */}
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0, height: 80,
            background: `linear-gradient(to top, ${BG}, transparent)`,
            zIndex: 10, pointerEvents: 'none',
          }}/>
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, transform: `translateY(${-scrollY}px)`, willChange: 'transform' }}>
            {ATTRACT_ROWS.map((r, idx) => {
              const isAI = r.kind === 'ai';
              const color = isAI
                ? (r.brand === 'anthropic' ? '#d4a574' : '#6fb39a')
                : '#ffffff';
              return (
                <div key={r.name} style={{
                  height: ROW_H, marginBottom: ROW_GAP,
                  display: 'flex', alignItems: 'center', gap: 16,
                  padding: '0 18px',
                  background: 'rgba(255,255,255,0.02)',
                  border: '1.5px solid rgba(255,255,255,0.04)',
                  borderRadius: 12,
                }}>
                  <div style={{
                    width: 44, textAlign: 'center',
                    fontFamily: '"Space Grotesk", system-ui, sans-serif',
                    fontSize: 22, fontWeight: 700,
                    color: 'rgba(245,245,250,0.35)',
                    fontVariantNumeric: 'tabular-nums',
                  }}>
                    {String(idx + 1).padStart(2, '0')}
                  </div>
                  <div style={{
                    width: 36, height: 36, borderRadius: 18, flexShrink: 0,
                    background: isAI ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.08)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 12, fontWeight: 700, color,
                    border: '1px solid rgba(255,255,255,0.1)',
                  }}>
                    {isAI ? 'AI' : r.name.split(' ').map(s => s[0]).slice(0, 2).join('')}
                  </div>
                  {/* Nombre + barra de puntuación */}
                  <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 7 }}>
                    <div style={{
                      fontSize: 20, fontWeight: 600,
                      color: 'rgba(245,245,250,0.75)',
                      fontFamily: '"Space Grotesk", system-ui, sans-serif',
                      letterSpacing: '-0.01em',
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    }}>
                      {r.name}
                      {isAI && <span style={{ marginLeft: 10, fontSize: 13, color: color, opacity: 0.7, fontWeight: 500 }}>{window.t('ai_tag')}</span>}
                    </div>
                    {/* Barra de puntuación */}
                    <div style={{ height: 6, background: 'rgba(255,255,255,0.07)', borderRadius: 3, overflow: 'hidden' }}>
                      <div style={{
                        height: '100%',
                        width: `${Math.round(r.score)}%`,
                        background: isAI ? color : 'rgba(255,255,255,0.45)',
                        borderRadius: 3,
                      }}/>
                    </div>
                  </div>
                  <div style={{
                    fontFamily: '"Space Grotesk", system-ui, sans-serif',
                    fontSize: 24, fontWeight: 700,
                    color: 'rgba(245,245,250,0.6)',
                    fontVariantNumeric: 'tabular-nums',
                    minWidth: 52, textAlign: 'right',
                  }}>
                    {Math.round(r.score)}%
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// LANGUAGE SWITCHER — shown on attract + inicio screens
// ══════════════════════════════════════════════════════════════
function LangSwitcher() {
  const langs = [
    { code: 'es', label: 'ES' },
    { code: 'en', label: 'EN' },
    { code: 'ca', label: 'CA' },
  ];
  return (
    <div style={{
      position: 'absolute', top: 80, right: 60,
      display: 'flex', gap: 10, zIndex: 100,
    }}>
      {langs.map(({ code, label }) => {
        const active = (window.currentLang || 'es') === code;
        return (
          <button key={code} onClick={() => window.setLang(code)}
            style={{
              padding: '12px 22px',
              background: active ? UNNIC_YELLOW : 'rgba(255,255,255,0.07)',
              color: active ? BG : TEXT_DIM,
              border: `1px solid ${active ? UNNIC_YELLOW : 'rgba(255,255,255,0.18)'}`,
              borderRadius: 10,
              fontSize: 20, fontWeight: 700, cursor: 'pointer',
              fontFamily: '"Space Grotesk", system-ui, sans-serif',
              letterSpacing: '0.08em',
              transition: 'all 180ms',
            }}>
            {label}
          </button>
        );
      })}
    </div>
  );
}

window.ScreenAttract = ScreenAttract;
window.ScreenInicio = ScreenInicio;
window.LangSwitcher = LangSwitcher;
window.ArcadeBG = ArcadeBG;
window.UnnicLogo = UnnicLogo;
window.CornerMarks = CornerMarks;
window.UNNIC_YELLOW = UNNIC_YELLOW;
window.PRIMARY = PRIMARY;
window.PRIMARY_SOFT = PRIMARY_SOFT;
window.PRIMARY_DARK = PRIMARY_DARK;
window.BG = BG;
window.SURFACE = SURFACE;
window.SURFACE_2 = SURFACE_2;
window.BORDER = BORDER;
window.TEXT = TEXT;
window.TEXT_DIM = TEXT_DIM;
window.OK = OK;
window.ERR = ERR;
