// pages-admin.jsx — ADM dashboard, products, orders, settings

const { useState: useAd1 } = React;

const ADMIN_TABS = [
  { id: "dashboard", label: "Dashboard", icon: "chart" },
  { id: "produtos", label: "Produtos", icon: "tag" },
  { id: "pedidos", label: "Pedidos", icon: "box" },
  { id: "logistica", label: "Logística", icon: "truck" },
  { id: "clientes", label: "Clientes", icon: "user" },
  { id: "config", label: "Configurações", icon: "cog" },
];

function AdminPage() {
  const { goto, currentUser, clearCurrentUser } = useShop();
  const [tab, setTab] = useAd1("dashboard");
  const [navOpen, setNavOpen] = useAd1(false);
  const adminUser = currentUser || { firstName: "—", fullName: "—" };
  const activeTab = ADMIN_TABS.find((t) => t.id === tab) || ADMIN_TABS[0];

  const pickTab = (id) => { setTab(id); setNavOpen(false); };

  const SidebarBody = (
    <>
      <div className="brand">ORAH<span style={{ fontSize: 10, marginLeft: 6, letterSpacing: "0.18em", opacity: 0.6 }}>ADM</span></div>
      <div style={{ display: "flex", flexDirection: "column", gap: 4, marginTop: 16 }}>
        {ADMIN_TABS.map((it) => (
          <a key={it.id} className={tab === it.id ? "active" : ""} onClick={() => pickTab(it.id)}>
            <Icon name={it.icon} size={16} /> {it.label}
          </a>
        ))}
      </div>
      <div style={{ marginTop: 24, padding: 12, borderRadius: 10, background: "var(--bg-alt)" }}>
        <div className="mono muted" style={{ fontSize: 10 }}>logado como</div>
        <div style={{ fontWeight: 700, fontSize: 14, marginTop: 4 }}>{adminUser.fullName}</div>
        <div className="muted" style={{ fontSize: 12 }}>admin</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 8 }}>
          <button className="btn ghost sm" style={{ fontSize: 11 }} onClick={() => goto("home")}>← voltar ao site</button>
          <button className="btn ghost sm" style={{ fontSize: 11 }} onClick={() => { clearCurrentUser(); goto("home"); }}>trocar usuário</button>
        </div>
      </div>
    </>
  );

  return (
    <div className="admin-shell">
      <header className="admin-topbar">
        <button className="admin-topbar-btn" onClick={() => setNavOpen(true)} aria-label="Abrir menu">
          <Icon name="menu" size={22} />
        </button>
        <div className="admin-topbar-title">
          <span style={{ color: "var(--brand)", fontWeight: 700 }}>ORAH</span>
          <span style={{ opacity: 0.55, fontSize: 11, marginLeft: 6, letterSpacing: "0.18em" }}>ADM</span>
          <span style={{ opacity: 0.4, margin: "0 8px" }}>›</span>
          <span style={{ fontWeight: 700 }}>{activeTab.label}</span>
        </div>
        <button className="admin-topbar-btn" onClick={() => goto("home")} aria-label="Voltar ao site">
          <Icon name="close" size={20} />
        </button>
      </header>

      <Drawer open={navOpen} side="left" onClose={() => setNavOpen(false)} title={<span><span style={{ color: "var(--brand)" }}>ORAH</span> · ADM</span>}>
        <div className="admin-side admin-side-in-drawer">
          {SidebarBody}
        </div>
      </Drawer>

      <aside className="admin-side admin-side-fixed">
        {SidebarBody}
      </aside>

      <main className="admin-main">
        {tab === "dashboard" && <AdminDashboard />}
        {tab === "produtos" && <AdminProducts />}
        {tab === "pedidos" && <AdminOrders />}
        {tab === "logistica" && <AdminLogistics />}
        {tab === "clientes" && <AdminCustomers />}
        {tab === "config" && <AdminSettings />}
      </main>
    </div>
  );
}

function AdminHead({ title, sub, actions }) {
  return (
    <div className="row" style={{ justifyContent: "space-between", alignItems: "end", marginBottom: 24, flexWrap: "wrap", gap: 12 }}>
      <div style={{ minWidth: 0, flex: "1 1 auto" }}>
        <span className="mono muted">{sub}</span>
        <h1 className="t-lg" style={{ marginTop: 8 }}>{title}</h1>
      </div>
      <div className="row gap-2" style={{ flexShrink: 0, flexWrap: "wrap" }}>{actions}</div>
    </div>
  );
}

function AdminDashboard() {
  const { currentUser } = useShop();
  const name = currentUser?.firstName || "—";
  return (
    <div>
      <AdminHead title={`bom dia, ${name}.`} sub="dashboard · ontem 02 jun" actions={
        <>
          <button className="btn ghost sm">exportar</button>
          <button className="btn brand sm"><Icon name="plus" size={14} /> nova venda</button>
        </>
      }/>

      <div className="kpis">
        {[
          { l: "vendas (mês)", v: "R$ 4.860", d: "+18% vs. abril", up: true },
          { l: "pedidos", v: "32", d: "+6 ontem", up: true },
          { l: "ticket médio", v: "R$ 152", d: "—", up: true },
          { l: "estoque crítico", v: "03", d: "-1 desde sex", up: false },
        ].map((k, i) => (
          <div key={i} className="kpi">
            <div className="label">{k.l}</div>
            <div className="value">{k.v}</div>
            <div className={"delta " + (k.up ? "" : "down")}>{k.d}</div>
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, marginTop: 24 }} className="dash-grid admin-2col">
        <div className="card" style={{ padding: 24 }}>
          <div className="row" style={{ justifyContent: "space-between", marginBottom: 16 }}>
            <div>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 22, textTransform: "uppercase" }}>vendas · últimos 14 dias</div>
              <div className="mono muted">drop 01 · em ritmo de crescimento</div>
            </div>
            <select style={{ width: "auto" }}><option>14 dias</option><option>30 dias</option></select>
          </div>
          <Sparkline />
        </div>

        <div className="card" style={{ padding: 24 }}>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 22, textTransform: "uppercase", marginBottom: 16 }}>top peças</div>
          {ORAH_PRODUCTS.slice(0, 4).map((p, i) => (
            <div key={p.id} className="row gap-3" style={{ paddingBottom: 12, borderBottom: i < 3 ? "1px solid var(--ink-line)" : "none", marginBottom: i < 3 ? 12 : 0 }}>
              <div style={{ width: 36, height: 46, borderRadius: 4, overflow: "hidden" }}><ProductVisual product={p} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 13 }}>{p.name}</div>
                <div className="mono muted" style={{ fontSize: 10 }}>{14 - i*3} vendidas</div>
              </div>
              <div style={{ width: 80, height: 6, background: "var(--bg-alt)", borderRadius: 999, overflow: "hidden" }}>
                <div style={{ width: `${100 - i*22}%`, height: "100%", background: "var(--brand)" }}></div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* recent orders */}
      <div className="card" style={{ padding: 0, marginTop: 24, overflow: "hidden" }}>
        <div className="row" style={{ justifyContent: "space-between", padding: 24 }}>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 22, textTransform: "uppercase" }}>últimos pedidos</div>
          <button className="btn ghost sm">ver todos →</button>
        </div>
        <table className="table">
          <thead><tr>
            <th>pedido</th><th>cliente</th><th>data</th><th>status</th><th>total</th><th></th>
          </tr></thead>
          <tbody>
            {[
              { id: "#ORAH-0042", c: "Rafael Costa", d: "28 mai", st: "entregue", co: "#1A8754", t: "R$ 299,80" },
              { id: "#ORAH-0041", c: "Marina Lima", d: "27 mai", st: "a caminho", co: "var(--orah-blue-700)", t: "R$ 169,90" },
              { id: "#ORAH-0040", c: "Pedro Vaz", d: "26 mai", st: "preparando", co: "var(--orah-fire-500)", t: "R$ 459,70" },
              { id: "#ORAH-0039", c: "Joana M.", d: "25 mai", st: "pago", co: "var(--orah-blue-500)", t: "R$ 149,90" },
            ].map((o) => (
              <tr key={o.id}>
                <td style={{ fontWeight: 700 }}>{o.id}</td>
                <td>{o.c}</td>
                <td className="muted">{o.d}</td>
                <td><span className="badge" style={{ background: o.co, color: "#fff", borderColor: o.co }}>{o.st}</span></td>
                <td style={{ fontWeight: 700 }}>{o.t}</td>
                <td><button className="icon-btn"><Icon name="eye" size={14} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <style>{`.viewport-frame[data-vp="mobile"] .dash-grid { grid-template-columns: 1fr; }`}</style>
    </div>
  );
}

function Sparkline() {
  // simple SVG line chart with brand color
  const pts = [12, 18, 14, 22, 28, 24, 36, 32, 44, 38, 56, 48, 64, 58];
  const w = 600, h = 180;
  const max = Math.max(...pts) * 1.1;
  const step = w / (pts.length - 1);
  const path = pts.map((p, i) => `${i === 0 ? "M" : "L"} ${i * step} ${h - (p / max) * h}`).join(" ");
  const area = path + ` L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: 180 }}>
      <defs>
        <linearGradient id="sparkfill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--brand)" stopOpacity="0.3" />
          <stop offset="100%" stopColor="var(--brand)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkfill)" />
      <path d={path} fill="none" stroke="var(--brand)" strokeWidth="2.5" strokeLinejoin="round" />
      {pts.map((p, i) => (
        <circle key={i} cx={i * step} cy={h - (p / max) * h} r={i === pts.length - 1 ? 5 : 0} fill="var(--accent)" />
      ))}
    </svg>
  );
}

/* PRODUCTS ===================================================== */
function AdminProducts() {
  const [items, setItems] = useAd1(ORAH_PRODUCTS);
  const [editing, setEditing] = useAd1(null);

  if (editing) return <ProductEditor product={editing} onClose={() => setEditing(null)} onSave={(p) => {
    setItems((arr) => arr.map((x) => x.id === p.id ? p : x));
    setEditing(null);
  }} />;

  return (
    <div>
      <AdminHead title="produtos" sub="catalog · 8 ativos" actions={
        <>
          <button className="btn ghost sm">importar planilha</button>
          <button className="btn brand sm" onClick={() => setEditing({ id: "novo", name: "", line: "Manifesto", drop: "Drop 01", price: 0, sizes: ["P","M","G","GG"], colors: [], quote: "", verse: "", bg: "var(--orah-blue-700)", fg: "var(--orah-cream-50)" })}>
            <Icon name="plus" size={14} /> novo produto
          </button>
        </>
      } />

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="row" style={{ padding: 16, gap: 12, borderBottom: "1px solid var(--ink-line)" }}>
          <input placeholder="buscar por nome, sku, drop…" style={{ maxWidth: 360 }} />
          <select style={{ width: "auto" }}><option>todas linhas</option><option>Manifesto</option><option>Eterno</option></select>
          <select style={{ width: "auto" }}><option>todos drops</option><option>Drop 01</option><option>Drop 02</option></select>
        </div>
        <table className="table table-cards">
          <thead><tr>
            <th></th><th>nome</th><th>linha</th><th>preço</th><th>estoque</th><th>status</th><th></th>
          </tr></thead>
          <tbody>
            {items.map((p) => (
              <tr key={p.id}>
                <td data-label="" style={{ width: 56 }} className="cell-thumb">
                  <div style={{ width: 40, height: 50, borderRadius: 4, overflow: "hidden" }}><ProductVisual product={p} /></div>
                </td>
                <td data-label="Nome" className="cell-main">
                  <div style={{ fontWeight: 700 }}>{p.name}</div>
                  <div className="mono muted" style={{ fontSize: 10 }}>{p.id.toUpperCase()} · {p.quote.slice(0, 30)}…</div>
                </td>
                <td data-label="Linha">{p.line}</td>
                <td data-label="Preço" style={{ fontWeight: 700 }}>R$ {p.price.toFixed(2).replace(".", ",")}</td>
                <td data-label="Estoque">
                  <span style={{ color: Math.random() > 0.7 ? "var(--accent)" : "var(--ink)", fontWeight: 700 }}>
                    {Math.floor(Math.random() * 40 + 5)}
                  </span>
                  <span className="muted"> peças</span>
                </td>
                <td data-label="Status">
                  <span className="badge brand">ativo</span>
                </td>
                <td data-label="Ações" className="row gap-1 cell-actions">
                  <button className="icon-btn" onClick={() => setEditing(p)}><Icon name="edit" size={14} /></button>
                  <button className="icon-btn"><Icon name="trash" size={14} /></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ProductEditor({ product, onClose, onSave }) {
  const [p, setP] = useAd1({ ...product });
  const upd = (k, v) => setP((s) => ({ ...s, [k]: v }));
  return (
    <div>
      <AdminHead
        title={product.id === "novo" ? "novo produto" : `editar · ${product.name}`}
        sub="produtos / editor"
        actions={
          <>
            <button className="btn ghost sm" onClick={onClose}>cancelar</button>
            <button className="btn brand sm" onClick={() => onSave(p)}>salvar produto</button>
          </>
        }
      />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 24 }} className="prod-edit">
        <div className="card">
          <h3 className="t-sm">básico</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 16 }}>
            <div><label>nome</label><input value={p.name} onChange={(e) => upd("name", e.target.value)} /></div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div><label>linha</label>
                <select value={p.line} onChange={(e) => upd("line", e.target.value)}>
                  <option>Manifesto</option><option>Eterno</option>
                </select>
              </div>
              <div><label>drop</label>
                <select value={p.drop} onChange={(e) => upd("drop", e.target.value)}>
                  <option>Drop 01</option><option>Drop 02</option><option>Em breve</option>
                </select>
              </div>
            </div>
            <div><label>frase / quote da estampa</label><input value={p.quote} onChange={(e) => upd("quote", e.target.value)} /></div>
            <div><label>versículo</label><input value={p.verse} onChange={(e) => upd("verse", e.target.value)} /></div>
            <div><label>descrição</label><textarea rows={4} placeholder="Detalhes da peça…"></textarea></div>
          </div>

          <h3 className="t-sm" style={{ marginTop: 28 }}>imagens</h3>
          <div className="row gap-2" style={{ marginTop: 12 }}>
            <div style={{ width: 80, height: 100, borderRadius: 6, overflow: "hidden" }}><ProductVisual product={p} /></div>
            <div style={{ width: 80, height: 100, borderRadius: 6, border: "1px dashed var(--ink-line)", display: "grid", placeItems: "center" }} className="muted">+ foto</div>
            <div style={{ width: 80, height: 100, borderRadius: 6, border: "1px dashed var(--ink-line)", display: "grid", placeItems: "center" }} className="muted">+ foto</div>
          </div>

          <h3 className="t-sm" style={{ marginTop: 28 }}>variantes</h3>
          <table className="table" style={{ marginTop: 12 }}>
            <thead><tr><th>tamanho</th><th>sku</th><th>estoque</th><th>preço</th></tr></thead>
            <tbody>
              {p.sizes.map((s) => (
                <tr key={s}>
                  <td style={{ fontWeight: 700 }}>{s}</td>
                  <td className="mono muted">{p.id.toUpperCase()}-{s}</td>
                  <td><input style={{ width: 80 }} defaultValue={Math.floor(Math.random() * 30 + 5)} /></td>
                  <td><input style={{ width: 110 }} defaultValue={"R$ " + p.price.toFixed(2).replace(".", ",")} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div>
          <div className="card">
            <h3 className="t-sm">preço</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 12 }}>
              <div><label>preço de venda</label><input value={p.price} onChange={(e) => upd("price", parseFloat(e.target.value || 0))} /></div>
              <div><label>preço promocional</label><input value={p.oldPrice || ""} onChange={(e) => upd("oldPrice", parseFloat(e.target.value || 0))} placeholder="—" /></div>
              <div><label>custo da peça</label><input placeholder="R$ 38,00" /></div>
              <div style={{ display: "flex", justifyContent: "space-between", padding: "10px 12px", background: "var(--bg-alt)", borderRadius: 8, fontSize: 13 }}>
                <span className="mono muted">margem</span>
                <span style={{ fontWeight: 700, color: "var(--brand)" }}>74,7%</span>
              </div>
            </div>
          </div>

          <div className="card" style={{ marginTop: 16 }}>
            <h3 className="t-sm">visibilidade</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 12, fontSize: 13 }}>
              <label className="row gap-2" style={{ textTransform: "none", color: "var(--ink)", marginBottom: 0 }}>
                <input type="checkbox" defaultChecked style={{ width: 18, height: 18 }} /> ativo na loja
              </label>
              <label className="row gap-2" style={{ textTransform: "none", color: "var(--ink)", marginBottom: 0 }}>
                <input type="checkbox" defaultChecked style={{ width: 18, height: 18 }} /> aparece na home
              </label>
              <label className="row gap-2" style={{ textTransform: "none", color: "var(--ink)", marginBottom: 0 }}>
                <input type="checkbox" style={{ width: 18, height: 18 }} /> destaque (badge novo)
              </label>
            </div>
          </div>

          <div className="card" style={{ marginTop: 16 }}>
            <h3 className="t-sm">visual da estampa</h3>
            <div className="row gap-2" style={{ marginTop: 12, flexWrap: "wrap" }}>
              {[
                "var(--orah-blue-700)",
                "var(--orah-blue-800)",
                "var(--orah-cream-100)",
                "var(--orah-ink)",
                "var(--orah-fire-500)",
              ].map((c) => (
                <button key={c} onClick={() => upd("bg", c)} style={{
                  width: 36, height: 36, borderRadius: "50%", background: c,
                  border: p.bg === c ? "2px solid var(--ink)" : "1px solid var(--ink-line)",
                  cursor: "pointer",
                }}></button>
              ))}
            </div>
          </div>
        </div>
      </div>
      <style>{`.viewport-frame[data-vp="mobile"] .prod-edit { grid-template-columns: 1fr; }`}</style>
    </div>
  );
}

/* ORDERS ====================================================== */
function AdminOrders() {
  const [statusFilter, setSf] = useAd1("todos");
  const orders = [
    { id: "#ORAH-0043", c: "Bia Souto", d: "02 jun", st: "pago", co: "var(--orah-blue-500)", t: 169.90, items: 1 },
    { id: "#ORAH-0042", c: "Rafael Costa", d: "28 mai", st: "entregue", co: "#1A8754", t: 299.80, items: 2 },
    { id: "#ORAH-0041", c: "Marina Lima", d: "27 mai", st: "a caminho", co: "var(--orah-blue-700)", t: 169.90, items: 1 },
    { id: "#ORAH-0040", c: "Pedro Vaz", d: "26 mai", st: "preparando", co: "var(--orah-fire-500)", t: 459.70, items: 3 },
    { id: "#ORAH-0039", c: "Joana M.", d: "25 mai", st: "pago", co: "var(--orah-blue-500)", t: 149.90, items: 1 },
    { id: "#ORAH-0038", c: "Diego R.", d: "24 mai", st: "cancelado", co: "var(--ink-soft)", t: 159.90, items: 1 },
  ];
  const filtered = orders.filter((o) => statusFilter === "todos" || o.st === statusFilter);

  return (
    <div>
      <AdminHead title="pedidos" sub={`${orders.length} pedidos · maio/jun 2026`} actions={
        <>
          <button className="btn ghost sm">exportar csv</button>
          <button className="btn brand sm">criar etiquetas</button>
        </>
      } />

      <div className="row gap-2" style={{ marginBottom: 16, flexWrap: "wrap" }}>
        {[
          { id: "todos", l: "todos", n: orders.length },
          { id: "pago", l: "pago", n: 2 },
          { id: "preparando", l: "preparando", n: 1 },
          { id: "a caminho", l: "a caminho", n: 1 },
          { id: "entregue", l: "entregue", n: 1 },
          { id: "cancelado", l: "cancelado", n: 1 },
        ].map((f) => (
          <button key={f.id} className={"badge " + (statusFilter === f.id ? "brand" : "")} style={{ cursor: "pointer" }} onClick={() => setSf(f.id)}>
            {f.l} <span style={{ opacity: 0.6 }}>{f.n}</span>
          </button>
        ))}
      </div>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="table">
          <thead><tr>
            <th><input type="checkbox" /></th>
            <th>pedido</th><th>cliente</th><th>data</th><th>itens</th><th>status</th><th>total</th><th></th>
          </tr></thead>
          <tbody>
            {filtered.map((o) => (
              <tr key={o.id}>
                <td data-label="" className="cell-thumb"><input type="checkbox" /></td>
                <td data-label="Pedido" style={{ fontWeight: 700 }}>{o.id}</td>
                <td data-label="Cliente">{o.c}</td>
                <td data-label="Data" className="muted">{o.d}</td>
                <td data-label="Itens">{o.items}</td>
                <td data-label="Status"><span className="badge" style={{ background: o.co, color: "#fff", borderColor: o.co }}>{o.st}</span></td>
                <td data-label="Total" style={{ fontWeight: 700 }}>R$ {o.t.toFixed(2).replace(".", ",")}</td>
                <td data-label="" className="row gap-1 cell-actions">
                  <button className="icon-btn"><Icon name="eye" size={14} /></button>
                  <button className="icon-btn"><Icon name="truck" size={14} /></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* LOGISTICS ================================================== */
function AdminLogistics() {
  return (
    <div>
      <AdminHead title="logística" sub="envios · estoque · rotas" actions={
        <button className="btn brand sm">novo envio</button>
      } />

      <div className="kpis">
        {[
          { l: "aguardando envio", v: "07" },
          { l: "em trânsito", v: "12" },
          { l: "atrasados", v: "01", down: true },
          { l: "entregues (mês)", v: "26" },
        ].map((k, i) => (
          <div key={i} className="kpi">
            <div className="label">{k.l}</div>
            <div className="value" style={{ color: k.down ? "var(--accent)" : "var(--brand)" }}>{k.v}</div>
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24 }} className="log-grid">
        <div className="card">
          <h3 className="t-sm">estoque por peça</h3>
          <div style={{ marginTop: 16 }}>
            {ORAH_PRODUCTS.slice(0, 5).map((p, i) => {
              const stock = Math.floor(Math.random() * 80 + 5);
              const low = stock < 15;
              return (
                <div key={p.id} className="row gap-3" style={{ paddingTop: 10, paddingBottom: 10, borderBottom: i < 4 ? "1px solid var(--ink-line)" : "none" }}>
                  <div style={{ width: 32, height: 40, borderRadius: 4, overflow: "hidden" }}><ProductVisual product={p} /></div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 13 }}>{p.name}</div>
                    <div className="mono muted" style={{ fontSize: 10 }}>P · M · G · GG</div>
                  </div>
                  <span style={{ fontWeight: 700, color: low ? "var(--accent)" : "var(--ink)" }}>{stock}</span>
                  {low && <span className="badge fire">repor</span>}
                </div>
              );
            })}
          </div>
        </div>

        <div className="card">
          <h3 className="t-sm">transportadoras</h3>
          <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 12 }}>
            {[
              { n: "Correios · Sedex", c: 18, d: "média 4 dias" },
              { n: "Correios · PAC", c: 9, d: "média 8 dias" },
              { n: "Loggi", c: 3, d: "Ponta Grossa · same day" },
              { n: "Retirada local", c: 2, d: "Batel · 14h-18h" },
            ].map((t) => (
              <div key={t.n} className="row" style={{ justifyContent: "space-between", padding: 12, background: "var(--bg-alt)", borderRadius: 8 }}>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{t.n}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{t.d}</div>
                </div>
                <div style={{ fontFamily: "var(--f-display)", fontSize: 28, color: "var(--brand)" }}>{t.c}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <style>{`.viewport-frame[data-vp="mobile"] .log-grid { grid-template-columns: 1fr; }`}</style>
    </div>
  );
}

function AdminCustomers() {
  return (
    <div>
      <AdminHead title="clientes" sub="base · 142 cadastros" actions={
        <button className="btn brand sm"><Icon name="plus" size={14} /> novo cliente</button>
      } />
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="table">
          <thead><tr><th>nome</th><th>email</th><th>pedidos</th><th>total gasto</th><th>último</th></tr></thead>
          <tbody>
            {[
              ["Rafael Costa", "rafael@email.com", 3, "R$ 759,50", "28 mai"],
              ["Marina Lima", "marina@email.com", 2, "R$ 319,80", "27 mai"],
              ["Pedro Vaz", "pedro@email.com", 1, "R$ 459,70", "26 mai"],
              ["Joana M.", "joana@email.com", 1, "R$ 149,90", "25 mai"],
              ["Bia Souto", "bia@email.com", 1, "R$ 169,90", "02 jun"],
            ].map((r, i) => (
              <tr key={i}>
                <td data-label="Nome" className="cell-main" style={{ fontWeight: 700 }}>{r[0]}</td>
                <td data-label="Email" className="muted">{r[1]}</td>
                <td data-label="Pedidos">{r[2]}</td>
                <td data-label="Total gasto" style={{ fontWeight: 700 }}>{r[3]}</td>
                <td data-label="Último" className="muted">{r[4]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AdminMarketing() {
  const coupons = [
    { c: "ORAH10", d: "10% off na primeira compra", used: 23, limit: 200, tag: "primeira compra" },
    { c: "PIX5", d: "5% off pagando no pix", used: 112, limit: null, tag: "sempre ativo" },
    { c: "PROPOSITO", d: "frete grátis acima de R$ 199", used: 8, limit: null, tag: "drop 01" },
  ];

  return (
    <div>
      <AdminHead title="marketing" sub="cupons · campanhas · drops" actions={
        <button className="btn brand sm"><Icon name="plus" size={14} /> novo cupom</button>
      } />

      {/* KPIs marketing */}
      <div className="kpis" style={{ marginBottom: 24 }}>
        <div className="kpi">
          <div className="label">cupons ativos</div>
          <div className="value">3</div>
          <div className="delta">143 usos no total</div>
        </div>
        <div className="kpi">
          <div className="label">desconto dado (mês)</div>
          <div className="value">R$ 487</div>
          <div className="delta">+12 pedidos</div>
        </div>
        <div className="kpi">
          <div className="label">campanhas ativas</div>
          <div className="value">1</div>
          <div className="delta">drop 01</div>
        </div>
        <div className="kpi">
          <div className="label">próximo drop</div>
          <div className="value" style={{ fontSize: 28 }}>14/07</div>
          <div className="delta">drop 02</div>
        </div>
      </div>

      <h3 className="t-sm" style={{ marginBottom: 12 }}>cupons</h3>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }} className="mk-grid">
        {coupons.map((c) => {
          const pct = c.limit ? Math.min(100, (c.used / c.limit) * 100) : null;
          return (
            <div key={c.c} className="coupon-card">
              <div className="coupon-body">
                <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                  <div className="coupon-tag">{c.tag}</div>
                  <span className="badge brand" style={{ fontSize: 9 }}>ativo</span>
                </div>
                <div className="coupon-code">{c.c}</div>
                <div className="coupon-desc">{c.d}</div>
                {pct !== null ? (
                  <div className="coupon-meter">
                    <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                      <span className="mono muted" style={{ fontSize: 10 }}>{c.used} de {c.limit} usos</span>
                      <span className="mono" style={{ fontSize: 10, color: "var(--brand)", fontWeight: 700 }}>{Math.round(pct)}%</span>
                    </div>
                    <div style={{ height: 6, background: "var(--bg-alt)", borderRadius: 999, overflow: "hidden" }}>
                      <div style={{ width: `${pct}%`, height: "100%", background: "var(--brand)" }} />
                    </div>
                  </div>
                ) : (
                  <div className="mono muted" style={{ marginTop: 14, fontSize: 11 }}>{c.used} usos · sem limite</div>
                )}
              </div>
              <div className="coupon-footer">
                <button className="btn ghost sm" style={{ fontSize: 11, padding: "6px 12px", flex: 1 }}>
                  <Icon name="tag" size={12} /> copiar código
                </button>
                <button className="btn ghost sm" style={{ fontSize: 11, padding: "6px 12px" }}>
                  <Icon name="edit" size={12} /> editar
                </button>
              </div>
            </div>
          );
        })}
      </div>

      <h3 className="t-sm" style={{ marginTop: 32, marginBottom: 12 }}>próximo drop</h3>
      <div className="card">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="mk-form-grid">
          <div><label>nome do drop</label><input defaultValue="Drop 02 — Em breve" /></div>
          <div><label>data de lançamento</label><input defaultValue="14/07/2026" /></div>
        </div>
        <div style={{ marginTop: 16 }}><label>copy do banner</label><input defaultValue="Prepare-se. Algo está prestes a acontecer." /></div>
        <div style={{ marginTop: 16, display: "flex", gap: 8, flexWrap: "wrap" }}>
          <button className="btn ghost sm">pré-visualizar</button>
          <button className="btn brand sm">salvar drop</button>
        </div>
      </div>

      <style>{`
        .coupon-card { display: flex; flex-direction: column; background: var(--bg-card); border: 1px solid var(--ink-line); border-radius: 14px; overflow: hidden; position: relative; }
        .coupon-card::before { content: ""; position: absolute; top: 0; bottom: 0; left: 0; width: 4px; background: var(--brand); }
        .coupon-body { padding: 18px 20px 16px; display: flex; flex-direction: column; flex: 1; }
        .coupon-tag { display: inline-block; font-family: var(--f-mono); font-size: 9px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--brand); padding: 4px 8px; border: 1px solid var(--brand); border-radius: 999px; }
        .coupon-code { font-family: var(--f-display); font-size: 30px; letter-spacing: 0.04em; margin-top: 12px; color: var(--ink); }
        .coupon-desc { color: var(--ink-soft); font-size: 13px; margin-top: 6px; }
        .coupon-meter { margin-top: 16px; }
        .coupon-footer { display: flex; gap: 8px; padding: 12px 16px; border-top: 1px dashed var(--ink-line); background: var(--bg-alt); }
        .coupon-footer .btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; }
        .viewport-frame[data-vp="mobile"] .mk-grid { grid-template-columns: 1fr; }
        .viewport-frame[data-vp="mobile"] .mk-form-grid { grid-template-columns: 1fr; }
      `}</style>
    </div>
  );
}

function AdminSettings() {
  return (
    <div>
      <AdminHead title="configurações" sub="loja · pagamento · contato" />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="set-grid">
        <div className="card">
          <h3 className="t-sm">a loja</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 16 }}>
            <div><label>nome da loja</label><input defaultValue="ORAH CULTURE" /></div>
            <div><label>slogan</label><input defaultValue="uma marca, um propósito." /></div>
            <div><label>email de contato</label><input defaultValue="contato@orahculture.com.br" /></div>
            <div><label>instagram</label><input defaultValue="@orahculture" /></div>
          </div>
        </div>

        <div className="card">
          <h3 className="t-sm">pagamentos</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 16 }}>
            {[
              { l: "Pix", on: true, d: "5% off automático" },
              { l: "Cartão de crédito", on: true, d: "até 3x sem juros" },
              { l: "Boleto", on: true, d: "vencimento em 3 dias" },
              { l: "Apple Pay / Google Pay", on: false, d: "em breve" },
            ].map((m) => (
              <div key={m.l} className="row" style={{ justifyContent: "space-between", padding: 12, background: "var(--bg-alt)", borderRadius: 8 }}>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{m.l}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{m.d}</div>
                </div>
                <div style={{
                  width: 40, height: 22, borderRadius: 999, padding: 2,
                  background: m.on ? "var(--brand)" : "var(--ink-line)",
                  display: "flex", justifyContent: m.on ? "flex-end" : "flex-start",
                }}>
                  <div style={{ width: 18, height: 18, borderRadius: "50%", background: "#fff" }}></div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <h3 className="t-sm">fretes</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 16 }}>
            <div><label>cep de origem</label><input defaultValue="80000-000" /></div>
            <div><label>frete grátis acima de</label><input defaultValue="R$ 250,00" /></div>
            <div><label>prazo mínimo (dias)</label><input defaultValue="3" /></div>
          </div>
        </div>

        <div className="card">
          <h3 className="t-sm">identidade visual</h3>
          <div style={{ marginTop: 16 }}>
            <label>logo</label>
            <div className="row gap-3" style={{ marginTop: 6 }}>
              <span style={{ width: 64, height: 64, borderRadius: "50%", overflow: "hidden", border: "2px solid var(--bg-card)" }}>
                <img src="assets/orah-logo.png" alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </span>
              <button className="btn ghost sm">trocar imagem</button>
            </div>

            <label style={{ marginTop: 18 }}>cor primária</label>
            <div className="row gap-2">
              <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--orah-blue-700)", border: "2px solid var(--ink)" }}></div>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--orah-blue-500)", opacity: 0.7 }}></div>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--orah-blue-800)", opacity: 0.7 }}></div>
            </div>
          </div>
        </div>
      </div>
      <style>{`.viewport-frame[data-vp="mobile"] .set-grid { grid-template-columns: 1fr; }`}</style>
    </div>
  );
}

Object.assign(window, { AdminPage });
