// Solo staff admin area — Price List: one unit price per (product, tier,
// currency) combination, edited inline as a grid. Reached via the
// sidebar nav in AdminShell (see admin-shell.jsx). Reuses MiniField/
// ActionButton/SectionLabel/EmptyNote/adminInputStyle/adminSelectStyle
// from admin-assets-page.jsx (loaded earlier — see index.html).

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

function AdminPricingPage({ onNavigate }) {
  const [state, setState] = useState({ status: "loading", admin: null, grid: [], tiers: [], currencies: [] });
  const [savingKey, setSavingKey] = useState(null);
  const [savedKey, setSavedKey] = useState(null);
  const [error, setError] = useState("");

  const load = () => {
    Promise.all([
      fetch("/api/admin/me", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
      fetch("/api/admin/price-list", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
    ])
      .then(([me, priceList]) => {
        setState({
          status: "ready", admin: me.admin,
          grid: priceList.grid || [], tiers: priceList.tiers || [], currencies: priceList.currencies || [],
        });
      })
      .catch(() => onNavigate("admin-login"));
  };

  useEffect(load, []); // eslint-disable-line react-hooks/exhaustive-deps -- mount-only

  const saveCell = async (productId, tier, currency, unitPrice) => {
    const key = `${productId}:${tier}:${currency}`;
    setSavingKey(key);
    setError("");
    try {
      const res = await fetch("/api/admin/price-list", {
        method: "PUT", credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ productId, tier, currency, unitPrice }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setError(data.error || "Something went wrong."); return; }
      setSavedKey(key);
      await load();
      setTimeout(() => setSavedKey((k) => (k === key ? null : k)), 1800);
    } catch {
      setError("Couldn't reach the server. Check your connection and try again.");
    } finally {
      setSavingKey(null);
    }
  };

  const isReadOnly = state.admin && state.admin.role !== "super_admin";

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

  return (
    <AdminShell admin={state.admin} page="admin-pricing" onNavigate={onNavigate}
      subtitle="Staff only" title="Price list.">
      <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "rgba(0,0,0,0.6)", marginBottom: 24, maxWidth: 760, lineHeight: 1.6 }}>
        One base price per product, per tier, per currency. This is the default price used when raising a new order — individual orders can still override the unit price or apply a discount on top.
      </div>
      {error && <ModalError>{error}</ModalError>}

      <SectionLabel>Products ({state.grid.length})</SectionLabel>
      {state.grid.length === 0 ? (
        <EmptyNote>No products in the catalogue yet.</EmptyNote>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          {state.grid.map((row) => (
            <PriceProductRow
              key={row.product.id} row={row}
              savingKey={savingKey} savedKey={savedKey} isReadOnly={isReadOnly}
              onSave={saveCell}
            />
          ))}
        </div>
      )}
    </AdminShell>
  );
}

function PriceProductRow({ row, savingKey, savedKey, isReadOnly, onSave }) {
  return (
    <div data-testid={`price-row-${row.product.id}`} style={{
      background: "rgba(0,0,0,0.03)", border: "1px solid rgba(0,0,0,0.14)", padding: "18px 20px",
    }}>
      <div style={{
        fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16,
        textTransform: "uppercase", color: "#000", marginBottom: 14,
      }}>{row.product.name}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {row.prices.map((tierRow) => (
          <div key={tierRow.tier} style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
            <div style={{
              width: 150, flex: "0 0 150px",
              fontFamily: "var(--font-body)", fontSize: 12, letterSpacing: "0.06em",
              textTransform: "uppercase", color: "rgba(180,110,0,0.95)",
            }}>{TIER_LABELS_PRICING[tierRow.tier] || tierRow.tier}</div>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {tierRow.currencies.map((c) => (
                <PriceCell
                  key={c.currency} productId={row.product.id} tier={tierRow.tier} currency={c.currency}
                  unitPrice={c.unitPrice} isReadOnly={isReadOnly}
                  saving={savingKey === `${row.product.id}:${tierRow.tier}:${c.currency}`}
                  saved={savedKey === `${row.product.id}:${tierRow.tier}:${c.currency}`}
                  onSave={(value) => onSave(row.product.id, tierRow.tier, c.currency, value)}
                />
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PriceCell({ currency, unitPrice, saving, saved, isReadOnly, onSave }) {
  const [value, setValue] = useState(unitPrice === null || unitPrice === undefined ? "" : String(unitPrice));

  useEffect(() => {
    setValue(unitPrice === null || unitPrice === undefined ? "" : String(unitPrice));
  }, [unitPrice]);

  const dirty = value !== "" && Number(value) !== unitPrice;

  const commit = () => {
    if (!dirty) return;
    const num = Number(value);
    if (!Number.isFinite(num) || num < 0) return;
    onSave(num);
  };

  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "rgba(0,0,0,0.5)" }}>{currency}</span>
      <input
        value={value}
        onChange={(e) => setValue(e.target.value)}
        onBlur={commit}
        onKeyDown={(e) => { if (e.key === "Enter") { e.currentTarget.blur(); } }}
        placeholder="—"
        inputMode="decimal"
        disabled={isReadOnly}
        title={isReadOnly ? "Master admins only — you have read-only access" : undefined}
        data-testid={`price-input-${currency}`}
        style={{ ...adminInputStyle, width: 90, textAlign: "right", opacity: isReadOnly ? 0.6 : 1, cursor: isReadOnly ? "not-allowed" : "text" }}
      />
      {saving && <span style={{ fontFamily: "var(--font-body)", fontSize: 10.5, color: "rgba(0,0,0,0.45)" }}>Saving…</span>}
      {saved && !saving && <span style={{ fontFamily: "var(--font-body)", fontSize: 10.5, color: "rgba(20,140,60,0.95)" }}>Saved ✓</span>}
    </div>
  );
}

Object.assign(window, { AdminPricingPage });
