/* ============================================================
   CURIO — Upgrade / Pricing page
   ============================================================ */

function PlanCard({ name, price, period, tagline, feats, highlight, ctaLabel, onCta, current, disabled }) {
  return (
    <div className="card" style={{
      padding: '28px 26px',
      display: 'flex',
      flexDirection: 'column',
      gap: 14,
      border: highlight ? '2px solid var(--brand)' : '1px solid var(--line)',
      boxShadow: highlight ? '0 6px 24px rgba(91,84,230,.18)' : 'var(--sh-xs)',
      background: highlight ? 'linear-gradient(180deg, var(--brand-tint) 0%, var(--surface) 60%)' : 'var(--surface)',
      position: 'relative',
    }}>
      {current && (
        <span className="badge badge-green" style={{ position: 'absolute', top: 16, right: 16 }}>
          <Check size={11} /> Current
        </span>
      )}
      {highlight && !current && (
        <span className="badge badge-brand" style={{ position: 'absolute', top: 16, right: 16, background: 'var(--brand)', color: '#fff' }}>
          Most popular
        </span>
      )}
      <div>
        <div className="mono" style={{ fontSize: 11.5, letterSpacing: '.12em', textTransform: 'uppercase', color: highlight ? 'var(--brand)' : 'var(--faint)' }}>{name}</div>
        <div className="row" style={{ alignItems: 'baseline', gap: 4, marginTop: 8 }}>
          <span style={{ fontSize: 36, fontWeight: 800, letterSpacing: '-0.03em' }}>${price}</span>
          {period && <span className="muted" style={{ fontSize: 14 }}>{period}</span>}
        </div>
        <div className="muted" style={{ fontSize: 14, marginTop: 4 }}>{tagline}</div>
      </div>
      <div className="hairline" />
      <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {feats.map((f, i) => (
          <li key={i} className="row" style={{ alignItems: 'flex-start', gap: 9, fontSize: 14, lineHeight: 1.4 }}>
            <Check size={15} style={{ color: 'var(--green)', marginTop: 2, flexShrink: 0 }} />
            <span>{f}</span>
          </li>
        ))}
      </ul>
      <Btn
        variant={current ? 'outline' : highlight ? 'brand' : 'soft'}
        block
        style={{ height: 44, marginTop: 'auto' }}
        disabled={disabled || current}
        onClick={onCta}
      >
        {ctaLabel}
      </Btn>
    </div>
  );
}

function UpgradePage({ go, user, setUser }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [stripeStatus, setStripeStatus] = useState(null);
  const [usingDirect, setUsingDirect] = useState(false);

  // Surface Stripe redirect outcomes when the user returns from Checkout.
  useEffect(() => {
    try {
      const sp = new URLSearchParams(window.location.search);
      const s = sp.get('stripe');
      if (s === 'success') {
        setStripeStatus('success');
        // Refresh the user so the new plan badge appears.
        window.API.me().then(d => {
          const u = d?.user;
          if (u) {
            window.__user = { ...(window.__user || {}), ...u };
            if (setUser) setUser(window.__user);
          }
        }).catch(() => {});
      } else if (s === 'cancel') {
        setStripeStatus('cancel');
      }
    } catch {}
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const planKey = (() => {
    if (!user) return 'free';
    if (user.plan === 'pro') return 'pro';
    if (user.plan === 'teams') return 'teams';
    return 'free';
  })();

  const doUpgrade = async (targetPlan) => {
    setBusy(true);
    setError(null);
    setSuccess(null);
    setUsingDirect(false);
    try {
      // 1. Try Stripe Checkout first.
      try {
        const res = await window.API.billingCheckout(targetPlan);
        if (res && res.url) {
          window.location.href = res.url;
          return;
        }
      } catch (e) {
        // Fall through to direct activation only on STRIPE_NOT_CONFIGURED.
        if (e?.code !== 'STRIPE_NOT_CONFIGURED') {
          throw e;
        }
        setUsingDirect(true);
      }
      // 2. Fallback: direct flip (beta mode).
      const res = await window.API.upgradePlan(targetPlan);
      if (res && res.user) {
        window.__user = { ...(window.__user || {}), ...res.user };
        if (setUser) setUser(window.__user);
      }
      setSuccess(`You are now on the ${targetPlan.charAt(0).toUpperCase() + targetPlan.slice(1)} plan.`);
    } catch (e) {
      setError(e?.message || 'Upgrade failed');
    } finally {
      setBusy(false);
    }
  };

  const doDowngrade = async () => {
    if (!window.confirm('Switch back to the free plan? You will keep your existing content but will hit free-tier limits when creating new things.')) return;
    setBusy(true);
    setError(null);
    setSuccess(null);
    try {
      const res = await window.API.downgradePlan();
      if (res && res.user) {
        window.__user = { ...(window.__user || {}), ...res.user };
        if (setUser) setUser(window.__user);
      }
      setSuccess('You are now on the Free plan.');
    } catch (e) {
      setError(e?.message || 'Could not switch plans');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--paper)', display: 'flex', flexDirection: 'column' }} data-screen-label="Pricing">
      {/* Top bar */}
      <div style={{ borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
        <div className="row" style={{ maxWidth: 1080, margin: '0 auto', padding: '14px 32px', gap: 14 }}>
          <button className="btn btn-icon btn-ghost btn-sm" onClick={() => go('library')}><ChevL size={18} /></button>
          <div style={{ fontSize: 14.5, fontWeight: 600 }}>Pricing</div>
          <div className="grow" />
          {user && (
            <span className="muted" style={{ fontSize: 13 }}>
              Signed in as <b style={{ color: 'var(--ink-2)' }}>{user.email}</b> · <span className="mono" style={{ textTransform: 'capitalize' }}>{user.plan || 'trial'}</span>
            </span>
          )}
        </div>
      </div>

      {/* Hero */}
      <div style={{ maxWidth: 820, margin: '0 auto', padding: '56px 32px 8px', textAlign: 'center' }}>
        <div className="mono" style={{ fontSize: 11.5, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--brand)', marginBottom: 14 }}>Pricing</div>
        <h1 style={{ fontSize: 'clamp(30px, 4vw, 40px)', letterSpacing: '-0.03em', lineHeight: 1.1 }}>Build at the speed of ideas</h1>
        <p className="lead" style={{ fontSize: 16, marginTop: 14, color: 'var(--muted)', lineHeight: 1.55 }}>
          Free covers a single course while you try Coursedy. Upgrade for unlimited courses, modules, and lessons.
        </p>
      </div>

      {/* Stripe redirect banner */}
      {stripeStatus && (
        <div style={{ maxWidth: 820, width: '100%', margin: '20px auto 0', padding: '0 32px' }}>
          {stripeStatus === 'success' && (
            <div className="card fade-in" style={{ padding: '16px 18px', background: 'var(--green-tint)', color: '#0e6b47', borderRadius: 12, fontSize: 15, fontWeight: 600 }}>
              Payment successful. Your plan will update within a moment.
            </div>
          )}
          {stripeStatus === 'cancel' && (
            <div className="card fade-in" style={{ padding: '12px 16px', background: 'var(--surface-2)', color: 'var(--muted)', borderRadius: 12, fontSize: 14 }}>
              Cancelled — no charge.
            </div>
          )}
        </div>
      )}

      {/* Notifications */}
      {(error || success || usingDirect) && (
        <div style={{ maxWidth: 820, width: '100%', margin: '20px auto 0', padding: '0 32px' }}>
          {error && (
            <div className="card fade-in" style={{ padding: '12px 16px', background: 'var(--rose-tint, #fde9ee)', color: '#9c1f3c', borderRadius: 12, fontSize: 14 }}>
              {error}
            </div>
          )}
          {success && (
            <div className="card fade-in" style={{ padding: '12px 16px', background: 'var(--green-tint)', color: '#0e6b47', borderRadius: 12, fontSize: 14 }}>
              {success}
              {usingDirect && <span className="muted" style={{ marginLeft: 8, fontSize: 13 }}>(Beta — direct activation, no payment required)</span>}
            </div>
          )}
        </div>
      )}

      {/* Plans */}
      <div style={{ maxWidth: 1080, margin: '0 auto', padding: '40px 32px 80px', width: '100%' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 22 }}>
          <PlanCard
            name="Free"
            price={0}
            period=""
            tagline="For trying things out"
            current={planKey === 'free'}
            feats={[
              '1 course',
              '1 module per course',
              '3 lessons per module',
              'DOCX, PDF, JSON exports',
              'AI chat with DeepSeek',
            ]}
            ctaLabel={planKey === 'free' ? 'Your current plan' : 'Switch to free'}
            onCta={() => planKey !== 'free' && doDowngrade()}
            disabled={busy}
          />
          <PlanCard
            name="Pro"
            price={24}
            period="/mo"
            tagline="For creators & coaches"
            highlight
            current={planKey === 'pro'}
            feats={[
              'Unlimited courses',
              'Unlimited modules per course',
              'Unlimited lessons per module',
              'Priority generation speed',
              'SCORM + ePub + branded exports',
              'Edit history & inline AI refinement',
            ]}
            ctaLabel={planKey === 'pro' ? 'Your current plan' : busy ? 'Upgrading…' : 'Upgrade to Pro'}
            onCta={() => doUpgrade('pro')}
            disabled={busy}
          />
          <PlanCard
            name="Teams"
            price={79}
            period="/mo"
            tagline="For orgs & schools"
            current={planKey === 'teams'}
            feats={[
              'Everything in Pro',
              'Shared workspace & roles',
              'Brand kit & templates',
              'Analytics & SSO',
              'Onboarding manager',
            ]}
            ctaLabel={planKey === 'teams' ? 'Your current plan' : busy ? 'Upgrading…' : 'Upgrade to Teams'}
            onCta={() => doUpgrade('teams')}
            disabled={busy}
          />
        </div>

        <div className="card" style={{ marginTop: 32, padding: '20px 24px', background: 'var(--surface-2)', border: 'none' }}>
          <div className="row" style={{ gap: 14 }}>
            <span className="center" style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--brand)', color: '#fff', flexShrink: 0 }}><Spark size={17} /></span>
            <div className="grow" style={{ minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Beta note</div>
              <div className="muted" style={{ fontSize: 13.5, marginTop: 4, lineHeight: 1.5 }}>
                We are in beta — no card is charged today. Clicking Upgrade activates the plan instantly for testing; clicking Switch to free at the top of the Free card reverts to the limited tier.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { UpgradePage });
