// Suppliers & Partners — live, read-only directory synced from the RDB Google Sheet.
// All columns as-is: Service Category · Company Name · Commission Details · Website · Notes.
// Data + fetch live in SupplierData.jsx (useSuppliers / supplierCategories).

function SuppliersPage() {
  const { rows, status } = useSuppliers();
  const [selectedCat, setSelectedCat] = React.useState("All");
  const [search, setSearch] = React.useState("");

  const cats = React.useMemo(() => supplierCategories(rows), [rows]);
  const q = search.trim().toLowerCase();
  const filtered = rows.filter(s =>
    (selectedCat === "All" || (s.category || "").split(",").map(c => c.trim()).includes(selectedCat)) &&
    (q === "" || s.company.toLowerCase().includes(q) || (s.category || "").toLowerCase().includes(q) || (s.notes || "").toLowerCase().includes(q))
  );

  return (
    <div style={{ padding: "48px 64px 96px", maxWidth: 1320, margin: "0 auto" }}>
      <PageHeader
        eyebrow="Backstage · Directory"
        title="Suppliers & Partners"
        intro="Approved travel suppliers and partners — service category, commission details, and account notes, kept current by RDB operations."
      />

      <StatStrip stats={[
        { label: "Partners",   value: status === "loading" ? "…" : String(rows.length), note: status === "live" ? "Up to date" : status === "sample" ? "Offline sample" : "Syncing…" },
        { label: "Categories", value: String(Math.max(0, cats.length - 1)), note: "Service types" },
        { label: "Access",     value: "Read-only", note: "Members only" },
        { label: "Updated",    value: "Live", note: "On every load" },
      ]} />

      {/* Controls: sync status · category chips · search */}
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 14, flexWrap: "wrap" }}>
        <SyncBadge status={status} />
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8, borderBottom: "1px solid var(--ink-4)", paddingBottom: 6 }}>
          <Icon name="search" size={15} color="var(--ink-6)" />
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search company, category, or notes" style={{ background: "transparent", border: "none", outline: "none", color: "var(--fg-1)", fontFamily: "var(--font-body)", fontSize: 13, width: 260 }} />
        </div>
      </div>

      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 18 }}>
        {cats.map(c => (
          <span key={c} onClick={() => setSelectedCat(c)} style={{
            fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase",
            padding: "7px 13px", lineHeight: 1, cursor: "pointer",
            border: c === selectedCat ? "1px solid var(--rdb-gold)" : "1px solid var(--ink-3)",
            background: c === selectedCat ? "var(--rdb-gold)" : "transparent",
            color: c === selectedCat ? "#0D0D0D" : "var(--fg-2)",
            transition: "all 160ms cubic-bezier(.22,1,.36,1)",
          }}>{c}</span>
        ))}
      </div>

      <div style={{ border: "1px solid var(--ink-3)" }}>
        <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 1040 }}>
          <thead>
            <tr style={{ borderBottom: "1px solid var(--ink-3)", background: "var(--ink-1)" }}>
              <Th sortable active>Company Name</Th>
              <Th style={{ minWidth: 160 }}>Service Category</Th>
              <Th style={{ minWidth: 200 }}>Commission Details</Th>
              <Th>Website</Th>
              <Th style={{ minWidth: 280 }}>Notes</Th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 && (
              <tr><td colSpan={5} style={{ padding: "40px 16px", textAlign: "center", fontFamily: "var(--font-body)", fontSize: 13, color: "var(--ink-6)" }}>No partners match your search.</td></tr>
            )}
            {filtered.map((s, i) => <SupplierRow key={s.company + i} s={s} last={i === filtered.length - 1} />)}
          </tbody>
        </table>
        </div>
        <TableFooter shown={filtered.length} total={rows.length} page={1} pages={1} />
      </div>
    </div>
  );
}

function prettyUrl(u) {
  return (u || "").replace(/^https?:\/\//, "").replace(/\/$/, "");
}

function SupplierRow({ s, last }) {
  const [hover, setHover] = React.useState(false);
  const cats = (s.category || "").split(",").map(c => c.trim()).filter(Boolean);
  return (
    <tr
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        borderBottom: last ? "none" : "1px solid var(--ink-2)",
        background: hover ? "var(--ink-1)" : "transparent",
        transition: "background 160ms cubic-bezier(.22,1,.36,1)",
      }}
    >
      <Td>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 32, height: 32, background: "var(--ink-2)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 13, color: "var(--rdb-gold)", flexShrink: 0 }}>
            {s.company.split(" ").slice(0, 2).map(w => w[0]).join("")}
          </div>
          <span style={{ fontWeight: 600, color: "var(--fg-1)", whiteSpace: "nowrap" }}>{s.company}</span>
        </div>
      </Td>
      <Td>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
          {cats.map(c => (
            <span key={c} style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-2)", border: "1px solid var(--ink-3)", padding: "3px 8px", whiteSpace: "nowrap" }}>{c}</span>
          ))}
        </div>
      </Td>
      <Td><span style={{ color: s.commission ? "var(--fg-2)" : "var(--ink-6)", fontSize: 12.5, lineHeight: 1.45, display: "block", maxWidth: 240 }}>{s.commission || "—"}</span></Td>
      <Td>{s.website ? <ExtLink href={s.website}>{prettyUrl(s.website)}</ExtLink> : <span style={{ color: "var(--ink-6)" }}>—</span>}</Td>
      <Td><span style={{ color: "var(--fg-3)", fontSize: 12, lineHeight: 1.5, display: "block", maxWidth: 380 }}>{s.notes || "—"}</span></Td>
    </tr>
  );
}

Object.assign(window, { SuppliersPage, prettyUrl });
