// Platform billing pages: pricing, billing management, billing success, admin billing.
// Uses BOOKUNO_API.invoke("billing-api", { action, ... }) for all server calls.

/* eslint-disable */
const { useState: useBillingState, useEffect: useBillingEffect, useCallback: useBillingCallback } = React;

// ─── Constants ──────────────────────────────────────────────────────────────

const PLAN_DISPLAY = {
  free: { color: '#6B57FF', label: "Free", tagline: 'One calendar. Unlimited bookings.' },
  starter:  { color: '#6B57FF', label: "Starter",  tagline: 'Get started with online bookings.' },
  pro:      { color: '#7C3AED', label: "Pro",       tagline: 'Everything you need to grow.' },
  business: { color: '#0EA5E9', label: "Business",  tagline: 'For multi-location teams.' },
};

const STATUS_DISPLAY = {
  active:             { color: '#10B981', label: "Active" },
  trialing:           { color: '#F59E0B', label: "Free trial" },
  past_due:           { color: '#EF4444', label: "Payment failed" },
  unpaid:             { color: '#EF4444', label: "Unpaid" },
  cancelled:          { color: '#6B7280', label: "Cancelled" },
  incomplete:         { color: '#F59E0B', label: "Incomplete" },
  incomplete_expired: { color: '#EF4444', label: "Expired" },
  paused:             { color: '#6B7280', label: "Paused" },
};

// ─── Shared helpers ──────────────────────────────────────────────────────────

function billingInvoke(action, extra = {}) {
  const api = window.BOOKUNO_API;
  if (!api) return Promise.reject(new Error('API not available'));
  // The server returns business_id. Keep the legacy UI alias at this boundary,
  // but never let the generic route fall back to a different default business.
  const { business_id, organisation_id, ...fields } = extra;
  const businessId = business_id ?? organisation_id;
  // Use named shortcuts when available (cleaner auth handling)
  if (action === 'get_subscription_status' && api.getSubscriptionStatus) return api.getSubscriptionStatus(businessId);
  if (action === 'get_plans' && api.getPlans) return api.getPlans();
  if (action === 'create_checkout_session' && api.createCheckoutSession) return api.createCheckoutSession(extra.plan_key, extra.billing_interval, businessId);
  if (action === 'create_portal_session' && api.createPortalSession) return api.createPortalSession(businessId);
  if (!api.invoke) return Promise.reject(new Error('API not available'));
  return api.invoke('billing-api', { ...fields, action, ...(businessId !== undefined ? { business_id: businessId } : {}) });
}

function fmtDate(isoStr) {
  if (!isoStr) return '—';
  return new Date(isoStr).toLocaleDateString(window.BOOKUNO_REGION.locale(), { day: 'numeric', month: 'short', year: 'numeric' });
}

// App Store 3.1.1: inside the native app the Stripe checkout (and its pricing)
// must not be reachable — these pages swap to a neutral no-CTA card there.
function isNativeApp() {
  try { return !!(window.BOOKUNO_API && window.BOOKUNO_API.isNativeApp && window.BOOKUNO_API.isNativeApp()); } catch { return false; }
}

function BillingShell({ children, title }) {
  return (
    <div style={{ minHeight: '100vh', background: '#F9FAFB', fontFamily: "'Plus Jakarta Sans', system-ui, sans-serif", display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, maxWidth: 900, margin: '0 auto', padding: '32px 20px 64px', width: '100%', boxSizing: 'border-box' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 32 }}>
          <a href="/app.html#/public" style={{ color: '#6B57FF', fontWeight: 700, textDecoration: 'none', fontSize: 14 }}>{uiText("← Bookuno")}</a>
          {title && <span style={{ color: '#9CA3AF', fontSize: 14 }}>/</span>}
          {title && <span style={{ color: '#374151', fontSize: 14, fontWeight: 600 }}>{title}</span>}
        </div>
        {children}
      </div>
      <div style={{ borderTop: '1px solid #E5E7EB', padding: '16px 20px', display: 'flex', justifyContent: 'center', gap: 24, flexWrap: 'wrap' }}>
        <span style={{ fontSize: 12, color: '#9CA3AF' }}>{uiText("© 2026 SVE Ventures Ltd trading as Bookuno")}</span>
        <a href="/privacy.html" style={{ fontSize: 12, color: '#6B7280', textDecoration: 'none' }}>{uiText("Privacy")}</a>
        <a href="/terms.html" style={{ fontSize: 12, color: '#6B7280', textDecoration: 'none' }}>{uiText("Terms")}</a>
        <a href="/terms.html#cancellations" style={{ fontSize: 12, color: '#6B7280', textDecoration: 'none' }}>{uiText("Refunds & cancellations")}</a>
        <a href="/app.html#/public" style={{ fontSize: 12, color: '#6B7280', textDecoration: 'none' }}>{uiText("Home")}</a>
      </div>
    </div>
  );
}

function PlanBadge({ planKey, size = 'sm' }) {
  const d = PLAN_DISPLAY[planKey] || {};
  return (
    <span style={{
      display: 'inline-block', background: d.color || '#6B57FF', color: '#fff',
      borderRadius: 20, padding: size === 'lg' ? '4px 14px' : '2px 10px',
      fontSize: size === 'lg' ? 14 : 12, fontWeight: 700,
    }}>{d.label || planKey || uiText("No plan")}</span>
  );
}

function StatusBadge({ status }) {
  const d = STATUS_DISPLAY[status] || { color: '#6B7280', label: status || 'None' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      background: d.color + '18', color: d.color,
      borderRadius: 20, padding: '3px 12px', fontSize: 13, fontWeight: 700,
    }}>
      <span style={{ width: 7, height: 7, borderRadius: '50%', background: d.color, display: 'inline-block' }}/>
      {uiText(d.label)}
    </span>
  );
}

function BillingCard({ children, style }) {
  return (
    <div style={{
      background: '#fff', borderRadius: 16, border: '1px solid #E5E7EB',
      padding: 24, ...style,
    }}>{children}</div>
  );
}

function BillingBtn({ children, onClick, loading, variant = 'primary', disabled, style }) {
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    padding: '12px 24px', minHeight: 44, borderRadius: 12, fontWeight: 700, fontSize: 15, cursor: 'pointer',
    border: 'none', transition: 'opacity .15s', opacity: loading || disabled ? 0.6 : 1,
    fontFamily: 'inherit', ...style,
  };
  const styles = {
    primary:   { background: '#6B57FF', color: '#fff' },
    secondary: { background: '#F3F4F6', color: '#374151' },
    danger:    { background: '#FEE2E2', color: '#DC2626' },
  };
  return (
    <button style={{ ...base, ...styles[variant] }} onClick={onClick} disabled={loading || disabled}>
      {loading ? '…' : children}
    </button>
  );
}

// Free signup and explicit Pro upgrade. Native purchase restrictions retained.
function PagePricing() {
  if (isNativeApp()) return <BillingShell title={uiText("Plans")}><BillingCard><h1>{uiText("Free and Pro")}</h1><p>{uiText("Your Free diary has no expiry. Manage your existing plan from your account.")}</p></BillingCard></BillingShell>;
  const plans = [
    {key:'free',name:'Free',price:'£0',period:'forever',features:['One calendar','Unlimited bookings','Booking page and customer diary','No card needed'],href:'/app.html#/business/start',cta:'Start Free'},
    {key:'pro',name:'Pro',price:'£7.99',period:'per month',features:['Team calendars and resource tools','Multiple staff calendars','Additional bookable resources','Or £79 billed yearly'],href:'/app.html#/billing',cta:'Explore Pro'}
  ];
  return <div className="web clarity-site cs-pricing-page">
    <header className="cs-header"><div className="cs-wrap cs-nav"><a className="cs-logo" href="/" aria-label={uiText("Bookuno home")}><img src="/business-app/brand/frame-lockup-blue.svg" alt="Bookuno" width="171" height="40"/></a><a className="cs-signin cs-pricing-signin" href="/app.html#/auth?type=business&mode=login">{uiText("Business sign in")}</a></div></header>
    <main className="cs-wrap cs-pricing-main"><div className="cs-section-heading cs-centred"><span className="cs-eyebrow">{uiText("Straightforward plans")}</span><h1>{uiText("Start Free.")}<br/>{uiText("Grow with Pro.")}</h1><p>{uiText("Free has no expiry. Upgrade only when you choose.")}</p></div>
      <div className="cs-plans">{plans.map(p=><article key={p.key} className={p.key==='pro'?'cs-pro-plan':''}><h2>{p.name}</h2><p className="cs-price">{p.price} <span>{uiText(p.period)}</span></p><ul>{p.features.map(f=><li key={uiText(f)}>✓ {uiText(f)}</li>)}</ul><a className={'cs-button '+(p.key==='free'?'cs-primary':'cs-secondary')} href={p.href}>{uiText(p.cta)} →</a></article>)}</div>
      <p className="cs-pricing-terms">{uiText("Pro renews at £7.99 each month or £79 each year. Cancel future renewal in billing. Free stays available. SMS and payment processing are separate. No booking commission.")}</p>
      <a className="cs-text-link" href="/business.html">{uiText("← Explore the workspace")}</a>
    </main><footer className="cs-wrap cs-pricing-footer"><span>{uiText("© 2026 SVE Ventures Ltd trading as Bookuno")}</span><a href="/privacy.html">{uiText("Privacy")}</a><a href="/terms.html">{uiText("Terms")}</a><a href="/terms.html#cancellations">{uiText("Refunds & cancellations")}</a></footer>
  </div>;
}

// ─── Billing management page ─────────────────────────────────────────────────

function PageBilling() {
  const [state, setState] = useBillingState(null);
  const [loadingPortal, setLoadingPortal] = useBillingState(false);
  const [loadingStatus, setLoadingStatus] = useBillingState(true);
  const [error, setError] = useBillingState('');
  // Default to the plan the owner picked during onboarding (if any), else yearly.
  const [checkoutInterval, setCheckoutInterval] = useBillingState(() => {
    try { return localStorage.getItem('bookuno.preferred_plan') || 'yearly'; } catch { return 'yearly'; }
  });
  const [loadingCheckout, setLoadingCheckout] = useBillingState(false);
  const [statusFailed, setStatusFailed] = useBillingState(false);
  const [statusAttempt, setStatusAttempt] = useBillingState(0);

  useBillingEffect(() => {
    let stopped = false;
    setLoadingStatus(true);
    setStatusFailed(false);
    billingInvoke('get_subscription_status')
      .then(data => {
        if (stopped) return;
        if (!data || typeof data !== 'object' || Array.isArray(data) ||
            typeof (data.business_id ?? data.organisation_id) !== 'string' || !Object.prototype.hasOwnProperty.call(data, 'status')) {
          throw new Error('Subscription status unavailable');
        }
        setState(data);
        setLoadingStatus(false);
      })
      .catch(() => { if (!stopped) { setState(null); setStatusFailed(true); setLoadingStatus(false); } });
    return () => { stopped = true; };
  }, [statusAttempt]);

  async function startCheckout() {
    setError('');
    setLoadingCheckout(true);
    const track = (event, props) => { try { window.BOOKUNO_ANALYTICS && window.BOOKUNO_ANALYTICS.track(event, props); } catch { /* never block checkout */ } };
    track('checkout_session_requested', { placement: 'billing_page', plan: checkoutInterval });
    try {
      const res = await billingInvoke('create_checkout_session', {
        plan_key: 'pro',
        billing_interval: checkoutInterval,
        organisation_id: state?.business_id,
      });
      if (res?.url) { track('checkout_redirect', { placement: 'billing_page', plan: checkoutInterval }); window.location.href = res.url; return; }
      track('checkout_session_failed', { placement: 'billing_page', plan: checkoutInterval, reason: (res && res.error) || 'no_url' });
      setError(res?.error || 'Could not start checkout. Please try again.');
    } catch (err) {
      track('checkout_session_failed', { placement: 'billing_page', plan: checkoutInterval, reason: (err && err.message) || 'error' });
      setError("Could not start checkout. Please try again, or sign in first if you were signed out.");
    }
    setLoadingCheckout(false);
  }

  async function openPortal() {
    setError('');
    setLoadingPortal(true);
    try {
      const res = await billingInvoke('create_portal_session', {
        business_id: state?.business_id ?? state?.organisation_id,
      });
      if (res?.url) window.location.href = res.url;
      else setError(res?.error || 'Could not open billing portal.');
    } catch {
      setError("Could not open billing portal. Please try again.");
    } finally {
      setLoadingPortal(false);
    }
  }

  if (loadingStatus) {
    return (
      <BillingShell title={uiText("Billing")}>
        <BillingCard style={{ textAlign: 'center', padding: 48, color: '#9CA3AF' }}>{uiText("Loading billing…")}</BillingCard>
      </BillingShell>
    );
  }

  if (statusFailed) {
    return (
      <BillingShell title={uiText("Billing")}>
        <BillingCard>
          <div role="alert">
            <h1 style={{ fontSize: 22, color: '#111827', margin: '0 0 12px' }}>{uiText("Could not check your subscription")}</h1>
            <p style={{ color: '#4B5563', margin: '0 0 20px' }}>{uiText("Try again before making billing changes.")}</p>
          </div>
          <BillingBtn onClick={() => setStatusAttempt(value => value + 1)}>{uiText("Try again")}</BillingBtn>
        </BillingCard>
      </BillingShell>
    );
  }

  const hasSubscription = Boolean(state?.status);
  const isPastDue = state?.is_past_due || state?.status === 'unpaid';
  const isCancelling = state?.cancel_at_period_end;
  const isCancelled = state?.is_cancelled;

  return (
    <BillingShell title={uiText("Billing")}>
      <h1 style={{ fontSize: 28, fontWeight: 900, color: '#111827', margin: '0 0 24px' }}>{uiText("Billing & plan")}</h1>

      {error && (
        <div style={{ background: '#FEE2E2', color: '#DC2626', borderRadius: 12, padding: '12px 16px', marginBottom: 20, fontWeight: 600 }}>
          {uiText(error)}
        </div>
      )}

      {/* Payment failed warning */}
      {isPastDue && (
        <div style={{ background: '#FEF3C7', border: '1px solid #F59E0B', borderRadius: 12, padding: '14px 18px', marginBottom: 20 }}>
          <div style={{ fontWeight: 800, color: '#92400E', marginBottom: 4 }}>{uiText("⚠ Payment failed")}</div>
          <div style={{ color: '#78350F', fontSize: 14 }}>{uiText("Your last payment could not be processed. Update your payment method to keep access.")}</div>
        </div>
      )}

      {/* Cancellation warning */}
      {isCancelling && !isCancelled && (
        <div style={{ background: '#FEF3C7', border: '1px solid #F59E0B', borderRadius: 12, padding: '14px 18px', marginBottom: 20 }}>
          <div style={{ fontWeight: 800, color: '#92400E', marginBottom: 4 }}>{uiText("Subscription ending")}</div>
          <div style={{ color: '#78350F', fontSize: 14 }}>{uiText("Your plan will be cancelled on ")}{fmtDate(state?.current_period_end)}{uiText(". You can reactivate at any time.")}</div>
        </div>
      )}

      {hasSubscription ? (
        <div style={{ display: 'grid', gap: 16 }}>
          {/* Current plan card */}
          <BillingCard>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                  <PlanBadge planKey={state?.plan_key} size="lg"/>
                  <StatusBadge status={state?.status}/>
                </div>
                <div style={{ color: '#6B7280', fontSize: 14, marginTop: 8 }}>
                  {state?.is_trialing && state?.trial_end
                    ? uiText("Trial ends {0}",{0:(fmtDate(state?.trial_end))})
                    : isCancelled
                    ? uiText("Cancelled — access ended {0}",{0:(fmtDate(state?.current_period_end))})
                    : isCancelling
                    ? uiText("Access until {0}",{0:(fmtDate(state?.current_period_end))})
                    : uiText("Renews {0}",{0:(fmtDate(state?.current_period_end))})
                  }
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                <BillingBtn loading={loadingPortal} onClick={openPortal}>{uiText("Manage billing")}</BillingBtn>
              </div>
            </div>
          </BillingCard>

          {/* What's included */}
          <BillingCard>
            <h3 style={{ fontSize: 16, fontWeight: 800, color: '#111827', margin: '0 0 12px' }}>{uiText("What's included")}</h3>
            <div style={{ color: '#6B7280', fontSize: 14 }}>{uiText("Manage invoices, update your payment method, change plan, or cancel — all from the Stripe billing portal.")}</div>
            <div style={{ marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <BillingBtn variant="secondary" onClick={() => { window.location.href = '/app.html#/pricing'; }}>{uiText("View all plans")}</BillingBtn>
            </div>
          </BillingCard>
        </div>
      ) : isNativeApp() ? (
        // App Store 3.1.1: the Stripe checkout must not be reachable in the
        // native app — no purchase CTA, no pricing, no external link.
        <BillingCard style={{ textAlign: 'center', padding: 48 }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>🗓️</div>
          <h2 style={{ fontWeight: 900, color: '#111827', fontSize: 22, margin: '0 0 8px' }}>{uiText("Billing is managed on the web")}</h2>
          <p style={{ color: '#6B7280', fontSize: 15, margin: 0 }}>{uiText("Your Bookuno subscription is set up and managed from your business dashboard on the web.")}</p>
        </BillingCard>
      ) : (
        <BillingCard style={{ textAlign: 'center', padding: 48 }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>⏳</div>
          <h2 style={{ fontWeight: 900, color: '#111827', fontSize: 22, margin: '0 0 8px' }}>{uiText("You're on Free")}</h2>
          <p style={{ color: '#6B7280', fontSize: 15, margin: '0 0 24px' }}>{uiText("Your Free calendar and bookings have no expiry. Choose Pro only when you need team and advanced tools. Your selected price is charged when you subscribe and renews until cancelled.")}</p>
          <div role="radiogroup" aria-label={uiText("Billing interval")} style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 24 }}>
            {[
              { key: 'monthly', label: "Monthly", detail: '£7.99/month' },
              { key: 'yearly', label: "Yearly", detail: '£79/year · one yearly payment' },
            ].map(opt => (
              <button
                key={opt.key}
                role="radio"
                aria-checked={checkoutInterval === opt.key}
                onClick={() => setCheckoutInterval(opt.key)}
                style={{
                  padding: '14px 20px', borderRadius: 12, cursor: 'pointer', fontFamily: 'inherit',
                  border: checkoutInterval === opt.key ? '2px solid #6B57FF' : '1px solid #E5E7EB',
                  background: checkoutInterval === opt.key ? '#F5F3FF' : '#fff',
                  textAlign: 'left', minWidth: 180,
                }}
              >
                <div style={{ fontWeight: 800, fontSize: 15, color: '#111827' }}>{uiText(opt.label)}</div>
                <div style={{ fontSize: 13, color: '#6B7280', marginTop: 2 }}>{uiText(opt.detail)}</div>
              </button>
            ))}
          </div>
          <BillingBtn loading={loadingCheckout} onClick={startCheckout}>{uiText("Upgrade to Pro →")}</BillingBtn>
          <p style={{ color: '#9CA3AF', fontSize: 13, margin: '16px 0 0' }}>{uiText("Stay on Free, or upgrade explicitly. SMS and payment processing are separate. ")}<a href="/app.html#/pricing" style={{ color: '#6B57FF', fontWeight: 600 }}>{uiText("Compare plans")}</a>
          </p>
        </BillingCard>
      )}
    </BillingShell>
  );
}

// ─── Billing success page ─────────────────────────────────────────────────────

function daysUntil(dateStr) {
  if (!dateStr) return null;
  const end = new Date(dateStr);
  if (isNaN(end.getTime())) return null;
  const ms = end.getTime() - Date.now();
  return Math.max(0, Math.ceil(ms / 86400000));
}

function PageBillingSuccess() {
  const [status, setStatus] = useBillingState('loading'); // loading | active | trialing | unknown
  const [trialEnd, setTrialEnd] = useBillingState(null);
  const [attempt, setAttempt] = useBillingState(0);

  useBillingEffect(() => {
    let stopped = false, timer, deadline, pollCount = 0;
    const stop = () => { stopped = true; clearTimeout(timer); clearTimeout(deadline); };
    const finish = (next, data) => {
      if (stopped) return;
      stop();
      setTrialEnd(next === 'trialing' ? data?.trial_end || null : null);
      setStatus(next);
    };
    function poll() {
      if (stopped) return;
      pollCount++;
      Promise.resolve().then(() => billingInvoke('get_subscription_status')).then(data => {
        if (stopped) return;
        if (data?.is_active === true) { finish('active', data); return; }
        if (data?.is_trialing === true) { finish('trialing', data); return; }
        if (pollCount < 8) timer = setTimeout(poll, 2000);
        else finish('unknown');
      }).catch(() => {
        if (stopped) return;
        if (pollCount < 8) timer = setTimeout(poll, 2000);
        else finish('unknown');
      });
    }
    // A hung request also reaches a bounded, honest pending state. Late results
    // from an old attempt or an unmounted page cannot overwrite the current one.
    deadline = setTimeout(() => finish('unknown'), 20000);
    timer = setTimeout(poll, 1500);
    return stop;
  }, [attempt]);

  const daysLeft = daysUntil(trialEnd);
  const trialBody = daysLeft != null
    ? `Your trial is confirmed. You have ${daysLeft} day${daysLeft === 1 ? '' : 's'} left. View your renewal date and cancellation options in billing.`
    : 'Your trial is confirmed. View your renewal date and cancellation options in billing.';

  const content = {
    loading:  { icon: '⏳', title: "Checking your subscription…",  body: 'We\'re waiting for your subscription to be verified. This may take a moment.' },
    active:   { icon: '🎉', title: "You're all set!",              body: 'Your subscription is active. You can now open your business dashboard.' },
    trialing: { icon: '🎉', title: "Your trial is confirmed",      body: trialBody },
    unknown:  { icon: '⏳', title: "Subscription not yet confirmed", body: 'We couldn\'t confirm your subscription yet. This page does not confirm a saved card or a payment. Check again or view billing before starting another checkout.' },
  }[status];

  return (
    <BillingShell>
      <BillingCard style={{ textAlign: 'center', padding: 'clamp(24px, 6vw, 56px)', maxWidth: 520, margin: '0 auto' }}>
        <div role="status" aria-live="polite" aria-atomic="true">
          <div aria-hidden="true" style={{ fontSize: 52, marginBottom: 16 }}>{content.icon}</div>
          <h1 style={{ fontSize: 26, fontWeight: 900, color: '#111827', margin: '0 0 10px' }}>{uiText(content.title)}</h1>
          <p style={{ color: '#4B5563', fontSize: 15, lineHeight: 1.6, margin: '0 0 28px' }}>{uiText(content.body)}</p>
        </div>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <BillingBtn onClick={() => { window.location.href = '/app.html#/billing'; }} variant="secondary">{uiText("View billing")}</BillingBtn>
          {status === 'unknown' && <BillingBtn onClick={() => {
            setStatus('loading'); setTrialEnd(null); setAttempt(value => value + 1);
          }}>{uiText("Check again")}</BillingBtn>}
          {(status === 'active' || status === 'trialing') &&
            <BillingBtn onClick={() => { window.location.href = '/business-app/app.html#today'; }}>{uiText("Go to dashboard →")}</BillingBtn>}
        </div>
      </BillingCard>
    </BillingShell>
  );
}

// ─── Admin billing dashboard ─────────────────────────────────────────────────

function PageAdminBilling() {
  const [rows, setRows] = useBillingState([]);
  const [filter, setFilter] = useBillingState('all');
  const [loading, setLoading] = useBillingState(true);
  const [search, setSearch] = useBillingState('');

  useBillingEffect(() => {
    const db = window.supabase?.createClient?.(
      window.BOOKUNO_CONFIG?.supabaseUrl,
      window.BOOKUNO_CONFIG?.supabaseAnonKey,
    );
    if (!db) { setLoading(false); return; }

    // Prod subscriptions are business_id-based (see _shared/billing.ts), so join
    // `businesses` — NOT the legacy organisations table, which doesn't back the
    // live schema and would make this list render empty.
    db.from('subscriptions')
      .select(`
        id, stripe_customer_id, stripe_subscription_id, plan_key, status,
        current_period_end, cancel_at_period_end, created_at,
        businesses ( id, name, stripe_billing_customer_id,
          profiles:created_by ( id, full_name, email )
        )
      `)
      .order('created_at', { ascending: false })
      .then(({ data, error }) => {
        if (!error && data) setRows(data);
        setLoading(false);
      });
  }, []);

  const FILTER_OPTIONS = [
    { key: 'all',       label: "All" },
    { key: 'active',    label: "Active" },
    { key: 'trialing',  label: "Trialing" },
    { key: 'past_due',  label: "Past due" },
    { key: 'unpaid',    label: "Unpaid" },
    { key: 'cancelled', label: "Cancelled" },
    { key: 'none',      label: "No subscription" },
  ];

  const filtered = rows.filter(r => {
    const matchFilter = filter === 'all' ? true : r.status === filter;
    const q = search.toLowerCase();
    const matchSearch = !q
      || r.businesses?.name?.toLowerCase().includes(q)
      || r.businesses?.profiles?.email?.toLowerCase().includes(q)
      || r.stripe_customer_id?.includes(q)
      || r.stripe_subscription_id?.includes(q);
    return matchFilter && matchSearch;
  });

  return (
    <div style={{ fontFamily: "'Plus Jakarta Sans', system-ui, sans-serif", padding: '32px 24px', minHeight: '100vh', background: '#F9FAFB' }}>
      <div style={{ maxWidth: 1100, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <h1 style={{ fontSize: 24, fontWeight: 900, color: '#111827', margin: 0 }}>{uiText("Platform billing")}</h1>
            <p style={{ color: '#6B7280', fontSize: 14, margin: '4px 0 0' }}>{rows.length}{uiText(" subscriptions total")}</p>
          </div>
          <input
            placeholder={uiText("Search org, email, Stripe ID…")}
            value={search}
            onChange={e => setSearch(e.target.value)}
            style={{
              border: '1px solid #E5E7EB', borderRadius: 10, padding: '9px 14px',
              fontSize: 14, fontFamily: 'inherit', width: 280, outline: 'none',
            }}
          />
        </div>

        {/* Filter pills */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
          {FILTER_OPTIONS.map(o => (
            <button key={o.key} onClick={() => setFilter(o.key)} style={{
              padding: '6px 14px', borderRadius: 20, border: 'none', cursor: 'pointer',
              fontWeight: 700, fontSize: 13, fontFamily: 'inherit',
              background: filter === o.key ? '#6B57FF' : '#E5E7EB',
              color: filter === o.key ? '#fff' : '#374151',
              transition: 'all .12s',
            }}>{uiText(o.label)}</button>
          ))}
        </div>

        {loading ? (
          <BillingCard style={{ textAlign: 'center', padding: 48, color: '#9CA3AF' }}>{uiText("Loading…")}</BillingCard>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', background: '#fff', borderRadius: 14, overflow: 'hidden', border: '1px solid #E5E7EB' }}>
              <thead>
                <tr style={{ background: '#F9FAFB', borderBottom: '1px solid #E5E7EB' }}>
                  {['Organisation', 'Owner email', 'Plan', 'Status', 'Renews / ends', 'Cancels EOT', 'Stripe customer', 'Stripe sub', 'Created'].map(h => (
                    <th key={h} style={{ padding: '12px 14px', textAlign: 'left', fontSize: 12, fontWeight: 800, color: '#6B7280', whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0 && (
                  <tr><td colSpan={9} style={{ textAlign: 'center', padding: 32, color: '#9CA3AF', fontSize: 14 }}>{uiText("No results")}</td></tr>
                )}
                {filtered.map((r, i) => (
                  <tr key={r.id} style={{ borderBottom: i < filtered.length - 1 ? '1px solid #F3F4F6' : 'none' }}>
                    <td style={{ padding: '12px 14px', fontSize: 14, fontWeight: 700, color: '#111827' }}>
                      {r.businesses?.name || '—'}
                    </td>
                    <td style={{ padding: '12px 14px', fontSize: 13, color: '#374151' }}>
                      {r.businesses?.profiles?.email || '—'}
                    </td>
                    <td style={{ padding: '12px 14px' }}>
                      {r.plan_key ? <PlanBadge planKey={r.plan_key}/> : <span style={{ color: '#9CA3AF', fontSize: 13 }}>—</span>}
                    </td>
                    <td style={{ padding: '12px 14px' }}>
                      {r.status ? <StatusBadge status={r.status}/> : <span style={{ color: '#9CA3AF', fontSize: 13 }}>—</span>}
                    </td>
                    <td style={{ padding: '12px 14px', fontSize: 13, color: '#6B7280', whiteSpace: 'nowrap' }}>
                      {fmtDate(r.current_period_end)}
                    </td>
                    <td style={{ padding: '12px 14px', fontSize: 13, color: r.cancel_at_period_end ? '#EF4444' : '#10B981', fontWeight: 700 }}>
                      {r.cancel_at_period_end ? uiText("Yes") : uiText("No")}
                    </td>
                    <td style={{ padding: '12px 14px', fontSize: 11, color: '#9CA3AF', fontFamily: 'monospace' }}>
                      {r.stripe_customer_id || r.businesses?.stripe_billing_customer_id || '—'}
                    </td>
                    <td style={{ padding: '12px 14px', fontSize: 11, color: '#9CA3AF', fontFamily: 'monospace' }}>
                      {r.stripe_subscription_id || '—'}
                    </td>
                    <td style={{ padding: '12px 14px', fontSize: 12, color: '#9CA3AF', whiteSpace: 'nowrap' }}>
                      {fmtDate(r.created_at)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PagePricing, PageBilling, PageBillingSuccess, PageAdminBilling });
