// Checkout overlay — multi-step
const { useState: useS, useEffect: useE } = React;

const STEPS = [
  { key: "tier", label: "Entrada" },
  { key: "qty", label: "Cantidad" },
  { key: "info", label: "Datos" },
  { key: "pay", label: "Pago" },
  { key: "done", label: "Confirmación" },
];

function Checkout({ open, onClose }) {
  const [step, setStep] = useS(0);
  const [tierId, setTierId] = useS("general");
  const [qty, setQty] = useS(1);
  const [form, setForm] = useS({
    fullName: "",
    email: "",
    dni: "",
    phone: "",
    city: "",
  });
  const [pay, setPay] = useS("mp");
  const [card, setCard] = useS({ num: "", name: "", exp: "", cvv: "" });
  const [processing, setProcessing] = useS(false);
  const [err, setErr] = useS(null);

  useE(() => {
    if (open) { setStep(0); setProcessing(false); setErr(null); }
  }, [open]);

  useE(() => {
    if (!open) return;
    const k = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [open, onClose]);

  const tier = DATA.tiers.find((t) => t.id === tierId) || DATA.tiers[1];
  const fee = Math.round(tier.price * qty * 0.07);
  const total = tier.price * qty + fee;

  const validateInfo = () => {
    if (!form.fullName.trim()) return "Nombre requerido";
    if (!/^\S+@\S+\.\S+$/.test(form.email)) return "Email inválido";
    if (!/^\d{7,8}$/.test(form.dni.replace(/\D/g, ""))) return "DNI inválido (7-8 dígitos)";
    if (!/^\d{8,}$/.test(form.phone.replace(/\D/g, ""))) return "Teléfono inválido";
    return null;
  };

  const validatePay = () => {
    if (pay !== "card") return null;
    if (!/^\d{16}$/.test(card.num.replace(/\s/g, ""))) return "Número de tarjeta inválido";
    if (!card.name.trim()) return "Nombre del titular requerido";
    if (!/^\d{2}\/\d{2}$/.test(card.exp)) return "Vencimiento inválido (MM/AA)";
    if (!/^\d{3,4}$/.test(card.cvv)) return "CVV inválido";
    return null;
  };

  const next = () => {
    setErr(null);
    if (step === 2) {
      const e = validateInfo();
      if (e) { setErr(e); return; }
    }
    if (step === 3) {
      const e = validatePay();
      if (e) { setErr(e); return; }
      setProcessing(true);
      setTimeout(() => { setProcessing(false); setStep(4); }, 1600);
      return;
    }
    setStep(Math.min(step + 1, STEPS.length - 1));
  };
  const back = () => { setErr(null); setStep(Math.max(0, step - 1)); };

  return (
    <div className={`checkout-root ${open ? "open" : ""}`} aria-hidden={!open}>
      <div className="checkout-backdrop" onClick={onClose}></div>
      <aside className="checkout-panel" role="dialog" aria-label="Comprar entradas">
        <div className="checkout-head">
          <div className="ev">
            <div className="t">{DATA.featured.code} · {DATA.featured.venue}</div>
            <div className="s">{DATA.featured.dateLabel} · {DATA.featured.year} · {DATA.featured.city}</div>
          </div>
          <button className="x-btn" onClick={onClose} aria-label="Cerrar" data-cursor="hot">
            <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.5"><path d="M1 1l12 12M13 1L1 13"/></svg>
          </button>
        </div>

        <div className="steps">
          {STEPS.map((s, i) => (
            <React.Fragment key={s.key}>
              <div className={`step ${i < step ? "done" : ""} ${i === step ? "active" : ""}`}>
                <span className="n">{i < step ? "✓" : i + 1}</span>
                <span>{s.label}</span>
              </div>
              {i < STEPS.length - 1 && <span className="step-sep"></span>}
            </React.Fragment>
          ))}
        </div>

        <div className="checkout-body">
          {step === 0 && <StepTier tierId={tierId} setTierId={setTierId} />}
          {step === 1 && <StepQty tier={tier} qty={qty} setQty={setQty} fee={fee} total={total} />}
          {step === 2 && <StepInfo form={form} setForm={setForm} />}
          {step === 3 && <StepPay pay={pay} setPay={setPay} card={card} setCard={setCard} processing={processing} />}
          {step === 4 && <StepDone tier={tier} qty={qty} total={total} form={form} />}
        </div>

        <div className="checkout-foot">
          <div className="error">{err || ""}</div>
          <div style={{ display: "flex", gap: 12 }}>
            {step > 0 && step < 4 && (
              <button className="btn ghost" onClick={back} data-cursor="hot" disabled={processing}>
                ← Atrás
              </button>
            )}
            {step < 3 && (
              <button className="btn solid" onClick={next} data-cursor="hot">
                Continuar <span className="arr">→</span>
              </button>
            )}
            {step === 3 && (
              <button className="btn solid" onClick={next} data-cursor="hot" disabled={processing}>
                {processing ? "Procesando…" : <>Pagar ${fmt(total)} <span className="arr">→</span></>}
              </button>
            )}
            {step === 4 && (
              <button className="btn solid" onClick={onClose} data-cursor="hot">
                Cerrar
              </button>
            )}
          </div>
        </div>
      </aside>
    </div>
  );
}

function fmt(n) {
  return n.toLocaleString("es-AR");
}

function StepTier({ tierId, setTierId }) {
  return (
    <div style={{ display: "grid", gap: 12 }}>
      <div className="tag">SELECCIONÁ TU ENTRADA · 4 TIERS</div>
      {DATA.tiers.map((t) => (
        <button
          key={t.id}
          className={`tier ${tierId === t.id ? "sel" : ""} ${t.sold ? "sold" : ""}`}
          onClick={() => !t.sold && setTierId(t.id)}
          data-cursor="hot"
          style={{ textAlign: "left" }}
        >
          <div>
            <div className="name">{t.name}</div>
            <div className="desc">{t.desc}</div>
            <ul className="perks">
              {t.perks.map((p, i) => <li key={i}>{p}</li>)}
            </ul>
          </div>
          <div className="price">
            <div className="amt">${fmt(t.price)}</div>
            <small>ARS · c/u</small>
            <div className={`stat ${t.statCls}`}>{t.stat}</div>
          </div>
        </button>
      ))}
      <div className="tag dim" style={{ paddingTop: 8 }}>
        + cargo por servicio del 7%. Mercado Pago, transferencia, 3 cuotas sin interés.
      </div>
    </div>
  );
}

function StepQty({ tier, qty, setQty, fee, total }) {
  const max = tier.id === "vip" ? 4 : 8;
  return (
    <div style={{ display: "grid", gap: 16 }}>
      <div className="tag">¿CUÁNTAS ENTRADAS?</div>
      <div className="qty-row">
        <div>
          <div className="name">{tier.name}</div>
          <div className="sub">${fmt(tier.price)} ARS · máx. {max} por compra</div>
        </div>
        <div className="qty-ctrl">
          <button onClick={() => setQty(Math.max(1, qty - 1))} disabled={qty <= 1}>−</button>
          <div className="n">{qty}</div>
          <button onClick={() => setQty(Math.min(max, qty + 1))} disabled={qty >= max}>+</button>
        </div>
      </div>
      <Summary tier={tier} qty={qty} fee={fee} total={total} />
    </div>
  );
}

function StepInfo({ form, setForm }) {
  const upd = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  return (
    <div style={{ display: "grid", gap: 18 }}>
      <div className="tag">DATOS DEL COMPRADOR · TITULAR DE LA ENTRADA</div>
      <div className="field">
        <label>Nombre completo</label>
        <input value={form.fullName} onChange={upd("fullName")} placeholder="Como figura en tu DNI" />
      </div>
      <div className="field-row">
        <div className="field">
          <label>Email</label>
          <input type="email" value={form.email} onChange={upd("email")} placeholder="vos@email.com" />
        </div>
        <div className="field">
          <label>Teléfono</label>
          <input value={form.phone} onChange={upd("phone")} placeholder="+54 9 381 ..." />
        </div>
      </div>
      <div className="field-row">
        <div className="field">
          <label>DNI</label>
          <input value={form.dni} onChange={upd("dni")} placeholder="00.000.000" />
        </div>
        <div className="field">
          <label>Ciudad</label>
          <input value={form.city} onChange={upd("city")} placeholder="Ej. San Miguel de Tucumán" />
        </div>
      </div>
      <div className="tag dim">
        Te enviamos las entradas QR a tu email. El DNI se valida en puerta.
      </div>
    </div>
  );
}

function StepPay({ pay, setPay, card, setCard, processing }) {
  const upd = (k) => (e) => setCard({ ...card, [k]: e.target.value });
  return (
    <div style={{ display: "grid", gap: 16 }}>
      <div className="tag">MÉTODO DE PAGO</div>
      <div className="pay-method-grid">
        {[
          { id: "mp", l: "Mercado Pago" },
          { id: "card", l: "Tarjeta" },
          { id: "tx", l: "Transferencia" },
        ].map((m) => (
          <button key={m.id} className={`pm ${pay === m.id ? "sel" : ""}`} onClick={() => setPay(m.id)} data-cursor="hot">
            <div className="ic">{m.id === "mp" ? "$" : m.id === "card" ? "▭▭▭▭" : "≡"}</div>
            <div className="l">{m.l}</div>
          </button>
        ))}
      </div>

      {pay === "card" && (
        <div style={{ display: "grid", gap: 14, padding: 18, border: "1px solid var(--line)", background: "var(--bg-2)" }}>
          <div className="field">
            <label>Número de tarjeta</label>
            <input
              value={card.num}
              onChange={(e) => setCard({ ...card, num: e.target.value.replace(/\D/g, "").slice(0, 16).replace(/(\d{4})(?=\d)/g, "$1 ") })}
              placeholder="0000 0000 0000 0000"
              maxLength={19}
            />
          </div>
          <div className="field">
            <label>Nombre del titular</label>
            <input value={card.name} onChange={upd("name")} placeholder="Como figura en la tarjeta" />
          </div>
          <div className="field-row">
            <div className="field">
              <label>Vencimiento</label>
              <input
                value={card.exp}
                onChange={(e) => {
                  let v = e.target.value.replace(/\D/g, "").slice(0, 4);
                  if (v.length >= 3) v = v.slice(0, 2) + "/" + v.slice(2);
                  setCard({ ...card, exp: v });
                }}
                placeholder="MM/AA"
                maxLength={5}
              />
            </div>
            <div className="field">
              <label>CVV</label>
              <input
                value={card.cvv}
                onChange={(e) => setCard({ ...card, cvv: e.target.value.replace(/\D/g, "").slice(0, 4) })}
                placeholder="123"
                maxLength={4}
              />
            </div>
          </div>
          <div className="tag dim">3 cuotas sin interés en tarjetas de crédito participantes.</div>
        </div>
      )}
      {pay === "mp" && (
        <div style={{ padding: 18, border: "1px solid var(--line)", background: "var(--bg-2)" }}>
          <div className="tag" style={{ marginBottom: 8 }}>REDIRECCIÓN MERCADO PAGO</div>
          <p className="dim" style={{ fontSize: 14, lineHeight: 1.5 }}>
            Te redirigimos a Mercado Pago para completar el pago de forma segura.
            Volvés acá automáticamente al confirmar.
          </p>
        </div>
      )}
      {pay === "tx" && (
        <div style={{ padding: 18, border: "1px solid var(--line)", background: "var(--bg-2)" }}>
          <div className="tag" style={{ marginBottom: 8 }}>CBU · TM RECORDINGS SRL</div>
          <div className="mono" style={{ fontSize: 14 }}>0000003100099999999999</div>
          <div className="tag dim" style={{ marginTop: 8 }}>Te enviamos las entradas al confirmar el pago (hasta 24hs hábiles)</div>
        </div>
      )}

      {processing && (
        <div style={{ textAlign: "center", padding: 20 }}>
          <div className="tag acc" style={{ marginBottom: 8 }}>PROCESANDO PAGO</div>
          <div className="mono dim">no cierres esta ventana...</div>
        </div>
      )}
    </div>
  );
}

function Summary({ tier, qty, fee, total }) {
  return (
    <div className="summary">
      <div className="line">
        <span>{tier.name} × {qty}</span>
        <span>${fmt(tier.price * qty)}</span>
      </div>
      <div className="line">
        <span>Cargo por servicio (7%)</span>
        <span>${fmt(fee)}</span>
      </div>
      <div className="line total">
        <span>Total</span>
        <span className="amt">${fmt(total)} ARS</span>
      </div>
    </div>
  );
}

function StepDone({ tier, qty, total, form }) {
  return (
    <div className="success">
      <div className="tag acc">PAGO CONFIRMADO · ORDEN #TM26-{Math.floor(10000 + Math.random() * 90000)}</div>
      <h3 className="big">¡Listo! <em>Nos vemos en Pampa.</em></h3>
      <p className="dim" style={{ maxWidth: 380, margin: "0 auto", fontSize: 14, lineHeight: 1.5 }}>
        Te enviamos {qty} {qty === 1 ? "entrada" : "entradas"} a <strong style={{ color: "var(--fg)" }}>{form.email || "tu email"}</strong>. Presentá el QR + DNI en puerta.
      </p>

      <div className="ticket">
        <div className="ticket-top">
          <div className="ev">{DATA.featured.code}</div>
          <div className="sub">{DATA.featured.venue} · {DATA.featured.city}</div>
          <div className="sub">{DATA.featured.dateLabel} · {DATA.featured.year} · {DATA.featured.doors}</div>
        </div>
        <div className="ticket-bot">
          <div className="meta">
            <div>TITULAR · <strong>{form.fullName || "Tommy Fan"}</strong></div>
            <div>TIER · <strong>{tier.name}</strong></div>
            <div>CANT · <strong>{qty}</strong></div>
            <div>TOTAL · <strong>${fmt(total)} ARS</strong></div>
          </div>
          <div className="qr" aria-label="QR de entrada"></div>
        </div>
      </div>

      <div className="tag dim">RECIBÍ AVISOS DE PUERTAS Y LINE-UP UN DÍA ANTES</div>
    </div>
  );
}

window.Checkout = Checkout;
