// Seller.jsx — Allen Adm (Ecommerce seller) panel.
// Lays the basis of the "Web primero" Allen ops surface mentioned in PRODUCT.md.
// Sidebar nav + 4 sections: Dashboard, Pedidos (kanban), Productos, Mi tienda.

const { useState: useSellerState } = React;

const SELLER_NAV = [
  { id: "dashboard", label: "Dashboard",  icon: "tune" },
  { id: "pedidos",   label: "Pedidos",    icon: "shopping_basket", badge: 4 },
  { id: "productos", label: "Productos",  icon: "shopping_cart" },
  { id: "tienda",    label: "Mi tienda",  icon: "storefront" },
];

const SellerPanel = ({ onNav }) => {
  const [tab, setTab] = useSellerState("dashboard");
  return (
    <div style={{ background: "var(--bg)", minHeight: "calc(100vh - 240px)" }}>
      <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: "0 32px", display: "grid", gridTemplateColumns: "260px 1fr", gap: 32, alignItems: "start" }}>
        {/* SIDEBAR */}
        <aside style={{ position: "sticky", top: 160 }}>
          <Breadcrumb items={["Inicio", "Vende en Allen", SELLER_NAV.find(s => s.id === tab)?.label]} />
          <div style={{ background: "var(--bg-elev-1)", borderRadius: "var(--radius-lg)", padding: 18, border: "1px solid var(--border-soft)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, padding: "0 6px" }}>
              <div style={{ width: 36, height: 36, borderRadius: 18, background: "var(--hub-black)", color: "#fff", display: "grid", placeItems: "center", font: "700 13px var(--font-sans)" }}>FE</div>
              <div>
                <div className="title-sm">Ferretería El Tornillo</div>
                <div className="body-sm" style={{ display: "flex", alignItems: "center", gap: 4 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 3, background: "var(--success)" }} /> Abierta
                </div>
              </div>
            </div>
            <nav style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {SELLER_NAV.map(s => (
                <button key={s.id} onClick={() => setTab(s.id)}
                  style={{
                    display: "flex", alignItems: "center", gap: 12,
                    padding: "10px 14px", 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(--error)", color: "#fff", font: "700 11px/20px var(--font-sans)", textAlign: "center" }}>{s.badge}</span>
                  )}
                </button>
              ))}
              <div style={{ height: 1, background: "var(--border-soft)", margin: "8px 14px" }} />
              <button onClick={() => onNav("home")}
                style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 14px", 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)" }} />
                Volver al marketplace
              </button>
            </nav>
          </div>
        </aside>

        {/* CONTENT */}
        <section>
          {tab === "dashboard" && <DashboardTab />}
          {tab === "pedidos"   && <OrdersKanbanTab />}
          {tab === "productos" && <ProductsAdmTab />}
          {tab === "tienda"    && <StoreSettingsTab />}
        </section>
      </div>
    </div>
  );
};

// ----- DASHBOARD -----
const DashboardTab = () => (
  <div>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: 24 }}>
      <div>
        <h1 className="display-sm">Hola, Ferretería El Tornillo</h1>
        <p className="body-sm" style={{ marginTop: 6 }}>Esto pasó en tu tienda en los últimos 7 días.</p>
      </div>
      <select defaultValue="7d" style={{ ...inputStyle, padding: "10px 14px", paddingRight: 36, appearance: "none", cursor: "pointer", backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23515259' stroke-width='2'><path d='m6 9 6 6 6-6'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }}>
        <option value="24h">Últimas 24 horas</option>
        <option value="7d">Últimos 7 días</option>
        <option value="30d">Últimos 30 días</option>
        <option value="90d">Últimos 90 días</option>
      </select>
    </div>

    {/* KPI cards */}
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 32 }}>
      <KpiCard label="Ingresos"      value="$48,290" delta="+12%" deltaUp icon="credit_card" />
      <KpiCard label="Pedidos"       value="127"     delta="+8%"  deltaUp icon="shopping_basket" />
      <KpiCard label="Ticket promedio" value="$380.5" delta="+3%" deltaUp icon="local_shipping" />
      <KpiCard label="Tasa de conversión" value="3.4%" delta="-0.4 pp" icon="tune" />
    </div>

    {/* Chart placeholder + activity feed */}
    <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16, marginBottom: 32 }}>
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
          <h3 className="title">Ingresos por día</h3>
          <div style={{ display: "flex", gap: 16, font: "500 12px var(--font-sans)", color: "var(--fg-muted)" }}>
            <span style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--primary)" }} /> Esta semana</span>
            <span style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--border-input)" }} /> Anterior</span>
          </div>
        </div>
        <RevenueChart />
      </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: 18 }}>Actividad reciente</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {[
            { icon: "shopping_basket", color: "var(--primary)",       fg: "var(--primary-soft)",  title: "Nuevo pedido #AL-712840", sub: "hace 3 min · $2,499" },
            { icon: "favorite",        color: "var(--favorite-selected, #B691FF)", fg: "var(--favorite-unselected, #FAF6FF)", title: "Tornillería Pro favoriteada", sub: "hace 12 min" },
            { icon: "check_circle",    color: "var(--success)",       fg: "var(--success-bg)",    title: "Pedido #AL-712820 entregado", sub: "hace 1 h" },
            { icon: "local_shipping",  color: "#8A6500",              fg: "var(--warning-bg)",    title: "Pedido #AL-712810 salió",     sub: "hace 2 h" },
            { icon: "credit_card",     color: "var(--primary)",       fg: "var(--primary-soft)",  title: "Pago procesado #AL-712802",   sub: "hace 4 h · $1,560" },
          ].map((it, i) => (
            <div key={i} style={{ display: "flex", gap: 12 }}>
              <span style={{ width: 32, height: 32, borderRadius: 16, background: it.fg, display: "grid", placeItems: "center", flexShrink: 0 }}>
                <AllenIcon name={it.icon} size={16} color={it.color} fill={it.icon === "favorite" || it.icon === "check_circle"} />
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="title-sm" style={{ fontSize: 13, lineHeight: 1.3 }}>{it.title}</div>
                <div className="body-sm" style={{ fontSize: 12, marginTop: 2 }}>{it.sub}</div>
              </div>
            </div>
          ))}
        </div>
        <button style={{ marginTop: 18, background: "transparent", border: 0, color: "var(--primary)", font: "700 13px var(--font-sans)", cursor: "pointer", padding: 0 }}>Ver todo →</button>
      </div>
    </div>

    {/* Top products */}
    <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24, marginBottom: 32 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
        <h3 className="title">Productos más vendidos</h3>
        <a style={{ color: "var(--primary)", font: "700 13px var(--font-sans)", cursor: "pointer" }}>Ver todos →</a>
      </div>
      <table style={{ width: "100%", borderCollapse: "collapse" }}>
        <thead>
          <tr style={{ borderBottom: "1px solid var(--border-soft)" }}>
            <Th>Producto</Th><Th align="right">Unidades</Th><Th align="right">Ingresos</Th><Th align="right">Stock</Th>
          </tr>
        </thead>
        <tbody>
          {CATALOG.slice(0, 5).map((p, i) => (
            <tr key={p.id} style={{ borderBottom: i === 4 ? "none" : "1px solid var(--border-soft)" }}>
              <td style={{ padding: "12px 0" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 44, height: 44, borderRadius: "var(--radius-sm)", overflow: "hidden", background: p.imgBg, flexShrink: 0 }}><img src={p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /></div>
                  <div style={{ minWidth: 0 }}>
                    <div className="title-sm" style={{ fontSize: 13 }}>{p.name}</div>
                    <div className="body-sm" style={{ fontSize: 12, marginTop: 2 }}>{p.brand}</div>
                  </div>
                </div>
              </td>
              <Td align="right">{(48 - i * 7).toLocaleString("es-MX")}</Td>
              <Td align="right" style={{ fontWeight: 700 }}>${((48 - i * 7) * p.price).toLocaleString("es-MX")}</Td>
              <Td align="right">
                <span style={{
                  font: "700 11px var(--font-sans)",
                  color: (p.inStock || 12) < 5 ? "var(--error)" : "var(--success)",
                  background: (p.inStock || 12) < 5 ? "var(--error-bg)" : "var(--success-bg)",
                  padding: "3px 10px", borderRadius: "9999px",
                }}>{p.inStock || 12} disp.</span>
              </Td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

const KpiCard = ({ label, value, delta, deltaUp, icon }) => (
  <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 22 }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
      <span className="label">{label}</span>
      <span style={{ width: 32, height: 32, borderRadius: 16, background: "var(--bg-section)", display: "grid", placeItems: "center" }}>
        <AllenIcon name={icon} size={16} color="var(--fg-strong)" />
      </span>
    </div>
    <div className="price-lg" style={{ marginTop: 14, marginBottom: 6 }}>{value}</div>
    <div style={{ font: "600 12px var(--font-sans)", color: deltaUp ? "var(--success)" : "var(--error)", display: "flex", alignItems: "center", gap: 4 }}>
      <span style={{ display: "inline-block", transform: deltaUp ? "" : "rotate(180deg)" }}>↑</span> {delta} vs. periodo anterior
    </div>
  </div>
);

// Tiny SVG bar chart — not a real data viz, just an aesthetic placeholder.
const RevenueChart = () => {
  const bars = [
    { day: "Lun", this: 60, prev: 40 },
    { day: "Mar", this: 80, prev: 70 },
    { day: "Mié", this: 50, prev: 55 },
    { day: "Jue", this: 95, prev: 60 },
    { day: "Vie", this: 110, prev: 80 },
    { day: "Sáb", this: 130, prev: 95 },
    { day: "Dom", this: 75, prev: 50 },
  ];
  const max = 140;
  return (
    <div style={{ display: "flex", gap: 16, alignItems: "flex-end", height: 180, padding: "0 4px" }}>
      {bars.map(b => (
        <div key={b.day} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
          <div style={{ display: "flex", gap: 4, alignItems: "flex-end", height: 140 }}>
            <div style={{ width: 14, height: `${(b.prev / max) * 100}%`, background: "var(--border-input)", borderRadius: "4px 4px 0 0" }} />
            <div style={{ width: 14, height: `${(b.this / max) * 100}%`, background: "var(--primary)", borderRadius: "4px 4px 0 0" }} />
          </div>
          <span style={{ font: "500 11px var(--font-sans)", color: "var(--fg-subtle)" }}>{b.day}</span>
        </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: "10px 0" }}>{children}</th>
);
const Td = ({ children, align = "left", style }) => (
  <td style={{ font: "500 13px var(--font-sans)", color: "var(--fg-strong)", textAlign: align, padding: "12px 0", ...style }}>{children}</td>
);

// ----- ORDERS KANBAN -----
const KAN_COLS = [
  { id: "REQUESTED",   label: "Nuevos",     color: "var(--warning)" },
  { id: "ACCEPTED",    label: "Aceptados",  color: "var(--primary)" },
  { id: "READY",       label: "Listos",     color: "var(--success-strong)" },
  { id: "IN_PROGRESS", label: "En camino",  color: "#8A6500" },
  { id: "COMPLETED",   label: "Entregados", color: "var(--success)" },
];
const KAN_ORDERS = [
  { id: "AL-712840", status: "REQUESTED",   client: "Bau Andalón",    items: 1, total: 2499, t: "hace 3 min",  pid: "p001" },
  { id: "AL-712841", status: "REQUESTED",   client: "Lucía Pérez",    items: 2, total: 1758, t: "hace 8 min",  pid: "p003" },
  { id: "AL-712830", status: "ACCEPTED",    client: "Carlos R.",      items: 1, total: 1899, t: "hace 22 min", pid: "p005" },
  { id: "AL-712820", status: "READY",       client: "María G.",       items: 3, total: 2247, t: "hace 1 h",    pid: "p006" },
  { id: "AL-712810", status: "IN_PROGRESS", client: "Diego T.",       items: 1, total: 5499, t: "hace 2 h",    pid: "p007" },
  { id: "AL-712802", status: "COMPLETED",   client: "Sofía L.",       items: 2, total: 1560, t: "hace 4 h",    pid: "p010" },
  { id: "AL-712790", status: "COMPLETED",   client: "Andrés M.",      items: 1, total: 4299, t: "hace 6 h",    pid: "p012" },
];

const OrdersKanbanTab = () => {
  const toast = useToast();
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: 8 }}>
        <h1 className="display-sm">Pedidos</h1>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span className="body-sm">Notificaciones de pedido</span>
          <Switch on onChange={() => {}} />
        </div>
      </div>
      <p className="body-sm" style={{ marginBottom: 24 }}>Acepta nuevos pedidos. Cuando estés online, los pedidos te avisan con sonido aunque tu cel esté en silencio.</p>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 14 }}>
        {KAN_COLS.map(col => {
          const items = KAN_ORDERS.filter(o => o.status === col.id);
          return (
            <div key={col.id} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 4px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 4, background: col.color }} />
                  <span className="title-sm" style={{ fontSize: 13 }}>{col.label}</span>
                </div>
                <span style={{ font: "700 11px var(--font-sans)", color: "var(--fg-muted)" }}>{items.length}</span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10, minHeight: 100 }}>
                {items.map(o => {
                  const p = CATALOG.find(x => x.id === o.pid);
                  return (
                    <div key={o.id} style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-md)", padding: 12, display: "flex", flexDirection: "column", gap: 8, cursor: "pointer", boxShadow: "var(--elev-1)" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                        <span style={{ font: "700 12px var(--font-sans)", color: "var(--fg-strong)" }}>#{o.id.split("-")[1]}</span>
                        <span style={{ font: "500 10px var(--font-sans)", color: "var(--fg-subtle)" }}>{o.t}</span>
                      </div>
                      <div className="title-sm" style={{ fontSize: 12, lineHeight: 1.3 }}>{o.client}</div>
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        {p && <div style={{ width: 28, height: 28, borderRadius: 6, background: p.imgBg, overflow: "hidden", flexShrink: 0 }}><img src={p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /></div>}
                        <span style={{ font: "500 11px var(--font-sans)", color: "var(--fg-muted)" }}>{o.items} producto{o.items === 1 ? "" : "s"}</span>
                      </div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 4 }}>
                        <span style={{ font: "800 14px var(--font-sans)", color: "var(--fg-strong)" }}>${o.total.toLocaleString("es-MX")}</span>
                        {col.id === "REQUESTED" && (
                          <button onClick={() => toast(`Pedido #${o.id} aceptado`)} style={{ background: "var(--primary)", color: "#fff", border: 0, padding: "6px 14px", borderRadius: "9999px", font: "700 11px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)" }}>Aceptar</button>
                        )}
                        {col.id === "ACCEPTED" && (
                          <button onClick={() => toast(`#${o.id} marcado como listo`)} style={{ background: "var(--success-strong)", color: "#fff", border: 0, padding: "6px 12px", borderRadius: "9999px", font: "700 11px var(--font-sans)", cursor: "pointer" }}>Listo</button>
                        )}
                      </div>
                    </div>
                  );
                })}
                {items.length === 0 && (
                  <div style={{ padding: 20, textAlign: "center", background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)", color: "var(--fg-subtle)", font: "500 12px var(--font-sans)" }}>Sin pedidos</div>
                )}
              </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", transition: "background var(--dur-fast)" }}>
    <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>
);

// ----- PRODUCTS ADM -----
const ProductsAdmTab = () => {
  const [q, setQ] = useSellerState("");
  const [showNew, setShowNew] = useSellerState(false);
  const list = CATALOG.filter(p => p.name.toLowerCase().includes(q.toLowerCase()));
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: 24 }}>
        <div>
          <h1 className="display-sm">Productos</h1>
          <p className="body-sm" style={{ marginTop: 6 }}>{CATALOG.length} productos en tu catálogo</p>
        </div>
        <PrimaryButton onClick={() => setShowNew(true)}><AllenIcon name="add" size={16} color="#fff" /> Nuevo producto</PrimaryButton>
      </div>

      <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
        <div style={{ flex: 1, 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={18} color="var(--fg-soft)" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar por nombre o SKU" style={{ flex: 1, border: 0, outline: 0, background: "transparent", font: "400 14px var(--font-sans)", color: "var(--fg-strong)" }} />
        </div>
        <button style={{ ...outlineBtnAdm, display: "flex", alignItems: "center", gap: 6 }}><AllenIcon name="tune" size={16} /> Filtros</button>
        <button style={outlineBtnAdm}>Exportar</button>
      </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>Producto</Th><Th>SKU</Th><Th align="right">Precio</Th><Th align="right">Stock</Th><Th align="right">Estado</Th><Th></Th>
            </tr>
          </thead>
          <tbody>
            {list.map((p, i) => (
              <tr key={p.id} style={{ borderTop: "1px solid var(--border-soft)" }}>
                <td style={{ padding: "14px 16px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <div style={{ width: 44, height: 44, borderRadius: "var(--radius-sm)", overflow: "hidden", background: p.imgBg, flexShrink: 0 }}><img src={p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /></div>
                    <div>
                      <div className="title-sm" style={{ fontSize: 13 }}>{p.name}</div>
                      <div className="body-sm" style={{ fontSize: 11, marginTop: 2 }}>{CATEGORIES.find(c => c.id === p.cat)?.label}</div>
                    </div>
                  </div>
                </td>
                <Td style={{ padding: "14px 16px", fontFamily: "var(--font-mono)", fontSize: 12 }}>{p.id.toUpperCase()}</Td>
                <Td align="right" style={{ padding: "14px 16px", fontWeight: 700 }}>${p.price.toLocaleString("es-MX")}</Td>
                <Td align="right" style={{ padding: "14px 16px" }}>{p.inStock || 12}</Td>
                <td style={{ padding: "14px 16px", textAlign: "right" }}>
                  <span style={{
                    font: "700 11px var(--font-sans)",
                    color: (p.inStock || 12) === 0 ? "var(--error)" : (p.inStock || 12) < 5 ? "#8A6500" : "var(--success)",
                    background: (p.inStock || 12) === 0 ? "var(--error-bg)" : (p.inStock || 12) < 5 ? "var(--warning-bg)" : "var(--success-bg)",
                    padding: "4px 10px", borderRadius: "9999px",
                  }}>
                    {(p.inStock || 12) === 0 ? "Agotado" : (p.inStock || 12) < 5 ? "Stock bajo" : "Activo"}
                  </span>
                </td>
                <td style={{ padding: "14px 16px", textAlign: "right" }}>
                  <button style={{ ...iconChipBtnAdm }}><AllenIcon name="tune" size={16} /></button>
                  <button style={{ ...iconChipBtnAdm, marginLeft: 4 }}><AllenIcon name="delete" size={16} /></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {showNew && <NewProductModal onClose={() => setShowNew(false)} />}
    </div>
  );
};

// ----- NEW PRODUCT MODAL -----
const NewProductModal = ({ onClose }) => {
  const [form, setForm] = useSellerState({
    name: "", brand: "", cat: "herramientas", desc: "", price: "", was: "",
    stock: "", sku: "", images: 0, status: "draft",
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toast = useToast();
  const commission = form.price ? Math.round(form.price * 0.085) : 0;
  const payout = form.price ? form.price - commission - Math.round(form.price * 0.029) - 4 : 0;

  return (
    <div onClick={onClose}
      style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.55)", zIndex: 100, display: "grid", placeItems: "center", padding: 32, animation: "modalFade .2s var(--ease-out-quart)" }}>
      <style>{`@keyframes modalFade { from { opacity: 0 } to { opacity: 1 } }
                @keyframes modalSlide { from { transform: translateY(20px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }`}</style>
      <div onClick={e => e.stopPropagation()} style={{
        background: "var(--bg-elev-1)", borderRadius: "var(--radius-xl)",
        maxWidth: 880, width: "100%", maxHeight: "calc(100vh - 64px)",
        display: "flex", flexDirection: "column", overflow: "hidden",
        boxShadow: "var(--elev-pop)", animation: "modalSlide .25s var(--ease-out-quart)",
      }}>
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 28px", borderBottom: "1px solid var(--border-soft)" }}>
          <div>
            <h2 className="headline-sm">Nuevo producto</h2>
            <p className="body-sm" style={{ marginTop: 2 }}>Llena los datos, sube fotos y publícalo cuando quieras.</p>
          </div>
          <button onClick={onClose} aria-label="Cerrar"
            style={{ width: 36, height: 36, borderRadius: 18, background: "var(--bg-elev-2)", border: 0, cursor: "pointer", display: "grid", placeItems: "center", color: "var(--fg-strong)" }}>
            <AllenIcon name="close" size={18} />
          </button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: "auto", padding: "24px 28px", display: "grid", gridTemplateColumns: "1fr 280px", gap: 32 }}>
          {/* Left — form */}
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Field label="Nombre del producto"><TextInput placeholder="Audífonos Bluetooth Pro con cancelación de ruido" value={form.name} onChange={e => set("name", e.target.value)} /></Field>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Marca"><TextInput placeholder="Sony" value={form.brand} onChange={e => set("brand", e.target.value)} /></Field>
              <Field label="Categoría">
                <select value={form.cat} onChange={e => set("cat", e.target.value)}
                  style={{ ...inputStyle, width: "100%", appearance: "none", paddingRight: 36, backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23515259' stroke-width='2'><path d='m6 9 6 6 6-6'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }}>
                  {CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
                </select>
              </Field>
            </div>
            <Field label="Descripción" hint="Hasta 2,000 caracteres. Apoya tus claims con datos reales.">
              <textarea rows={4} value={form.desc} onChange={e => set("desc", e.target.value)}
                placeholder="Sofisticado audio con cancelación activa de ruido y 30 horas de batería. Incluye estuche de carga rápida."
                style={{ ...inputStyle, fontFamily: "var(--font-sans)", resize: "vertical" }} />
            </Field>

            {/* Images */}
            <div>
              <label style={{ font: "600 13px var(--font-sans)", color: "var(--fg-strong)", display: "block", marginBottom: 6 }}>Fotos</label>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
                {[0, 1, 2, 3].map(i => (
                  <button key={i} onClick={() => set("images", Math.max(form.images, i + 1))}
                    style={{
                      aspectRatio: 1, borderRadius: "var(--radius-md)",
                      border: i < form.images ? "1.5px solid var(--primary)" : "2px dashed var(--border-strong)",
                      background: i < form.images ? "var(--primary-soft)" : "var(--bg-elev-2)",
                      cursor: "pointer", display: "grid", placeItems: "center", color: "var(--fg-muted)",
                    }}>
                    {i < form.images ? (
                      <AllenIcon name="check" size={24} color="var(--primary)" weight={3} />
                    ) : (
                      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                        <AllenIcon name="add" size={20} />
                        <span style={{ font: "500 11px var(--font-sans)" }}>{i === 0 ? "Principal" : `Foto ${i + 1}`}</span>
                      </div>
                    )}
                  </button>
                ))}
              </div>
              <p className="body-sm" style={{ marginTop: 6 }}>Mínimo 1 foto. La primera es la principal. JPG o PNG, máximo 5 MB cada una.</p>
            </div>

            {/* Pricing */}
            <div>
              <h4 className="title-sm" style={{ marginBottom: 10 }}>Precio y stock</h4>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
                <Field label="Precio venta (MXN)"><TextInput type="number" placeholder="1249" value={form.price} onChange={e => set("price", +e.target.value || "")} /></Field>
                <Field label="Precio anterior" hint="Opcional"><TextInput type="number" placeholder="1799" value={form.was} onChange={e => set("was", +e.target.value || "")} /></Field>
                <Field label="Stock"><TextInput type="number" placeholder="50" value={form.stock} onChange={e => set("stock", +e.target.value || "")} /></Field>
              </div>
              <Field label="SKU"><TextInput placeholder="AUDIO-BT-PRO-01" value={form.sku} onChange={e => set("sku", e.target.value.toUpperCase())} style={{ fontFamily: "var(--font-mono)", letterSpacing: ".05em" }} /></Field>
            </div>
          </div>

          {/* Right — sidebar */}
          <aside style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div style={{ background: "var(--bg-elev-2)", borderRadius: "var(--radius-lg)", padding: 18 }}>
              <h4 className="title-sm" style={{ marginBottom: 4 }}>Vista previa</h4>
              <p className="body-sm" style={{ marginBottom: 12, fontSize: 11 }}>Así te verán los compradores.</p>
              <div style={{ background: "var(--bg-elev-1)", borderRadius: "var(--radius-md)", padding: 10, boxShadow: "var(--elev-1)" }}>
                <div style={{ aspectRatio: 1, borderRadius: "var(--radius-sm)", background: "var(--bg-section)", display: "grid", placeItems: "center", color: "var(--fg-hint)" }}>
                  {form.images > 0 ? <AllenIcon name="check_circle" size={28} color="var(--success)" /> : <AllenIcon name="shopping_basket" size={28} />}
                </div>
                <div style={{ font: "500 10px var(--font-sans)", color: "var(--fg-subtle)", textTransform: "uppercase", letterSpacing: ".05em", marginTop: 8 }}>{form.brand || "Marca"}</div>
                <div style={{ font: "600 13px/1.3 var(--font-sans)", color: "var(--fg-strong)", marginTop: 2, minHeight: 34 }}>{form.name || "Nombre del producto"}</div>
                <div style={{ font: "800 16px var(--font-sans)", color: "var(--fg-strong)", marginTop: 6 }}>
                  ${form.price ? form.price.toLocaleString("es-MX") : "—"}
                  {form.was && <span style={{ marginLeft: 6, font: "500 11px var(--font-sans)", color: "var(--fg-hint)", textDecoration: "line-through" }}>${form.was.toLocaleString("es-MX")}</span>}
                </div>
              </div>
            </div>

            {/* Payout */}
            <div style={{ background: "var(--bg-elev-2)", borderRadius: "var(--radius-lg)", padding: 18 }}>
              <h4 className="title-sm" style={{ marginBottom: 10 }}>Tu pago neto</h4>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <PayLine k="Precio venta" v={form.price ? `$${form.price.toLocaleString("es-MX")}` : "—"} />
                <PayLine k="Comisión Allen 8.5%" v={form.price ? `−$${commission.toLocaleString("es-MX")}` : "—"} muted />
                <PayLine k="Procesamiento pago" v={form.price ? `−$${(Math.round(form.price * 0.029) + 4).toLocaleString("es-MX")}` : "—"} muted />
              </div>
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <span className="title-sm" style={{ fontSize: 13 }}>Recibes</span>
                <span className="price" style={{ fontSize: 18, color: "var(--success)" }}>{form.price ? `$${payout.toLocaleString("es-MX")}` : "—"}</span>
              </div>
            </div>
          </aside>
        </div>

        {/* Footer */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 28px", borderTop: "1px solid var(--border-soft)", gap: 12 }}>
          <button onClick={() => { set("status", "draft"); toast("Guardado como borrador"); onClose(); }}
            style={{ background: "transparent", color: "var(--fg-muted)", border: 0, font: "600 13px var(--font-sans)", cursor: "pointer", padding: "10px 16px" }}>
            Guardar borrador
          </button>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={onClose}
              style={{ background: "var(--bg-elev-2)", color: "var(--fg-strong)", border: "1px solid var(--border-strong)", padding: "12px 20px", borderRadius: "9999px", font: "700 13px var(--font-sans)", cursor: "pointer" }}>Cancelar</button>
            <PrimaryButton onClick={() => { toast(`"${form.name || "Producto"}" publicado`); onClose(); }}>Publicar producto</PrimaryButton>
          </div>
        </div>
      </div>
    </div>
  );
};

const PayLine = ({ k, v, muted }) => (
  <div style={{ display: "flex", justifyContent: "space-between", font: "500 12px var(--font-sans)", color: muted ? "var(--fg-muted)" : "var(--fg-strong)" }}>
    <span>{k}</span><span style={{ fontVariantNumeric: "tabular-nums" }}>{v}</span>
  </div>
);

// ----- STORE SETTINGS -----
const StoreSettingsTab = () => {
  const toast = useToast();
  return (
    <div>
      <h1 className="display-sm" style={{ marginBottom: 8 }}>Mi tienda</h1>
      <p className="body-sm" style={{ marginBottom: 24 }}>Información pública de tu tienda en Allen.</p>

      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 28, marginBottom: 16 }}>
        <h3 className="title" style={{ marginBottom: 16 }}>Datos de la tienda</h3>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <Field label="Nombre de la tienda"><TextInput defaultValue="Ferretería El Tornillo" /></Field>
          <Field label="Categoría principal">
            <select defaultValue="herramientas" style={{ ...inputStyle, appearance: "none", width: "100%", paddingRight: 36, backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23515259' stroke-width='2'><path d='m6 9 6 6 6-6'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }}>
              {CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
            </select>
          </Field>
          <Field label="Descripción" hint="Máximo 200 caracteres">
            <textarea defaultValue="Ferretería con 25 años en Puerto Vallarta. Tornillería, herramientas y materiales para construcción." rows={3} style={{ ...inputStyle, fontFamily: "var(--font-sans)", resize: "vertical" }} />
          </Field>
          <Field label="WhatsApp de soporte"><TextInput defaultValue="+52 322 145 2287" /></Field>
        </div>
      </div>

      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 28, marginBottom: 16 }}>
        <h3 className="title" style={{ marginBottom: 4 }}>Comisión y pagos</h3>
        <p className="body-sm" style={{ marginBottom: 16 }}>Allen cobra una comisión transparente sobre cada venta.</p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
          {[
            { k: "Comisión Allen",      v: "8.5%",     sub: "Por venta concretada" },
            { k: "Comisión por pago",   v: "2.9% + $4",sub: "Procesamiento" },
            { k: "Tu tasa efectiva",    v: "~11.4%",   sub: "Promedio últimos 30 días" },
          ].map(s => (
            <div key={s.k} style={{ padding: 14, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
              <div className="label">{s.k}</div>
              <div className="price" style={{ marginTop: 6 }}>{s.v}</div>
              <div className="body-sm" style={{ marginTop: 4 }}>{s.sub}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 28 }}>
        <h3 className="title" style={{ marginBottom: 16 }}>Estado de la tienda</h3>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 16px", background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 10, height: 10, borderRadius: 5, background: "var(--success)", boxShadow: "0 0 0 4px var(--success-bg)" }} />
            <div>
              <div className="title-sm" style={{ fontSize: 14 }}>Tienda abierta</div>
              <div className="body-sm">Recibiendo pedidos en tiempo real</div>
            </div>
          </div>
          <Switch on onChange={() => toast("Estado actualizado")} />
        </div>
      </div>
    </div>
  );
};

const outlineBtnAdm = { background: "var(--bg-elev-1)", color: "var(--fg-strong)", border: "1px solid var(--border-strong)", padding: "10px 16px", borderRadius: "var(--radius-input)", font: "600 13px var(--font-sans)", cursor: "pointer" };
const iconChipBtnAdm = { width: 32, height: 32, borderRadius: 16, background: "var(--bg-elev-2)", border: 0, display: "inline-grid", placeItems: "center", cursor: "pointer", color: "var(--fg-muted)" };

window.SellerPanel = SellerPanel;
