// ════════════════════════════════════════════════════════════════════════
// PropMystro · Phase E · pm-e-billing.jsx
// The Plans & Billing screen. Shows the three tiers, marks the current plan,
// and turns "Upgrade" into a real Stripe Checkout redirect (via the
// create-checkout function). "Manage billing" opens the Stripe Customer
// Portal. If the functions aren't deployed yet it explains what to do, so the
// screen is useful before AND after you wire Stripe. → window.PMBilling.
// ════════════════════════════════════════════════════════════════════════
(function () {
  const { useState } = React;

  const PLANS = [
    { tier: 'starter', name: 'Starter', price: 29, blurb: 'For a landlord getting organised and staying compliant.',
      caps: 'Up to 3 properties · 1 user',
      feats: ['Compliance tracking + reminders', 'Document vault with AI extraction', 'Tenancy & Right-to-Rent onboarding', 'Tenant messaging — email, SMS & WhatsApp', 'Alerts + calendar planner', 'Mission-Control dashboard'] },
    { tier: 'professional', name: 'Professional', price: 59, blurb: 'For active portfolios that need the money & ops tools.', popular: true,
      caps: 'Up to 15 properties · 3 users',
      feats: ['Everything in Starter', 'Rent ledger & arrears tracking', 'Expenses & bank reconciliation', 'Rent reviews — official Form 4A', 'Maintenance board (Awaab\u2019s Law clock)', 'Inspections + on-site capture', 'Multi-owner — up to 2, with joint splits'] },
    { tier: 'portfolio', name: 'Portfolio', price: 99, blurb: 'For larger portfolios, accountants & teams.',
      caps: 'Unlimited properties & users',
      feats: ['Everything in Professional', 'Unlimited owners & team seats', 'Making Tax Digital — SA105 & quarterly packs', 'Full inspection runner (HMO templates)', 'Export centre — CSV & JSON', 'Roles, permissions & custom roles', 'Priority support'] },
  ];
  const RANK = { starter: 1, professional: 2, portfolio: 3 };

  function Spin() { return <span className="spin" />; }

  function Billing({ sb, account, onClose, toast }) {
    const [interval, setInterval] = useState('monthly');
    const [busy, setBusy] = useState('');
    const [note, setNote] = useState('');
    const current = account.plan || 'starter';
    const isAdminTrial = account.status === 'trialing';

    const checkout = async (tier) => {
      setNote(''); setBusy(tier);
      try {
        const { data, error } = await sb.functions.invoke('create-checkout', {
          body: { tier, interval, return_url: location.origin + location.pathname },
        });
        if (error) throw error;
        if (data?.url) { location.href = data.url; return; }
        throw new Error(data?.error || 'No checkout URL returned.');
      } catch (e) {
        setBusy('');
        setNote('Billing isn\'t connected yet. Once you\'ve deployed the Stripe functions (see the Phase E setup guide), this button opens Stripe Checkout. [' + (e.message || e) + ']');
      }
    };

    const portal = async () => {
      setNote(''); setBusy('portal');
      try {
        const { data, error } = await sb.functions.invoke('customer-portal', {
          body: { return_url: location.origin + location.pathname },
        });
        if (error) throw error;
        if (data?.url) { location.href = data.url; return; }
        throw new Error(data?.error || 'No portal URL.');
      } catch (e) {
        setBusy('');
        setNote('Manage-billing opens the Stripe Customer Portal once billing is connected and you have a paid subscription. [' + (e.message || e) + ']');
      }
    };

    return <div className="modal-scrim" onClick={onClose}>
      <div className="modal billing-modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h2>Plans &amp; billing</h2>
            <p className="modal-sub">You're on the <b>{current.replace(/^\w/, c => c.toUpperCase())}</b> plan{isAdminTrial ? ' · free trial' : ''}.</p>
          </div>
          <button className="x" onClick={onClose}>✕</button>
        </div>

        <div className="interval-toggle">
          <button className={interval === 'monthly' ? 'on' : ''} onClick={() => setInterval('monthly')}>Monthly</button>
          <button className={interval === 'annual' ? 'on' : ''} onClick={() => setInterval('annual')}>Annual <span className="save">2 months free</span></button>
        </div>

        <div className="plan-grid">
          {PLANS.map(p => {
            const isCurrent = p.tier === current;
            const isDown = RANK[p.tier] < RANK[current];
            const price = interval === 'annual' ? Math.round(p.price * 10) : p.price;
            return <div className={'plan' + (p.popular ? ' popular' : '') + (isCurrent ? ' current' : '')} key={p.tier}>
              {p.popular && <div className="ribbon">Most popular</div>}
              <h3>{p.name}</h3>
              <div className="price"><span className="amt">£{price}</span><span className="per">/{interval === 'annual' ? 'year' : 'month'}</span></div>
              <div className="caps">{p.caps}</div>
              <p className="blurb">{p.blurb}</p>
              <ul className="feats">{p.feats.map((f, i) => <li key={i}><span className="t">✓</span>{f}</li>)}</ul>
              {isCurrent ? <button className="btn btn-ghost" disabled>Current plan</button>
                : isDown ? <button className="btn btn-ghost" onClick={portal}>Change in portal</button>
                : <button className="btn btn-primary" onClick={() => checkout(p.tier)} disabled={busy === p.tier}>{busy === p.tier ? <Spin /> : (current === 'starter' && isAdminTrial ? 'Choose ' + p.name : 'Upgrade to ' + p.name)}</button>}
            </div>;
          })}
        </div>

        {note && <div className="alert alert-info" style={{ margin: '4px 24px 0' }}><span className="ic">ℹ</span><div>{note}</div></div>}

        <div className="modal-foot">
          <button className="linkbtn" onClick={portal} disabled={busy === 'portal'}>{busy === 'portal' ? 'Opening…' : 'Manage billing & invoices →'}</button>
          <span className="foot-note">Secure payments by Stripe · cancel anytime</span>
        </div>
      </div>
    </div>;
  }

  window.PMBilling = Billing;
})();
