// =================================================================
// pw-shared.jsx — small helpers shared by the paywall screens.
//   - PageHead: screen title block + actions (wraps ScreenHeader)
//   - StatusPill: maps domain statuses to Pill tones
//   - money / coins formatting
//   - ad-tier plain-English summary + ad-load bar
// =================================================================

// Map any domain status to a Pill tone.
const PW_STATUS_TONE = {
  active: "good", live: "good", granted: "good",
  trialing: "info", onboarding: "info", draft: "neutral",
  paused: "warn", past_due: "warn", capped: "warn",
  canceled: "neutral", cancelled: "neutral", ended: "neutral",
  expired: "neutral", retired: "neutral", inactive: "neutral",
  already_granted: "neutral", no_rule: "warn",
};
const pwTone = (s) => PW_STATUS_TONE[String(s || "").toLowerCase()] || "neutral";

const StatusPill = ({ status, children }) => {
  const label = children || String(status || "").replace(/_/g, " ");
  return <Pill tone={pwTone(status)} style={{ textTransform: "capitalize" }}>{label}</Pill>;
};

// money: null → "Custom"; 0 → "Free"
const pwMoney = (n, currency = "USD") => {
  if (n == null) return "Custom";
  if (n === 0) return "Free";
  return fmt.currency(n, currency);
};
const pwCoins = (n) => `${fmt.number(n)}`;

// A coin chip with the coin glyph.
const CoinChip = ({ amount, tone }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--mono)", fontSize: 12.5,
    color: tone === "neg" ? "var(--bad)" : tone === "pos" ? "var(--good)" : "var(--ink-2)", fontWeight: 500 }}>
    <IconCoin size={13} style={{ color: "var(--warn)" }}/>
    {amount > 0 && tone === "pos" ? "+" : ""}{fmt.number(amount)}
  </span>
);

// nullable numeric → "Unlimited" affordance
const pwNum = (v, suffix = "") => (v == null ? "Unlimited" : `${v}${suffix}`);

// Plain-English summary of an ad tier (spec §7a live preview).
function adTierSummary(t) {
  if (!t) return "—";
  if (t.max_ad_seconds === 0 || t.max_ads_per_session === 0) return "Ad-free — no ads served.";
  const parts = [];
  parts.push(`Up to ${t.max_ads_per_session == null ? "unlimited" : t.max_ads_per_session} ad${t.max_ads_per_session === 1 ? "" : "s"}/session`);
  if (t.max_ad_seconds != null) parts.push(`max ${t.max_ad_seconds}s total`);
  if (t.min_gap_seconds != null) parts.push(`≥${t.min_gap_seconds}s apart`);
  const fmtMap = { preroll: "pre", midroll: "mid", postroll: "post" };
  if (t.allowed_formats && t.allowed_formats.length)
    parts.push(`${t.allowed_formats.map(f => fmtMap[f] || f).join("/")}-roll`);
  if (t.skippable_after_seconds != null) parts.push(`skippable after ${t.skippable_after_seconds}s`);
  return parts.join(", ") + ".";
}

// 0..1 ad-load score keyed off rank (for the little load bar).
function adLoadScore(t, maxRank = 200) {
  if (!t) return 0;
  if (t.max_ad_seconds === 0) return 0;
  return Math.max(0.06, Math.min(1, t.rank / maxRank));
}

const AdLoadBar = ({ tier, width = 90 }) => {
  const s = adLoadScore(tier);
  const color = s === 0 ? "var(--good)" : s < 0.4 ? "var(--accent)" : s < 0.8 ? "var(--warn)" : "var(--bad)";
  return (
    <div title={`Ad load · rank ${tier?.rank}`} style={{ display: "inline-flex", alignItems: "center", gap: 8, width }}>
      <div style={{ flex: 1, height: 6, borderRadius: 999, background: "var(--line-2)", overflow: "hidden" }}>
        <div style={{ width: `${Math.max(4, s * 100)}%`, height: "100%", borderRadius: 999, background: color }}/>
      </div>
    </div>
  );
};

// Screen header with a subtle right-aligned action slot.
const PageHead = ({ icon, title, subtitle, actions }) => (
  <ScreenHeader
    icon={icon ? React.createElement(icon, { size: 22 }) : undefined}
    title={title}
    subtitle={subtitle}
    right={actions ? <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>{actions}</div> : undefined}
  />
);

// A standard screen scaffold: header + spaced sections.
const Screen = ({ children }) => <div className="hx-screen">{children}</div>;

// Tiny labelled metric used in detail drawers.
const MiniStat = ({ label, value }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
    <span style={{ fontSize: 12, color: "var(--muted)" }}>{label}</span>
    <span style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)" }}>{value}</span>
  </div>
);

Object.assign(window, {
  pwTone, StatusPill, pwMoney, pwCoins, pwNum, CoinChip,
  adTierSummary, adLoadScore, AdLoadBar, PageHead, Screen, MiniStat,
});
