/* global React, useApp, Photo, Icon, NEIGHBORHOODS */
const { useState: useStateC, useMemo: useMemoC } = React;

const FEES = { Centro: 6, "Rua das Pedras": 6, Ossos: 7, Armação: 8, Geribá: 9, Manguinhos: 9, Ferradura: 11, "João Fernandes": 12 };
const PROMOS = { BREAK10: { type: "pct", val: 0.1, label: "10% de desconto" }, VERAO15: { type: "pct", val: 0.15, label: "15% de desconto" }, SOL5: { type: "flat", val: 5, label: "R$ 5 de desconto" } };
const WA_NUMBER = "5522999990000";

function Checkout() {
  const { cart, subtotal, nav, setQty, removeItem, clearCart, showToast } = useApp();
  const [mode, setMode] = useStateC("delivery");
  const [when, setWhen] = useStateC("asap");
  const [time, setTime] = useStateC("");
  const [pay, setPay] = useStateC("pix");
  const [form, setForm] = useStateC({ name: "", phone: "", bairro: "Centro", street: "", number: "", ref: "", notes: "" });
  const [promo, setPromo] = useStateC("");
  const [applied, setApplied] = useStateC(null);
  const [promoErr, setPromoErr] = useStateC("");
  const [placed, setPlaced] = useStateC(null);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const fee = mode === "delivery" ? (FEES[form.bairro] ?? 9) : 0;
  const discount = useMemoC(() => {
    if (!applied) return 0;
    const p = PROMOS[applied];
    return p.type === "pct" ? Math.round(subtotal * p.val) : Math.min(p.val, subtotal);
  }, [applied, subtotal]);
  const total = Math.max(0, subtotal + fee - discount);

  const applyPromo = () => {
    const code = promo.trim().toUpperCase();
    if (PROMOS[code]) { setApplied(code); setPromoErr(""); showToast("Cupom aplicado! " + PROMOS[code].label); }
    else { setApplied(null); setPromoErr("Cupom inválido. Tente BREAK10."); }
  };

  const valid = cart.length > 0 && form.name.trim() && form.phone.trim() && (mode === "pickup" || (form.street.trim() && form.number.trim())) && (when === "asap" || time);

  const buildMessage = () => {
    let m = `*Novo pedido — Break Búzios* %0A%0A`;
    cart.forEach((it) => { m += `• ${it.qty}x ${it.name}${it.note && it.note !== "Tradicional" ? ` _(${it.note})_` : ""} — R$ ${(it.unit * it.qty).toFixed(0)}%0A`; });
    m += `%0A*${mode === "delivery" ? "Entrega" : "Retirada no balcão"}*%0A`;
    if (mode === "delivery") m += `${form.street}, ${form.number} — ${form.bairro}${form.ref ? ` (${form.ref})` : ""}%0A`;
    m += `Quando: ${when === "asap" ? "O quanto antes" : "Agendado " + time}%0A`;
    m += `Pagamento: ${pay === "pix" ? "Pix online" : pay === "card" ? "Cartão online" : "Combinar no WhatsApp"}%0A%0A`;
    m += `Subtotal: R$ ${subtotal}${fee ? `%0AEntrega: R$ ${fee}` : ""}${discount ? `%0ADesconto: -R$ ${discount}` : ""}%0A*Total: R$ ${total}*%0A%0ACliente: ${form.name} — ${form.phone}`;
    return m;
  };

  const place = () => {
    const order = { id: "BRK" + Math.floor(1000 + Math.random() * 9000), mode, total, pay, when, time, name: form.name };
    if (pay === "whats") window.open(`https://wa.me/${WA_NUMBER}?text=${buildMessage()}`, "_blank");
    setPlaced(order);
    clearCart();
    window.scrollTo({ top: 0 });
  };

  if (placed) return <Success order={placed} />;

  if (cart.length === 0) return (
    <main className="page wrap" style={{ padding: "80px 24px", textAlign: "center" }}>
      <div style={{ opacity: .4, marginBottom: 16 }}><Icon name="bag2" size={64} stroke={1.3} /></div>
      <h1 style={{ fontSize: 32 }}>Seu carrinho está vazio</h1>
      <p className="muted" style={{ marginTop: 10, fontSize: 17 }}>Escolha seus sanduíches favoritos para continuar.</p>
      <button className="btn btn-amber btn-lg" style={{ marginTop: 26 }} onClick={() => nav("/cardapio")}>Ver cardápio <Icon name="arrow" size={18} /></button>
    </main>
  );

  return (
    <main className="page">
      <section style={{ background: "var(--pine)", padding: "36px 0 34px" }}>
        <div className="wrap"><span className="dash-label" style={{ color: "var(--cream-50)" }}>Finalizar pedido</span>
          <h1 style={{ color: "var(--cream-50)", fontSize: "clamp(30px,4vw,46px)", marginTop: 12 }}>Quase lá 🌅</h1></div>
      </section>

      <section className="section" style={{ paddingTop: 40 }}>
        <div className="wrap checkout-grid">
          {/* LEFT: form */}
          <div>
            {/* mode */}
            <div className="card" style={{ padding: 22, marginBottom: 20 }}>
              <h3 style={{ fontSize: 17, marginBottom: 14 }}>Como você quer receber?</h3>
              <div className="seg" style={{ gridTemplateColumns: "1fr 1fr" }}>
                <button className={mode === "delivery" ? "on" : ""} onClick={() => setMode("delivery")}><Icon name="bike" size={22} />Entrega<small>~30–40 min</small></button>
                <button className={mode === "pickup" ? "on" : ""} onClick={() => setMode("pickup")}><Icon name="bag2" size={22} />Retirada<small>no balcão</small></button>
              </div>
            </div>

            {/* contact */}
            <div className="card" style={{ padding: 22, marginBottom: 20 }}>
              <h3 style={{ fontSize: 17, marginBottom: 14 }}>Seus dados</h3>
              <div className="field-row">
                <div className="field"><label>Nome</label><input className="input" placeholder="Seu nome" value={form.name} onChange={(e) => set("name", e.target.value)} /></div>
                <div className="field"><label>WhatsApp</label><input className="input" placeholder="(22) 9 9999-0000" value={form.phone} onChange={(e) => set("phone", e.target.value)} /></div>
              </div>
            </div>

            {/* address */}
            {mode === "delivery" && (
              <div className="card" style={{ padding: 22, marginBottom: 20 }}>
                <h3 style={{ fontSize: 17, marginBottom: 14 }}>Endereço de entrega</h3>
                <div className="field"><label>Bairro</label>
                  <select className="select" value={form.bairro} onChange={(e) => set("bairro", e.target.value)}>
                    {NEIGHBORHOODS.map((b) => <option key={b}>{b}</option>)}
                  </select>
                </div>
                <div className="field-row">
                  <div className="field" style={{ gridColumn: "span 1" }}><label>Rua</label><input className="input" placeholder="Nome da rua" value={form.street} onChange={(e) => set("street", e.target.value)} /></div>
                  <div className="field"><label>Número</label><input className="input" placeholder="123" value={form.number} onChange={(e) => set("number", e.target.value)} /></div>
                </div>
                <div className="field"><label>Complemento / referência</label><input className="input" placeholder="Apto, bloco, ponto de referência" value={form.ref} onChange={(e) => set("ref", e.target.value)} /></div>
              </div>
            )}

            {/* schedule */}
            <div className="card" style={{ padding: 22, marginBottom: 20 }}>
              <h3 style={{ fontSize: 17, marginBottom: 14 }}>Quando?</h3>
              <div className="seg" style={{ gridTemplateColumns: "1fr 1fr", marginBottom: when === "sched" ? 14 : 0 }}>
                <button className={when === "asap" ? "on" : ""} onClick={() => setWhen("asap")}><Icon name="clock" size={20} />O quanto antes</button>
                <button className={when === "sched" ? "on" : ""} onClick={() => setWhen("sched")}><Icon name="cal" size={20} />Agendar</button>
              </div>
              {when === "sched" && (
                <div className="field-row">
                  <div className="field" style={{ marginBottom: 0 }}><label>Horário</label>
                    <select className="select" value={time} onChange={(e) => setTime(e.target.value)}>
                      <option value="">Selecione</option>
                      {["12:00", "12:30", "13:00", "13:30", "19:00", "19:30", "20:00", "20:30", "21:00"].map((t) => <option key={t}>{t}</option>)}
                    </select>
                  </div>
                  <div className="field" style={{ marginBottom: 0 }}><label>Observações</label><input className="input" placeholder="Ex.: caprichar no molho" value={form.notes} onChange={(e) => set("notes", e.target.value)} /></div>
                </div>
              )}
            </div>

            {/* payment */}
            <div className="card" style={{ padding: 22 }}>
              <h3 style={{ fontSize: 17, marginBottom: 14 }}>Pagamento</h3>
              {[["pix", "pix", "Pix online", "Aprovação na hora"], ["card", "card", "Cartão online", "Crédito ou débito"], ["whats", "whats", "Combinar no WhatsApp", "Fala direto com a gente"]].map(([id, ic, t, s]) => (
                <div key={id} className={"opt" + (pay === id ? " sel" : "")} onClick={() => setPay(id)} style={{ marginBottom: 9 }}>
                  <div className="opt-l"><span className="opt-check" style={{ borderRadius: "50%" }}>{pay === id && <Icon name="check" size={14} />}</span>
                    <Icon name={ic} size={20} style={{ color: "var(--pine)" }} />
                    <span><b style={{ fontFamily: "var(--font-d)" }}>{t}</b><br /><span className="muted" style={{ fontSize: 13 }}>{s}</span></span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* RIGHT: summary */}
          <div className="summary">
            <div className="card" style={{ padding: 22 }}>
              <h3 style={{ fontSize: 18, marginBottom: 16 }}>Resumo do pedido</h3>
              <div style={{ maxHeight: 230, overflow: "auto", marginBottom: 6 }}>
                {cart.map((it) => (
                  <div key={it.lineId} style={{ display: "flex", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--line)" }}>
                    <Photo tone={it.tone} icon="sun" src={it.image} alt="" style={{ width: 48, height: 48, borderRadius: 10, flexShrink: 0 }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: "var(--font-d)", fontWeight: 600, fontSize: 14.5, color: "var(--pine)" }}>{it.name}</div>
                      {it.note && it.note !== "Tradicional" && <div style={{ fontSize: 12, color: "var(--muted)" }}>{it.note}</div>}
                      <div className="mini-step" style={{ marginTop: 5 }}>
                        <button onClick={() => setQty(it.lineId, it.qty - 1)}><Icon name="minus" size={13} /></button>
                        <span>{it.qty}</span>
                        <button onClick={() => setQty(it.lineId, it.qty + 1)}><Icon name="plus" size={13} /></button>
                      </div>
                    </div>
                    <strong style={{ fontFamily: "var(--font-d)", color: "var(--pine)", fontSize: 14.5 }}>R$ {it.unit * it.qty}</strong>
                  </div>
                ))}
              </div>

              {/* promo */}
              <div style={{ display: "flex", gap: 8, margin: "16px 0 8px" }}>
                <input className="input" placeholder="Cupom (ex.: BREAK10)" value={promo} onChange={(e) => setPromo(e.target.value)} style={{ textTransform: "uppercase" }} />
                <button className="btn btn-ghost btn-sm" onClick={applyPromo}>Aplicar</button>
              </div>
              {promoErr && <div style={{ color: "#c0492f", fontSize: 13, marginBottom: 6 }}>{promoErr}</div>}
              {applied && <div style={{ color: "var(--ok)", fontSize: 13, marginBottom: 6, display: "flex", alignItems: "center", gap: 6 }}><Icon name="spark" size={15} /> {PROMOS[applied].label} aplicado</div>}

              <div className="divider" />
              <div className="row-line"><span>Subtotal</span><span>R$ {subtotal}</span></div>
              <div className="row-line"><span>{mode === "delivery" ? `Entrega · ${form.bairro}` : "Retirada"}</span><span>{fee ? `R$ ${fee}` : "Grátis"}</span></div>
              {discount > 0 && <div className="row-line" style={{ color: "var(--ok)" }}><span>Desconto</span><span>- R$ {discount}</span></div>}
              <div className="row-line total"><span>Total</span><span>R$ {total}</span></div>

              <button className="btn btn-amber btn-block btn-lg" style={{ marginTop: 14 }} disabled={!valid} onClick={place}>
                {pay === "whats" ? <><Icon name="whats" size={19} /> Enviar pelo WhatsApp</> : <>Pagar R$ {total}</>}
              </button>
              {!valid && <p className="muted center" style={{ fontSize: 12.5, marginTop: 10 }}>Preencha seus dados {mode === "delivery" ? "e endereço " : ""}para continuar</p>}
              <div className="center" style={{ marginTop: 12, display: "flex", gap: 8, justifyContent: "center", color: "var(--muted)", fontSize: 12 }}>
                <Icon name="spark" size={14} /> Você acumula {Math.round(total * 0.1)} pontos no Clube Break
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function Success({ order }) {
  const { nav } = useApp();
  return (
    <main className="page wrap" style={{ padding: "70px 24px", maxWidth: 640 }}>
      <div className="card center" style={{ padding: "44px 32px" }}>
        <div style={{ width: 76, height: 76, borderRadius: "50%", background: "var(--ok)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 22px" }}><Icon name="check" size={40} /></div>
        <span className="badge-amber">Pedido #{order.id}</span>
        <h1 style={{ fontSize: 32, marginTop: 14 }}>Pedido confirmado!</h1>
        <p className="muted" style={{ fontSize: 17, marginTop: 10 }}>
          Valeu, {order.name.split(" ")[0]}! {order.pay === "whats" ? "Confirme os detalhes na conversa do WhatsApp que abrimos pra você." : `Recebemos seu pagamento via ${order.pay === "pix" ? "Pix" : "cartão"}.`}
        </p>
        <div style={{ display: "flex", justifyContent: "center", gap: 22, margin: "26px 0", flexWrap: "wrap" }}>
          <div><div style={{ fontFamily: "var(--font-d)", fontWeight: 700, fontSize: 22, color: "var(--pine)" }}>{order.mode === "delivery" ? "Entrega" : "Retirada"}</div><span className="muted" style={{ fontSize: 13 }}>{order.when === "asap" ? "O quanto antes" : "Às " + order.time}</span></div>
          <div><div style={{ fontFamily: "var(--font-d)", fontWeight: 700, fontSize: 22, color: "var(--pine)" }}>R$ {order.total}</div><span className="muted" style={{ fontSize: 13 }}>Total pago</span></div>
          <div><div style={{ fontFamily: "var(--font-d)", fontWeight: 700, fontSize: 22, color: "var(--pine)" }}>~30 min</div><span className="muted" style={{ fontSize: 13 }}>Tempo estimado</span></div>
        </div>
        <div className="divider" />
        <p className="muted" style={{ fontSize: 14 }}>Acompanhe o preparo — a gente avisa quando estiver a caminho 🌅</p>
        <button className="btn btn-pine btn-lg" style={{ marginTop: 22 }} onClick={() => nav("/")}>Voltar ao início</button>
      </div>
    </main>
  );
}
Object.assign(window, { Checkout });
