/* global React, useAuth, useMeta, formatMoney */

// =========================================================================
// UPGRADE — pricing page. Four tiers (Free, Pro, Team, Enterprise). Paid
// tiers don't take payment yet; instead each Upgrade button captures an
// email into a waitlist so we can reach back out when billing is wired.
// =========================================================================
function UpgradePage({ navigate }) {
  const { user, tier, signedIn } = useAuth();
  const { models } = useMeta();
  const currentPlan = tier?.name || 'free';
  const enabledModelCount = models.filter((m) => m.enabled).length;

  // Modal state. Null = closed; otherwise tracks the plan we're processing.
  const [modalFor, setModalFor] = React.useState(null);
  // 'submitting' | 'done' | 'error' — there is no 'idle' anymore because the
  // submit is fired the moment the user clicks Upgrade.
  const [submitState, setSubmitState] = React.useState('submitting');
  const [submitErr, setSubmitErr] = React.useState('');
  const [submittedEmail, setSubmittedEmail] = React.useState('');
  const [alreadyOn, setAlreadyOn] = React.useState(false);

  // Live count for the "X people already on the list" social-proof line.
  const [waitlistCount, setWaitlistCount] = React.useState(null);
  React.useEffect(() => {
    window.CloudLayerAPI.waitlistCount().then((d) => setWaitlistCount(d.count)).catch(() => {});
  }, []);

  function closeModal() { setModalFor(null); }

  async function startUpgrade(planId) {
    if (!signedIn || !user?.email) {
      // Edge case: no signed-in email to send. Punt to sign-in.
      alert('Please sign in first so we can add your email to the waitlist.');
      return navigate('home');
    }
    setModalFor(planId);
    setSubmitState('submitting');
    setSubmitErr('');
    setSubmittedEmail(user.email);
    setAlreadyOn(false);
    try {
      const r = await window.CloudLayerAPI.joinWaitlist({
        email: user.email,
        plan: planId,
        name: user.name || '',
        handle: user.handle || '',
      });
      setAlreadyOn(!!r.alreadyOn);
      setSubmitState('done');
      window.CloudLayerAPI.waitlistCount().then((d) => setWaitlistCount(d.count)).catch(() => {});
    } catch (err) {
      setSubmitErr(err?.message || 'Could not join the waitlist. Please try again.');
      setSubmitState('error');
    }
  }

  function onChoosePlan(planId) {
    if (planId === 'free') return navigate('profile');
    // All paid tiers fire the upgrade flow (which currently routes to the
    // waitlist until live billing is wired).
    startUpgrade(planId);
  }

  const plans = [
    {
      id: 'free',
      name: 'Free',
      price: '$0',
      cadence: 'forever',
      tagline: 'Track a prompt, see real ground-truth accuracy.',
      features: [
        { ok: true,  text: '2 tracked prompts' },
        { ok: true,  text: '1 model per prompt' },
        { ok: true,  text: 'Web search included' },
        { ok: true,  text: 'Top 5 markets per category, soonest to resolve' },
        { ok: true,  text: 'Community leaderboard ranking' },
        { ok: false, text: 'Multi-model head-to-head' },
        { ok: false, text: 'Full market pool' },
        { ok: false, text: 'Custom timing windows' },
      ],
      cta: currentPlan === 'free' ? 'Current plan' : 'Downgrade',
      ctaDisabled: currentPlan === 'free',
      accent: false,
    },
    {
      id: 'pro',
      name: 'Pro',
      price: '$9',
      cadence: 'per month',
      tagline: 'Head-to-head benchmark across every model.',
      features: [
        { ok: true,  text: '5 tracked prompts' },
        { ok: true,  text: `Up to ${enabledModelCount} models per prompt` },
        { ok: true,  text: 'Web search included' },
        { ok: true,  text: 'Full market pool' },
        { ok: true,  text: 'Custom timing windows (≤1h to ≤7d)' },
        { ok: true,  text: 'Priority community leaderboard placement' },
        { ok: true,  text: 'API export of your predictions' },
        { ok: false, text: 'Team workspace' },
      ],
      cta: currentPlan === 'pro' ? 'Current plan' : 'Upgrade →',
      ctaDisabled: currentPlan === 'pro',
      accent: true,
    },
    {
      id: 'team',
      name: 'Team',
      price: '$49',
      cadence: 'per month',
      tagline: 'Shared workspace for a small forecasting team.',
      features: [
        { ok: true,  text: 'Everything in Pro' },
        { ok: true,  text: 'Up to 5 seats, shared billing' },
        { ok: true,  text: 'Shared prompt library across the team' },
        { ok: true,  text: '15 tracked prompts pooled across seats' },
        { ok: true,  text: 'Team-private leaderboard view' },
        { ok: true,  text: 'Slack / Discord notifications on resolutions' },
        { ok: true,  text: 'CSV + JSON data export' },
        { ok: false, text: 'SAML / SSO' },
      ],
      cta: currentPlan === 'team' ? 'Current plan' : 'Upgrade →',
      ctaDisabled: currentPlan === 'team',
      accent: false,
    },
    {
      id: 'enterprise',
      name: 'Enterprise',
      price: 'Custom',
      cadence: 'monthly',
      tagline: 'API access, custom models, dedicated infra.',
      features: [
        { ok: true,  text: 'Everything in Team' },
        { ok: true,  text: 'Unlimited prompts and seats' },
        { ok: true,  text: 'Bring-your-own model identities' },
        { ok: true,  text: 'Dedicated provider keys (no shared limits)' },
        { ok: true,  text: 'SAML / SSO' },
        { ok: true,  text: 'SLA + priority support' },
        { ok: true,  text: 'Custom resolution-data pipeline' },
        { ok: true,  text: 'On-prem option' },
      ],
      cta: 'Upgrade →',
      ctaDisabled: false,
      accent: false,
    },
  ];

  const planName = (id) => plans.find((p) => p.id === id)?.name || id;

  return (
    <div data-screen-label="07 Upgrade">
      <div className="page-head">
        <div className="container">
          <div className="crumb">
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('home')}>Benchmark</span>
            <span style={{ margin: '0 8px' }}>/</span>
            <span>Pricing</span>
          </div>
          <h1 style={{
            margin: 0, fontSize: 72, fontFamily: 'var(--ff-display)',
            fontWeight: 300, letterSpacing: '-0.025em',
          }}>
            Choose your <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>tier</em>
          </h1>
          <div className="dim" style={{ marginTop: 16, fontSize: 16, maxWidth: 680, lineHeight: 1.6 }}>
            Start free. Paid tiers are launching soon — click Upgrade and we will reserve a spot for you.
            {waitlistCount > 0 && (
              <span className="mono faint" style={{ marginLeft: 8, fontSize: 13 }}>
                · {waitlistCount} {waitlistCount === 1 ? 'person' : 'people'} reserved
              </span>
            )}
          </div>
        </div>
      </div>

      <section className="container" style={{ padding: '40px 32px 96px' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))',
          gap: 20,
        }}>
          {plans.map((p) => (
            <div
              key={p.id}
              className="panel"
              style={{
                padding: 28,
                position: 'relative',
                border: p.accent ? '1.5px solid var(--accent)' : '1px solid var(--line)',
                background: p.accent ? 'rgba(212, 174, 90, 0.04)' : undefined,
              }}
            >
              {p.id === currentPlan && (
                <div className="mono" style={{
                  position: 'absolute', top: 14, right: 14, fontSize: 9, letterSpacing: '0.08em',
                  textTransform: 'uppercase', color: 'var(--accent)',
                }}>
                  current
                </div>
              )}
              {p.accent && p.id !== currentPlan && (
                <div className="mono" style={{
                  position: 'absolute', top: 14, right: 14, fontSize: 9, letterSpacing: '0.08em',
                  textTransform: 'uppercase', color: 'var(--accent)',
                }}>
                  popular
                </div>
              )}

              <div className="uppercase faint" style={{ fontSize: 10, letterSpacing: '0.1em', marginBottom: 10 }}>
                {p.name}
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
                <div style={{
                  fontFamily: 'var(--ff-display)', fontSize: 48, fontWeight: 300, lineHeight: 1,
                }}>
                  {p.price}
                </div>
                <div className="mono faint" style={{ fontSize: 12 }}>
                  {p.cadence}
                </div>
              </div>
              <div className="dim" style={{ fontSize: 13, lineHeight: 1.5, marginBottom: 22, minHeight: 56 }}>
                {p.tagline}
              </div>

              <ul style={{
                listStyle: 'none', padding: 0, margin: 0, marginBottom: 24,
                display: 'grid', gap: 8,
              }}>
                {p.features.map((f, i) => (
                  <li key={i} style={{
                    display: 'flex', alignItems: 'flex-start', gap: 8,
                    fontSize: 13, opacity: f.ok ? 1 : 0.4,
                  }}>
                    <span className="mono" style={{
                      width: 14, flexShrink: 0,
                      color: f.ok ? 'var(--pos)' : 'var(--neg)',
                      lineHeight: 1.4,
                    }}>
                      {f.ok ? '✓' : '—'}
                    </span>
                    <span style={{ lineHeight: 1.4 }}>{f.text}</span>
                  </li>
                ))}
              </ul>

              <button
                className={`btn ${p.accent && !p.ctaDisabled ? 'btn-accent' : ''}`}
                disabled={p.ctaDisabled}
                onClick={() => onChoosePlan(p.id)}
                style={{ width: '100%', fontSize: 14 }}
              >
                {p.cta}
              </button>
            </div>
          ))}
        </div>

        <div className="panel" style={{
          marginTop: 36, padding: '20px 24px', fontSize: 13, lineHeight: 1.6,
        }}>
          <div className="uppercase faint" style={{ fontSize: 10, letterSpacing: '0.08em', marginBottom: 10 }}>
            What you pay for
          </div>
          <div className="dim" style={{ maxWidth: 720 }}>
            Each prediction is a real provider call — Anthropic, OpenAI, Google, xAI, DeepSeek — and web-search runs cost meaningfully more (~$0.04 per call). Paid tiers cover the headroom to run every enabled model on every market without us going underwater. If you only ever want one model on one prompt, free is fine forever.
          </div>
        </div>
      </section>

      {/* Upgrade-click modal — fires the waitlist submit instantly using
          the signed-in user's email. No form to fill in. */}
      {modalFor && (
        <div
          onClick={closeModal}
          style={{
            position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: 50, padding: 16,
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            className="panel"
            style={{
              maxWidth: 460, width: '100%', padding: 32,
              background: 'var(--bg)', position: 'relative',
              textAlign: 'center',
            }}
          >
            <button
              onClick={closeModal}
              className="btn-ghost"
              style={{
                position: 'absolute', top: 12, right: 12, padding: '4px 10px',
                fontSize: 16, lineHeight: 1,
              }}
              aria-label="Close"
            >×</button>

            {submitState === 'submitting' && (
              <>
                <div className="uppercase faint" style={{ fontSize: 10, letterSpacing: '0.1em', marginBottom: 8 }}>
                  {planName(modalFor)}
                </div>
                <div className="dim" style={{ fontSize: 15, padding: '20px 0' }}>
                  Adding you to the waitlist…
                </div>
              </>
            )}

            {submitState === 'done' && (
              <>
                <div className="uppercase faint" style={{ fontSize: 10, letterSpacing: '0.1em', marginBottom: 10 }}>
                  {planName(modalFor)} waitlist
                </div>
                <div style={{
                  fontFamily: 'var(--ff-display)', fontSize: 40, fontWeight: 300,
                  letterSpacing: '-0.02em', margin: '4px 0 14px',
                }}>
                  Thank you{alreadyOn ? '' : ''}.
                </div>
                <div className="dim" style={{ fontSize: 14, lineHeight: 1.6, marginBottom: 4 }}>
                  {alreadyOn
                    ? "You're already on the waitlist for this tier."
                    : 'You have been added to the waitlist.'}
                </div>
                <div className="dim" style={{ fontSize: 14, lineHeight: 1.6, marginBottom: 22 }}>
                  We will reach out at{' '}
                  <span className="mono" style={{ color: 'var(--accent)' }}>{submittedEmail}</span>
                  {' '}the moment this tier opens.
                </div>
                <button className="btn btn-accent" onClick={closeModal} style={{ minWidth: 160 }}>
                  Back to pricing
                </button>
              </>
            )}

            {submitState === 'error' && (
              <>
                <div className="uppercase faint" style={{ fontSize: 10, letterSpacing: '0.1em', marginBottom: 10 }}>
                  {planName(modalFor)} waitlist
                </div>
                <div className="mono neg" style={{ fontSize: 14, marginBottom: 18, lineHeight: 1.5 }}>
                  {submitErr}
                </div>
                <div className="row gap-12" style={{ justifyContent: 'center' }}>
                  <button className="btn btn-accent" onClick={() => startUpgrade(modalFor)}>
                    Try again
                  </button>
                  <button className="btn" onClick={closeModal}>Close</button>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

window.UpgradePage = UpgradePage;
