// AllenOps.jsx — Internal backoffice for the Allen ops team.
// Per PRODUCT.md: "Allen ops: curación de destacados, fee overrides, disputas,
// aprobaciones. Web primero." — the only canonical web surface in spec.
//
// Sections: Dashboard, Aprobaciones (KYC), Disputas, Comisiones, Curación, Sellers.

const { useState: useOpsState } = React;

const OPS_NAV = [
  { id: "dashboard",    label: "Dashboard",       icon: "tune" },
  { id: "aprobaciones", label: "Aprobaciones",    icon: "verified",      badge: 7 },
  { id: "disputas",     label: "Disputas",        icon: "support_agent", badge: 12 },
  { id: "comisiones",   label: "Comisiones",      icon: "credit_card" },
  { id: "curacion",     label: "Curación",        icon: "favorite" },
  { id: "sellers",      label: "Sellers",         icon: "storefront" },
];

const AllenOpsPage = ({ onNav }) => {
  const [tab, setTab] = useOpsState("dashboard");
  return (
    <div style={{ background: "var(--bg)", minHeight: "calc(100vh - 240px)" }}>
      {/* Internal banner */}
      <div style={{ background: "var(--hub-black)", color: "#fff", padding: "8px 32px", display: "flex", alignItems: "center", gap: 10, font: "500 12px var(--font-sans)" }}>
        <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--warning)" }} />
        <strong>Allen Ops</strong> · Herramienta interna · No compartir con sellers ni clientes
        <span style={{ flex: 1 }} />
        <span style={{ color: "var(--fg-on-dark-muted)" }}>Sesión: ana.ruiz@allenmx.com · Admin · Vallarta HQ</span>
      </div>

      <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: "0 32px", display: "grid", gridTemplateColumns: "240px 1fr", gap: 32, alignItems: "start", paddingTop: 24 }}>
        {/* SIDEBAR */}
        <aside style={{ position: "sticky", top: 184 }}>
          <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 10px", marginBottom: 12 }}>
              <div style={{ width: 32, height: 32, borderRadius: 16, background: "var(--hub-black)", color: "#fff", display: "grid", placeItems: "center", font: "700 12px var(--font-sans)" }}>AR</div>
              <div style={{ minWidth: 0 }}>
                <div className="title-sm" style={{ fontSize: 13 }}>Ana Ruiz</div>
                <div className="body-sm" style={{ fontSize: 11 }}>Admin · Vallarta HQ</div>
              </div>
            </div>
            <nav style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {OPS_NAV.map(s => (
                <button key={s.id} onClick={() => setTab(s.id)}
                  style={{
                    display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: "var(--radius-md)",
                    background: tab === s.id ? "var(--primary-soft)" : "transparent",
                    color: tab === s.id ? "var(--primary-press)" : "var(--fg-strong)",
                    border: 0, font: tab === s.id ? "700 13px var(--font-sans)" : "500 13px var(--font-sans)",
                    cursor: "pointer", textAlign: "left",
                  }}
                  onMouseEnter={e => { if (tab !== s.id) e.currentTarget.style.background = "var(--bg-elev-2)"; }}
                  onMouseLeave={e => { if (tab !== s.id) e.currentTarget.style.background = "transparent"; }}>
                  <AllenIcon name={s.icon} size={18} />
                  <span style={{ flex: 1 }}>{s.label}</span>
                  {s.badge != null && (
                    <span style={{ minWidth: 20, height: 20, padding: "0 6px", borderRadius: 10, background: "var(--warning)", color: "var(--fg-strong)", font: "700 11px/20px var(--font-sans)", textAlign: "center" }}>{s.badge}</span>
                  )}
                </button>
              ))}
              <div style={{ height: 1, background: "var(--border-soft)", margin: "8px 12px" }} />
              <button onClick={() => onNav("home")}
                style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: "var(--radius-md)", background: "transparent", color: "var(--fg-muted)", border: 0, font: "500 13px var(--font-sans)", cursor: "pointer", textAlign: "left" }}>
                <AllenIcon name="chevron_right" size={16} style={{ transform: "rotate(180deg)" }} />
                Salir a Marketplace
              </button>
            </nav>
          </div>
        </aside>

        {/* CONTENT */}
        <section>
          {tab === "dashboard"    && <OpsDashboard onTab={setTab} />}
          {tab === "aprobaciones" && <OpsApprovals />}
          {tab === "disputas"     && <OpsDisputes />}
          {tab === "comisiones"   && <OpsCommissions />}
          {tab === "curacion"     && <OpsCuration />}
          {tab === "sellers"      && <OpsSellers />}
        </section>
      </div>
    </div>
  );
};

// ===== DASHBOARD =====
const OpsDashboard = ({ onTab }) => (
  <div>
    <div style={{ marginBottom: 24 }}>
      <h1 className="display-sm">Operaciones</h1>
      <p className="body-sm" style={{ marginTop: 6 }}>Estado del marketplace · últimos 7 días</p>
    </div>

    {/* Pending action queues */}
    <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24, marginBottom: 16 }}>
      <h3 className="title" style={{ marginBottom: 16 }}>Tu cola</h3>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
        <QueueCard count={7}  label="KYC pendientes"   sub="SLA 24 h · 2 vencen hoy" tone="warning" onClick={() => onTab("aprobaciones")} />
        <QueueCard count={12} label="Disputas abiertas" sub="3 críticas, 9 estándar"  tone="error"   onClick={() => onTab("disputas")} />
        <QueueCard count={4}  label="Override de comisión" sub="Solicitudes de sellers"  tone="primary" onClick={() => onTab("comisiones")} />
      </div>
    </div>

    {/* KPI strip */}
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 16 }}>
      <OpsKpi label="GMV semana"      value="$2.4M"  delta="+18%" up />
      <OpsKpi label="Pedidos totales" value="3,872"  delta="+12%" up />
      <OpsKpi label="Sellers activos" value="284"    delta="+6"   up />
      <OpsKpi label="Tasa de éxito"   value="96.4%"  delta="−0.3 pp" />
    </div>

    {/* Marketplace health */}
    <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24 }}>
        <h3 className="title" style={{ marginBottom: 16 }}>Salud del marketplace</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {[
            { k: "Pedidos entregados a tiempo", v: 96.4, target: 95,  unit: "%" },
            { k: "Cumplimiento de SLA disputas (24h)", v: 87,  target: 90, unit: "%" },
            { k: "Tasa de cancelación por seller", v: 2.1, target: 3,   unit: "%", lowerBetter: true },
            { k: "Sellers con stock 0",            v: 4,   target: 8,  unit: "%", lowerBetter: true },
          ].map(m => {
            const good = m.lowerBetter ? m.v <= m.target : m.v >= m.target;
            return (
              <div key={m.k}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span className="body-sm" style={{ color: "var(--fg-strong)" }}>{m.k}</span>
                  <span style={{ font: "700 13px var(--font-mono)", color: good ? "var(--success)" : "var(--warning)" }}>{m.v}{m.unit}</span>
                </div>
                <div style={{ height: 6, borderRadius: 3, background: "var(--bg-elev-2)", overflow: "hidden" }}>
                  <div style={{ width: `${m.lowerBetter ? Math.min(100, m.v * 4) : m.v}%`, height: "100%", background: good ? "var(--success)" : "var(--warning)" }} />
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24 }}>
        <h3 className="title" style={{ marginBottom: 16 }}>Top sellers por GMV</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {[
            { name: "Ferretería El Tornillo", gmv: 184500, n: 142 },
            { name: "Cremas L'Oréal MX",      gmv: 156200, n: 98  },
            { name: "Hogar Vallarta",         gmv: 128900, n: 76  },
            { name: "Sony Store PV",          gmv: 112400, n: 54  },
            { name: "Adidas Outlet",          gmv:  98800, n: 71  },
          ].map((s, i) => (
            <div key={s.name} style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ width: 22, height: 22, borderRadius: 11, background: "var(--bg-elev-2)", color: "var(--fg-muted)", font: "700 11px/22px var(--font-mono)", textAlign: "center", flexShrink: 0 }}>{i + 1}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="title-sm" style={{ fontSize: 13 }}>{s.name}</div>
                <div className="body-sm" style={{ fontSize: 11, marginTop: 2 }}>{s.n} pedidos</div>
              </div>
              <span style={{ font: "700 13px var(--font-mono)", color: "var(--fg-strong)" }}>${(s.gmv / 1000).toFixed(0)}K</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  </div>
);

const QueueCard = ({ count, label, sub, tone, onClick }) => {
  const tones = {
    warning: { bg: "var(--warning-bg)", fg: "var(--warning)" },
    error:   { bg: "var(--error-bg)",   fg: "var(--error)" },
    primary: { bg: "var(--primary-soft)", fg: "var(--primary-press)" },
  };
  const c = tones[tone];
  return (
    <button onClick={onClick} style={{
      padding: 18, background: c.bg, border: 0, borderRadius: "var(--radius-md)",
      cursor: "pointer", textAlign: "left", display: "flex", flexDirection: "column", gap: 4,
    }}>
      <div style={{ font: "800 28px var(--font-sans)", color: c.fg, letterSpacing: "-0.01em" }}>{count}</div>
      <div className="title-sm" style={{ color: "var(--fg-strong)" }}>{label}</div>
      <div className="body-sm" style={{ fontSize: 12 }}>{sub}</div>
    </button>
  );
};

const OpsKpi = ({ label, value, delta, up }) => (
  <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-md)", padding: 18 }}>
    <div className="label" style={{ fontSize: 11 }}>{label}</div>
    <div className="price-lg" style={{ marginTop: 8, marginBottom: 6, fontSize: 24 }}>{value}</div>
    <div style={{ font: "600 11px var(--font-sans)", color: up ? "var(--success)" : "var(--error)", display: "flex", alignItems: "center", gap: 4 }}>
      <span style={{ display: "inline-block", transform: up ? "" : "rotate(180deg)" }}>↑</span> {delta}
    </div>
  </div>
);

// ===== APPROVALS (KYC) =====
const OpsApprovals = () => {
  const [selected, setSelected] = useOpsState("k1");
  const list = [
    { id: "k1", name: "Hogar Vallarta",     who: "Diana Ruiz",     since: "hace 14 h", risk: "low",    rfc: "HVA920310G47" },
    { id: "k2", name: "TechZone MX",        who: "Pablo Cárdenas", since: "hace 22 h", risk: "medium", rfc: "TZM010415AB1", flag: "RFC inactivo en SAT" },
    { id: "k3", name: "Boutique Daniela",   who: "Daniela Pérez",  since: "hace 26 h", risk: "low",    rfc: "BUD850612QR8" },
    { id: "k4", name: "Pinturas El Pintor", who: "Mario González", since: "hace 36 h", risk: "high",   rfc: "PIN700125XY3", flag: "Documentos ilegibles · CLABE no validada" },
  ];
  const cur = list.find(k => k.id === selected) || list[0];
  const toast = useToast();
  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h1 className="display-sm">Aprobaciones KYC</h1>
        <p className="body-sm" style={{ marginTop: 6 }}>{list.length} sellers esperan revisión · SLA 24 h</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "360px 1fr", gap: 16, alignItems: "start" }}>
        {/* Queue */}
        <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
          {list.map((k, i) => (
            <button key={k.id} onClick={() => setSelected(k.id)}
              style={{
                width: "100%", textAlign: "left", padding: 16, border: 0,
                background: selected === k.id ? "var(--primary-soft)" : "transparent",
                borderTop: i === 0 ? "none" : "1px solid var(--border-soft)",
                cursor: "pointer", display: "flex", flexDirection: "column", gap: 6,
              }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <span className="title-sm">{k.name}</span>
                <RiskBadge risk={k.risk} />
              </div>
              <div className="body-sm" style={{ fontSize: 12 }}>{k.who}</div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 2 }}>
                <span style={{ font: "500 11px var(--font-mono)", color: "var(--fg-subtle)" }}>{k.rfc}</span>
                <span className="body-sm" style={{ fontSize: 11 }}>{k.since}</span>
              </div>
              {k.flag && (
                <div style={{ marginTop: 4, font: "600 11px var(--font-sans)", color: "var(--error)", display: "flex", alignItems: "center", gap: 4 }}>
                  <AllenIcon name="close" size={12} color="var(--error)" /> {k.flag}
                </div>
              )}
            </button>
          ))}
        </div>

        {/* Detail */}
        <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 28 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start", marginBottom: 18 }}>
            <div>
              <RiskBadge risk={cur.risk} />
              <h2 className="headline-sm" style={{ marginTop: 8 }}>{cur.name}</h2>
              <p className="body-sm" style={{ marginTop: 4 }}>Representante: {cur.who}</p>
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              <button onClick={() => toast("Documentación solicitada")} style={{ background: "transparent", color: "var(--fg-strong)", border: "1px solid var(--border-strong)", padding: "10px 16px", borderRadius: "9999px", font: "600 13px var(--font-sans)", cursor: "pointer" }}>Pedir más docs</button>
              <button onClick={() => toast(`${cur.name} rechazado`)} style={{ background: "transparent", color: "var(--error)", border: "1.5px solid var(--error)", padding: "10px 16px", borderRadius: "9999px", font: "700 13px var(--font-sans)", cursor: "pointer" }}>Rechazar</button>
              <PrimaryButton onClick={() => toast(`${cur.name} aprobado`)}>Aprobar y activar</PrimaryButton>
            </div>
          </div>

          {cur.flag && (
            <div style={{ marginBottom: 18, padding: 14, background: "var(--error-bg)", borderRadius: "var(--radius-md)", display: "flex", alignItems: "center", gap: 10 }}>
              <AllenIcon name="close" size={18} color="var(--error)" />
              <span className="body-sm" style={{ color: "var(--fg-strong)" }}><strong>Alerta:</strong> {cur.flag}</span>
            </div>
          )}

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <KvBlock title="Datos fiscales" rows={[
              ["RFC", cur.rfc], ["Razón social", `${cur.name} S.A. de C.V.`], ["Régimen", "Régimen General"],
              ["Estatus SAT", cur.flag?.includes("SAT") ? "Inactivo" : "Activo"],
            ]} />
            <KvBlock title="Cuenta bancaria" rows={[
              ["Banco", "BBVA"], ["CLABE", "012 320 0123 4567 8901"], ["Titular", `${cur.name} S.A. de C.V.`],
              ["SPEI", cur.flag?.includes("CLABE") ? "No validada" : "Validada"],
            ]} />
          </div>

          <div style={{ marginTop: 18 }}>
            <h4 className="title-sm" style={{ marginBottom: 10 }}>Documentos</h4>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
              {["CSF", "Comprobante", "Estado cta.", "Acta"].map(d => (
                <div key={d} style={{ aspectRatio: "3/4", background: "var(--bg-elev-2)", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-soft)", display: "grid", placeItems: "center", color: "var(--fg-muted)", cursor: "pointer" }}>
                  <div style={{ textAlign: "center" }}>
                    <AllenIcon name="credit_card" size={28} />
                    <div style={{ font: "600 11px var(--font-sans)", marginTop: 6 }}>{d}.pdf</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const RiskBadge = ({ risk }) => {
  const cfg = { low: { l: "Riesgo bajo", fg: "var(--success)", bg: "var(--success-bg)" }, medium: { l: "Riesgo medio", fg: "#8A6500", bg: "var(--warning-bg)" }, high: { l: "Riesgo alto", fg: "var(--error)", bg: "var(--error-bg)" } }[risk];
  return <span style={{ font: "700 10px var(--font-sans)", color: cfg.fg, background: cfg.bg, padding: "3px 10px", borderRadius: "9999px", textTransform: "uppercase", letterSpacing: ".05em" }}>{cfg.l}</span>;
};

const KvBlock = ({ title, rows }) => (
  <div style={{ background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)", padding: 16 }}>
    <h4 className="title-sm" style={{ marginBottom: 10, fontSize: 13 }}>{title}</h4>
    {rows.map(([k, v]) => (
      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px solid var(--border-soft)" }}>
        <span className="body-sm" style={{ fontSize: 12 }}>{k}</span>
        <span style={{ font: "600 12px var(--font-sans)", color: "var(--fg-strong)" }}>{v}</span>
      </div>
    ))}
  </div>
);

// ===== DISPUTES =====
const OpsDisputes = () => {
  const [filter, setFilter] = useOpsState("all");
  const list = [
    { id: "D-2840", order: "AL-712840", buyer: "Lucía Pérez",   seller: "TechZone MX",          amount: 1499, reason: "Producto no recibido",    priority: "high",   age: "hace 6 h",  state: "Buyer abrió disputa" },
    { id: "D-2839", order: "AL-712830", buyer: "Carlos Rojas",  seller: "Adidas Outlet",        amount: 1899, reason: "Talla equivocada",         priority: "medium", age: "hace 18 h", state: "Esperando seller" },
    { id: "D-2838", order: "AL-712820", buyer: "María García",  seller: "Hogar Vallarta",       amount: 879,  reason: "Producto dañado",          priority: "high",   age: "hace 22 h", state: "Reembolso ofrecido" },
    { id: "D-2837", order: "AL-712802", buyer: "Sofía Luna",    seller: "Cremas L'Oréal MX",    amount: 459,  reason: "Producto falsificado",     priority: "high",   age: "hace 1 d",  state: "Investigación interna" },
    { id: "D-2836", order: "AL-712790", buyer: "Andrés Mata",   seller: "Sony Store PV",        amount: 4299, reason: "Cargo duplicado",          priority: "medium", age: "hace 1 d",  state: "Reembolso parcial" },
    { id: "D-2835", order: "AL-712779", buyer: "Bau Andalón",   seller: "Ferretería Tornillo",  amount: 549,  reason: "No corresponde",           priority: "low",    age: "hace 2 d",  state: "Esperando buyer" },
  ];
  const filtered = filter === "all" ? list : list.filter(d => d.priority === filter);
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: 8 }}>
        <h1 className="display-sm">Disputas</h1>
        <div style={{ display: "flex", gap: 8 }}>
          {[{ id: "all", l: "Todas" }, { id: "high", l: "Críticas" }, { id: "medium", l: "Estándar" }, { id: "low", l: "Bajas" }].map(f => (
            <button key={f.id} onClick={() => setFilter(f.id)}
              style={{
                padding: "8px 14px", borderRadius: "9999px",
                background: filter === f.id ? "var(--hub-black)" : "var(--bg-elev-1)",
                color: filter === f.id ? "#fff" : "var(--fg-strong)",
                border: filter === f.id ? 0 : "1px solid var(--border)",
                font: filter === f.id ? "700 12px var(--font-sans)" : "500 12px var(--font-sans)",
                cursor: "pointer",
              }}>{f.l}</button>
          ))}
        </div>
      </div>
      <p className="body-sm" style={{ marginBottom: 20 }}>{filtered.length} disputas · ordenadas por urgencia</p>

      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ background: "var(--bg-elev-2)" }}>
              <Th>Disputa</Th><Th>Pedido</Th><Th>Buyer / Seller</Th><Th>Motivo</Th><Th align="right">Monto</Th><Th align="right">Estado</Th><Th></Th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((d, i) => (
              <tr key={d.id} style={{ borderTop: "1px solid var(--border-soft)" }}>
                <td style={{ padding: "14px 16px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    {d.priority === "high" && <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--error)" }} title="Crítica" />}
                    {d.priority === "medium" && <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--warning)" }} />}
                    {d.priority === "low" && <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--border-strong)" }} />}
                    <span style={{ font: "700 12px var(--font-mono)" }}>{d.id}</span>
                  </div>
                  <div className="body-sm" style={{ fontSize: 11, marginTop: 2 }}>{d.age}</div>
                </td>
                <td style={{ padding: "14px 16px", font: "500 12px var(--font-mono)", color: "var(--fg-muted)" }}>{d.order}</td>
                <td style={{ padding: "14px 16px" }}>
                  <div className="title-sm" style={{ fontSize: 13 }}>{d.buyer}</div>
                  <div className="body-sm" style={{ fontSize: 11, marginTop: 2 }}>vs. {d.seller}</div>
                </td>
                <td style={{ padding: "14px 16px", font: "500 13px var(--font-sans)", color: "var(--fg-strong)" }}>{d.reason}</td>
                <td style={{ padding: "14px 16px", textAlign: "right", font: "700 14px var(--font-sans)", fontVariantNumeric: "tabular-nums" }}>${d.amount.toLocaleString("es-MX")}</td>
                <td style={{ padding: "14px 16px", textAlign: "right" }}>
                  <span style={{ font: "500 12px var(--font-sans)", color: "var(--fg-muted)" }}>{d.state}</span>
                </td>
                <td style={{ padding: "14px 16px", textAlign: "right" }}>
                  <button style={{ background: "var(--primary)", color: "#fff", border: 0, padding: "8px 14px", borderRadius: "9999px", font: "700 12px var(--font-sans)", cursor: "pointer" }}>Resolver</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ===== COMMISSIONS =====
const OpsCommissions = () => {
  const toast = useToast();
  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h1 className="display-sm">Comisiones</h1>
        <p className="body-sm" style={{ marginTop: 6 }}>Tabla base + overrides por seller o categoría</p>
      </div>

      {/* Base table */}
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24, marginBottom: 16 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
          <h3 className="title">Tabla base por categoría</h3>
          <button onClick={() => toast("Cambios publicados")} style={{ background: "transparent", color: "var(--primary)", border: 0, font: "700 13px var(--font-sans)", cursor: "pointer" }}>Editar</button>
        </div>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ borderBottom: "1px solid var(--border-soft)" }}>
              <Th>Categoría</Th><Th align="right">Comisión Allen</Th><Th align="right">Procesamiento pago</Th><Th align="right">Total seller paga</Th><Th align="right">Tasa promedio realizada</Th>
            </tr>
          </thead>
          <tbody>
            {[
              ["Electrónica",   "8.5%", 4.2,  98 ],
              ["Hogar",          "10.0%", 4.5, 165 ],
              ["Belleza",        "12.5%", 5.1, 92 ],
              ["Moda",           "11.0%", 4.8, 76 ],
              ["Deportes",        "9.0%", 4.3, 54 ],
              ["Herramientas",    "8.0%", 4.0, 23 ],
            ].map(([cat, pct, totalPct, sellers], i) => (
              <tr key={cat} style={{ borderBottom: i === 5 ? "none" : "1px solid var(--border-soft)" }}>
                <Td>{cat}</Td>
                <Td align="right" style={{ fontWeight: 700, fontFamily: "var(--font-mono)" }}>{pct}</Td>
                <Td align="right" style={{ fontFamily: "var(--font-mono)" }}>2.9% + $4</Td>
                <Td align="right" style={{ fontWeight: 700, fontFamily: "var(--font-mono)", color: "var(--primary)" }}>{totalPct}%</Td>
                <Td align="right" style={{ color: "var(--fg-muted)" }}>{sellers} sellers</Td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Overrides */}
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
          <h3 className="title">Overrides activos (4)</h3>
          <PrimaryButton><AllenIcon name="add" size={16} color="#fff" /> Nuevo override</PrimaryButton>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {[
            { seller: "Ferretería El Tornillo", reason: "Top seller · pricing match", base: "8.0%", override: "6.5%", until: "30 jun 2026" },
            { seller: "Cremas L'Oréal MX",      reason: "Acuerdo marca",              base: "12.5%", override: "9.0%", until: "31 dic 2026" },
            { seller: "Sony Store PV",          reason: "Lanzamiento Q1",             base: "8.5%", override: "7.0%", until: "15 abr 2026" },
            { seller: "Hogar Vallarta",         reason: "Promoción Mes del Hogar",    base: "10.0%", override: "8.5%", until: "31 mar 2026" },
          ].map((o, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr auto auto auto", gap: 16, alignItems: "center", padding: "14px 16px", background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
              <div>
                <div className="title-sm" style={{ fontSize: 13 }}>{o.seller}</div>
                <div className="body-sm" style={{ fontSize: 11, marginTop: 2 }}>{o.reason}</div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ font: "500 13px var(--font-mono)", color: "var(--fg-muted)", textDecoration: "line-through" }}>{o.base}</span>
                <span style={{ color: "var(--fg-hint)" }}>→</span>
                <span style={{ font: "800 14px var(--font-mono)", color: "var(--success)" }}>{o.override}</span>
              </div>
              <div className="body-sm" style={{ fontSize: 12 }}>Vence {o.until}</div>
              <button style={{ background: "transparent", border: 0, color: "var(--primary)", font: "700 12px var(--font-sans)", cursor: "pointer" }}>Editar</button>
              <button style={{ background: "transparent", border: 0, color: "var(--error)", font: "700 12px var(--font-sans)", cursor: "pointer" }}>Remover</button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ===== CURATION =====
const OpsCuration = () => {
  const toast = useToast();
  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h1 className="display-sm">Curación</h1>
        <p className="body-sm" style={{ marginTop: 6 }}>Edita "Lo más nuevo", "Ofertas" y "Marcas destacadas" del home</p>
      </div>

      {/* Slot: Lo más nuevo */}
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24, marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <div>
            <h3 className="title">Lo más nuevo</h3>
            <div className="body-sm" style={{ marginTop: 2 }}>4 slots · próxima publicación: lunes 10:00</div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button style={{ background: "var(--bg-elev-2)", color: "var(--fg-strong)", border: "1px solid var(--border-strong)", padding: "8px 14px", borderRadius: "9999px", font: "600 12px var(--font-sans)", cursor: "pointer" }}>Vista previa</button>
            <PrimaryButton onClick={() => toast("Cambios publicados al home")}>Publicar</PrimaryButton>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
          {CATALOG.slice(0, 4).map((p, i) => (
            <div key={p.id} style={{ background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)", padding: 10, position: "relative" }}>
              <div style={{ position: "absolute", top: 8, left: 8, width: 24, height: 24, borderRadius: 12, background: "var(--hub-black)", color: "#fff", font: "700 11px/24px var(--font-sans)", textAlign: "center", zIndex: 2 }}>{i + 1}</div>
              <div style={{ aspectRatio: 1, borderRadius: "var(--radius-sm)", overflow: "hidden", background: p.imgBg }}>
                <img src={p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </div>
              <div className="title-sm" style={{ fontSize: 12, marginTop: 8, minHeight: 32 }}>{p.name}</div>
              <div style={{ display: "flex", gap: 4, marginTop: 8 }}>
                <button style={{ flex: 1, background: "transparent", color: "var(--fg-muted)", border: 0, font: "600 11px var(--font-sans)", cursor: "pointer", padding: 4 }}>↑</button>
                <button style={{ flex: 1, background: "transparent", color: "var(--fg-muted)", border: 0, font: "600 11px var(--font-sans)", cursor: "pointer", padding: 4 }}>↓</button>
                <button style={{ flex: 2, background: "var(--error-bg)", color: "var(--error)", border: 0, font: "700 11px var(--font-sans)", borderRadius: "var(--radius-sm)", cursor: "pointer", padding: 4 }}>Quitar</button>
              </div>
            </div>
          ))}
        </div>
        <button style={{ marginTop: 12, width: "100%", padding: 12, border: "2px dashed var(--border-strong)", borderRadius: "var(--radius-md)", background: "transparent", color: "var(--fg-muted)", font: "600 13px var(--font-sans)", cursor: "pointer" }}>
          <AllenIcon name="add" size={16} /> Agregar slot (máx 6)
        </button>
      </div>

      {/* Slot: Ofertas */}
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24, marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <div>
            <h3 className="title">Ofertas</h3>
            <div className="body-sm" style={{ marginTop: 2 }}>Auto: top 12 productos con descuento ≥20% · {CATALOG.filter(p => p.discount >= 20).length} elegibles</div>
          </div>
          <Switch on={true} onChange={() => toast("Modo automático actualizado")} />
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: 14, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
          <AllenIcon name="tune" size={18} color="var(--fg-muted)" />
          <span className="body-sm" style={{ color: "var(--fg-strong)" }}>Modo automático activo. Para curar manualmente, apaga el toggle.</span>
        </div>
      </div>

      {/* Featured brands */}
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24 }}>
        <h3 className="title" style={{ marginBottom: 16 }}>Marcas destacadas</h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8 }}>
          {BRANDS.map((b, i) => (
            <div key={b.id} style={{ ...b.style, border: b.style.border || 0, borderRadius: "var(--radius-md)", padding: "20px 12px", font: "700 14px var(--font-sans)", textAlign: "center", position: "relative" }}>
              <span style={{ position: "absolute", top: 4, left: 4, font: "700 10px var(--font-sans)", background: "rgba(0,0,0,.4)", color: "#fff", padding: "2px 6px", borderRadius: 6 }}>{i + 1}</span>
              {b.name}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const Switch = ({ on, onChange }) => (
  <button onClick={() => onChange(!on)} style={{ width: 44, height: 26, borderRadius: 13, background: on ? "var(--primary)" : "var(--border-strong)", border: 0, cursor: "pointer", position: "relative" }}>
    <span style={{ position: "absolute", top: 2, left: on ? 20 : 2, width: 22, height: 22, borderRadius: 11, background: "#fff", boxShadow: "var(--elev-1)", transition: "left var(--dur-fast) var(--ease-out-quart)" }} />
  </button>
);

// ===== SELLERS =====
const OpsSellers = () => (
  <div>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: 24 }}>
      <div>
        <h1 className="display-sm">Sellers</h1>
        <p className="body-sm" style={{ marginTop: 6 }}>284 sellers activos · 7 pendientes</p>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--bg-elev-1)", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-input)", padding: "10px 14px" }}>
          <AllenIcon name="search" size={16} color="var(--fg-soft)" />
          <input placeholder="Buscar seller…" style={{ border: 0, outline: 0, background: "transparent", font: "400 13px var(--font-sans)", color: "var(--fg-strong)", width: 200 }} />
        </div>
      </div>
    </div>
    <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
      <table style={{ width: "100%", borderCollapse: "collapse" }}>
        <thead><tr style={{ background: "var(--bg-elev-2)" }}><Th>Seller</Th><Th>Categoría</Th><Th align="right">GMV 30d</Th><Th align="right">Pedidos</Th><Th align="right">Tasa cancel.</Th><Th align="right">Rating</Th><Th align="right">Estado</Th></tr></thead>
        <tbody>
          {[
            { n: "Ferretería El Tornillo", c: "Herramientas",  g: 184500, o: 142, x: 1.2, r: 4.8, s: "active" },
            { n: "Cremas L'Oréal MX",      c: "Belleza",       g: 156200, o: 98,  x: 0.8, r: 4.9, s: "active" },
            { n: "Hogar Vallarta",         c: "Hogar",         g: 128900, o: 76,  x: 2.1, r: 4.7, s: "active" },
            { n: "Sony Store PV",          c: "Electrónica",   g: 112400, o: 54,  x: 1.5, r: 4.8, s: "active" },
            { n: "Adidas Outlet",          c: "Deportes",      g:  98800, o: 71,  x: 3.4, r: 4.5, s: "warning" },
            { n: "TechZone MX",            c: "Electrónica",   g:  76300, o: 42,  x: 5.8, r: 4.2, s: "warning" },
            { n: "Boutique Daniela",       c: "Moda",          g:  54100, o: 38,  x: 1.8, r: 4.6, s: "review" },
          ].map((s, i, a) => (
            <tr key={s.n} style={{ borderTop: "1px solid var(--border-soft)" }}>
              <Td style={{ padding: "14px 16px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--bg-section)", display: "grid", placeItems: "center", font: "700 12px var(--font-sans)", color: "var(--fg-muted)" }}>{s.n.split(/\s+/).map(w => w[0]).slice(0, 2).join("")}</div>
                  <span className="title-sm" style={{ fontSize: 13 }}>{s.n}</span>
                </div>
              </Td>
              <Td style={{ padding: "14px 16px" }}>{s.c}</Td>
              <Td align="right" style={{ padding: "14px 16px", fontWeight: 700, fontFamily: "var(--font-mono)" }}>${(s.g / 1000).toFixed(0)}K</Td>
              <Td align="right" style={{ padding: "14px 16px" }}>{s.o}</Td>
              <Td align="right" style={{ padding: "14px 16px", color: s.x > 5 ? "var(--error)" : s.x > 3 ? "var(--warning)" : "var(--success)", fontWeight: 600 }}>{s.x}%</Td>
              <Td align="right" style={{ padding: "14px 16px" }}>★ {s.r}</Td>
              <Td align="right" style={{ padding: "14px 16px" }}>
                {s.s === "active"  && <span style={{ font: "700 10px var(--font-sans)", color: "var(--success)", background: "var(--success-bg)", padding: "3px 10px", borderRadius: "9999px", textTransform: "uppercase", letterSpacing: ".05em" }}>Activo</span>}
                {s.s === "warning" && <span style={{ font: "700 10px var(--font-sans)", color: "#8A6500", background: "var(--warning-bg)", padding: "3px 10px", borderRadius: "9999px", textTransform: "uppercase", letterSpacing: ".05em" }}>Vigilado</span>}
                {s.s === "review"  && <span style={{ font: "700 10px var(--font-sans)", color: "var(--primary-press)", background: "var(--primary-soft)", padding: "3px 10px", borderRadius: "9999px", textTransform: "uppercase", letterSpacing: ".05em" }}>En revisión</span>}
              </Td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

const Th = ({ children, align = "left" }) => (
  <th style={{ font: "700 11px var(--font-sans)", color: "var(--fg-subtle)", textTransform: "uppercase", letterSpacing: ".06em", textAlign: align, padding: "12px 16px" }}>{children}</th>
);
const Td = ({ children, align = "left", style }) => (
  <td style={{ font: "500 13px var(--font-sans)", color: "var(--fg-strong)", textAlign: align, padding: "12px 16px", ...style }}>{children}</td>
);

window.AllenOpsPage = AllenOpsPage;
