// Reseller portal — User Manuals. Read-only, download-focused document
// library — see GET /api/portal/user-manuals (not company-scoped; manuals
// are general product/reseller literature, same access rule as Spec
// Sheets) and GET /api/portal/user-manuals/:id/file (streams the uploaded
// PDF from R2 as a download — Content-Disposition: attachment, NOT
// inline, per the customer's explicit "also they will be downloadable by
// the reseller"). Every admin-only control (name editing, upload/replace/
// remove) lives exclusively on admin-user-manuals-page.jsx — a reseller
// only ever gets a "Download" button per manual.

const formatManualFileSize = (bytes) => {
  if (!bytes) return "";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
};

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

  const loadManuals = () => {
    fetch("/api/portal/user-manuals", { credentials: "same-origin" })
      .then((r) => (r.ok ? r.json() : { manuals: [] }))
      .then((data) => setManuals({ status: "ready", items: data.manuals || [] }))
      .catch(() => setManuals({ 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(loadManuals))
      .catch(() => { /* switch failed silently */ });
  };

  useEffect(() => {
    loadMe();
    loadManuals();
  }, []); // 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-user-manuals" onNavigate={onNavigate}
      userName={user.name} companyName={company.name}
      isSoloStaff={isSoloStaff} companies={companies}
      currentCompanyId={company.id} onSwitchCompany={handleSwitchCompany}
      subtitle="Reseller portal"
      title="User manuals."
    >
      <p style={{
        fontFamily: "var(--font-body)", fontSize: 14,
        color: "var(--pt-fg-dim)", margin: "-16px 0 36px",
      }}>
        Installation guides, firmware notes and other reference PDFs — download whichever you need.
      </p>

      {manuals.status === "loading" ? (
        <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--pt-fg-faint2)" }}>Loading…</div>
      ) : manuals.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 user manuals available yet.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {manuals.items.map((m) => (
            <div key={m.id} data-testid={`portal-user-manual-row-${m.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)" }}>
                  <i className="fas fa-file-pdf" style={{ color: "rgba(190,40,40,0.9)", marginRight: 8 }} />
                  {m.name}
                </div>
                {(m.file_size || m.uploaded_at) && (
                  <div style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--pt-fg-faint2)", marginTop: 4 }}>
                    {[formatManualFileSize(m.file_size), m.file_filename].filter(Boolean).join(" · ")}
                  </div>
                )}
              </div>
              <a
                href={`/api/portal/user-manuals/${m.id}/file`} download
                data-testid={`portal-user-manual-download-${m.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",
                }}
              >
                <i className="fas fa-download" style={{ marginRight: 8 }} />
                Download
              </a>
            </div>
          ))}
        </div>
      )}
    </ResellerShell>
  );
}

Object.assign(window, { ResellerUserManualsPage });
