/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

/* ============================================================================
   STEPS — espelham os 3 passos da Home.tsx em produção
   + um quarto "Aproveite" para mostrar o estado validado do operador.
   ============================================================================ */
const STEPS = [
  {
    title: "Escolha seu passe",
    desc: "Veja os passes disponíveis e compare. Cada passe combina atrações imperdíveis já incluídas com uma cota de atrações livres pra você escolher.",
  },
  {
    title: "Selecione as atrações",
    desc: "Após a compra, monte sua jornada: as imperdíveis já vêm prontas e você escolhe as livres respeitando a cota. Cada seleção compromete um slot.",
  },
  {
    title: "Gere o QR Code",
    desc: "Na hora da visita, gere o QR Code no app. Validade de 4 horas, código curto como fallback sem câmera, regeneração sem custo se precisar.",
  },
  {
    title: "Aproveite. Sem fila.",
    desc: "O operador escaneia o QR na catraca e libera a entrada. Histórico atualizado em tempo real, validade do passe rastreada pelo app.",
  },
];

const STEP_MS = 5600;
const TICK = 60;

/* ============================================================================
   Ícones Lucide (extraídos de lucide.dev) — inlineados para evitar dependência
   ============================================================================ */
const Icon = {
  MapPin: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/></svg>,
  Ticket: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"/><path d="M13 5v2M13 17v2M13 11v2"/></svg>,
  CheckCircle2: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>,
  AlertCircle: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>,
  ArrowLeft: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>,
  Calendar: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
  QrCode: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="5" height="5" x="3" y="3" rx="1"/><rect width="5" height="5" x="16" y="3" rx="1"/><rect width="5" height="5" x="3" y="16" rx="1"/><path d="M21 16h-3a2 2 0 0 0-2 2v3M21 21v.01M12 7v3a2 2 0 0 1-2 2H7M3 12h.01M12 3h.01M12 16v.01M16 12h1M21 12v.01M12 21v-1"/></svg>,
  Clock: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>,
  Maximize2: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>,
  Copy: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>,
  Filters: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="21" y1="4" x2="14" y2="4"/><line x1="10" y1="4" x2="3" y2="4"/><line x1="21" y1="12" x2="12" y2="12"/><line x1="8" y1="12" x2="3" y2="12"/><line x1="21" y1="20" x2="16" y2="20"/><line x1="12" y1="20" x2="3" y2="20"/><line x1="14" y1="2" x2="14" y2="6"/><line x1="8" y1="10" x2="8" y2="14"/><line x1="16" y1="18" x2="16" y2="22"/></svg>,
  Gift: (p) => <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="8" width="18" height="4" rx="1"/><path d="M12 8v13M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"/><path d="M7.5 8a2.5 2.5 0 0 1 0-5C9 3 12 5 12 8c0-3 3-5 4.5-5a2.5 2.5 0 0 1 0 5"/></svg>,
};

/* ============================================================================
   QR grid (21×21) — finders + timing + noise determinístico
   ============================================================================ */
const QR_GRID = (function () {
  const N = 21;
  const arr = new Array(N * N).fill(false);
  function paintFinder(r, c) {
    for (let i = 0; i < 7; i++) for (let j = 0; j < 7; j++) {
      const outer = i === 0 || i === 6 || j === 0 || j === 6;
      const inner = i >= 2 && i <= 4 && j >= 2 && j <= 4;
      arr[(r + i) * N + (c + j)] = outer || inner;
    }
  }
  paintFinder(0, 0); paintFinder(0, 14); paintFinder(14, 0);
  for (let i = 8; i < 13; i++) {
    arr[6 * N + i] = i % 2 === 0;
    arr[i * N + 6] = i % 2 === 0;
  }
  let seed = 1337;
  function rand() { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; }
  for (let r = 0; r < N; r++) {
    for (let c = 0; c < N; c++) {
      const inTL = r < 8 && c < 8;
      const inTR = r < 8 && c >= 13;
      const inBL = r >= 13 && c < 8;
      const inTiming = r === 6 || c === 6;
      if (inTL || inTR || inBL || inTiming) continue;
      if (rand() > 0.5) arr[r * N + c] = true;
    }
  }
  return arr;
})();

/* ============================================================================
   PHONE STATUS BAR — claro ou escuro conforme tema da tela
   ============================================================================ */
function PhoneStatus({ dark }) {
  const color = dark ? "#ffffff" : "#0f172a";
  return (
    <div className="phone-status" style={{ color }}>
      <span>9:41</span>
      <span style={{ display: "inline-flex", gap: 4, alignItems: "center" }}>
        <svg width="14" height="9" viewBox="0 0 16 10" fill="currentColor"><rect x="0" y="6" width="3" height="4" rx="0.5"/><rect x="4" y="4" width="3" height="6" rx="0.5"/><rect x="8" y="2" width="3" height="8" rx="0.5"/><rect x="12" y="0" width="3" height="10" rx="0.5"/></svg>
        <svg width="16" height="9" viewBox="0 0 18 10" fill="none" stroke="currentColor" strokeWidth="1.2"><rect x="0.6" y="0.6" width="14" height="8.8" rx="2"/><rect x="2" y="2" width="11" height="6" rx="1" fill="currentColor"/><path d="M16 3.5v3" strokeLinecap="round"/></svg>
      </span>
    </div>
  );
}

/* ============================================================================
   SCREEN 1 — Catalog
   Espelha PassList.tsx + PassCard.tsx:
   - top bar branca com h1 "Passes turísticos disponíveis"
   - results bar "2 passes" + chip de filtros
   - PassCard: img-area verde com badge -45% OFF, info com MapPin+destino+nome,
     savings block (line-through + economia em emerald-600), price + CTA
   ============================================================================ */
function ScreenCatalog() {
  return (
    <div className="scr s-catalog">
      <div className="top-bar">
        <h1>Passes turísticos disponíveis</h1>
        <p>Combine atrações e economize até 50%.</p>
      </div>

      <div className="body">
        <div className="results-bar">
          <span>2 passes</span>
          <span className="filters"><Icon.Filters width="9" height="9"/> Filtros</span>
        </div>

        <article className="pc-card">
          <div className="img-area">
            <span className="off-badge">-45% OFF</span>
            <svg className="scene" width="180" height="80" viewBox="0 0 180 80" fill="none" aria-hidden="true">
              <path d="M0 80 L36 28 L66 54 L106 14 L140 44 L180 28 L180 80 Z" fill="rgba(255,255,255,0.14)"/>
              <path d="M0 80 L28 48 L60 62 L88 38 L122 54 L180 32 L180 80 Z" fill="rgba(255,255,255,0.07)"/>
            </svg>
          </div>
          <div className="info">
            <div className="loc"><Icon.MapPin/> Campos do Jordão, Brasil</div>
            <h3>VillePass Campos do Jordão</h3>
          </div>
          <div className="access-line">
            <Icon.Ticket/>
            <span>Acesso a 5 de 12 atrações</span>
          </div>
          <div className="savings">
            <div className="r1"><span>Preço de balcão</span><span className="strike">R$ 480,00</span></div>
            <div className="r2"><span className="left"><Icon.CheckCircle2 width="9" height="9"/> Economia</span><span>R$ 191,00</span></div>
          </div>
          <div className="footer">
            <div className="price-block">
              <div className="l">Preço final</div>
              <div className="v"><span className="cur">R$</span>289,00</div>
            </div>
            <span className="cta">Ver detalhes</span>
          </div>
        </article>
      </div>
    </div>
  );
}

/* ============================================================================
   SCREEN 2 — PurchasedPassDetail
   Espelha a tela de detalhe do passe comprado:
   - slate-900 header com pthumb + status "ATIVO" + nome + "Válido até..."
   - card branco sobreposto (-mt-16px) com progress bar 2/5
   - seção "Imperdíveis" (CheckCircle2 emerald) com 2 itens "Usado" + "Disponível"
   - seção "Livres" (AlertCircle indigo) com botão "Gerar QR Code" slate-900
   ============================================================================ */
function ScreenSelect() {
  return (
    <div className="scr s-select">
      <div className="top-bar">
        <div className="back"><Icon.ArrowLeft width="10" height="10"/> Voltar</div>
        <div className="head">
          <div className="pthumb"></div>
          <div className="meta">
            <div className="row1">
              <span className="status">ATIVO</span>
              <span className="loc"><Icon.MapPin width="8" height="8"/> Campos do Jordão</span>
            </div>
            <h2>VillePass Campos do Jordão</h2>
            <span className="validity"><Icon.Calendar/> Válido até <strong>23 jun, 2026</strong></span>
          </div>
        </div>
      </div>

      <div className="body">
        <div className="progress-row">
          <h3>Progresso geral</h3>
          <span className="count">2 de 5</span>
        </div>
        <div className="progress-bar"><div className="fill"></div></div>

        <div className="section">
          <div className="label anchor">
            <Icon.CheckCircle2/> Imperdíveis
            <span className="qpill">2 / 2</span>
          </div>
          <div className="item">
            <div className="thumb"></div>
            <div className="info">
              <div className="n">Palácio Boa Vista</div>
              <div className="d">Museu</div>
            </div>
            <span className="used"><Icon.CheckCircle2/> Usado</span>
          </div>
          <div className="item">
            <div className="thumb" style={{background:"linear-gradient(135deg,#6ee7b7,#10b981)"}}></div>
            <div className="info">
              <div className="n">Teleférico</div>
              <div className="d">Atração âncora</div>
            </div>
            <span className="used"><Icon.CheckCircle2/> Usado</span>
          </div>
        </div>

        <div className="section">
          <div className="label free">
            <Icon.AlertCircle/> Livres
            <span className="qpill">0 / 3</span>
          </div>
          <div className="item">
            <div className="thumb" style={{background:"linear-gradient(135deg,#a7f3d0,#6ee7b7)"}}></div>
            <div className="info">
              <div className="n">Horto Florestal</div>
              <div className="d">Natureza</div>
            </div>
            <span className="gen-btn"><Icon.QrCode/> Gerar</span>
          </div>
          <div className="item">
            <div className="thumb" style={{background:"linear-gradient(135deg,#d1fae5,#a7f3d0)"}}></div>
            <div className="info">
              <div className="n">Tarundu</div>
              <div className="d">Parque</div>
            </div>
            <span className="avail">Disponível</span>
          </div>
          <div className="item">
            <div className="thumb" style={{background:"linear-gradient(135deg,#bbf7d0,#86efac)"}}></div>
            <div className="info">
              <div className="n">Capivari Garden</div>
              <div className="d">Centro</div>
            </div>
            <span className="avail">Disponível</span>
          </div>
        </div>

        <div className="section">
          <div className="label bonus">
            <Icon.Gift/> Bônus
            <span className="qpill">0 / 2</span>
          </div>
          <div className="item benefit">
            <div className="thumb bonus-thumb"><Icon.Gift width="14" height="14"/></div>
            <div className="info">
              <div className="n">10% off no Vemaget</div>
              <div className="d">Consumindo R$ 180+</div>
            </div>
            <span className="gen-btn bonus-btn"><Icon.QrCode/> Resgatar</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================================
   SCREEN 3 — AttractionQR (active QR state)
   Espelha AttractionQR.tsx:
   - top-bar: imagem da atração + back + pass-pill emerald-400 + nome
   - white card com emerald-500 top stripe
   - "INGRESSO INDIVIDUAL" caption
   - QR em slate-50 frame
   - emerald-50 pill "Toque para ampliar"
   - "Mostre este QR..." + subtext
   - amber-50 pill "Válido até..."
   - slate-50 shortcode panel "Sem câmera?" + mono code + copy btn
   ============================================================================ */
function ScreenQr() {
  return (
    <div className="scr s-qr">
      <div className="top-bar">
        <span className="back"><Icon.ArrowLeft/></span>
        <span className="pass-pill">VillePass C. Jordão</span>
        <h1>Palácio Boa Vista</h1>
      </div>
      <div className="body">
        <div className="qr-card">
          <div className="cap">Ingresso individual</div>
          <div className="qr-frame">
            <div className="qr-grid">
              {QR_GRID.map((on, i) => <span key={i} className={on ? "b" : ""}></span>)}
            </div>
          </div>
          <span className="zoom-pill"><Icon.Maximize2/> Toque para ampliar</span>
          <div className="show-text">Mostre este QR para o atendente</div>
          <div className="show-sub">Aproxime o celular do leitor na catraca.</div>
          <div className="clock-pill"><Icon.Clock/> Válido até 13:42</div>
          <div className="shortcode">
            <div>
              <div className="l">Sem câmera?</div>
              <div className="code">VLPS-7A29</div>
            </div>
            <span className="cp"><Icon.Copy/> Copiar</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================================
   SCREEN 4 — Validated (allUsed branch da AttractionQR)
   Réplica visual do estado terminal de validação:
   - emerald-900/35 ring com CheckCircle2 emerald-500 (size 40)
   - pulse ring animado em torno
   - "Atração utilizada!" bold white
   - subtext slate-400 explicando
   - ticket slate-900 com Atração / Visitante / Validado em / Restantes
   - botão back slate-800
   ============================================================================ */
function ScreenOk() {
  return (
    <div className="scr s-ok">
      <div className="ring-wrap">
        <div className="ring"><Icon.CheckCircle2/></div>
      </div>
      <h2>Atração utilizada!</h2>
      <p className="lead">Você realizou o check-in no Palácio Boa Vista. Aproveite a visita.</p>
      <div className="ticket">
        <div className="row"><span className="k">Atração</span><span className="v">Palácio Boa Vista</span></div>
        <div className="row"><span className="k">Visitante</span><span className="v">Pedro · Você</span></div>
        <div className="row"><span className="k">Validado em</span><span className="v">Hoje, 13:55</span></div>
        <div className="row"><span className="k">Status</span><span className="v"><span className="ok"><Icon.CheckCircle2/> Confirmado</span></span></div>
      </div>
      <div className="btn-back">Ver demais atrações</div>
    </div>
  );
}

const SCREENS = [ScreenCatalog, ScreenSelect, ScreenQr, ScreenOk];
const SCREEN_DARK = [false, true, true, true]; // status bar color por tela (telas com header escuro = branco)

/* ============================================================================
   PHONE — frame + cycling screens
   ============================================================================ */
function Phone({ active }) {
  return (
    <div className="phone-wrap">
      <div className="phone">
        <div className="phone-screen">
          <div className="phone-notch"></div>
          <PhoneStatus dark={SCREEN_DARK[active]} />
          <div className="phone-screens">
            {SCREENS.map((S, i) => (
              <div key={i} style={{
                position: "absolute", inset: 0,
                opacity: i === active ? 1 : 0,
                transform: i === active ? "none" : "translateY(12px) scale(0.985)",
                transition: "opacity .55s ease, transform .55s ease",
                pointerEvents: i === active ? "auto" : "none",
              }}>
                {i === active ? <S /> : null}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================================
   HOW IT WORKS — auto-cycle + click to focus
   ============================================================================ */
function HowItWorks() {
  const [active, setActive] = useState(0);
  const [progress, setProgress] = useState(0);
  const [paused, setPaused] = useState(false);
  const startRef = useRef(Date.now());
  const lastClickRef = useRef(0);

  useEffect(() => {
    startRef.current = Date.now();
    setProgress(0);
  }, [active]);

  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => {
      const t = (Date.now() - startRef.current) / STEP_MS;
      if (t >= 1) setActive((a) => (a + 1) % STEPS.length);
      else setProgress(t);
    }, TICK);
    return () => clearInterval(id);
  }, [active, paused]);

  function handleClick(i) {
    lastClickRef.current = Date.now();
    setActive(i);
    setPaused(true);
    setTimeout(() => {
      if (Date.now() - lastClickRef.current >= 1400) setPaused(false);
    }, 1500);
  }

  return (
    <>
      <div className="steps-col">
        <div className="steps">
          {STEPS.map((s, i) => {
            const isActive = i === active;
            const isDone = i < active;
            const p = isActive ? progress : (isDone ? 1 : 0);
            return (
              <div
                key={i}
                className={`step${isActive ? " active" : ""}${isDone ? " done" : ""}`}
                onClick={() => handleClick(i)}
              >
                <span className="marker">
                  {isDone ? (
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                  ) : (i + 1)}
                </span>
                <h3>{s.title}</h3>
                <p>{s.desc}</p>
                <span className="progress"><span className="fill" style={{ transform: `scaleY(${p})` }}></span></span>
              </div>
            );
          })}
        </div>
      </div>
      <div className="phone-col">
        <Phone active={active} />
      </div>
    </>
  );
}

const mount = document.getElementById("how-mount");
if (mount) {
  ReactDOM.createRoot(mount).render(<HowItWorks />);
}
