/* ============================================================
   admin.jsx — shell (sidebar+topbar) + Dashboard + Sales + Customers + Settings
   ============================================================ */

const NAV = [
  { key: "dashboard", label: "Dashboard", icon: "dash" },
  { key: "checkouts", label: "Criar checkout", icon: "plus", primary: true },
  { key: "products",  label: "Produtos",     icon: "tag" },
  { key: "bumps",     label: "Order bumps",  icon: "bolt" },
  { key: "sales",     label: "Vendas",       icon: "cart" },
  { key: "customers", label: "Clientes",     icon: "users" },
  { key: "settings",  label: "Configurações",icon: "set" },
];

function Sidebar({ active, onNav }){
  const { setUser, setRoute, sales } = useApp();
  const pendings = sales.filter(s => s.status === "pendente").length;
  return (
    <aside className="sidebar">
      <a className="brand" href="#/dashboard" onClick={(e) => { e.preventDefault(); onNav("dashboard"); }}>
        <BrandLogo theme="light" height={20} />
      </a>

      <div className="side-section">Operação</div>
      {NAV.slice(0, 2).map((n) => (
        <a key={n.key} className={cls("nav-item", active === n.key && "active")}
          href={`#/${n.key}`} onClick={(e) => { e.preventDefault(); onNav(n.key); }}>
          <Icon name={n.icon} />
          <span>{n.label}</span>
          {n.primary && <span className="count">novo</span>}
        </a>
      ))}

      <div className="side-section">Catálogo</div>
      {NAV.slice(2, 4).map((n) => (
        <a key={n.key} className={cls("nav-item", active === n.key && "active")}
          href={`#/${n.key}`} onClick={(e) => { e.preventDefault(); onNav(n.key); }}>
          <Icon name={n.icon} />
          <span>{n.label}</span>
        </a>
      ))}

      <div className="side-section">Receita</div>
      {NAV.slice(4, 6).map((n) => (
        <a key={n.key} className={cls("nav-item", active === n.key && "active")}
          href={`#/${n.key}`} onClick={(e) => { e.preventDefault(); onNav(n.key); }}>
          <Icon name={n.icon} />
          <span>{n.label}</span>
          {n.key === "sales" && pendings > 0 && <span className="count">{pendings}</span>}
        </a>
      ))}

      <div className="side-section">Sistema</div>
      {NAV.slice(6).map((n) => (
        <a key={n.key} className={cls("nav-item", active === n.key && "active")}
          href={`#/${n.key}`} onClick={(e) => { e.preventDefault(); onNav(n.key); }}>
          <Icon name={n.icon} />
          <span>{n.label}</span>
        </a>
      ))}

      <div className="sidebar-footer">
        <div className="avatar">BX</div>
        <div className="who">
          <span className="n">Studio BlackX</span>
          <span className="e">admin@blackx.studio</span>
        </div>
        <button className="out" aria-label="Sair"
          onClick={() => { setUser(null); setRoute("/login"); }}>
          <Icon name="log-out" size={16}/>
        </button>
      </div>
    </aside>
  );
}

function Topbar({ title, eyebrow, actions }){
  return (
    <div className="topbar">
      <div className="title">
        {eyebrow && <span className="eyebrow">{eyebrow}</span>}
        <h1>{title}</h1>
      </div>
      <div className="spacer"></div>
      <div className="search">
        <Icon name="search" />
        <input placeholder="Pesquisar vendas, clientes, links…" />
      </div>
      <button className="btn-icon" aria-label="Notificações"><Icon name="bell" /></button>
      <div style={{ width: 1, alignSelf: "stretch", background: "var(--line)" }}></div>
      {actions}
    </div>
  );
}

function Shell({ title, eyebrow, page, actions, children }){
  const { setRoute } = useApp();
  return (
    <div className="shell">
      <Sidebar active={page} onNav={(k) => setRoute("/" + k)} />
      <div className="main">
        <Topbar title={title} eyebrow={eyebrow} actions={actions} />
        <div className="content in">{children}</div>
      </div>
    </div>
  );
}

// ============================================================
// Dashboard
// ============================================================
function Dashboard(){
  const { sales, series, setRoute } = useApp();
  const paid = sales.filter(s => s.status === "pago");
  const pending = sales.filter(s => s.status === "pendente");
  const totalSales = paid.reduce((a, s) => a + s.amount, 0);
  const pendingAmount = pending.reduce((a, s) => a + s.amount, 0);
  const newCustomers = 6;
  const conversionRate = 38.4;

  return (
    <Shell page="dashboard" eyebrow="Visão geral" title="Bom dia, Studio."
      actions={<button className="btn" onClick={() => setRoute("/checkouts")}><Icon name="plus" size={16}/> Novo checkout</button>}>

      <div className="page-head" style={{ marginBottom: 18 }}>
        <div className="lead">
          <span className="eyebrow" style={{ fontSize: 11, letterSpacing: ".2em", color: "var(--mute)", textTransform: "uppercase", fontWeight: 600 }}>Resumo</span>
          <h2>Cobrar com <em className="serif-em">presença,</em> medir com clareza.</h2>
          <p className="sub">Acompanhamento em tempo real das suas vendas, links gerados e cobranças pendentes integradas ao Mercado Pago.</p>
        </div>
        <div className="actions">
          <div className="seg" role="tablist">
            <button className="active">7 dias</button>
            <button>30 dias</button>
            <button>90 dias</button>
            <button>Tudo</button>
          </div>
        </div>
      </div>

      <div className="kpis" style={{ marginBottom: 18 }}>
        <div className="kpi dark">
          <div className="lbl">Receita aprovada</div>
          <div className="val">{fmtBRL(totalSales)}</div>
          <div className="delta up"><Icon name="arrow" size={12}/> +18,2% vs. semana anterior</div>
          <Sparkline data={series.slice(-14)} color="rgba(255,255,255,.7)" />
        </div>
        <div className="kpi">
          <div className="lbl">Cobranças pendentes</div>
          <div className="val">{fmtBRL(pendingAmount)}</div>
          <div className="delta"><Icon name="bell" size={12}/> {pending.length} aguardando confirmação</div>
          <Sparkline data={series.slice(-14).map(v => v * 0.4)} />
        </div>
        <div className="kpi">
          <div className="lbl">Conversão de checkout</div>
          <div className="val">{conversionRate}%</div>
          <div className="delta up"><Icon name="arrow" size={12}/> +2,1 p.p.</div>
          <Sparkline data={series.slice(-14).map((v, i) => 40 + Math.sin(i / 2) * 8 + (i / 8))} />
        </div>
        <div className="kpi">
          <div className="lbl">Novos clientes</div>
          <div className="val">{newCustomers}</div>
          <div className="delta"><Icon name="users" size={12}/> últimas 24h</div>
          <Sparkline data={[3, 4, 2, 5, 4, 6, 7, 5, 6, 7, 8, 6, 7, 6]} />
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 16 }}>
        <div className="chart-card">
          <div className="chart-meta">
            <div>
              <h3>Receita por dia</h3>
              <div className="sub">Últimos 29 dias · timezone Brasília</div>
            </div>
            <div className="seg">
              <button className="active">Receita</button>
              <button>Pedidos</button>
              <button>Ticket</button>
            </div>
          </div>
          <LineChart data={series} />
          <div style={{
            display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 0,
            marginTop: 14, borderTop: "1px solid var(--line-2)", paddingTop: 14,
          }}>
            <Stat label="Ticket médio" value={fmtBRL(totalSales / paid.length)} />
            <Stat label="Pix" value={`${Math.round(paid.filter(s => s.method === "pix").length / paid.length * 100)}%`} />
            <Stat label="Cartão" value={`${Math.round(paid.filter(s => s.method === "card").length / paid.length * 100)}%`} />
            <Stat label="Reembolsos" value="0,0%" />
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>Atividade recente</h3>
            <a className="btn-icon" href="#/sales" onClick={(e) => { e.preventDefault(); setRoute("/sales"); }} aria-label="Ver todas">
              <Icon name="arrow" />
            </a>
          </div>
          <div style={{ padding: "6px 8px 14px" }}>
            {sales.slice(0, 6).map((s) => (
              <div key={s.id} className="list-row" style={{ gridTemplateColumns: "auto 1fr auto" }}>
                <div className="avatar-sm">{initials(s.customer)}</div>
                <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, marginLeft: 4 }}>
                  <b style={{ fontSize: 13.5 }}>{s.customer}</b>
                  <span style={{ fontSize: 12, color: "var(--mute)" }}>{s.product} · {ago(s.date)}</span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
                  <b style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(s.amount)}</b>
                  <StatusBadge status={s.status}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16, marginTop: 16 }}>
        <QuickAction icon="plus" title="Gerar checkout" sub="Crie um link em 30 segundos"
          onClick={() => setRoute("/checkouts")} />
        <QuickAction icon="bolt" title="Novo order bump" sub="Aumente o ticket médio"
          onClick={() => setRoute("/bumps")} />
        <QuickAction icon="set" title="Integrar Mercado Pago" sub="Webhook + token no servidor"
          onClick={() => setRoute("/settings")} />
      </div>
    </Shell>
  );
}

function Stat({ label, value }){
  return (
    <div style={{ paddingRight: 12 }}>
      <div style={{ fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em", marginTop: 4, fontVariantNumeric: "tabular-nums" }}>{value}</div>
    </div>
  );
}

function QuickAction({ icon, title, sub, onClick }){
  return (
    <button className="card card-pad" onClick={onClick}
      style={{ textAlign: "left", cursor: "pointer", border: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 10, transition: "transform .35s var(--ease), box-shadow .35s var(--ease)" }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 22px 44px -28px rgba(10,10,10,.22)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}>
      <div style={{ width: 38, height: 38, borderRadius: 12, background: "var(--ink)", color: "#fff", display: "grid", placeItems: "center" }}>
        <Icon name={icon} size={18}/>
      </div>
      <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>{title}</div>
      <div style={{ fontSize: 13, color: "var(--mute)" }}>{sub}</div>
    </button>
  );
}

// ============================================================
// Sales
// ============================================================
function Sales(){
  const { sales, setRoute, setModal } = useApp();
  const [filter, setFilter] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const filtered = sales.filter((s) =>
    (filter === "all" || s.status === filter) &&
    (s.id.toLowerCase().includes(search.toLowerCase()) ||
     s.customer.toLowerCase().includes(search.toLowerCase()) ||
     s.product.toLowerCase().includes(search.toLowerCase()))
  );

  const openDetail = (s) => setModal({
    title: s.id,
    sub: `${s.product} · ${fmtDateTime(s.date)}`,
    body: <SaleDetail sale={s}/>,
    foot: <>
      <button className="btn btn-light" onClick={() => setModal(null)}>Fechar</button>
      <button className="btn"><Icon name="send" size={14}/> Reenviar recibo</button>
    </>
  });

  return (
    <Shell page="sales" eyebrow="Receita" title="Vendas"
      actions={<button className="btn btn-light"><Icon name="filter" size={14}/> Exportar CSV</button>}>

      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 14, alignItems: "center", padding: 16, flexWrap: "wrap" }}>
          <div className="seg">
            {[
              ["all", "Todas"],
              ["pago", "Pagas"],
              ["pendente", "Pendentes"],
              ["recusado", "Recusadas"],
              ["expirado", "Expiradas"],
            ].map(([k, l]) => (
              <button key={k} className={cls(filter === k && "active")} onClick={() => setFilter(k)}>{l}</button>
            ))}
          </div>
          <div className="spacer" style={{ flex: 1 }}></div>
          <div style={{ position: "relative", width: 280 }}>
            <Icon name="search" size={16} style={{ position: "absolute", left: 12, top: 11, color: "var(--graphite)" }}/>
            <input className="input" placeholder="ID, cliente ou produto" value={search}
              onChange={(e) => setSearch(e.target.value)} style={{ paddingLeft: 36 }}/>
          </div>
        </div>

        <table className="table">
          <thead>
            <tr>
              <th>Pedido</th>
              <th>Cliente</th>
              <th>Produto</th>
              <th>Método</th>
              <th className="num">Valor</th>
              <th>Status</th>
              <th>Data</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((s) => (
              <tr key={s.id} className="row-hover" onClick={() => openDetail(s)}>
                <td className="mono">{s.id}</td>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div className="avatar-sm">{initials(s.customer)}</div>
                    {s.customer}
                  </div>
                </td>
                <td>{s.product}</td>
                <td><MethodPill method={s.method}/>{s.method === "card" && s.installments > 1 && <span style={{ color: "var(--mute)", fontSize: 12, marginLeft: 8 }}>{s.installments}x</span>}</td>
                <td className="num"><b>{fmtBRL(s.amount)}</b></td>
                <td><StatusBadge status={s.status}/></td>
                <td style={{ color: "var(--mute)" }}>{fmtDateTime(s.date)}</td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan="7"><div className="empty">
                <div className="ic"><Icon name="cart"/></div>
                <h4>Nenhuma venda encontrada</h4>
                <span>Ajuste o filtro ou pesquise por outro termo.</span>
              </div></td></tr>
            )}
          </tbody>
        </table>
      </div>
    </Shell>
  );
}

function SaleDetail({ sale }){
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: 14, borderRadius: 14, background: "var(--paper)", border: "1px solid var(--line)",
      }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: ".16em", textTransform: "uppercase", color: "var(--mute)" }}>Valor total</div>
          <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em" }}>{fmtBRL(sale.amount)}</div>
        </div>
        <StatusBadge status={sale.status}/>
      </div>
      <Pair k="Cliente" v={sale.customer}/>
      <Pair k="Produto" v={sale.product}/>
      <Pair k="Método" v={<MethodPill method={sale.method}/>}/>
      {sale.method === "card" && <Pair k="Parcelamento" v={`${sale.installments}x`}/>}
      <Pair k="Data" v={fmtDateTime(sale.date)}/>
      <Pair k="ID Transação" v={<span className="mono" style={{ fontSize: 12 }}>tx_98277{Math.floor(Math.random() * 999)}</span>}/>
    </div>
  );
}
function Pair({ k, v }){
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
      padding: "10px 0", borderBottom: "1px dashed var(--line)" }}>
      <span style={{ fontSize: 12, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600 }}>{k}</span>
      <span style={{ fontWeight: 500 }}>{v}</span>
    </div>
  );
}

// ============================================================
// Customers — left sidebar groups them by status:
//   • Compraram    → têm ao menos uma venda paga
//   • Não aprovou  → só têm vendas recusadas / expiradas
//   • Pendentes    → têm cobrança em andamento mas nenhuma paga ainda
// ============================================================
function Customers(){
  const { customers, sales } = useApp();

  // Build a per-customer summary derived from the sales table
  const enriched = React.useMemo(() => customers.map((c) => {
    const list = sales.filter(s => s.customer === c.name);
    const paid     = list.filter(s => s.status === "pago");
    const declined = list.filter(s => s.status === "recusado" || s.status === "expirado");
    const pending  = list.filter(s => s.status === "pendente");
    let group = "outros";
    if (paid.length > 0) group = "comprou";
    else if (pending.length > 0) group = "pendente";
    else if (declined.length > 0) group = "recusado";
    const lastSale = list.sort((a, b) => new Date(b.date) - new Date(a.date))[0];
    return { ...c, sales: list, paid, declined, pending, group, lastDate: lastSale?.date };
  }), [customers, sales]);

  const [group, setGroup] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const filtered = enriched.filter(c =>
    (group === "all" || c.group === group) &&
    (c.name.toLowerCase().includes(search.toLowerCase()) ||
     c.email.toLowerCase().includes(search.toLowerCase()))
  );
  const [active, setActive] = React.useState(enriched[0]?.id);
  React.useEffect(() => {
    if (!filtered.find(c => c.id === active)) setActive(filtered[0]?.id);
  }, [group, search]);

  const cur = enriched.find(c => c.id === active) || enriched[0];

  const counts = {
    all: enriched.length,
    comprou: enriched.filter(c => c.group === "comprou").length,
    pendente: enriched.filter(c => c.group === "pendente").length,
    recusado: enriched.filter(c => c.group === "recusado").length,
  };

  const groupBadge = (g) => {
    if (g === "comprou") return <StatusBadge status="pago"/>;
    if (g === "pendente") return <StatusBadge status="pendente"/>;
    if (g === "recusado") return <span className="badge badge-bad"><span className="dot"></span>Não aprovou</span>;
    return <span className="badge badge-mute"><span className="dot"></span>Sem compras</span>;
  };

  return (
    <Shell page="customers" eyebrow="Pessoas" title="Clientes"
      actions={<button className="btn btn-light"><Icon name="filter" size={14}/> Filtros</button>}>
      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 16 }}>
        {/* Left list with status tabs */}
        <div className="card" style={{ display: "flex", flexDirection: "column", maxHeight: "calc(100vh - 160px)" }}>
          <div style={{ padding: 14, borderBottom: "1px solid var(--line-2)" }}>
            <div style={{ position: "relative" }}>
              <Icon name="search" size={16} style={{ position: "absolute", left: 12, top: 11, color: "var(--graphite)" }}/>
              <input className="input" placeholder="Buscar cliente" value={search}
                onChange={(e) => setSearch(e.target.value)} style={{ paddingLeft: 36 }}/>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4, marginTop: 10 }}>
              <GroupTab label="Todos"        count={counts.all}      active={group === "all"}      onClick={() => setGroup("all")}      tone="mute"/>
              <GroupTab label="Compraram"    count={counts.comprou}  active={group === "comprou"}  onClick={() => setGroup("comprou")}  tone="ok"/>
              <GroupTab label="Pendentes"    count={counts.pendente} active={group === "pendente"} onClick={() => setGroup("pendente")} tone="warn"/>
              <GroupTab label="Não aprovou"  count={counts.recusado} active={group === "recusado"} onClick={() => setGroup("recusado")} tone="bad"/>
            </div>
          </div>

          <div style={{ padding: 8, overflowY: "auto", flex: 1 }}>
            {filtered.length === 0 && (
              <div className="empty" style={{ margin: 8, padding: "30px 16px" }}>
                <div className="ic"><Icon name="users"/></div>
                <h4>Nenhum cliente</h4>
                <span>Ajuste a busca ou troque a aba.</span>
              </div>
            )}
            {filtered.map((c) => (
              <div key={c.id} className="list-row"
                style={{ gridTemplateColumns: "auto 1fr auto", background: c.id === active ? "var(--paper)" : undefined }}
                onClick={() => setActive(c.id)}>
                <div className="avatar-sm">{initials(c.name)}</div>
                <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, gap: 2, minWidth: 0 }}>
                  <b style={{ fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</b>
                  <span style={{ fontSize: 12, color: "var(--mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.email}</span>
                  <span style={{ marginTop: 4 }}>{groupBadge(c.group)}</span>
                </div>
                <div style={{ textAlign: "right" }}>
                  <b style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(c.paid.reduce((a, s) => a + s.amount, 0))}</b>
                  <div style={{ fontSize: 11.5, color: "var(--mute)" }}>{c.paid.length} {c.paid.length === 1 ? "pedido" : "pedidos"}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Right detail */}
        <div className="card">
          {cur && <>
            <div className="card-head">
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <div className="avatar-sm" style={{ width: 38, height: 38, fontSize: 13 }}>{initials(cur.name)}</div>
                <div>
                  <h3>{cur.name}</h3>
                  <div className="sub">{cur.email}</div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                {groupBadge(cur.group)}
                <button className="btn btn-light btn-sm"><Icon name="wa" size={14}/> WhatsApp</button>
              </div>
            </div>
            <div style={{ padding: 24 }}>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 20 }}>
                <KpiBlock label="Aprovado"
                  value={fmtBRL(cur.paid.reduce((a, s) => a + s.amount, 0))}/>
                <KpiBlock label="Pedidos pagos" value={cur.paid.length}/>
                <KpiBlock label="Recusados / expirados" value={cur.declined.length}/>
                <KpiBlock label="Ticket médio"
                  value={cur.paid.length > 0 ? fmtBRL(cur.paid.reduce((a, s) => a + s.amount, 0) / cur.paid.length) : "—"}/>
              </div>

              <Pair k="E-mail" v={cur.email}/>
              <Pair k="WhatsApp" v={cur.phone}/>
              <Pair k="Cadastrado em" v={fmtDate("2026-03-12")}/>
              {cur.lastDate && <Pair k="Última interação" v={fmtDateTime(cur.lastDate)}/>}

              <div style={{ marginTop: 22 }}>
                <h4 style={{ margin: "0 0 10px", fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)" }}>Histórico de cobranças</h4>
                {cur.sales.length === 0 ? (
                  <div className="empty"><div className="ic"><Icon name="cart"/></div>
                    <h4>Nenhuma cobrança ainda</h4><span>O cliente ainda não recebeu uma cobrança.</span></div>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {cur.sales.map((s) => (
                      <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: 12,
                        border: "1px solid var(--line)", borderRadius: 12, background: "#fff" }}>
                        <span className="mono" style={{ fontSize: 12, color: "var(--mute)" }}>{s.id}</span>
                        <span style={{ flex: 1 }}>{s.product}</span>
                        <MethodPill method={s.method}/>
                        <b>{fmtBRL(s.amount)}</b>
                        <StatusBadge status={s.status}/>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </>}
        </div>
      </div>
    </Shell>
  );
}

function GroupTab({ label, count, active, onClick, tone }){
  const toneColor = {
    ok: "var(--ok)",
    warn: "var(--warn)",
    bad: "var(--bad)",
    mute: "var(--graphite)",
  }[tone] || "var(--graphite)";
  return (
    <button onClick={onClick} type="button"
      style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "8px 10px", borderRadius: 10,
        background: active ? "var(--paper)" : "transparent",
        border: 0, cursor: "pointer",
        font: "inherit", color: "inherit", textAlign: "left",
        transition: "background var(--t)",
      }}>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: toneColor }}></span>
      <span style={{ flex: 1, fontWeight: 500, fontSize: 13.5 }}>{label}</span>
      <span style={{
        fontSize: 11.5, fontWeight: 700,
        padding: "2px 8px", borderRadius: 999,
        background: active ? "var(--ink)" : "var(--paper-2)",
        color: active ? "#fff" : "var(--mute)",
        fontVariantNumeric: "tabular-nums",
      }}>{count}</span>
    </button>
  );
}

function KpiBlock({ label, value }){
  return (
    <div style={{ background: "var(--paper)", padding: 14, borderRadius: 14, border: "1px solid var(--line)" }}>
      <div style={{ fontSize: 11, letterSpacing: ".16em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em", marginTop: 4 }}>{value}</div>
    </div>
  );
}

// ============================================================
// Settings
// ============================================================
function Settings(){
  const { pushToast, stripeEnabled, setStripeEnabled, pixel, setPixel, webhooks, setWebhooks } = useApp();
  const [section, setSection] = React.useState("mp");
  const [tokenVisible, setTokenVisible] = React.useState(false);

  const sections = [
    { k: "mp", l: "Mercado Pago", icon: "money" },
    { k: "stripe", l: "Stripe", icon: "card" },
    { k: "webhook", l: "Webhook & notificações", icon: "bell" },
    { k: "custom", l: "Webhooks personalizados", icon: "link" },
    { k: "pixel", l: "Pixels & Tags", icon: "bolt" },
    { k: "brand", l: "Branding", icon: "tag" },
    { k: "urls", l: "URLs & domínio", icon: "globe" },
  ];

  return (
    <Shell page="settings" eyebrow="Sistema" title="Configurações">
      <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 16 }}>
        <div className="card" style={{ padding: 8 }}>
          {sections.map((s) => (
            <div key={s.k} className={cls("nav-item", section === s.k && "active")}
              onClick={() => setSection(s.k)}
              style={{ color: section === s.k ? "var(--ink)" : "var(--mute)", background: section === s.k ? "var(--paper)" : "transparent" }}>
              <Icon name={s.icon} /><span>{s.l}</span>
            </div>
          ))}
        </div>

        <div className="card">
          {section === "mp" && (
            <div>
              <div className="card-head">
                <div>
                  <h3>Integração Mercado Pago</h3>
                  <div className="sub">Configure o seu Access Token. Ele será armazenado e usado <b>apenas no servidor</b>.</div>
                </div>
                <span className="badge badge-ok"><span className="dot"></span>Conectado</span>
              </div>
              <div style={{ padding: 24, display: "grid", gap: 16 }}>
                <div className="field">
                  <label>Access Token (PRD)</label>
                  <div style={{ position: "relative" }}>
                    <input className="input mono" type={tokenVisible ? "text" : "password"}
                      defaultValue="APP_USR-1234-************-************-987654321"
                      style={{ paddingRight: 86 }} />
                    <button className="btn-icon" style={{ position: "absolute", right: 42, top: 5 }}
                      onClick={() => setTokenVisible(v => !v)} aria-label="Mostrar">
                      <Icon name={tokenVisible ? "eye-off" : "eye"} />
                    </button>
                    <button className="btn-icon" style={{ position: "absolute", right: 6, top: 5 }}
                      onClick={() => { pushToast("Token copiado."); }} aria-label="Copiar">
                      <Icon name="copy" />
                    </button>
                  </div>
                  <div className="hint">O token <b>nunca</b> é exposto no front-end. Toda chamada à API passa pelo backend.</div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <div className="field">
                    <label>Public Key</label>
                    <input className="input mono" defaultValue="APP_USR-pubk-abcdef-1234567890"/>
                  </div>
                  <div className="field">
                    <label>Ambiente</label>
                    <select className="select" defaultValue="prod">
                      <option value="prod">Produção</option>
                      <option value="sandbox">Sandbox</option>
                    </select>
                  </div>
                </div>
                <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
                  <button className="btn btn-light">Testar conexão</button>
                  <button className="btn" onClick={() => pushToast("Configurações salvas.")}>Salvar alterações</button>
                </div>
              </div>
            </div>
          )}

          {section === "stripe" && (
            <div>
              <div className="card-head">
                <div>
                  <h3>Integração Stripe</h3>
                  <div className="sub">Pagamentos internacionais e cartões globais. Chave secreta protegida no servidor.</div>
                </div>
                <span className={cls("badge", stripeEnabled ? "badge-ok" : "badge-mute")}>
                  <span className="dot"></span>
                  {stripeEnabled ? "Ativa no checkout" : "Não configurada"}
                </span>
              </div>
              <div style={{ padding: 24, display: "grid", gap: 16 }}>
                <div style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
                  padding: 14, borderRadius: 14,
                  background: stripeEnabled ? "var(--ok-soft)" : "var(--paper)",
                  border: "1px solid " + (stripeEnabled ? "rgba(31,125,58,.22)" : "var(--line)"),
                }}>
                  <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                    <Icon name="bolt" size={16} style={{ marginTop: 2, color: stripeEnabled ? "var(--ok)" : "var(--mute)" }}/>
                    <div>
                      <b style={{ fontSize: 14 }}>
                        {stripeEnabled ? "Stripe ativa para clientes" : "Habilitar Stripe no checkout"}
                      </b>
                      <div style={{ fontSize: 13, color: "var(--mute)", marginTop: 2 }}>
                        Quando ativa, aparece como método na página de pagamento. Quando desligada, fica oculta para o cliente.
                      </div>
                    </div>
                  </div>
                  <label className="switch" style={{ flex: "0 0 auto" }}>
                    <input type="checkbox" checked={stripeEnabled}
                      onChange={(e) => { setStripeEnabled(e.target.checked); pushToast(e.target.checked ? "Stripe ativa no checkout." : "Stripe oculta do checkout."); }}/>
                    <span className="track"></span><span className="knob"></span>
                  </label>
                </div>
                <div className="field">
                  <label>Publishable key</label>
                  <input className="input mono" defaultValue="pk_live_51N9z0K2eZvKYlo2C..."/>
                  <div className="hint">Esta chave pode ir ao front (usada no Stripe.js).</div>
                </div>
                <div className="field">
                  <label>Secret key</label>
                  <div style={{ position: "relative" }}>
                    <input className="input mono" type={tokenVisible ? "text" : "password"}
                      defaultValue="sk_live_51N9z0K2eZvKYlo2C************************"
                      style={{ paddingRight: 86 }} />
                    <button className="btn-icon" style={{ position: "absolute", right: 42, top: 5 }}
                      onClick={() => setTokenVisible(v => !v)} aria-label="Mostrar">
                      <Icon name={tokenVisible ? "eye-off" : "eye"} />
                    </button>
                    <button className="btn-icon" style={{ position: "absolute", right: 6, top: 5 }}
                      onClick={() => { pushToast("Chave copiada."); }} aria-label="Copiar">
                      <Icon name="copy" />
                    </button>
                  </div>
                  <div className="hint">Permanece <b>somente</b> no servidor. Toda chamada Stripe passa pelo backend.</div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <div className="field">
                    <label>Webhook signing secret</label>
                    <input className="input mono" defaultValue="whsec_8Zk***"/>
                  </div>
                  <div className="field">
                    <label>Moedas aceitas</label>
                    <select className="select" defaultValue="brl">
                      <option value="brl">BRL — Real</option>
                      <option value="usd">USD — Dólar</option>
                      <option value="eur">EUR — Euro</option>
                      <option value="multi">Multi-moeda (auto)</option>
                    </select>
                  </div>
                </div>
                <div>
                  <h4 style={{ margin: "10px 0 8px", fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)" }}>Métodos habilitados</h4>
                  <PushToggle label="Cartão internacional (Visa/Master/Amex)" defaultOn/>
                  <PushToggle label="Apple Pay" defaultOn/>
                  <PushToggle label="Google Pay" defaultOn/>
                  <PushToggle label="Link by Stripe (1-tap)" />
                </div>
                <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
                  <button className="btn btn-light">Testar conexão</button>
                  <button className="btn" onClick={() => pushToast("Stripe configurado.")}>Salvar alterações</button>
                </div>
              </div>
            </div>
          )}

          {section === "webhook" && (
            <div>
              <div className="card-head">
                <div>
                  <h3>Webhook & notificações</h3>
                  <div className="sub">Endpoint que o Mercado Pago chamará a cada evento.</div>
                </div>
              </div>
              <div style={{ padding: 24, display: "grid", gap: 16 }}>
                <div className="field">
                  <label>Endpoint do webhook</label>
                  <input className="input mono" defaultValue="https://pagblackx.holdingcriativa.com.br/api/webhook/mp"/>
                  <div className="hint">Valide assinatura via header <span className="mono">x-signature</span>.</div>
                </div>
                <div>
                  <h4 style={{ margin: "12px 0 8px", fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)" }}>Push notifications</h4>
                  <PushToggle label="Venda aprovada" defaultOn/>
                  <PushToggle label="Pix aprovado" defaultOn/>
                  <PushToggle label="Cartão recusado" defaultOn/>
                  <PushToggle label="Novo checkout gerado" />
                  <PushToggle label="Pix expirado" />
                </div>
                <div style={{ display: "flex", justifyContent: "flex-end" }}>
                  <button className="btn" onClick={() => pushToast("Webhook salvo.")}>Salvar</button>
                </div>
              </div>
            </div>
          )}

          {section === "custom" && (
            <CustomWebhooks webhooks={webhooks} setWebhooks={setWebhooks} pushToast={pushToast}/>
          )}

          {section === "pixel" && (
            <PixelSettings pixel={pixel} setPixel={setPixel} pushToast={pushToast}/>
          )}

          {section === "brand" && (
            <div>
              <div className="card-head">
                <div><h3>Branding</h3><div className="sub">Como o checkout aparece para o seu cliente.</div></div>
              </div>
              <div style={{ padding: 24, display: "grid", gap: 16 }}>
                <div className="field"><label>Nome exibido</label><input className="input" defaultValue="BlackX Studio"/></div>
                <div className="field"><label>Tagline curta</label><input className="input" defaultValue="Identidades visuais de alto padrão"/></div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <div className="field"><label>Cor principal</label><input className="input" defaultValue="#0a0a0a"/></div>
                  <div className="field"><label>Cor de fundo</label><input className="input" defaultValue="#f7f6f4"/></div>
                </div>
                <div style={{ display: "flex", justifyContent: "flex-end" }}>
                  <button className="btn" onClick={() => pushToast("Branding atualizado.")}>Salvar</button>
                </div>
              </div>
            </div>
          )}

          {section === "urls" && (
            <div>
              <div className="card-head"><div><h3>URLs & domínio</h3><div className="sub">Personalize o link público dos seus checkouts.</div></div></div>
              <div style={{ padding: 24, display: "grid", gap: 16 }}>
                <div className="field"><label>Domínio do checkout</label><input className="input mono" defaultValue="pagblackx.holdingcriativa.com.br"/></div>
                <div className="field"><label>URL pós-compra padrão</label><input className="input mono" defaultValue="https://blackx.holdingcriativa.com.br/obrigado"/></div>
                <div className="field"><label>Política de privacidade</label><input className="input mono" defaultValue="https://blackx.holdingcriativa.com.br/privacidade"/></div>
                <div style={{ display: "flex", justifyContent: "flex-end" }}>
                  <button className="btn" onClick={() => pushToast("URLs salvas.")}>Salvar</button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </Shell>
  );
}

function PushToggle({ label, defaultOn }){
  const [on, setOn] = React.useState(!!defaultOn);
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "12px 0", borderBottom: "1px dashed var(--line)" }}>
      <span>{label}</span>
      <label className="switch">
        <input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)}/>
        <span className="track"></span><span className="knob"></span>
      </label>
    </div>
  );
}

// ============================================================
// Pixels & Tags
// ============================================================
function PixelSettings({ pixel, setPixel, pushToast }){
  const update = (patch) => setPixel({ ...pixel, ...patch });
  const test = () => {
    if (!pixel.fbPixelId){ pushToast("Informe um Pixel ID antes de testar.", "warn"); return; }
    if (window.__pagblackx){
      window.__pagblackx.initPixel(pixel.fbPixelId);
      window.__pagblackx.trackPixel("PageView");
      window.__pagblackx.trackPixel("InitiateCheckout", { value: 0, currency: "BRL", test: true });
    }
    pushToast("Eventos de teste disparados para o Pixel.");
  };
  return (
    <div>
      <div className="card-head">
        <div>
          <h3>Pixels & Tags</h3>
          <div className="sub">Rastreie a jornada do cliente no Facebook / Meta Ads.</div>
        </div>
        <span className={cls("badge", pixel.enabled && pixel.fbPixelId ? "badge-ok" : "badge-mute")}>
          <span className="dot"></span>{pixel.enabled && pixel.fbPixelId ? "Rastreando" : "Inativo"}
        </span>
      </div>
      <div style={{ padding: 24, display: "grid", gap: 16 }}>

        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
          padding: 14, borderRadius: 14,
          background: pixel.enabled ? "var(--ok-soft)" : "var(--paper)",
          border: "1px solid " + (pixel.enabled ? "rgba(31,125,58,.22)" : "var(--line)"),
        }}>
          <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
            <Icon name="bolt" size={16} style={{ marginTop: 2, color: pixel.enabled ? "var(--ok)" : "var(--mute)" }}/>
            <div>
              <b style={{ fontSize: 14 }}>
                {pixel.enabled ? "Facebook Pixel ativo" : "Habilitar Facebook Pixel"}
              </b>
              <div style={{ fontSize: 13, color: "var(--mute)", marginTop: 2 }}>
                Quando ativo, eventos <span className="mono">PageView</span>, <span className="mono">InitiateCheckout</span> e <span className="mono">Purchase</span> são disparados automaticamente nas páginas do cliente.
              </div>
            </div>
          </div>
          <label className="switch" style={{ flex: "0 0 auto" }}>
            <input type="checkbox" checked={pixel.enabled} onChange={(e) => update({ enabled: e.target.checked })}/>
            <span className="track"></span><span className="knob"></span>
          </label>
        </div>

        <div className="field">
          <label>Pixel ID do Facebook</label>
          <input className="input mono" value={pixel.fbPixelId} placeholder="1234567890123456 (16 dígitos)"
            onChange={(e) => update({ fbPixelId: e.target.value.replace(/[^0-9]/g, "") })}/>
          <div className="hint">Pegue no Gerenciador de Eventos da Meta. Apenas dígitos.</div>
        </div>

        <div>
          <h4 style={{ margin: "8px 0 8px", fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)" }}>Eventos disparados</h4>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 0", borderBottom: "1px dashed var(--line)" }}>
            <div>
              <b style={{ fontSize: 14 }}>InitiateCheckout</b>
              <div style={{ fontSize: 12.5, color: "var(--mute)" }}>quando o cliente abre a página de pagamento</div>
            </div>
            <label className="switch">
              <input type="checkbox" checked={pixel.trackInitiate} onChange={(e) => update({ trackInitiate: e.target.checked })}/>
              <span className="track"></span><span className="knob"></span>
            </label>
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 0", borderBottom: "1px dashed var(--line)" }}>
            <div>
              <b style={{ fontSize: 14 }}>Purchase</b>
              <div style={{ fontSize: 12.5, color: "var(--mute)" }}>quando o pagamento é aprovado · envia value + currency</div>
            </div>
            <label className="switch">
              <input type="checkbox" checked={pixel.trackPurchase} onChange={(e) => update({ trackPurchase: e.target.checked })}/>
              <span className="track"></span><span className="knob"></span>
            </label>
          </div>
        </div>

        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn btn-light" onClick={test}>Disparar evento de teste</button>
          <button className="btn" onClick={() => pushToast("Pixel salvo.")}>Salvar</button>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// Webhooks personalizados — Make / Zapier / n8n / endpoint próprio
// ============================================================
const WH_EVENTS = [
  { k: "checkout.criado",    l: "Checkout criado" },
  { k: "pagamento.aprovado", l: "Pagamento aprovado" },
  { k: "pagamento.recusado", l: "Pagamento recusado" },
  { k: "pix.expirado",       l: "Pix expirado" },
  { k: "novo.cliente",       l: "Novo cliente" },
];

function CustomWebhooks({ webhooks, setWebhooks, pushToast }){
  const [draft, setDraft] = React.useState({ name: "", url: "", event: "pagamento.aprovado" });
  const custom = webhooks.filter(w => !w.system);
  const system = webhooks.filter(w => w.system);

  const add = () => {
    if (!draft.name.trim() || !/^https?:\/\//.test(draft.url)) {
      pushToast("Informe um nome e uma URL https válida.", "warn"); return;
    }
    setWebhooks([...webhooks, { id: uid(), active: true, system: false, ...draft }]);
    setDraft({ name: "", url: "", event: "pagamento.aprovado" });
    pushToast("Webhook adicionado.");
  };
  const toggle = (id) => setWebhooks(webhooks.map(w => w.id === id ? { ...w, active: !w.active } : w));
  const del = (id) => { setWebhooks(webhooks.filter(w => w.id !== id)); pushToast("Webhook removido.", "bad"); };
  const test = (w) => {
    const payload = { test: true, event: w.event, fired_at: new Date().toISOString() };
    if (window.__pagblackx) window.__pagblackx.fireWebhook(w.url, payload);
    pushToast(`Teste enviado para ${w.name}.`);
  };

  return (
    <div>
      <div className="card-head">
        <div>
          <h3>Webhooks personalizados</h3>
          <div className="sub">Conecte ao Make, Zapier, n8n ou ao seu próprio endpoint. Dispara JSON em cada evento.</div>
        </div>
        <span className="badge badge-mute"><span className="dot"></span>{custom.length} configurado{custom.length === 1 ? "" : "s"}</span>
      </div>
      <div style={{ padding: 24, display: "grid", gap: 18 }}>

        <div className="card" style={{ padding: 16, background: "var(--paper)", borderStyle: "dashed" }}>
          <div style={{ fontSize: 11.5, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600, marginBottom: 10 }}>
            Adicionar novo webhook
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.2fr 2fr 1fr auto", gap: 8 }}>
            <input className="input" placeholder="Ex: Notion CRM" value={draft.name}
              onChange={(e) => setDraft({ ...draft, name: e.target.value })}/>
            <input className="input mono" placeholder="https://hook.us2.make.com/..." value={draft.url}
              onChange={(e) => setDraft({ ...draft, url: e.target.value })}/>
            <select className="select" value={draft.event}
              onChange={(e) => setDraft({ ...draft, event: e.target.value })}>
              {WH_EVENTS.map(ev => <option key={ev.k} value={ev.k}>{ev.l}</option>)}
            </select>
            <button className="btn" onClick={add}>
              <Icon name="plus" size={14}/> Adicionar
            </button>
          </div>
        </div>

        <div>
          <div style={{ fontSize: 11.5, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600, marginBottom: 10 }}>
            Sistema (Mercado Pago / Stripe)
          </div>
          {system.map((w) => (
            <div key={w.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: 12,
              border: "1px solid var(--line)", borderRadius: 12, background: "#fff", marginBottom: 8 }}>
              <Icon name="link" size={16} style={{ color: "var(--mute)" }}/>
              <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, flex: 1, minWidth: 0 }}>
                <b style={{ fontSize: 13.5 }}>{w.name}</b>
                <span className="mono" style={{ fontSize: 11.5, color: "var(--mute)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{w.url}</span>
              </div>
              <span className="badge badge-ok"><span className="dot"></span>Ativo</span>
            </div>
          ))}
        </div>

        <div>
          <div style={{ fontSize: 11.5, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600, marginBottom: 10 }}>
            Personalizados ({custom.length})
          </div>
          {custom.length === 0 && (
            <div className="empty">
              <div className="ic"><Icon name="link"/></div>
              <h4>Sem webhooks personalizados</h4>
              <span>Cole uma URL acima para receber JSON em cada evento.</span>
            </div>
          )}
          {custom.map((w) => (
            <div key={w.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: 12,
              border: "1px solid var(--line)", borderRadius: 12, background: "#fff", marginBottom: 8 }}>
              <span style={{ width: 36, height: 36, borderRadius: 10, background: "var(--ink)", color: "#fff",
                display: "grid", placeItems: "center", flex: "0 0 auto" }}>
                <Icon name="link" size={16}/>
              </span>
              <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, flex: 1, minWidth: 0 }}>
                <b style={{ fontSize: 13.5 }}>{w.name}</b>
                <span className="mono" style={{ fontSize: 11.5, color: "var(--mute)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{w.url}</span>
                <span style={{ fontSize: 11, color: "var(--graphite)", letterSpacing: ".14em", textTransform: "uppercase", fontWeight: 600, marginTop: 2 }}>
                  → {WH_EVENTS.find(e => e.k === w.event)?.l || w.event}
                </span>
              </div>
              <label className="switch" style={{ flex: "0 0 auto" }}>
                <input type="checkbox" checked={w.active} onChange={() => toggle(w.id)}/>
                <span className="track"></span><span className="knob"></span>
              </label>
              <button className="btn-icon" onClick={() => test(w)} title="Disparar teste"><Icon name="send"/></button>
              <button className="btn-icon" onClick={() => del(w.id)} title="Remover"><Icon name="trash"/></button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Shell, Sidebar, Topbar, Dashboard, Sales, Customers, Settings });
