// Billing / payment page — Stripe Checkout integration

const API_BASE_BILLING  = 'https://r5vefiej3l.execute-api.eu-central-1.amazonaws.com/prod';
const COGNITO_CLIENT_B  = '7nffjheavp985k7b4bgug45jf4';

function getBillingToken() {
  const last = localStorage.getItem(`CognitoIdentityServiceProvider.${COGNITO_CLIENT_B}.LastAuthUser`);
  if (!last) return null;
  return localStorage.getItem(`CognitoIdentityServiceProvider.${COGNITO_CLIENT_B}.${last}.idToken`);
}

async function billingApi(method, path, body) {
  const token = getBillingToken();
  const res = await fetch(`${API_BASE_BILLING}${path}`, {
    method,
    headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
    ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
  return data;
}

function fmtInvDate(ts) {
  return new Date(ts * 1000).toISOString().slice(0, 10);
}

function fmtAmount(cents, currency = 'eur') {
  return new Intl.NumberFormat('de-DE', {
    style: 'currency', currency: currency.toUpperCase(), minimumFractionDigits: 2,
  }).format(cents / 100);
}

// ── Plan catalogue ─────────────────────────────────────────────────────────────

const PLAN_INFO = {
  specimen: { name: 'Specimen', price: 2400, unit: 'one-off', sub: 'single scan · 30-day retention',  perks: ['1 scan, single codebase', 'Self-contained HTML report', 'AI explanations', '30-day report retention'] },
  field:    { name: 'Field',    price: 190,  unit: '/ mo',    sub: '5 scans · 90-day retention',       perks: ['5 scans / month', 'Up to 2 seats', 'Self-contained HTML report', 'MySQL schema mapping', '90-day retention'] },
  team:     { name: 'Team',     price: 490,  unit: '/ mo',    sub: 'unlimited · 5 seats · 1yr',        perks: ['Unlimited scans on unlimited codebases', '5 seats, € 60 per additional seat', 'Shared workspace & report history', 'MySQL schema mapping', 'Slack integration', 'Priority support, 8h SLA', '1-year report retention'] },
  agency:   { name: 'Agency',   price: null, unit: 'custom',  sub: 'contact sales',                    perks: ['White-label HTML reports', 'Unlimited seats & workspaces', 'On-premise deployment available', 'Custom ingestion adapters', 'SSO (SAML / OIDC), SCIM', 'Dedicated CSM, 4h SLA'] },
};

// ── BillingPage ────────────────────────────────────────────────────────────────

function BillingPage() {
  const { go }                              = useNav();
  const { plan: storedPlan, setPlan }       = useAuth();
  const { toast }                           = useToast();

  const [selected,    setSelected]    = useState(storedPlan && PLAN_INFO[storedPlan] ? storedPlan : 'team');
  const [extraSeats,  setExtraSeats]  = useState(0);
  const [confirming,  setConfirming]  = useState(false);
  const [terms,       setTerms]       = useState(false);
  const [showTerms,   setShowTerms]   = useState(false);
  const [invoices,    setInvoices]    = useState([]);
  const [invLoading,  setInvLoading]  = useState(true);

  const companyRef      = useRef();
  const vatRef          = useRef();
  const billingEmailRef = useRef();
  const addressRef      = useRef();

  useEffect(() => { setPlan(selected); setExtraSeats(0); }, [selected]);

  useEffect(() => {
    billingApi('GET', '/billing/invoices')
      .then(d => setInvoices(d.invoices || []))
      .catch(() => {})
      .finally(() => setInvLoading(false));
  }, []);

  const info      = PLAN_INFO[selected];
  const isAgency  = selected === 'agency';
  const seatCost  = selected === 'team' ? extraSeats * 60 : 0;
  const total     = (info.price || 0) + seatCost;

  const onConfirm = async () => {
    if (isAgency) { toast('Agency plan is bespoke — our team will reach out.', { duration: 3000 }); return; }
    if (!terms)   { toast('Please accept the terms first', { tone: 'error' }); return; }

    const companyName = companyRef.current?.value?.trim();
    setConfirming(true);
    try {
      // Sync company name to workspace org_name before checkout
      if (companyName) {
        await billingApi('PUT', '/account/workspace', { org_name: companyName }).catch(() => {});
      }
      const { url } = await billingApi('POST', '/billing/checkout', {
        plan:          selected,
        extra_seats:   extraSeats,
        billing_email: billingEmailRef.current?.value?.trim() || undefined,
        company:       companyName || undefined,
      });
      window.location.href = url;
    } catch (err) {
      toast(err.message || 'Could not initiate checkout', { tone: 'error' });
      setConfirming(false);
    }
  };

  const onManageSubscription = async () => {
    try {
      const { url } = await billingApi('POST', '/billing/portal', { return_url: 'https://getfossyl.dev' });
      window.location.href = url;
    } catch (err) {
      toast(err.message || 'Could not open billing portal', { tone: 'error' });
    }
  };

  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '240px 1fr', background: 'var(--bg)' }}>
      <AccountSidebar current="billing" go={go}/>
      <div style={{ overflow: 'auto' }}>
        <AccountTopBar crumb={['settings', 'billing']}/>
        <div style={{ padding: '32px', maxWidth: 1180 }}>
          <SectionHeader number="B1" eyebrow="Billing" title={`Checkout — ${info.name} plan.`}
            kicker="Annual billing saves 20% versus monthly. Cancel or downgrade any time; prorated credit applied automatically."/>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 420px', gap: 32, marginTop: 32 }}>
            <div className="col g-24">

              {/* 01 — Plan */}
              <div className="panel">
                <div className="panel-h"><span className="caps">01 — Plan</span><span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>change anytime</span></div>
                <div className="panel-b col g-12">
                  {Object.entries(PLAN_INFO).map(([id, p]) => (
                    <PlanRadio
                      key={id}
                      name={p.name}
                      price={p.price ? `€ ${p.price.toLocaleString('en-US')} ${p.unit}` : 'Custom'}
                      sub={p.sub}
                      checked={selected === id}
                      onSelect={() => setSelected(id)}
                    />
                  ))}
                  {selected === 'team' && (
                    <div className="row ai-c g-12" style={{ padding: '10px 16px', border: '1px solid var(--line)', borderRadius: 2 }}>
                      <span className="mono" style={{ fontSize: 12, color: 'var(--ink-dim)', flex: 1 }}>Additional seats · € 60 / seat / mo</span>
                      <div className="row g-0" style={{ border: '1px solid var(--line-2)', borderRadius: 2, overflow: 'hidden' }}>
                        <button className="btn" style={{ padding: '3px 10px', borderRadius: 0, borderRight: '1px solid var(--line-2)' }}
                          onClick={() => setExtraSeats(s => Math.max(0, s - 1))}>−</button>
                        <span className="mono" style={{ padding: '3px 16px', fontSize: 13, lineHeight: '24px', display: 'block', minWidth: 40, textAlign: 'center' }}>{extraSeats}</span>
                        <button className="btn" style={{ padding: '3px 10px', borderRadius: 0, borderLeft: '1px solid var(--line-2)' }}
                          onClick={() => setExtraSeats(s => s + 1)}>+</button>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* 02 — Billing details */}
              <div className="panel">
                <div className="panel-h"><span className="caps">02 — Billing details</span></div>
                <div className="panel-b col g-16">
                  <div className="row g-12">
                    <div style={{ flex: 1 }}>
                      <span className="label">Company</span>
                      <input ref={companyRef} className="input" />
                    </div>
                    <div style={{ flex: 1 }}>
                      <span className="label">VAT ID</span>
                      <input ref={vatRef} className="input mono" />
                    </div>
                  </div>
                  <div>
                    <span className="label">Billing email</span>
                    <input ref={billingEmailRef} className="input mono" type="email" />
                  </div>
                  <div>
                    <span className="label">Address</span>
                    <input ref={addressRef} className="input" />
                  </div>
                </div>
              </div>

              {/* 03 — Payment */}
              <div className="panel">
                <div className="panel-h"><span className="caps">03 — Payment</span></div>
                <div className="panel-b">
                  <div className="row g-12 ai-c">
                    <div style={{
                      width: 36, height: 36, flexShrink: 0,
                      display: 'grid', placeItems: 'center',
                      border: '1px solid var(--line-2)', color: 'var(--bone)',
                      fontFamily: 'var(--serif)', fontSize: 18,
                    }}>S</div>
                    <div className="col g-4">
                      <div style={{ fontSize: 14, fontWeight: 500 }}>Secure payment via Stripe</div>
                      <div className="mono" style={{ fontSize: 11.5, color: 'var(--muted)', lineHeight: 1.55 }}>
                        Card, SEPA direct debit, and invoice accepted. You will be redirected to Stripe's hosted checkout to complete payment.
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <label className="row g-8 ai-c" style={{ fontSize: 12, color: 'var(--ink-dim)', cursor: 'pointer' }}>
                <input type="checkbox" checked={terms} onChange={e => { if (e.target.checked) setShowTerms(true); else setTerms(false); }} style={{ accentColor: 'var(--bone)' }}/>
                <span>I have read and accept the <a className="bone" style={{ cursor: 'pointer' }} onClick={e => { e.preventDefault(); setShowTerms(true); }}>Fossyl terms of service</a> and <a className="bone" style={{ cursor: 'pointer' }} onClick={e => { e.preventDefault(); setShowTerms(true); }}>data handling addendum</a>.</span>
              </label>
              {showTerms && (
                <TermsModal
                  onAccept={() => { setTerms(true); setShowTerms(false); }}
                  onDecline={() => { setTerms(false); setShowTerms(false); }}
                />
              )}
            </div>

            {/* Summary */}
            <div style={{ position: 'sticky', top: 64, alignSelf: 'flex-start' }}>
              <div className="panel">
                <div className="panel-h"><span className="caps">Order summary</span></div>
                <div className="panel-b col g-12">
                  <div className="row jc-b">
                    <span>{info.name} plan{info.unit !== 'custom' ? ` · ${info.unit.replace('/ ', '')}` : ''}</span>
                    <span className="num">{info.price ? `€ ${info.price.toLocaleString('en-US')}.00` : 'Custom'}</span>
                  </div>
                  {selected === 'team' && (
                    <div className="row jc-b">
                      <span className="ink-dim">Additional seats ({extraSeats})</span>
                      <span className="num ink-dim">€ {seatCost.toLocaleString('en-US')}.00</span>
                    </div>
                  )}
                  <div className="hr" style={{ margin: '4px 0' }}/>
                  <div className="row jc-b"><span>Subtotal</span><span className="num">{info.price ? `€ ${total.toLocaleString('en-US')}.00` : '—'}</span></div>
                  <div className="row jc-b"><span className="ink-dim">Reverse-charge VAT (DE)</span><span className="num ink-dim">€ 0.00</span></div>
                  <div className="hr" style={{ margin: '4px 0' }}/>
                  <div className="row jc-b ai-c" style={{ gap: 12 }}>
                    <span className="serif" style={{ fontSize: 18, whiteSpace: 'nowrap' }}>Total due today</span>
                    <span className="serif num" style={{ fontSize: 26, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>
                      {info.price ? `€ ${total.toLocaleString('en-US')}.00` : 'Custom'}
                    </span>
                  </div>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>
                    {isAgency ? 'priced per engagement' : info.unit === 'one-off' ? 'one-time charge' : 'recurring · cancel anytime'}
                  </div>
                  <button className="btn btn-primary btn-lg" style={{ justifyContent: 'center', marginTop: 8 }}
                    onClick={onConfirm} disabled={confirming}>
                    {confirming ? 'Redirecting to Stripe…' : isAgency ? 'Talk to sales →' : 'Confirm & start scanning →'}
                  </button>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--dim)', textAlign: 'center' }}>Payments processed by Stripe · PCI-DSS compliant</div>
                </div>
              </div>

              <div className="panel" style={{ marginTop: 16 }}>
                <div className="panel-h"><span className="caps">What you get</span></div>
                <div className="panel-b col g-8">
                  {info.perks.map(x => (
                    <div key={x} className="row g-8" style={{ fontSize: 12.5, color: 'var(--ink-dim)' }}><span className="bone">▸</span>{x}</div>
                  ))}
                </div>
              </div>

              <button className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 16 }}
                onClick={onManageSubscription}>
                Manage subscription →
              </button>
            </div>
          </div>

          {/* Invoice history */}
          <div className="panel" style={{ marginTop: 40 }}>
            <div className="panel-h"><span className="caps">Invoice history</span></div>
            {invLoading ? (
              <div className="panel-b mono" style={{ fontSize: 12, color: 'var(--muted)' }}>Loading invoices…</div>
            ) : invoices.length === 0 ? (
              <div className="panel-b mono" style={{ fontSize: 12, color: 'var(--muted)' }}>No invoices yet — your first invoice will appear here after payment.</div>
            ) : (
              <table className="table">
                <thead><tr><th>Invoice</th><th>Date</th><th>Plan</th><th>Amount</th><th>Status</th><th></th></tr></thead>
                <tbody>
                  {invoices.map(inv => (
                    <tr key={inv.id}>
                      <td className="mono" style={{ color: 'var(--ink)' }}>{inv.id}</td>
                      <td style={{ color: 'var(--muted)' }}>{fmtInvDate(inv.date)}</td>
                      <td>{inv.label}</td>
                      <td className="text-right">{fmtAmount(inv.amount, inv.currency)}</td>
                      <td><span className="badge safe">{inv.status}</span></td>
                      <td>
                        {inv.pdf
                          ? <a className="bone mono" style={{ fontSize: 11, cursor: 'pointer' }} href={inv.pdf} target="_blank" rel="noreferrer">PDF →</a>
                          : <span className="mono" style={{ fontSize: 11, color: 'var(--dim)' }}>—</span>
                        }
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

        </div>
      </div>
    </div>
  );
}

function MethodBtn({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      padding: '5px 14px', cursor: 'pointer',
      background: active ? 'var(--bg-2)' : 'transparent',
      color: active ? 'var(--ink)' : 'var(--muted)',
      border: 0, borderRight: '1px solid var(--line-2)',
      fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.02em',
    }}>{children}</button>
  );
}

function PlanRadio({ name, price, sub, checked, onSelect }) {
  return (
    <label onClick={onSelect} style={{
      display: 'flex', gap: 14, alignItems: 'center',
      padding: '14px 16px',
      border: '1px solid ' + (checked ? 'var(--bone-dim)' : 'var(--line)'),
      background: checked ? 'var(--bg-2)' : 'var(--bg-1)',
      borderRadius: 2, cursor: 'pointer',
      transition: 'border-color 120ms, background 120ms',
    }}>
      <span style={{
        width: 14, height: 14, borderRadius: '50%',
        border: '1px solid ' + (checked ? 'var(--bone)' : 'var(--line-2)'),
        display: 'grid', placeItems: 'center', flexShrink: 0,
      }}>
        {checked && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--bone)' }}/>}
      </span>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{name}</div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{sub}</div>
      </div>
      <div className="serif" style={{ fontSize: 18, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>{price}</div>
    </label>
  );
}

Object.assign(window, { BillingPage });
