// 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 = {
  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'));
  // Use named shortcuts when available (cleaner auth handling)
  if (action === 'get_subscription_status' && api.getSubscriptionStatus) return api.getSubscriptionStatus(extra.organisation_id);
  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, extra.organisation_id);
  if (action === 'create_portal_session' && api.createPortalSession) return api.createPortalSession(extra.organisation_id);
  if (!api.invoke) return Promise.reject(new Error('API not available'));
  return api.invoke('billing-api', { action, ...extra });
}

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

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 }}>← 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' }}>© 2026 Bookuno</span>
        <a href="/privacy.html" style={{ fontSize: 12, color: '#6B7280', textDecoration: 'none' }}>Privacy</a>
        <a href="/terms.html" style={{ fontSize: 12, color: '#6B7280', textDecoration: 'none' }}>Terms</a>
        <a href="/app.html#/public" style={{ fontSize: 12, color: '#6B7280', textDecoration: 'none' }}>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 || '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' }}/>
      {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', 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>
  );
}

// ─── Pricing page (two-plan: Monthly £29, Yearly £19) ──────────────────────

function PagePricing() {
  const PRICING_PLANS = [
    {
      key: 'monthly',
      label: 'Monthly',
      price: 29,
      tagline: 'Everything you need to run your bookings.',
      features: [
        'Unlimited bookings',
        'Online booking page',
        'Customer management',
        'Calendar & scheduling',
        'Email confirmations',
        'Stripe payments',
        'Priority support',
      ],
    },
    {
      key: 'yearly',
      label: 'Yearly',
      price: 19,
      badge: 'Save £120/yr',
      tagline: 'Same plan, better price — billed £228/year.',
      features: [
        'Everything in Monthly',
        '£19/mo instead of £29/mo',
        'One payment covers the whole year',
      ],
      highlighted: true,
    },
  ];

  return (
    <BillingShell title="Pricing">
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <h1 style={{ fontSize: 36, fontWeight: 900, color: '#111827', margin: '0 0 12px' }}>
          Simple, transparent pricing
        </h1>
        <p style={{ color: '#6B7280', fontSize: 16, margin: '0 0 8px' }}>
          Free for 3 months. No charge until your trial ends. Cancel anytime.
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 24, maxWidth: 680, margin: '0 auto' }}>
        {PRICING_PLANS.map((plan) => (
          <BillingCard key={plan.key} style={{
            border: plan.highlighted ? '2px solid #6B57FF' : '1px solid #E5E7EB',
            position: 'relative', display: 'flex', flexDirection: 'column',
          }}>
            {plan.highlighted && (
              <div style={{
                position: 'absolute', top: -13, left: '50%', transform: 'translateX(-50%)',
                background: '#6B57FF', color: '#fff', borderRadius: 20,
                padding: '3px 14px', fontSize: 12, fontWeight: 800, whiteSpace: 'nowrap',
              }}>Best value</div>
            )}
            <div style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ fontWeight: 800, fontSize: 18, color: '#111827' }}>{plan.label}</div>
                {plan.badge && (
                  <span style={{ background: '#D1FAE5', color: '#059669', borderRadius: 6, padding: '2px 8px', fontSize: 11, fontWeight: 800 }}>{plan.badge}</span>
                )}
              </div>
              <p style={{ color: '#6B7280', fontSize: 13, margin: '6px 0 0' }}>{plan.tagline}</p>
            </div>

            <div style={{ marginBottom: 20 }}>
              <span style={{ fontSize: 42, fontWeight: 900, color: '#111827', letterSpacing: -1 }}>&pound;{plan.price}</span>
              <span style={{ fontSize: 15, color: '#9CA3AF', fontWeight: 600 }}>/mo</span>
            </div>

            <div style={{ marginBottom: 24, borderTop: '1px solid #F3F4F6', paddingTop: 16 }}>
              {plan.features.map((f, fi) => (
                <div key={fi} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 9, fontSize: 14, color: '#374151' }}>
                  <span style={{ color: '#10B981', fontWeight: 800, flexShrink: 0 }}>&#10003;</span>
                  {f}
                </div>
              ))}
            </div>

            <a
              href="/app.html#/business/start"
              style={{
                display: 'block', width: '100%', textAlign: 'center', boxSizing: 'border-box',
                padding: '12px 0', borderRadius: 10, fontWeight: 700, fontSize: 15,
                textDecoration: 'none', marginTop: 'auto',
                background: plan.highlighted ? '#6B57FF' : '#F3F4F6',
                color: plan.highlighted ? '#fff' : '#111827',
              }}
            >
              Start free trial &rarr;
            </a>
          </BillingCard>
        ))}
      </div>

      <p style={{ textAlign: 'center', color: '#9CA3AF', fontSize: 13, marginTop: 32 }}>
        Both options include the same 3 months free and every feature. Your card isn't charged until the trial ends. Cancel anytime. Payments processed by Stripe.
      </p>

      {/* Trusted section */}
      <div style={{ textAlign: 'center', marginTop: 60 }}>
        <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.07em', color: '#9CA3AF', textTransform: 'uppercase', marginBottom: 14 }}>TRUSTED BY BUSINESSES ACROSS THE UK</div>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 24, flexWrap: 'wrap', margin: '0 auto', maxWidth: 560 }}>
          {[
            { emoji: '✂️', label: 'Barbers' },
            { emoji: '💇', label: 'Hair Salons' },
            { emoji: '💅', label: 'Nail Salons' },
            { emoji: '🧖', label: 'Spas' },
            { emoji: '🏋️', label: 'Personal Trainers' },
            { emoji: '🧹', label: 'Cleaners' },
          ].map(c => (
            <div key={c.label} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 52, height: 52, borderRadius: 16, background: '#F3F4F6', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24 }}>{c.emoji}</div>
              <span style={{ fontSize: 12, fontWeight: 600, color: '#6B7280' }}>{c.label}</span>
            </div>
          ))}
        </div>
      </div>

      {/* FAQ */}
      <div style={{ maxWidth: 600, margin: '56px auto 0' }}>
        <h2 style={{ fontSize: 24, fontWeight: 900, color: '#111827', marginBottom: 24, textAlign: 'center' }}>Frequently asked questions</h2>
        <div style={{ display: 'grid', gap: 14 }}>
          {[
            { q: 'Can I cancel anytime?', a: "Yes, you can cancel your subscription from your dashboard at any time. You'll keep access until the end of your billing period." },
            { q: 'Is my card charged during the trial?', a: "No. You add a card when you start your trial, but nothing is charged for 3 months. We'll email you before your trial ends, and if you cancel before then you pay nothing." },
            { q: 'What payment methods do you accept?', a: 'All major credit and debit cards via Stripe. We support Visa, Mastercard, and American Express.' },
            { q: 'Can I switch plans?', a: 'Yes, you can upgrade or downgrade between monthly and yearly billing any time from your account settings.' },
          ].map((faq, i) => (
            <div key={i} style={{ background: '#fff', borderRadius: 14, border: '1px solid #E5E7EB', padding: '18px 22px' }}>
              <div style={{ fontWeight: 800, fontSize: 15, color: '#111827', marginBottom: 8 }}>{faq.q}</div>
              <div style={{ fontSize: 14, color: '#6B7280', lineHeight: 1.6 }}>{faq.a}</div>
            </div>
          ))}
        </div>
      </div>
    </BillingShell>
  );
}

// ─── 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);

  useBillingEffect(() => {
    setLoadingStatus(true);
    billingInvoke('get_subscription_status')
      .then(data => {
        setState(data || null);
        setLoadingStatus(false);
      })
      .catch(() => setLoadingStatus(false));
  }, []);

  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', {
        organisation_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="Billing">
        <BillingCard style={{ textAlign: 'center', padding: 48, color: '#9CA3AF' }}>Loading billing…</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="Billing">
      <h1 style={{ fontSize: 28, fontWeight: 900, color: '#111827', margin: '0 0 24px' }}>Billing & plan</h1>

      {error && (
        <div style={{ background: '#FEE2E2', color: '#DC2626', borderRadius: 12, padding: '12px 16px', marginBottom: 20, fontWeight: 600 }}>
          {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 }}>⚠ Payment failed</div>
          <div style={{ color: '#78350F', fontSize: 14 }}>
            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 }}>Subscription ending</div>
          <div style={{ color: '#78350F', fontSize: 14 }}>
            Your plan will be cancelled on {fmtDate(state?.current_period_end)}. 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
                    ? `Trial ends ${fmtDate(state?.trial_end)}`
                    : isCancelled
                    ? `Cancelled — access ended ${fmtDate(state?.current_period_end)}`
                    : isCancelling
                    ? `Access until ${fmtDate(state?.current_period_end)}`
                    : `Renews ${fmtDate(state?.current_period_end)}`
                  }
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                <BillingBtn loading={loadingPortal} onClick={openPortal}>
                  Manage billing
                </BillingBtn>
              </div>
            </div>
          </BillingCard>

          {/* What's included */}
          <BillingCard>
            <h3 style={{ fontSize: 16, fontWeight: 800, color: '#111827', margin: '0 0 12px' }}>
              What's included
            </h3>
            <div style={{ color: '#6B7280', fontSize: 14 }}>
              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'; }}>
                View all plans
              </BillingBtn>
            </div>
          </BillingCard>
        </div>
      ) : (
        <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' }}>
            Your free trial hasn't started yet
          </h2>
          <p style={{ color: '#6B7280', fontSize: 15, margin: '0 0 24px' }}>
            Pick your billing and add a card to start your 3 months free. Nothing is charged until the trial ends, and you can cancel anytime.
          </p>
          <div role="radiogroup" aria-label="Billing interval" style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 24 }}>
            {[
              { key: 'monthly', label: 'Monthly', detail: '£29/month' },
              { key: 'yearly', label: 'Yearly', detail: '£19/month · billed £228/year' },
            ].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' }}>{opt.label}</div>
                <div style={{ fontSize: 13, color: '#6B7280', marginTop: 2 }}>{opt.detail}</div>
              </button>
            ))}
          </div>
          <BillingBtn loading={loadingCheckout} onClick={startCheckout}>
            Start 3 months free →
          </BillingBtn>
          <p style={{ color: '#9CA3AF', fontSize: 13, margin: '16px 0 0' }}>
            No charge today. <a href="/app.html#/pricing" style={{ color: '#6B57FF', fontWeight: 600 }}>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 maxPolls = 8;
  let pollCount = 0;

  useBillingEffect(() => {
    function poll() {
      pollCount++;
      billingInvoke('get_subscription_status').then(data => {
        if (data?.trial_end) setTrialEnd(data.trial_end);
        if (data?.is_active) { setStatus('active'); return; }
        if (data?.is_trialing) { setStatus('trialing'); return; }
        if (pollCount < maxPolls) {
          setTimeout(poll, 2000);
        } else {
          setStatus('unknown');
        }
      }).catch(() => {
        if (pollCount < maxPolls) setTimeout(poll, 2000);
        else setStatus('unknown');
      });
    }
    setTimeout(poll, 1500);
  }, []);

  const daysLeft = daysUntil(trialEnd);
  const trialBody = daysLeft != null
    ? `Your card is saved securely — nothing has been charged. Your 3 months free starts now: you have ${daysLeft} day${daysLeft === 1 ? '' : 's'} left, we'll email you before it ends, and you can cancel anytime.`
    : 'Your card is saved securely — nothing has been charged. Your 3 months free starts now. We\'ll email you before it ends, and you can cancel anytime.';

  const content = {
    loading:  { icon: '⏳', title: 'Setting up your trial…',        body: 'We\'re saving your card securely with Stripe. This takes a moment.' },
    active:   { icon: '🎉', title: 'You\'re all set!',              body: 'Your subscription is active. Everything is ready to go.' },
    trialing: { icon: '🎉', title: 'Your trial starts now!',        body: trialBody },
    unknown:  { icon: '✅', title: 'Card saved',                    body: 'Your card is saved — nothing has been charged. Your trial will show as active here shortly.' },
  }[status];

  return (
    <BillingShell>
      <BillingCard style={{ textAlign: 'center', padding: 56, maxWidth: 520, margin: '0 auto' }}>
        <div style={{ fontSize: 52, marginBottom: 16 }}>{content.icon}</div>
        <h1 style={{ fontSize: 26, fontWeight: 900, color: '#111827', margin: '0 0 10px' }}>{content.title}</h1>
        <p style={{ color: '#6B7280', fontSize: 15, margin: '0 0 28px' }}>{content.body}</p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <BillingBtn onClick={() => { window.location.href = '/app.html#/billing'; }} variant="secondary">
            View billing
          </BillingBtn>
          <BillingBtn onClick={() => { window.location.href = '/business-app/app.html#today'; }}>
            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 }}>Platform billing</h1>
            <p style={{ color: '#6B7280', fontSize: 14, margin: '4px 0 0' }}>{rows.length} subscriptions total</p>
          </div>
          <input
            placeholder="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',
            }}>{o.label}</button>
          ))}
        </div>

        {loading ? (
          <BillingCard style={{ textAlign: 'center', padding: 48, color: '#9CA3AF' }}>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 }}>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 ? 'Yes' : '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 });
