// Reseller portal — Price List. Purely a READ-ONLY view of the same
// price grid admin-pricing-page.jsx edits, filtered server-side to the
// signed-in reseller's OWN tier only (see GET /api/portal/products —
// the query already joins price_list_entries WHERE tier = company.tier,
// so there is no tier dimension to render here at all — just one price
// per product per currency, exactly what the reseller is quoted at).
// Deliberately no input/save controls anywhere on this page — a
// reseller should never be able to edit their own price list.
//
// Reuses the same loadMe/handleSwitchCompany + portalMoney conventions
// as reseller-quotes-page.jsx (which also fetches this exact
// /api/portal/products endpoint for its "New quote" builder).

function ResellerPriceListPage({ onNavigate }) {
  const [state, setState] = useState({ status: "loading", user: null, company: null, isSoloStaff: false });
  const [companies, setCompanies] = useState([]);
  const [catalogue, setCatalogue] = useState({ status: "loading", products: [], tier: "", defaultCurrency: "GBP" });

  const loadCatalogue = () => {
    setCatalogue((c) => ({ ...c, status: "loading" }));
    fetch("/api/portal/products", { credentials: "same-origin" })
      .then((r) => (r.ok ? r.json() : { products: [], tier: "", defaultCurrency: "GBP" }))
      .then((data) => setCatalogue({
        status: "ready",
        products: data.products || [],
        tier: data.tier || "",
        defaultCurrency: data.defaultCurrency || "GBP",
      }))
      .catch(() => setCatalogue({ status: "ready", products: [], tier: "", defaultCurrency: "GBP" }));
  };

  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(loadCatalogue))
      .catch(() => { /* switch failed silently */ });
  };

  useEffect(() => {
    loadMe();
    loadCatalogue();
  }, []); // 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;
  const currencies = Array.from(
    new Set(catalogue.products.flatMap((p) => p.prices.map((pr) => pr.currency)))
  ).sort((a, b) => (a === catalogue.defaultCurrency ? -1 : b === catalogue.defaultCurrency ? 1 : a.localeCompare(b)));

  return (
    <ResellerShell
      page="portal-price-list" onNavigate={onNavigate}
      userName={user.name} companyName={company.name}
      isSoloStaff={isSoloStaff} companies={companies}
      currentCompanyId={company.id} onSwitchCompany={handleSwitchCompany}
      subtitle="Reseller portal"
      title="Price list."
    >
      <p style={{
        fontFamily: "var(--font-body)", fontSize: 14,
        color: "var(--pt-fg-dim)", margin: "-16px 0 8px",
      }}>
        Your prices for the {SETTINGS_TIER_LABELS_PL[catalogue.tier] || "current"} tier — the same figures used when you build a quote.
      </p>
      <p style={{
        fontFamily: "var(--font-body)", fontSize: 12.5,
        color: "var(--pt-fg-faint2)", margin: "0 0 36px",
      }}>
        Need a different tier or a custom rate? Contact your account manager.
      </p>

      {catalogue.status === "loading" ? (
        <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--pt-fg-faint2)" }}>Loading\u2026</div>
      ) : catalogue.products.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 priced products yet — contact your account manager to get your price list set up.
        </div>
      ) : (
        <div style={{
          background: "var(--pt-surface)", border: "1px solid var(--pt-border)", overflowX: "auto",
        }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
            <thead>
              <tr style={{ borderBottom: "1px solid var(--pt-border-2)" }}>
                <PriceTh>Product</PriceTh>
                {currencies.map((cur) => <PriceTh key={cur} right>{cur}</PriceTh>)}
              </tr>
            </thead>
            <tbody>
              {catalogue.products.map((p) => (
                <tr key={p.id} style={{ borderBottom: "1px solid var(--pt-surface-3)" }}>
                  <td style={{ padding: "16px 18px" }}>
                    <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "var(--pt-fg-2)", fontWeight: 500 }}>{p.name}</div>
                    {p.description && (
                      <div style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--pt-fg-faint2)", marginTop: 3 }}>{p.description}</div>
                    )}
                  </td>
                  {currencies.map((cur) => {
                    const entry = p.prices.find((pr) => pr.currency === cur);
                    return (
                      <td key={cur} style={{ padding: "16px 18px", textAlign: "right", fontFamily: "var(--font-body)", fontSize: 14.5, color: entry ? "var(--pt-fg)" : "var(--pt-fg-faint2)" }}>
                        {entry ? portalMoney(entry.unitPrice, cur) : "\u2014"}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </ResellerShell>
  );
}

const SETTINGS_TIER_LABELS_PL = { gold: "Gold", platinum: "Platinum", regional_reseller: "Regional Reseller" };

function PriceTh({ children, right }) {
  return (
    <th style={{
      textAlign: right ? "right" : "left", padding: "14px 18px",
      fontFamily: "var(--font-body)", fontSize: 10.5,
      letterSpacing: "0.16em", textTransform: "uppercase",
      color: "var(--pt-fg-faint)", fontWeight: 500,
    }}>{children}</th>
  );
}

Object.assign(window, { ResellerPriceListPage });
