// public/pricing.jsx — Upgrade / pricing screen (the "door" out of the credit wall).
//
// Two render paths:
//   1. Clerk Billing is live (billing.enabled) AND clerk-js exposes a pricing
//      table → mount Clerk's native <PricingTable>, which drives Stripe checkout
//      end-to-end. No plan IDs needed; it reads plans straight from the instance.
//   2. Otherwise → our own static grid from /api/auth-config billing config. This
//      is the source of truth for tiers/prices and is what shows before Billing
//      is switched on in the Clerk dashboard (CTA falls back to "add your key").
//
// Self-contained: depends only on window.Clerk (set after sign-in), AppTopBar,
// and Icon/IconText. No edits to auth.jsx required.

const { useState: usePriceState, useEffect: usePriceEffect, useRef: usePriceRef } = React;

const PRICING_APPEARANCE = {
  variables: { colorPrimary: "#1E1E5A", borderRadius: "10px", fontFamily: "inherit" },
};

function priceLabel(p) {
  if (!p || p.priceUsd === 0) return "Free";
  return `$${p.priceUsd}`;
}
function periodSuffix(p) {
  if (!p || p.priceUsd === 0) return "";
  return p.period === "month" ? " / month" : " / week";
}

function PlanCard({ plan, isCurrent, onChoose, ctaLabel, ctaDisabled }) {
  return (
    <div className={`pricing-card${isCurrent ? " is-current" : ""}`} style={{
      border: isCurrent ? "2px solid var(--ink, #1E1E5A)" : "1px solid rgba(30,30,90,0.14)",
      borderRadius: 14, padding: "22px 20px", background: "#fff",
      display: "flex", flexDirection: "column", gap: 12, minWidth: 0,
    }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8 }}>
        <h3 className="display-sm" style={{ margin: 0, fontSize: 20 }}>{plan.label}</h3>
        {isCurrent && (
          <span className="key-pill key-pill-ok" style={{ fontSize: 11 }}>
            <Icon name="check" size={12}/> Current
          </span>
        )}
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
        <span style={{ fontSize: 30, fontWeight: 700 }}>{priceLabel(plan)}</span>
        <span style={{ opacity: 0.6, fontSize: 13 }}>{periodSuffix(plan)}</span>
      </div>
      <div style={{ fontWeight: 600, fontSize: 13 }}>
        {plan.allowance.toLocaleString()} credits{plan.period === "month" ? " / month" : " / week"}
      </div>
      <p style={{ margin: 0, fontSize: 13, opacity: 0.75, lineHeight: 1.45, flex: 1 }}>{plan.blurb}</p>
      <button
        className={isCurrent ? "btn-secondary" : "btn-primary"}
        disabled={ctaDisabled || isCurrent}
        onClick={() => onChoose(plan)}
        style={{ width: "100%", opacity: ctaDisabled && !isCurrent ? 0.55 : 1 }}
      >
        {isCurrent ? "Your plan" : ctaLabel}
      </button>
    </div>
  );
}

function PricingScreen({ user, billing, creditStatus, byoKeyStatus, onBack, onOpenSettings, onSignOut }) {
  const plans = (billing && billing.plans) || [];
  const currentPlan = (creditStatus && creditStatus.plan) || "free";
  const billingLive = Boolean(billing && billing.enabled);
  const clerkRef = usePriceRef(null);
  const [clerkMounted, setClerkMounted] = usePriceState(false);

  // Try Clerk's native pricing table when Billing is live and clerk-js supports it.
  usePriceEffect(() => {
    const clerk = window.Clerk;
    const el = clerkRef.current;
    if (!billingLive || !el || !clerk || typeof clerk.mountPricingTable !== "function") return undefined;
    let mounted = false;
    try {
      clerk.mountPricingTable(el, { appearance: PRICING_APPEARANCE });
      mounted = true;
      setClerkMounted(true);
    } catch {
      setClerkMounted(false);
    }
    return () => {
      if (mounted) { try { clerk.unmountPricingTable && clerk.unmountPricingTable(el); } catch {} }
    };
  }, [billingLive]);

  function choosePlan(plan) {
    const clerk = window.Clerk;
    // Clerk's hosted account/billing portal handles checkout + management when
    // Billing is enabled. (When clerk-js exposes a dedicated checkout, prefer it.)
    if (clerk && typeof clerk.__internal_openCheckout === "function") {
      try { clerk.__internal_openCheckout({ planId: plan.slug, planPeriod: plan.period === "month" ? "month" : "annual" }); return; } catch {}
    }
    if (clerk && typeof clerk.openUserProfile === "function") {
      try { clerk.openUserProfile(); return; } catch {}
    }
    if (billing && billing.upgradeUrl) { window.location.href = billing.upgradeUrl; return; }
  }

  const ctaDisabled = false;

  // Rank tiers by price (then allowance) so we can label a target plan relative
  // to the user's current one: higher → Upgrade, lower → Downgrade.
  const rankOf = (p) => (p ? (p.priceUsd || 0) * 1e6 + (p.allowance || 0) : 0);
  const currentRank = rankOf(plans.find((p) => p.slug === currentPlan));
  const ctaFor = (plan) => {
    if (!plan.paid) return "Switch";
    return rankOf(plan) < currentRank ? "Downgrade" : "Upgrade";
  };

  return (
    <div className="pricing-screen">
      <AppTopBar
        user={user}
        active="pricing"
        onOpenWorkspace={onBack}
        onOpenSettings={onOpenSettings}
        onSignOut={onSignOut}
        byoKeyStatus={byoKeyStatus}
        creditStatus={creditStatus}
      />

      <main className="pricing-main" style={{ maxWidth: 1000, margin: "0 auto", padding: "32px 24px 64px" }}>
        <button className="app-topbar-link" onClick={onBack} style={{ marginBottom: 16 }}>
          <IconText name="arrow-left">Back</IconText>
        </button>

        <header style={{ marginBottom: 24 }}>
          <h1 className="display-sm" style={{ margin: "0 0 8px" }}>Plans &amp; credits</h1>
          <p style={{ margin: 0, opacity: 0.75, lineHeight: 1.5, maxWidth: 640 }}>
            Credits cover platform AI calls — chat, research, and final plans. Bringing your own
            OpenAI or Anthropic key is always unmetered and never touches these credits.
          </p>
        </header>

        {/* Clerk native pricing table (checkout-enabled) when available */}
        <div ref={clerkRef} className="pricing-clerk" style={{ display: clerkMounted ? "block" : "none" }}/>

        {/* Static grid — always correct, shown unless Clerk's table took over */}
        {!clerkMounted && (
          <div className="pricing-grid" style={{
            display: "grid", gap: 16,
            gridTemplateColumns: "repeat(auto-fit, minmax(210px, 1fr))",
          }}>
            {plans.map((plan) => (
              <PlanCard
                key={plan.slug}
                plan={plan}
                isCurrent={plan.slug === currentPlan}
                onChoose={choosePlan}
                ctaLabel={ctaFor(plan)}
                ctaDisabled={!plan.paid && plan.slug !== currentPlan ? false : ctaDisabled}
              />
            ))}
          </div>
        )}

      </main>
    </div>
  );
}

window.PricingScreen = PricingScreen;
