// Buyer toast — fixed at top, appears every 8s, stays 4s
const TOAST_BUYERS = [
  { name: 'João Silva', city: 'Braga', kit: 'Campeão', img: 'uploads/homem-1.jpg' },
  { name: 'Sofia Almeida', city: 'Porto', kit: 'Inicial', img: 'uploads/mulher-1.jpg' },
  { name: 'Miguel Costa', city: 'Lisboa', kit: 'Colecionador', img: 'uploads/homem-2.jpg' },
  { name: 'Rita Fernandes', city: 'Coimbra', kit: 'Campeão', img: 'uploads/avatar-rita.png' },
  { name: 'André Pereira', city: 'Faro', kit: 'Inicial', img: 'uploads/homem-3.jpg' },
  { name: 'Carolina Dias', city: 'Aveiro', kit: 'Basic', img: 'uploads/mulher-2.jpg' },
  { name: 'Bruno Oliveira', city: 'Setúbal', kit: 'Campeão', img: 'uploads/avatar-carlos.png' },
  { name: 'Inês Martins', city: 'Funchal', kit: 'Colecionador', img: 'uploads/mulher-3.jpg' },
  { name: 'Tiago Ribeiro', city: 'Évora', kit: 'Campeão', img: 'uploads/avatar-roberto.png' },
];

function BuyerAvatar({ buyer, size = 44 }) {
  const [errored, setErrored] = React.useState(false);
  const colors = [
    [C.green, C.gold], [C.red, C.gold], [C.greenDeep, C.cream],
    [C.gold, C.red], [C.green, C.cream],
  ];
  const [c1, c2] = colors[buyer.name.charCodeAt(0) % colors.length];
  if (buyer.img && !errored) {
    return (
      <img
        src={buyer.img}
        alt={buyer.name}
        data-buyer-photo={buyer.name}
        onError={() => setErrored(true)}
        style={{
          width: size, height: size, borderRadius: '50%',
          objectFit: 'cover', flexShrink: 0,
          border: `2px solid ${C.gold}`,
          background: '#eee',
        }}
      />
    );
  }
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: `linear-gradient(135deg, ${c1}, ${c2})`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff', fontWeight: 800, fontSize: size * 0.42,
      flexShrink: 0, border: `2px solid ${C.gold}`,
      fontFamily: '"Bebas Neue", sans-serif',
      letterSpacing: '0.04em',
    }}>{buyer.name.split(' ').map(n => n[0]).slice(0,2).join('')}</div>
  );
}

function BuyerToast() {
  const [idx, setIdx] = React.useState(0);
  const [visible, setVisible] = React.useState(false);
  const [secondsAgo, setSecondsAgo] = React.useState(0);

  // First appearance delayed slightly
  React.useEffect(() => {
    const initial = setTimeout(() => setVisible(true), 1800);
    return () => clearTimeout(initial);
  }, []);

  // Rhythm: visible 4s → hidden 4s → next buyer
  React.useEffect(() => {
    if (visible) {
      setSecondsAgo(Math.floor(2 + Math.random() * 40));
      const t = setTimeout(() => setVisible(false), 4000);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(() => {
        setIdx((i) => i + 1);
        setVisible(true);
      }, 4000);
      return () => clearTimeout(t);
    }
  }, [visible]);

  const buyer = TOAST_BUYERS[idx % TOAST_BUYERS.length];

  return (
    <div
      aria-live="polite"
      style={{
        position: 'fixed', top: 10, left: 0, right: 0,
        zIndex: 1000, display: 'flex', justifyContent: 'center',
        pointerEvents: 'none', padding: '0 12px',
      }}
    >
      <div style={{
        background: '#fff',
        borderRadius: 14,
        padding: '8px 14px 8px 8px',
        display: 'flex', alignItems: 'center', gap: 10,
        boxShadow: '0 10px 28px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.04)',
        maxWidth: 360, width: '100%',
        transform: visible ? 'translateY(0)' : 'translateY(-120%)',
        opacity: visible ? 1 : 0,
        transition: 'transform 0.5s cubic-bezier(0.34,1.56,0.64,1), opacity 0.3s',
        pointerEvents: visible ? 'auto' : 'none',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Pulse dot */}
        <div style={{
          position: 'absolute', top: 8, right: 10,
          width: 7, height: 7, borderRadius: '50%',
          background: '#27c267',
          boxShadow: '0 0 0 0 rgba(39,194,103,0.6)',
          animation: visible ? 'pulse 1.4s infinite' : 'none',
        }} />

        <BuyerAvatar buyer={buyer} size={42} />

        <div style={{ flex: 1, minWidth: 0, lineHeight: 1.25 }}>
          <div style={{ fontSize: 12.5, color: C.greenInk, fontWeight: 700 }}>
            <span style={{ color: C.red }}>⚽</span> {buyer.name.split(' ')[0]} <span style={{ color: '#888', fontWeight: 500 }}>de {buyer.city}</span>
          </div>
          <div style={{
            fontSize: 11, color: '#555',
            display: 'flex', alignItems: 'center', gap: 6,
            marginTop: 1,
          }}>
            <span>comprou o <strong style={{ color: C.greenInk }}>Kit {buyer.kit}</strong></span>
          </div>
          <div style={{ fontSize: 10, color: '#999', marginTop: 1 }}>há {secondsAgo}s · pagamento confirmado ✓</div>
        </div>
      </div>
    </div>
  );
}

// Landing / Hero screen
function Landing({ onStart }) {
  const [tick, setTick] = React.useState(0);
  const [buyerIdx, setBuyerIdx] = React.useState(0);
  const [buyerVisible, setBuyerVisible] = React.useState(true);
  const [secondsAgo, setSecondsAgo] = React.useState(12);

  React.useEffect(() => {
    const t = setInterval(() => setTick((x) => x + 1), 1000);
    return () => clearInterval(t);
  }, []);

  // Buyer notification rotates every 9–14s with a fade transition
  React.useEffect(() => {
    let active = true;
    const cycle = () => {
      if (!active) return;
      const wait = 9000 + Math.random() * 5000;
      setTimeout(() => {
        if (!active) return;
        setBuyerVisible(false);
        setTimeout(() => {
          if (!active) return;
          setBuyerIdx((i) => i + 1);
          setSecondsAgo(Math.floor(2 + Math.random() * 30));
          setBuyerVisible(true);
          cycle();
        }, 400);
      }, wait);
    };
    cycle();
    return () => { active = false; };
  }, []);

  // Tick the "há Xs" counter up while a buyer is showing
  React.useEffect(() => {
    const t = setInterval(() => setSecondsAgo((s) => s + 1), 1000);
    return () => clearInterval(t);
  }, [buyerIdx]);

  // Countdown to a fixed future date
  const deadline = React.useMemo(() => Date.now() + 1000 * 60 * 60 * 23 + 1000 * 47 * 60 + 1000 * 12, []);
  const remaining = Math.max(0, deadline - Date.now());
  const hh = String(Math.floor(remaining / 3600000)).padStart(2, '0');
  const mm = String(Math.floor((remaining % 3600000) / 60000)).padStart(2, '0');
  const ss = String(Math.floor((remaining % 60000) / 1000)).padStart(2, '0');

  // Rotating "just bought" notifications
  const buyers = [
    { name: 'João', city: 'Braga', kit: 'Campeão', img: 'uploads/homem-1.jpg' },
    { name: 'Sofia', city: 'Porto', kit: 'Inicial', img: 'uploads/mulher-1.jpg' },
    { name: 'Miguel', city: 'Lisboa', kit: 'Colecionador', img: 'uploads/homem-2.jpg' },
    { name: 'Rita', city: 'Coimbra', kit: 'Campeão', img: 'uploads/avatar-rita.png' },
    { name: 'André', city: 'Faro', kit: 'Inicial', img: 'uploads/homem-3.jpg' },
    { name: 'Carolina', city: 'Aveiro', kit: 'Basic', img: 'uploads/mulher-2.jpg' },
  ];
  const buyer = buyers[buyerIdx % buyers.length];

  return (
    <div style={{ background: C.cream, minHeight: '100%', paddingBottom: 40 }}>
      <BuyerToast />
      {/* Top notice strip */}
      <div style={{
        background: C.greenInk, color: C.gold, textAlign: 'center',
        padding: '10px 16px', fontFamily: '"Bebas Neue", sans-serif',
        fontSize: 12, letterSpacing: '0.1em',
      }}>
        ⚡ ENVIO PARA TODO PORTUGAL · STOCK LIMITADO ⚡
      </div>

      {/* Hero */}
      <div style={{
        background: `
          radial-gradient(circle at 80% 20%, rgba(255,200,60,0.35) 0%, transparent 50%),
          radial-gradient(circle at 10% 90%, rgba(214,38,58,0.25) 0%, transparent 45%),
          linear-gradient(160deg, ${C.green} 0%, ${C.greenDeep} 70%, ${C.greenInk} 100%)
        `,
        padding: '20px 18px 30px',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Subtle stadium stripes */}
        <div style={{
          position: 'absolute', inset: 0, opacity: 0.08,
          background: 'repeating-linear-gradient(90deg, transparent 0px, transparent 28px, rgba(255,255,255,0.5) 28px, rgba(255,255,255,0.5) 56px)',
          pointerEvents: 'none',
        }} />

        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <Logo size={20} light />
            <SoundToggle />
          </div>

          {/* Countdown */}
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 22 }}>
            <Chip color={C.red}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#fff', animation: 'pulse 1s infinite' }} />
              OFERTA TERMINA EM {hh}:{mm}:{ss}
            </Chip>
          </div>

          {/* Headline */}
          <div style={{ textAlign: 'center', marginBottom: 16 }}>
            <div style={{
              fontFamily: '"Bebas Neue", sans-serif', color: C.gold,
              fontSize: 16, letterSpacing: '0.18em', marginBottom: 6,
            }}>MUNDIAL · NORTE AMÉRICA · 2026</div>
            <div style={{
              fontFamily: '"Bebas Neue", "Arial Black", sans-serif',
              color: C.cream, fontSize: 54, lineHeight: 0.88,
              letterSpacing: '0.005em', textShadow: '0 4px 12px rgba(0,0,0,0.4)',
            }}>
              COLECIONA<br />
              <span style={{ color: C.gold }}>O MUNDIAL</span><br />
              INTEIRO
            </div>
            <div style={{
              color: 'rgba(253,247,232,0.85)', fontSize: 15,
              marginTop: 10, lineHeight: 1.4, padding: '0 4px',
            }}>
              Álbum + saquetas de cromos · 48 seleções · 736 craques.<br />
              <strong style={{ color: C.gold }}>Faz o quiz e desbloqueia até 35% OFF.</strong>
            </div>
          </div>

          {/* Floating cromo trio */}
          <div style={{
            display: 'flex', justifyContent: 'center', alignItems: 'flex-end',
            gap: -10, margin: '18px 0 14px', height: 165,
          }}>
            <div style={{ marginRight: -18, marginBottom: 12 }}>
              <Cromo team="POR" num={22} pos="GR" name="Diogo Costa" img="uploads/diogo-costa-figurinha.jpg" tilt={-10} size={1} />
            </div>
            <div style={{ zIndex: 2, marginBottom: 0 }}>
              <Cromo team="POR" num={7} pos="AVA" name="Cristiano Ronaldo" img="uploads/ronaldo-figurinha.webp" rare tilt={0} size={1.15} />
            </div>
            <div style={{ marginLeft: -18, marginBottom: 12 }}>
              <Cromo team="POR" num={18} pos="MEI" name="Rúben Neves" img="uploads/ruben-neves-figurinha.jpg" tilt={10} size={1} />
            </div>
          </div>

          <CTA color="gold" onClick={onStart}>
            🎯 Fazer Quiz · Ganhar Desconto
          </CTA>

          <div style={{
            display: 'flex', justifyContent: 'center', gap: 14,
            marginTop: 14, fontSize: 11, color: 'rgba(253,247,232,0.7)',
            fontFamily: 'system-ui, sans-serif',
          }}>
            <span>✓ Stock em PT</span>
            <span>✓ Envio 24-48h</span>
            <span>✓ MB Way</span>
          </div>
        </div>
      </div>

      {/* Live buyer ticker */}
      <div key={buyerIdx} style={{
        margin: '14px 14px 0', padding: '10px 12px',
        background: '#fff', borderRadius: 14,
        boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
        display: 'flex', alignItems: 'center', gap: 10,
        opacity: buyerVisible ? 1 : 0,
        transform: buyerVisible ? 'translateY(0)' : 'translateY(-6px)',
        transition: 'opacity 0.4s ease, transform 0.4s ease',
      }}>
        <BuyerAvatar buyer={buyer} size={34} />
        <div style={{ flex: 1, fontSize: 12.5, color: C.greenInk, lineHeight: 1.3 }}>
          <strong>{buyer.name}</strong> de {buyer.city} acabou de comprar<br />
          <span style={{ color: '#666' }}>Kit {buyer.kit} · há {secondsAgo < 60 ? `${secondsAgo}s` : `${Math.floor(secondsAgo / 60)}min`}</span>
        </div>
        <div style={{ fontSize: 18, color: C.green }}>✓</div>
      </div>

      {/* Social proof stats */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
        gap: 8, padding: '14px',
      }}>
        {[
          ['12 384', 'Colecionadores'],
          ['4,9★', '1 207 reviews'],
          ['48h', 'Envio máx.'],
        ].map(([n, l]) => (
          <div key={l} style={{
            background: '#fff', borderRadius: 12, padding: '10px 8px',
            textAlign: 'center', boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
          }}>
            <div style={{
              fontFamily: '"Bebas Neue", sans-serif', fontSize: 22,
              color: C.greenInk, letterSpacing: '0.02em',
            }}>{n}</div>
            <div style={{ fontSize: 10, color: '#666', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{l}</div>
          </div>
        ))}
      </div>

      {/* Why */}
      <div style={{ padding: '6px 14px 20px' }}>
        <SectionTitle kicker="Porquê CRAQUES 26" title={<>A coleção <span style={{ color: C.red }}>oficial</span> da temporada</>} />
        <div style={{ display: 'grid', gap: 10 }}>
          {[
            { i: '⚽', t: '736 craques', d: 'Todos os 48 plantéis do Mundial 2026' },
            { i: '✨', t: 'Cromos raros', d: 'Holográficos, foil, lendas e edições limitadas' },
            { i: '📦', t: 'Saquetas seladas', d: 'Diretamente do fornecedor — sem cromos repetidos garantidos por kit' },
            { i: '🇵🇹', t: 'Stock em Portugal', d: 'Envio CTT 24-48h · Pagamento MB Way' },
          ].map((f, i) => (
            <div key={i} style={{
              background: '#fff', borderRadius: 14, padding: '12px 14px',
              display: 'flex', gap: 12, alignItems: 'center',
              boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
            }}>
              <div style={{ fontSize: 26 }}>{f.i}</div>
              <div style={{ flex: 1 }}>
                <div style={{
                  fontFamily: '"Bebas Neue", sans-serif', fontSize: 18,
                  color: C.greenInk, letterSpacing: '0.02em',
                }}>{f.t.toUpperCase()}</div>
                <div style={{ fontSize: 12, color: '#555', lineHeight: 1.35 }}>{f.d}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 20 }}>
          <CTA color="red" onClick={onStart}>Quero o meu desconto →</CTA>
          <div style={{ textAlign: 'center', fontSize: 11, color: '#888', marginTop: 8 }}>
            🔒 Pagamento seguro · Garantia 30 dias
          </div>
        </div>
      </div>
    </div>
  );
}

function SoundToggle() {
  const [muted, setMuted] = React.useState(false);
  return (
    <button
      onClick={() => {
        const m = !muted;
        setMuted(m);
        window.Sound?.setMuted(m);
        if (!m) { window.Sound?.getCtx(); window.Sound?.playTap(); }
      }}
      style={{
        background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.25)',
        color: C.cream, fontSize: 11, borderRadius: 999,
        padding: '5px 10px', cursor: 'pointer',
        fontFamily: 'system-ui, sans-serif',
      }}
    >{muted ? '🔇 Som OFF' : '🔊 Som ON'}</button>
  );
}

Object.assign(window, { Landing, SoundToggle });
