// account.jsx — auth chip na nav + página de "Meus pedidos" (rota #/pedidos e #/pedido/:code)

const { useState: useAcState, useEffect: useAcEffect, useCallback: useAcCb } = React;

const acFmt = (cents) => "R$ " + (cents / 100).toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const acDt = (s) => s ? new Date(s).toLocaleString("pt-BR") : "—";
const STATUS_LABEL = {
  pending_payment: "Aguardando pagamento",
  paid: "Pagamento confirmado",
  processing: "Em produção",
  shipped: "Enviado",
  delivered: "Entregue",
  cancelled: "Cancelado",
  refunded: "Reembolsado"
};

// ── Chip de auth na nav ──────────────────────────────────────────────────────
function AuthChip() {
  const auth = useAuth();
  const [mode, setMode] = useAcState(null); // null | "login" | "register"
  const [form, setForm] = useAcState({ email: "", password: "", name: "", phone: "" });
  const [err, setErr] = useAcState("");
  const [busy, setBusy] = useAcState(false);

  if (auth?.loading) return <span className="nav-ig mono">…</span>;

  if (auth?.user) {
    return (
      <div style={{ position: "relative" }}>
        <button type="button" className="nav-ig" onClick={() => setMode(m => m ? null : "me")} title={auth.user.email}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>
          <span>{auth.user.name.split(" ")[0].toUpperCase()}</span>
        </button>
        {mode === "me" && (
          <div onMouseLeave={() => setMode(null)} style={{ position: "absolute", top: "calc(100% + 8px)", right: 0, minWidth: 220, background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 8, padding: 8, zIndex: 200 }}>
            <a href="#/pedidos" onClick={() => setMode(null)} style={{ display: "block", padding: "10px 12px", borderRadius: 4, fontSize: 12, color: "var(--fg)" }}>Meus pedidos</a>
            <button onClick={() => { auth.logout(); setMode(null); }} type="button" style={{ display: "block", width: "100%", textAlign: "left", padding: "10px 12px", borderRadius: 4, fontSize: 12, color: "var(--accent)", background: "transparent", border: 0, cursor: "pointer", fontFamily: "inherit" }}>Sair</button>
          </div>
        )}
      </div>
    );
  }

  return (
    <div style={{ position: "relative" }}>
      <button type="button" className="nav-ig" onClick={() => { setMode("login"); setErr(""); }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>
        <span>ENTRAR</span>
      </button>
      {mode && (
        <div style={{ position: "absolute", top: "calc(100% + 8px)", right: 0, width: 300, background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 8, padding: 16, zIndex: 200 }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--accent)", letterSpacing: "0.14em", marginBottom: 10 }}>{mode === "login" ? "ENTRAR" : "CRIAR CONTA"}</div>
          <form onSubmit={async (e) => {
            e.preventDefault();
            setBusy(true); setErr("");
            try {
              if (mode === "login") {
                await auth.login(form.email, form.password);
              } else {
                await auth.register({ email: form.email, password: form.password, name: form.name, phone: form.phone.replace(/\D/g, "") });
              }
              setMode(null);
            } catch (e2) {
              setErr(e2.message);
            } finally { setBusy(false); }
          }} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {mode === "register" && (
              <input required placeholder="Seu nome" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} style={inputStyle} />
            )}
            <input type="email" required placeholder="E-mail" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} style={inputStyle} />
            <input type="password" required minLength={6} placeholder="Senha" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))} style={inputStyle} />
            {mode === "register" && (
              <input placeholder="WhatsApp (opcional)" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} style={inputStyle} />
            )}
            {err && <div style={{ color: "#ff7a55", fontSize: 11 }}>{err}</div>}
            <button type="submit" disabled={busy} className="btn btn-primary" style={{ padding: "10px 14px", fontSize: 13, justifyContent: "center" }}>
              {busy ? "..." : (mode === "login" ? "ENTRAR" : "CRIAR CONTA")}
            </button>
            <button type="button" onClick={() => setMode(mode === "login" ? "register" : "login")} style={{ background: "none", border: 0, color: "var(--accent)", fontSize: 11, cursor: "pointer", marginTop: 4 }}>
              {mode === "login" ? "Não tem conta? Criar" : "Já tenho conta"}
            </button>
            <button type="button" onClick={() => setMode(null)} style={{ background: "none", border: 0, color: "var(--muted)", fontSize: 10, cursor: "pointer" }}>fechar</button>
          </form>
        </div>
      )}
    </div>
  );
}
const inputStyle = { background: "var(--bg)", color: "var(--fg)", border: "1px solid var(--line)", borderRadius: 4, padding: "10px 12px", fontSize: 13, fontFamily: "inherit" };

// ── Página: Meus Pedidos ─────────────────────────────────────────────────────
function OrdersPage({ onClose }) {
  const auth = useAuth();
  const [orders, setOrders] = useAcState(null);
  const [err, setErr] = useAcState("");
  useAcEffect(() => {
    if (!auth?.user) return;
    window.dropxApi.orders.mine().then(r => setOrders(r.orders)).catch(e => setErr(e.message));
  }, [auth?.user]);

  return (
    <div className="ck-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="ck-modal" style={{ maxWidth: 880 }}>
        <header className="ck-head">
          <div>
            <span className="ck-head-mono mono">CONTA</span>
            <h2 className="display ck-head-title">Meus pedidos</h2>
          </div>
          <button type="button" className="cat-close" onClick={onClose}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
          </button>
        </header>
        <div style={{ padding: 24 }}>
          {!auth?.user ? <p style={{ color: "var(--muted)" }}>Entre na sua conta para ver seus pedidos.</p>
            : err ? <p style={{ color: "#ff7a55" }}>{err}</p>
            : !orders ? <p style={{ color: "var(--muted)" }}>Carregando…</p>
            : !orders.length ? <p style={{ color: "var(--muted)" }}>Você ainda não tem pedidos.</p>
            : (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {orders.map(o => (
                  <a key={o.code} href={`#/pedido/${o.code}`} style={{ display: "block", background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 6, padding: 16, color: "var(--fg)" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                      <div>
                        <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>{acDt(o.created_at)}</div>
                        <div className="display" style={{ fontSize: 22, marginTop: 2, letterSpacing: "0.02em" }}>{o.code}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="mono" style={{ fontSize: 11, color: "var(--accent)", letterSpacing: "0.1em", textTransform: "uppercase" }}>{STATUS_LABEL[o.status] || o.status}</div>
                        <div className="display" style={{ fontSize: 22, color: "var(--accent)" }}>{acFmt(o.total_cents)}</div>
                      </div>
                    </div>
                  </a>
                ))}
              </div>
            )}
        </div>
      </div>
    </div>
  );
}

// ── Página: Detalhe de um pedido (rastreio) ──────────────────────────────────
function OrderTrackPage({ code, onClose }) {
  const [data, setData] = useAcState(null);
  const [err, setErr] = useAcState("");
  const auth = useAuth();

  useAcEffect(() => {
    // Tenta autenticado (mais detalhe); cai pra tracking público
    const fetcher = auth?.user
      ? window.dropxApi.orders.get(code).then(r => r.order).catch(() => window.dropxApi.orders.track(code).then(r => r.order))
      : window.dropxApi.orders.track(code).then(r => r.order);
    fetcher.then(setData).catch(e => setErr(e.message));
  }, [code, auth?.user]);

  return (
    <div className="ck-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="ck-modal" style={{ maxWidth: 720 }}>
        <header className="ck-head">
          <div>
            <span className="ck-head-mono mono">PEDIDO {code}</span>
            <h2 className="display ck-head-title">{data ? STATUS_LABEL[data.status] || data.status : "Carregando…"}</h2>
          </div>
          <button type="button" className="cat-close" onClick={onClose}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
          </button>
        </header>
        <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
          {err && <div style={{ color: "#ff7a55" }}>{err}</div>}
          {data && (
            <React.Fragment>
              <section>
                <div className="mono" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.14em", marginBottom: 8 }}>ITENS</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {(data.items || []).map((i, idx) => (
                    <div key={idx} style={{ display: "flex", justifyContent: "space-between", gap: 8, padding: "8px 0", borderBottom: "1px dashed var(--line)" }}>
                      <span>{i.quantity}× {i.name_snapshot}{i.size_snapshot ? ` (${i.size_snapshot})` : ""}</span>
                      <span className="mono">{acFmt(i.price_cents_snapshot * i.quantity)}</span>
                    </div>
                  ))}
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12, fontFamily: "var(--display)", fontSize: 20 }}>
                  <span>Total</span><span style={{ color: "var(--accent)" }}>{acFmt(data.total_cents)}</span>
                </div>
              </section>

              {data.tracking_code && (
                <section style={{ background: "var(--surface)", padding: 14, borderRadius: 6 }}>
                  <div className="mono" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.14em" }}>CÓDIGO DE RASTREIO</div>
                  <div className="mono" style={{ fontSize: 18, marginTop: 4 }}>{data.tracking_code}</div>
                </section>
              )}

              <section>
                <div className="mono" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.14em", marginBottom: 8 }}>HISTÓRICO</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {(data.events || []).map((ev, idx) => (
                    <div key={idx} style={{ display: "flex", gap: 10 }}>
                      <div style={{ width: 8, height: 8, borderRadius: 50, background: "var(--accent)", marginTop: 6, flex: "none" }} />
                      <div>
                        <div>{ev.message || ev.status}</div>
                        <div className="mono" style={{ fontSize: 10, color: "var(--muted)" }}>{ev.status} · {acDt(ev.created_at)}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </section>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Roteador hash ────────────────────────────────────────────────────────────
function AccountRouter() {
  const [hash, setHash] = useAcState(typeof location !== "undefined" ? location.hash : "");
  useAcEffect(() => {
    const onHash = () => setHash(location.hash);
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const close = () => { history.replaceState(null, "", location.pathname + location.search); setHash(""); };

  if (hash === "#/pedidos") return <OrdersPage onClose={close} />;
  const m = hash.match(/^#\/pedido\/(.+)$/);
  if (m) return <OrderTrackPage code={m[1]} onClose={close} />;
  return null;
}

Object.assign(window, { AuthChip, OrdersPage, OrderTrackPage, AccountRouter, STATUS_LABEL });
