// /upgrade/ — where someone lands when the free scan is already spent.
//
// Reached from the 402 on /authorize/ when a verified account tries a second
// distinct repository. Two ways out, and they are the two already published on
// /pricing/ rather than a paywall-only SKU invented for this moment:
//
//   Managed Scan  one payment, one more repository
//   Developer     $49/month, unlimited repositories while it lasts
//
// Card details are never collected here. The buttons create a Stripe Checkout
// Session server-side and hand off to Stripe's hosted page, so the card never
// touches sekura.ai and the PCI surface stays Stripe's.

function UpgradeView() {
  const { React } = window;
  const { useState, useEffect } = React;

  const params = typeof window !== 'undefined'
    ? new URLSearchParams(window.location.search) : new URLSearchParams();

  const repo = (params.get('repo') || '').trim();
  const canceled = params.get('canceled') === '1';

  const [email, setEmail] = useState('');
  const [busy, setBusy] = useState(null);   // which product is checking out
  const [error, setError] = useState(null);

  useEffect(() => { document.title = 'Sekura — add a scan'; }, []);

  // The grant proves which GitHub account the credit belongs to. Kept in
  // session storage by /authorize/ so a round trip through Stripe does not
  // lose it — and so credits cannot be bought into someone else's account by
  // editing a form field.
  const grant = (() => {
    try { return window.sessionStorage.getItem('sekura.grant') || ''; } catch { return ''; }
  })();

  const checkout = async (product) => {
    setError(null);
    if (!/.+@.+\..+/.test(email)) {
      setError('Enter the email the receipt should go to.');
      return;
    }
    setBusy(product);
    try {
      const res = await fetch('/api/scan-checkout', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ product, email: email.trim(), repo, grant }),
      });
      const data = await res.json().catch(() => ({}));
      if (!data.ok || !data.checkoutUrl) {
        setError(data.error || 'Could not start checkout. Try again, or email hello@sekura.ai.');
        setBusy(null);
        return;
      }
      window.location.href = data.checkoutUrl;
    } catch {
      setError('Network error. Try again, or email hello@sekura.ai.');
      setBusy(null);
    }
  };

  const options = [
    {
      k: 'managed_scan',
      name: 'Managed Scan',
      price: '$199',
      per: 'one scan',
      body: 'One more repository, run by us. Full pipeline, proof-of-exploit, and the report in your inbox. No subscription.',
      cta: 'Pay $199 and continue',
      points: ['Covers one repository', 'Nothing to install', 'Report within 24 hours'],
    },
    {
      k: 'developer',
      name: 'Developer',
      price: '$49',
      per: 'per month',
      body: 'Unlimited repositories and unlimited scans, run from your own editor on your own model key. Cancel any time.',
      cta: 'Subscribe and continue',
      featured: true,
      points: ['Unlimited repositories', 'Unlimited scans', 'Cancel any time'],
    },
  ];

  return (
    <div className="ah-auth">
      <section className="ah-auth-hero">
        <div className="ah-auth-inner ah-upgrade-head">
          <p className="ah-eyebrow">Add a scan</p>
          <h1 className="ah-h1">Your free scan is already used.</h1>
          <p className="ah-sub">
            The first repository is free for every account. To scan
            {repo ? <> <strong>{repo}</strong></> : ' another repository'} as well,
            pick whichever of these fits — both are the published prices, not a
            surcharge for arriving here.
          </p>
          {canceled && (
            <p className="ah-auth-err">Checkout was cancelled. Nothing has been charged.</p>
          )}
        </div>
      </section>

      <div className="ah-auth-body">
        <div className="ah-auth-inner">
          <div className="ah-upgrade-email">
            <label className="ah-auth-label" htmlFor="up-email">Email for the receipt</label>
            <input
              id="up-email" type="email" className="ah-auth-input"
              value={email} onChange={(e) => setEmail(e.target.value)}
              placeholder="you@company.com" autoComplete="email"
            />
          </div>

          <div className="ah-upgrade-grid">
            {options.map((o) => (
              <div className={`ah-upgrade-card ${o.featured ? 'is-featured' : ''}`} key={o.k}>
                <h2 className="ah-h3">{o.name}</h2>
                <p className="ah-upgrade-price">
                  {o.price}<span className="ah-upgrade-per"> {o.per}</span>
                </p>
                <p className="ah-body ah-upgrade-body">{o.body}</p>
                <ul className="ah-caps ah-upgrade-points">
                  {o.points.map((pt) => (
                    <li className="ah-cap" key={pt}><window.AhCheck />{pt}</li>
                  ))}
                </ul>
                <button
                  type="button"
                  className="ah-btn ah-upgrade-cta"
                  onClick={() => checkout(o.k)}
                  disabled={!!busy}
                >
                  {busy === o.k ? 'Opening checkout…' : o.cta}
                </button>
              </div>
            ))}
          </div>

          {error && <p className="ah-auth-err ah-auth-err--form">{error}</p>}

          <p className="ah-caption ah-upgrade-foot">
            Payment is handled by Stripe. Your card details never reach Sekura.
            After paying you will come straight back to finish authorizing the scan.
            {' '}<a className="ah-link" href="/pricing/">See all plans<span className="ah-chev">›</span></a>
          </p>
        </div>
      </div>
    </div>
  );
}

window.UpgradeView = UpgradeView;
