// Reseller portal — Spec Sheets. Read-only product literature — see
// GET /api/portal/spec-sheets (not company-scoped; spec sheets are
// product literature, not pricing) and GET /api/portal/spec-sheets/:id/
// file (streams the uploaded PDF from R2). Deliberately strips every
// upload/replace/remove/URL-edit control that admin-spec-sheets-page.jsx
// has — those are Solo-staff-only actions; a reseller only ever gets a
// single "Open \u2197" link per product, exactly like the admin page's
// own openHref fallback pattern (prefer the uploaded PDF, fall back to
// the external URL).

function ResellerSpecSheetsPage({ onNavigate }) {
  const [state, setState] = useState({ status: "loading", user: null, company: null, isSoloStaff: false });
  const [companies, setCompanies] = useState([]);
  const [products, setProducts] = useState({ status: "loading", items: [] });

  const loadSheets = () => {
    fetch("/api/portal/spec-sheets", { credentials: "same-origin" })
      .then((r) => (r.ok ? r.json() : { products: [] }))
      .then((data) => setProducts({ status: "ready", items: data.products || [] }))
      .catch(() => setProducts({ status: "ready", items: [] }));
  };

  const loadMe = (onDone) => {
    fetch("/api/portal/me", { credentials: "same-origin" })
      .then(async (r) => {
        if (!r.ok) throw new Error("not signed in");
        return r.json();
      })
      .then((data) => {
        setState({ status: "ready", user: data.user, company: data.company, isSoloStaff: !!data.isSoloStaff });
        if (data.isSoloStaff) {
          fetch("/api/portal/companies", { credentials: "same-origin" })
            .then((r) => (r.ok ? r.json() : { companies: [] }))
            .then((d) => setCompanies(d.companies || []))
            .catch(() => setCompanies([]));
        }
        if (onDone) onDone();
      })
      .catch(() => onNavigate("reseller-login"));
  };

  const handleSwitchCompany = (companyId) => {
    fetch("/api/portal/switch-company", {
      method: "POST", credentials: "same-origin",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ companyId }),
    })
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then(() => loadMe(loadSheets))
      .catch(() => { /* switch failed silently */ });
  };

  useEffect(() => {
    loadMe();
    loadSheets();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps -- mount-only

  if (state.status === "loading") {
    return <section style={{ background: "var(--pt-bg)", minHeight: "calc(100vh - 88px)" }} />;
  }

  const { user, company, isSoloStaff } = state;

  return (
    <ResellerShell
      page="portal-spec-sheets" onNavigate={onNavigate}
      userName={user.name} companyName={company.name}
      isSoloStaff={isSoloStaff} companies={companies}
      currentCompanyId={company.id} onSwitchCompany={handleSwitchCompany}
      subtitle="Reseller portal"
      title="Spec sheets."
    >
      <p style={{
        fontFamily: "var(--font-body)", fontSize: 14,
        color: "var(--pt-fg-dim)", margin: "-16px 0 36px",
      }}>
        Product literature for every item in the catalogue — open or download the PDF straight from here.
      </p>

      {products.status === "loading" ? (
        <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--pt-fg-faint2)" }}>Loading\u2026</div>
      ) : products.items.length === 0 ? (
        <div style={{
          background: "var(--pt-surface)", border: "1px solid var(--pt-border)",
          padding: "22px 24px", fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--pt-fg-dimmer)",
        }}>
          No products in the catalogue yet.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {products.items.map((p) => {
            const hasFile = Boolean(p.spec_sheet_key);
            const openHref = hasFile ? `/api/portal/spec-sheets/${p.id}/file` : p.spec_sheet_url;
            const hasSheet = hasFile || Boolean(p.spec_sheet_url);
            return (
              <div key={p.id} data-testid={`portal-spec-sheet-row-${p.id}`} style={{
                background: "var(--pt-surface)", border: "1px solid var(--pt-border-2)",
                padding: "18px 22px", display: "flex", justifyContent: "space-between",
                alignItems: "center", flexWrap: "wrap", gap: 14,
              }}>
                <div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, textTransform: "uppercase", color: "var(--pt-fg)" }}>{p.name}</div>
                  {p.description && (
                    <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--pt-fg-dim)", marginTop: 4 }}>{p.description}</div>
                  )}
                </div>
                {hasSheet ? (
                  <a
                    href={openHref} target="_blank" rel="noreferrer"
                    data-testid={`portal-spec-sheet-open-${p.id}`}
                    style={{
                      fontFamily: "var(--font-body)", fontSize: 12, fontWeight: 500,
                      letterSpacing: "0.1em", textTransform: "uppercase",
                      color: "var(--pt-accent-fg)", background: "var(--pt-accent-bg)",
                      border: "1px solid var(--pt-accent-bg)", padding: "10px 18px",
                      textDecoration: "none", whiteSpace: "nowrap",
                    }}
                  >Open \u2197</a>
                ) : (
                  <span style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--pt-fg-faint2)", textTransform: "uppercase", letterSpacing: "0.08em" }}>
                    Not yet available
                  </span>
                )}
              </div>
            );
          })}
        </div>
      )}
    </ResellerShell>
  );
}

Object.assign(window, { ResellerSpecSheetsPage });
