// pages-checkout.jsx — Cart, Checkout, Wishlist

const { useState: useC1 } = React;

/* ============================ CART PAGE ============================ */
function CartPage() {
  const { goto, cart, updateCart, clearCart } = useShop();
  const items = cart.map((c) => ({ ...c, product: ORAH_PRODUCTS.find((p) => p.id === c.productId) })).filter((x) => x.product);
  const subtotal = items.reduce((a, b) => a + b.product.price * b.qty, 0);
  const frete = subtotal > 250 ? 0 : subtotal > 0 ? 24.9 : 0;
  const total = subtotal + frete;
  const [coupon, setCoupon] = useC1("");

  return (
    <main>
      <div className="wrap" style={{ paddingTop: 32 }}>
        <div className="mono muted">
          <span onClick={() => goto("home")} style={{ cursor: "pointer" }}>home</span> / sacola
        </div>
      </div>

      <section className="section" style={{ paddingTop: 24 }}>
        <div className="wrap">
          <div className="row" style={{ justifyContent: "space-between", alignItems: "end", marginBottom: 32 }}>
            <h1 className="t-xl">sua sacola.</h1>
            <span className="mono muted">{items.length} {items.length === 1 ? "peça" : "peças"}</span>
          </div>

          {items.length === 0 ? (
            <div className="card" style={{ textAlign: "center", padding: 64 }}>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 48 }}>nada por aqui ainda.</div>
              <div style={{ fontFamily: "var(--f-hand)", fontSize: 28, color: "var(--brand)", marginTop: 12 }}>tá esperando o quê?</div>
              <button className="btn brand lg" style={{ marginTop: 32 }} onClick={() => goto("shop")}>ir pra loja</button>
            </div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 40 }} className="cart-grid">
              {/* line items */}
              <div>
                <div style={{ border: "1px solid var(--ink-line)", borderRadius: 12, overflow: "hidden" }}>
                  {items.map((it, idx) => (
                    <div key={idx} className="row gap-4" style={{ padding: 18, borderBottom: idx < items.length - 1 ? "1px solid var(--ink-line)" : "none", alignItems: "flex-start" }}>
                      <div style={{ width: 120, height: 150, borderRadius: 8, overflow: "hidden", flexShrink: 0 }}>
                        <ProductVisual product={it.product} />
                      </div>
                      <div style={{ flex: 1 }}>
                        <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
                          <div>
                            <div style={{ fontFamily: "var(--f-display)", fontSize: 28, textTransform: "uppercase", lineHeight: 1 }}>{it.product.name}</div>
                            <div className="mono muted" style={{ marginTop: 6 }}>{it.product.line} · {it.product.drop}</div>
                            <div className="row gap-3" style={{ marginTop: 12 }}>
                              <span className="badge">Tamanho {it.size}</span>
                              <span className="badge">azul</span>
                            </div>
                          </div>
                          <button className="icon-btn" onClick={() => updateCart(idx, 0)} title="Remover"><Icon name="trash" size={16} /></button>
                        </div>

                        <div className="row" style={{ justifyContent: "space-between", marginTop: 18 }}>
                          <div className="row" style={{ border: "1px solid var(--ink-line)", borderRadius: 999 }}>
                            <button className="icon-btn" style={{ width: 32, height: 32 }} onClick={() => updateCart(idx, it.qty - 1)}><Icon name="minus" size={14} /></button>
                            <span style={{ minWidth: 28, textAlign: "center", fontWeight: 700 }}>{it.qty}</span>
                            <button className="icon-btn" style={{ width: 32, height: 32 }} onClick={() => updateCart(idx, it.qty + 1)}><Icon name="plus" size={14} /></button>
                          </div>
                          <div style={{ fontFamily: "var(--f-display)", fontSize: 24 }}>R$ {(it.product.price * it.qty).toFixed(2).replace(".", ",")}</div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                <div className="row" style={{ marginTop: 16, justifyContent: "space-between" }}>
                  <button className="btn ghost sm" onClick={() => goto("shop")}>← continuar comprando</button>
                  <button className="btn ghost sm" onClick={clearCart}>esvaziar</button>
                </div>
              </div>

              {/* summary */}
              <div>
                <div className="card" style={{ padding: 24 }}>
                  <div style={{ fontFamily: "var(--f-display)", fontSize: 28, textTransform: "uppercase", marginBottom: 16 }}>resumo</div>

                  <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 14 }}>
                    <div className="row" style={{ justifyContent: "space-between" }}><span>Subtotal</span><span>R$ {subtotal.toFixed(2).replace(".", ",")}</span></div>
                    <div className="row" style={{ justifyContent: "space-between" }}>
                      <span>Frete {frete === 0 && subtotal > 0 && <span style={{ color: "var(--accent)", fontWeight: 700 }}>· grátis!</span>}</span>
                      <span>{frete === 0 ? "—" : "R$ " + frete.toFixed(2).replace(".", ",")}</span>
                    </div>
                  </div>

                  <div style={{ marginTop: 16 }}>
                    <label>Cupom</label>
                    <div className="row gap-2">
                      <input value={coupon} onChange={(e) => setCoupon(e.target.value)} placeholder="ORAH10" />
                      <button className="btn sm">aplicar</button>
                    </div>
                  </div>

                  <div className="hr" style={{ margin: "20px 0" }}></div>

                  <div className="row" style={{ justifyContent: "space-between", alignItems: "baseline" }}>
                    <span className="mono muted">Total</span>
                    <span style={{ fontFamily: "var(--f-display)", fontSize: 40, color: "var(--brand)" }}>R$ {total.toFixed(2).replace(".", ",")}</span>
                  </div>
                  <div className="mono muted" style={{ fontSize: 11, marginTop: 4 }}>
                    em até 3x de R$ {(total / 3).toFixed(2).replace(".", ",")} sem juros
                  </div>

                  <button className="btn brand block lg" style={{ marginTop: 20 }} onClick={() => goto("checkout")}>
                    finalizar compra <Icon name="arrowR" size={14} />
                  </button>

                  <div className="mono muted" style={{ textAlign: "center", marginTop: 16, fontSize: 10 }}>
                    pagamento seguro · pix · cartão · boleto
                  </div>
                </div>

                <div className="card" style={{ marginTop: 16, padding: 18, background: "var(--brand)", color: "var(--on-brand)", border: "none" }}>
                  <div style={{ fontFamily: "var(--f-hand)", fontSize: 22 }}>frete grátis</div>
                  <div className="mono" style={{ opacity: 0.8, marginTop: 4 }}>acima de R$ 250 · falta R$ {Math.max(0, 250 - subtotal).toFixed(2).replace(".", ",")}</div>
                  <div style={{ height: 6, background: "rgba(255,255,255,0.2)", borderRadius: 999, marginTop: 10, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: Math.min(100, (subtotal / 250) * 100) + "%", background: "var(--accent-warm)" }}></div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </section>

      <style>{`
        .viewport-frame[data-vp="mobile"] .cart-grid { grid-template-columns: 1fr; gap: 24px; }
      `}</style>
    </main>
  );
}

/* ============================ CHECKOUT ============================ */
function CheckoutPage() {
  const { goto, cart, clearCart, currentUser } = useShop();
  const [step, setStep] = useC1(1);
  const [paymentMethod, setPm] = useC1("pix");
  const items = cart.map((c) => ({ ...c, product: ORAH_PRODUCTS.find((p) => p.id === c.productId) })).filter((x) => x.product);
  const subtotal = items.reduce((a, b) => a + b.product.price * b.qty, 0);
  const ckUser = currentUser || { firstName: "", fullName: "", email: "" };
  const ckLastName = ckUser.fullName ? ckUser.fullName.split(" ").slice(1).join(" ") : "";
  const frete = subtotal > 250 ? 0 : 24.9;
  const total = subtotal + frete;

  const steps = [
    { n: 1, label: "Identificação" },
    { n: 2, label: "Entrega" },
    { n: 3, label: "Pagamento" },
    { n: 4, label: "Confirmação" },
  ];

  if (items.length === 0 && step < 4) {
    return (
      <main>
        <div className="wrap" style={{ padding: "80px 24px", textAlign: "center" }}>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 48 }}>sua sacola está vazia</div>
          <button className="btn brand lg" style={{ marginTop: 24 }} onClick={() => goto("shop")}>ver loja</button>
        </div>
      </main>
    );
  }

  return (
    <main>
      <div style={{ background: "var(--brand)", color: "var(--on-brand)", padding: "24px 0" }}>
        <div className="wrap row" style={{ justifyContent: "space-between" }}>
          <div className="row gap-3">
            <span style={{ width: 36, height: 36, borderRadius: "50%", overflow: "hidden", border: "1.5px solid currentColor" }}>
              <img src="assets/orah-logo.png" alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            </span>
            <span style={{ fontFamily: "var(--f-display)", fontSize: 22 }}>ORAH · CHECKOUT</span>
          </div>
          <div className="row gap-2 mono" style={{ fontSize: 11, opacity: 0.85 }}>
            <Icon name="check" size={14} /> ambiente seguro
          </div>
        </div>
      </div>

      <div className="wrap" style={{ paddingTop: 32 }}>
        {/* stepper */}
        <div className="row" style={{ justifyContent: "space-between", marginBottom: 32, flexWrap: "wrap", gap: 8 }} className="ck-steps">
          {steps.map((s, i) => (
            <div key={s.n} className="row gap-2" style={{ flex: 1, minWidth: 140 }}>
              <div style={{
                width: 32, height: 32, borderRadius: "50%",
                background: step >= s.n ? "var(--brand)" : "var(--bg-alt)",
                color: step >= s.n ? "var(--on-brand)" : "var(--ink-soft)",
                display: "grid", placeItems: "center",
                fontFamily: "var(--f-display)", fontSize: 16,
                flexShrink: 0,
              }}>{s.n}</div>
              <span style={{ fontWeight: 700, fontSize: 13, color: step >= s.n ? "var(--ink)" : "var(--ink-soft)", textTransform: "uppercase", letterSpacing: 0.05 }}>{s.label}</span>
              {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: "var(--ink-line)" }} className="only-desktop"></div>}
            </div>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: step === 4 ? "1fr" : "1.5fr 1fr", gap: 40 }} className="ck-grid">
          <div>
            {step === 1 && (
              <div className="card">
                <h2 className="t-md">identificação</h2>
                <p className="muted" style={{ marginTop: 4 }}>pra gente saber pra quem mandar.</p>
                <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 16 }}>
                  <div><label>email</label><input key={ckUser.email || "ck-email"} defaultValue={ckUser.email || "voce@email.com"} /></div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                    <div><label>nome</label><input key={ckUser.firstName || "ck-fn"} defaultValue={ckUser.firstName} placeholder="seu nome" /></div>
                    <div><label>sobrenome</label><input key={ckLastName || "ck-ln"} defaultValue={ckLastName} placeholder="sobrenome" /></div>
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                    <div><label>cpf</label><input placeholder="000.000.000-00" /></div>
                    <div><label>celular</label><input placeholder="(00) 00000-0000" /></div>
                  </div>
                  <label className="row gap-2" style={{ textTransform: "none", marginBottom: 0, color: "var(--ink)", fontSize: 13 }}>
                    <input type="checkbox" defaultChecked style={{ width: 18, height: 18 }} /> quero receber os próximos drops por email
                  </label>
                </div>
                <button className="btn brand block lg" style={{ marginTop: 24 }} onClick={() => setStep(2)}>continuar pra entrega →</button>
              </div>
            )}

            {step === 2 && (
              <div className="card">
                <h2 className="t-md">entrega</h2>
                <p className="muted" style={{ marginTop: 4 }}>onde quer receber?</p>
                <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 16 }}>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 12 }}>
                    <div><label>cep</label><input placeholder="00000-000" /></div>
                    <div><label>endereço</label><input placeholder="rua, av…" /></div>
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr 1fr", gap: 12 }}>
                    <div><label>número</label><input /></div>
                    <div><label>complemento</label><input /></div>
                    <div><label>uf</label><input placeholder="PR" /></div>
                  </div>
                  <div><label>cidade</label><input defaultValue="Ponta Grossa" placeholder="cidade" /></div>
                </div>

                <div style={{ marginTop: 24 }}>
                  <label>opções de frete</label>
                  {[
                    { id: "sedex", l: "Sedex", t: "3-5 dias úteis", p: 24.9 },
                    { id: "pac", l: "PAC", t: "7-10 dias úteis", p: 14.9 },
                    { id: "retira", l: "Retirar em Ponta Grossa", t: "agendar", p: 0 },
                  ].map((o, i) => (
                    <label key={o.id} className="row" style={{
                      justifyContent: "space-between", padding: 14, marginTop: 8,
                      border: i === 0 ? "2px solid var(--brand)" : "1px solid var(--ink-line)",
                      borderRadius: 10, cursor: "pointer", textTransform: "none", color: "var(--ink)", fontSize: 14,
                    }}>
                      <div className="row gap-3">
                        <input type="radio" name="frete" defaultChecked={i === 0} />
                        <div><div style={{ fontWeight: 700 }}>{o.l}</div><div className="muted">{o.t}</div></div>
                      </div>
                      <span style={{ fontWeight: 700 }}>{o.p === 0 ? "grátis" : "R$ " + o.p.toFixed(2).replace(".", ",")}</span>
                    </label>
                  ))}
                </div>

                <div className="row gap-2" style={{ marginTop: 24 }}>
                  <button className="btn ghost" onClick={() => setStep(1)}>← voltar</button>
                  <button className="btn brand fill" onClick={() => setStep(3)}>continuar pra pagamento →</button>
                </div>
              </div>
            )}

            {step === 3 && (
              <div className="card">
                <h2 className="t-md">pagamento</h2>
                <p className="muted" style={{ marginTop: 4 }}>como quer pagar?</p>

                <div className="row gap-2" style={{ marginTop: 20, flexWrap: "wrap" }}>
                  {[
                    { id: "pix", l: "Pix", d: "5% off" },
                    { id: "card", l: "Cartão", d: "até 3x sem juros" },
                    { id: "boleto", l: "Boleto", d: "vence em 3 dias" },
                  ].map((m) => (
                    <button key={m.id} onClick={() => setPm(m.id)} style={{
                      flex: 1, minWidth: 140, padding: 16,
                      borderRadius: 10,
                      border: paymentMethod === m.id ? "2px solid var(--brand)" : "1px solid var(--ink-line)",
                      background: paymentMethod === m.id ? "var(--bg-card)" : "transparent",
                      cursor: "pointer", textAlign: "left",
                      color: "var(--ink)", fontFamily: "var(--f-body)",
                    }}>
                      <div style={{ fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.05, fontSize: 14 }}>{m.l}</div>
                      <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>{m.d}</div>
                    </button>
                  ))}
                </div>

                {paymentMethod === "card" && (
                  <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 16 }}>
                    <div><label>número do cartão</label><input placeholder="0000 0000 0000 0000" /></div>
                    <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 12 }}>
                      <div><label>nome impresso</label><input /></div>
                      <div><label>validade</label><input placeholder="MM/AA" /></div>
                      <div><label>cvv</label><input placeholder="123" /></div>
                    </div>
                    <div><label>parcelas</label>
                      <select>
                        <option>1x de R$ {total.toFixed(2).replace(".", ",")}</option>
                        <option>2x de R$ {(total/2).toFixed(2).replace(".", ",")}</option>
                        <option>3x de R$ {(total/3).toFixed(2).replace(".", ",")}</option>
                      </select>
                    </div>
                  </div>
                )}

                {paymentMethod === "pix" && (
                  <div className="card" style={{ marginTop: 20, background: "var(--bg-alt)", textAlign: "center" }}>
                    <div className="mono muted">qr code aparece após confirmar</div>
                    <div style={{ width: 180, height: 180, margin: "16px auto", border: "1px solid var(--ink-line)", borderRadius: 12, display: "grid", placeItems: "center", background: "var(--bg-card)" }}>
                      <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, opacity: 0.5 }}>[ qr code pix ]</div>
                    </div>
                    <div style={{ fontFamily: "var(--f-hand)", fontSize: 22, color: "var(--brand)" }}>5% de desconto no pix!</div>
                  </div>
                )}

                {paymentMethod === "boleto" && (
                  <div className="card" style={{ marginTop: 20, background: "var(--bg-alt)" }}>
                    <div className="mono muted">o boleto será gerado em seguida.</div>
                    <div style={{ marginTop: 12, fontSize: 14 }}>vencimento em 3 dias úteis. enviado por email.</div>
                  </div>
                )}

                <div className="row gap-2" style={{ marginTop: 24 }}>
                  <button className="btn ghost" onClick={() => setStep(2)}>← voltar</button>
                  <button className="btn fire fill lg" onClick={() => { setStep(4); setTimeout(() => clearCart(), 500); }}>
                    pagar R$ {total.toFixed(2).replace(".", ",")} <Icon name="check" size={16} />
                  </button>
                </div>
              </div>
            )}

            {step === 4 && (
              <div className="card" style={{ textAlign: "center", padding: 48 }}>
                <div style={{
                  width: 80, height: 80, borderRadius: "50%",
                  background: "var(--brand)", color: "var(--on-brand)",
                  display: "grid", placeItems: "center", margin: "0 auto 16px",
                }}>
                  <Icon name="check" size={36} />
                </div>
                <h2 className="t-lg">pedido confirmado!</h2>
                <div style={{ fontFamily: "var(--f-hand)", fontSize: 28, color: "var(--brand)", marginTop: 8 }}>
                  Deus abençoe sua compra.
                </div>
                <div className="mono muted" style={{ marginTop: 16 }}>número do pedido</div>
                <div style={{ fontFamily: "var(--f-display)", fontSize: 36, marginTop: 4 }}>#ORAH-0043</div>

                <p style={{ maxWidth: 480, margin: "24px auto", color: "var(--ink-soft)" }}>
                  Enviamos uma confirmação pro seu email. Você pode acompanhar o status no seu painel de pedidos.
                </p>

                <div className="row gap-2" style={{ justifyContent: "center" }}>
                  <button className="btn" onClick={() => goto("account")}>ver meu pedido</button>
                  <button className="btn ghost" onClick={() => goto("home")}>voltar pra home</button>
                </div>
              </div>
            )}
          </div>

          {step < 4 && (
            <div>
              <div className="card" style={{ position: "sticky", top: 96 }}>
                <div style={{ fontFamily: "var(--f-display)", fontSize: 22, textTransform: "uppercase", marginBottom: 12 }}>seu pedido</div>
                {items.map((it, i) => (
                  <div key={i} className="row gap-3" style={{ paddingBottom: 12, borderBottom: "1px solid var(--ink-line)", marginBottom: 12 }}>
                    <div style={{ width: 56, height: 70, borderRadius: 6, overflow: "hidden" }}><ProductVisual product={it.product} /></div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 700, fontSize: 13, textTransform: "uppercase" }}>{it.product.name}</div>
                      <div className="muted" style={{ fontSize: 12 }}>Tam. {it.size} · qty {it.qty}</div>
                    </div>
                    <div style={{ fontWeight: 700, fontSize: 13 }}>R$ {(it.product.price * it.qty).toFixed(0)}</div>
                  </div>
                ))}
                <div className="stack gap-2" style={{ fontSize: 13 }}>
                  <div className="row" style={{ justifyContent: "space-between" }}><span>Subtotal</span><span>R$ {subtotal.toFixed(2).replace(".", ",")}</span></div>
                  <div className="row" style={{ justifyContent: "space-between" }}><span>Frete</span><span>{frete === 0 ? "grátis" : "R$ " + frete.toFixed(2).replace(".", ",")}</span></div>
                </div>
                <div className="hr" style={{ margin: "12px 0" }}></div>
                <div className="row" style={{ justifyContent: "space-between" }}>
                  <span style={{ fontFamily: "var(--f-display)", fontSize: 20 }}>TOTAL</span>
                  <span style={{ fontFamily: "var(--f-display)", fontSize: 28, color: "var(--brand)" }}>R$ {total.toFixed(2).replace(".", ",")}</span>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      <style>{`
        .viewport-frame[data-vp="mobile"] .ck-grid { grid-template-columns: 1fr; }
        .viewport-frame[data-vp="mobile"] .ck-steps { gap: 4px; }
        .viewport-frame[data-vp="mobile"] .ck-steps > div { min-width: 0; }
        .viewport-frame[data-vp="mobile"] .ck-steps > div span { display: none; }
      `}</style>
    </main>
  );
}

/* ============================ WISHLIST ============================ */
function WishlistPage() {
  const { goto, wish, toggleWish, addToCart, setDrawer } = useShop();
  const items = wish.map((id) => ORAH_PRODUCTS.find((p) => p.id === id)).filter(Boolean);

  return (
    <main>
      <div className="wrap" style={{ paddingTop: 32 }}>
        <div className="mono muted">
          <span onClick={() => goto("home")} style={{ cursor: "pointer" }}>home</span> / lista de desejos
        </div>
      </div>

      <section className="section" style={{ paddingTop: 24 }}>
        <div className="wrap">
          <div className="row" style={{ justifyContent: "space-between", alignItems: "end", marginBottom: 32, flexWrap: "wrap", gap: 12 }}>
            <div>
              <h1 className="t-xl">desejos.</h1>
              <div style={{ fontFamily: "var(--f-hand)", fontSize: 24, color: "var(--brand)" }}>guardadas pra depois.</div>
            </div>
            <span className="mono muted">{items.length} {items.length === 1 ? "peça" : "peças"}</span>
          </div>

          {items.length === 0 ? (
            <div className="card" style={{ textAlign: "center", padding: 64 }}>
              <Icon name="heart" size={48} />
              <div style={{ fontFamily: "var(--f-display)", fontSize: 32, marginTop: 16 }}>nada guardado ainda.</div>
              <p className="muted" style={{ marginTop: 8 }}>clica no ♡ das peças que você ama, elas aparecem aqui.</p>
              <button className="btn brand lg" style={{ marginTop: 24 }} onClick={() => goto("shop")}>explorar loja</button>
            </div>
          ) : (
            <div className="products-grid">
              {items.map((p) => (
                <div key={p.id}>
                  <ProductCard product={p} onClick={(pr) => goto({ name: "product", params: { id: pr.id } })} />
                  <div className="row gap-2" style={{ marginTop: 8 }}>
                    <button className="btn fill sm" onClick={(e) => { e.stopPropagation(); addToCart(p.id, "M", 1); setDrawer("cart"); }}>
                      <Icon name="bag" size={14} /> sacola
                    </button>
                    <button className="btn ghost sm" onClick={() => toggleWish(p.id)}>remover</button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { CartPage, CheckoutPage, WishlistPage });
