// FPDS Signup — multi-tier onboarding flow.
// Route: #/signup?tier=public|explorer|professional|advanced|enterprise|custom
// Flows: public → email-verified key
//        | explorer/professional/advanced → Stripe checkout (t05/tier1/tier2)
//        | enterprise/custom → inline Calendly booking (consultation-gated)

const API_BASE = 'https://analytics-api.kenosaconsulting.com';
const CALENDLY_URL = 'https://calendly.com/nkalosakenyon-kenosaconsulting/30min';

const SIGNUP_STEPS = {
  FORM: 'form',
  CALENDLY: 'calendly',
  KEY: 'key',
  STRIPE: 'stripe',
  VERIFY: 'verify',
  SUCCESS: 'success',
};

const TIER_INFO = {
  public:       { label:'Public',       price:'Free',       color:'#64748B', stripe:false, consultation:false, apiTier:null },
  explorer:     { label:'Explorer',     price:'$75/mo',     color:'#0369A1', stripe:true,  consultation:false, apiTier:'t05' },
  professional: { label:'Professional', price:'$800/mo',    color:'#0D9488', stripe:true,  consultation:false, apiTier:'tier1' },
  advanced:     { label:'Advanced',     price:'$5,000/mo',  color:'#7C3AED', stripe:true,  consultation:false, apiTier:'tier2' },
  enterprise:   { label:'Enterprise',   price:'$18,000/mo', color:'#BE185D', stripe:false, consultation:true },
  custom:       { label:'Custom',       price:'Negotiated', color:'#991B1B', stripe:false, consultation:true },
};

const TIER_KEY_MAP = {
  public:'public', explorer:'t05', professional:'t1', advanced:'t2', enterprise:'t3', custom:'custom',
  // Reverse mapping for legacy API-key style links
  t05:'explorer', t1:'professional', t2:'advanced', t3:'enterprise',
};

const parseTier = () => {
  const h = window.location.hash || '';
  const m = h.match(/tier=(\w+)/);
  const raw = m ? m[1] : 'public';
  // Prefer the slug directly; only fall back to the API-key map (t1, t2, t05...)
  // when someone links with a legacy API tier key.
  const tier = TIER_INFO[raw] ? raw : (TIER_KEY_MAP[raw] || 'public');
  return TIER_INFO[tier] ? tier : 'public';
};

const hashParam = (name) => {
  const h = window.location.hash || '';
  const m = h.match(new RegExp('[?&]' + name + '=([^&#]*)'));
  return m ? decodeURIComponent(m[1]) : null;
};

// ── Form Fields Component ──

const SignupForm = ({ tier, onSubmit, loading }) => {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [org, setOrg] = React.useState('');
  const [useCase, setUseCase] = React.useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit({ name, email, organization: org, intended_use: useCase });
  };

  const isValid = name.trim() && email.trim() && email.includes('@');

  return (
    <form onSubmit={handleSubmit} style={{ maxWidth:440 }}>
      <div style={{ marginBottom:16 }}>
        <label style={{ display:'block', fontSize:13, fontWeight:600, color:'#334155', marginBottom:6 }}>
          Full name
        </label>
        <input
          type="text" value={name} onChange={e => setName(e.target.value)}
          placeholder="Jane Smith"
          style={{
            width:'100%', padding:'10px 14px', border:'1px solid #CBD5E1',
            borderRadius:8, fontSize:15, color:'#0F172A', outline:'none',
            fontFamily:'var(--font-sans)',
            transition:'border-color 0.15s',
          }}
          onFocus={e => e.target.style.borderColor = '#000080'}
          onBlur={e => e.target.style.borderColor = '#CBD5E1'}
        />
      </div>
      <div style={{ marginBottom:16 }}>
        <label style={{ display:'block', fontSize:13, fontWeight:600, color:'#334155', marginBottom:6 }}>
          Work email
        </label>
        <input
          type="email" value={email} onChange={e => setEmail(e.target.value)}
          placeholder="jane@agency.gov"
          style={{
            width:'100%', padding:'10px 14px', border:'1px solid #CBD5E1',
            borderRadius:8, fontSize:15, color:'#0F172A', outline:'none',
            fontFamily:'var(--font-sans)',
            transition:'border-color 0.15s',
          }}
          onFocus={e => e.target.style.borderColor = '#000080'}
          onBlur={e => e.target.style.borderColor = '#CBD5E1'}
        />
      </div>
      <div style={{ marginBottom:16 }}>
        <label style={{ display:'block', fontSize:13, fontWeight:600, color:'#334155', marginBottom:6 }}>
          Organization
        </label>
        <input
          type="text" value={org} onChange={e => setOrg(e.target.value)}
          placeholder="Department of Defense"
          style={{
            width:'100%', padding:'10px 14px', border:'1px solid #CBD5E1',
            borderRadius:8, fontSize:15, color:'#0F172A', outline:'none',
            fontFamily:'var(--font-sans)',
            transition:'border-color 0.15s',
          }}
          onFocus={e => e.target.style.borderColor = '#000080'}
          onBlur={e => e.target.style.borderColor = '#CBD5E1'}
        />
      </div>
      <div style={{ marginBottom:24 }}>
        <label style={{ display:'block', fontSize:13, fontWeight:600, color:'#334155', marginBottom:6 }}>
          How do you plan to use FPDS?
        </label>
        <textarea
          value={useCase} onChange={e => setUseCase(e.target.value)}
          placeholder="Market research, capture planning, competitive analysis..."
          rows={3}
          style={{
            width:'100%', padding:'10px 14px', border:'1px solid #CBD5E1',
            borderRadius:8, fontSize:15, color:'#0F172A', outline:'none',
            fontFamily:'var(--font-sans)', resize:'vertical',
            transition:'border-color 0.15s',
          }}
          onFocus={e => e.target.style.borderColor = '#000080'}
          onBlur={e => e.target.style.borderColor = '#CBD5E1'}
        />
      </div>
      <button
        type="submit" disabled={!isValid || loading}
        style={{
          width:'100%', padding:'13px 20px',
          background: isValid ? '#000080' : '#CBD5E1',
          color:'#FFFFFF', border:'none', borderRadius:9,
          fontSize:15, fontWeight:600, cursor: isValid ? 'pointer' : 'not-allowed',
          transition:'all 0.15s',
          fontFamily:'var(--font-sans)',
        }}
        onMouseEnter={e => { if (isValid) e.target.style.background = '#1E3A8A'; }}
        onMouseLeave={e => { if (isValid) e.target.style.background = '#000080'; }}
      >
        {loading ? 'Creating your account...' : 'Continue'}
      </button>
      <div style={{fontSize:12, color:'var(--slate-500)', textAlign:'center', lineHeight:1.6}}>
        By continuing you agree to our <a href="/legal/terms" style={{color:'#000080'}}>Terms of Service</a> and{' '}
        <a href="/legal/privacy" style={{color:'#000080'}}>Privacy Policy</a>.
      </div>
    </form>
  );
};

// ── Key Display Component ──

const KeyDisplay = ({ apiKey, tier }) => {
  const [copied, setCopied] = React.useState(false);

  const copy = () => {
    navigator.clipboard.writeText(apiKey).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }).catch(() => {});
  };

  return (
    <div style={{ maxWidth:520 }}>
      <div style={{
        background:'#F0FDFA', border:'1px solid #99F6E4',
        borderRadius:10, padding:20, marginBottom:20,
      }}>
        <div style={{
          display:'flex', alignItems:'center', gap:8, marginBottom:12,
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#0D9488" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
          <span style={{ fontSize:15, fontWeight:700, color:'#0F766E' }}>
            Your API key is ready
          </span>
        </div>
        <div style={{
          display:'flex', alignItems:'center', gap:10,
          background:'#FFFFFF', border:'1px solid #99F6E4',
          borderRadius:8, padding:'12px 16px',
        }}>
          <code style={{
            flex:1, fontFamily:'var(--font-mono)', fontSize:13,
            color:'#0F172A', wordBreak:'break-all',
          }}>
            {apiKey}
          </code>
          <button
            onClick={copy}
            style={{
              flexShrink:0, padding:'6px 14px',
              background: copied ? '#D1FAE5' : '#F0FDFA',
              color: copied ? '#065F46' : '#0D9488',
              border:'1px solid', borderColor: copied ? '#6EE7B7' : '#5EEAD4',
              borderRadius:6, fontSize:11, fontWeight:700,
              letterSpacing:'0.04em', cursor:'pointer',
              fontFamily:'var(--font-mono)',
              transition:'all 0.15s',
            }}
          >
            {copied ? 'COPIED' : 'COPY'}
          </button>
        </div>
      </div>

      <div style={{
        background:'#FFFBEB', border:'1px solid #FDE68A',
        borderRadius:10, padding:16, marginBottom:24,
        fontSize:13, lineHeight:1.55, color:'#92400E',
      }}>
        <strong>Store this key securely.</strong> It will not be shown again.
        We store only a SHA-256 hash, not the key itself.
      </div>

      <a href="#/docs/getting-started" style={{
        display:'inline-flex', alignItems:'center', gap:8,
        padding:'12px 24px', background:'#000080', color:'#FFFFFF',
        borderRadius:9, textDecoration:'none', fontWeight:600, fontSize:14,
        transition:'all 0.15s',
      }}
        onMouseEnter={e => e.target.style.background = '#1E3A8A'}
        onMouseLeave={e => e.target.style.background = '#000080'}
      >
        Go to docs
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>
        </svg>
      </a>
    </div>
  );
};

// ── Calendly Booking View (Enterprise + Custom) ──

const CalendlyBooking = ({ tier, formData }) => {
  const containerRef = React.useRef(null);
  const [ready, setReady] = React.useState(Boolean(window.Calendly));
  const info = TIER_INFO[tier];

  React.useEffect(() => {
    let cancelled = false;
    const init = () => {
      if (!window.Calendly || !containerRef.current) return;
      window.Calendly.initInlineWidget({
        url: CALENDLY_URL,
        parentElement: containerRef.current,
        prefill: {
          name: formData ? formData.name : undefined,
          email: formData ? formData.email : undefined,
        },
        utm: {
          utmCampaign: 'fpds-signup',
          utmSource: 'fpds.kenosaconsulting.com',
          utmContent: tier,
        },
      });
      if (!cancelled) setReady(true);
    };
    if (window.Calendly) {
      init();
    } else {
      const script = document.createElement('script');
      script.src = 'https://assets.calendly.com/assets/external/widget.js';
      script.async = true;
      script.onload = init;
      script.onerror = () => { if (!cancelled) setReady(false); };
      document.head.appendChild(script);
    }
    return () => { cancelled = true; };
  }, []);

  return (
    <div style={{ maxWidth:640 }}>
      <div style={{
        background:'#F0F9FF', border:'1px solid #BAE6FD',
        borderRadius:10, padding:16, marginBottom:20, fontSize:14,
        lineHeight:1.55, color:'#0C4A6E',
      }}>
        {tier === 'enterprise'
          ? 'Enterprise access is provisioned after a conversation with our team. Pick a 30-minute slot and we\u2019ll tailor the demo to your agency and use case — no commitment.'
          : 'Custom contracts are scoped together — dedicated GPU capacity, white-label deployment, custom corpora. Pick a 30-minute slot and we\u2019ll come prepared with numbers.'}
      </div>
      <div
        ref={containerRef}
        style={{
          width:'100%', minWidth:320, height:700,
          border:'1px solid #E2E8F0', borderRadius:12,
          overflow:'hidden', background:'#FAFBFC',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}
      >
        {!ready && (
          <div style={{ textAlign:'center', color:'#94A3B8', fontSize:14 }}>
            Loading scheduler…
          </div>
        )}
      </div>
      <p style={{ fontSize:13, color:'#94A3B8', margin:'16px 0 0' }}>
        Widget not loading?{' '}
        <a
          href={CALENDLY_URL}
          target="_blank"
          rel="noopener noreferrer"
          style={{ color:'#000080', fontWeight:600 }}
        >
          Open the scheduling page in a new tab
        </a>
        . You can also email us at nkalosakenyon@kenosaconsulting.com.
      </p>
    </div>
  );
};

// ── Stripe Redirect View ──

const StripeRedirect = ({ tier, formData, interval, onError }) => {
  const info = TIER_INFO[tier];
  const [message, setMessage] = React.useState('Redirecting to secure checkout...');

  React.useEffect(() => {
    let cancelled = false;
    const createCheckout = async () => {
      try {
        const res = await fetch(`${API_BASE}/v1/billing/checkout`, {
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body:JSON.stringify({ tier:info.apiTier, email:formData.email, interval: interval || 'month' }),
        });
        const data = await res.json();
        if (!res.ok) {
          const msg = (data && data.error && data.error.message) || 'Checkout could not be started.';
          if (cancelled) return;
          setMessage(msg);
          if (onError) onError(msg);
          return;
        }
        if (data.checkout_url) {
          window.location.href = data.checkout_url;
        }
      } catch (err) {
        if (cancelled) return;
        const msg = 'Network error while starting checkout. Please try again.';
        setMessage(msg);
        if (onError) onError(msg);
      }
    };
    createCheckout();
    return () => { cancelled = true; };
  }, []);

  return (
    <div style={{ maxWidth:440, textAlign:'center' }}>
      <div style={{
        width:48, height:48, borderRadius:'50%',
        background:'#F0FDFA', display:'flex', alignItems:'center', justifyContent:'center',
        margin:'0 auto 20px',
      }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#0D9488" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 16 14"/>
        </svg>
      </div>
      <p style={{ fontSize:16, lineHeight:1.55, color:'#475569', margin:'0 0 8px' }}>
        {message}
      </p>
      <p style={{ fontSize:13, color:'#94A3B8', margin:0 }}>
        You'll receive your API key by email immediately after payment.
      </p>
    </div>
  );
};

// ── Email Verification View ──

const VerifyCode = ({ requestId, email, onVerified, onError }) => {
  const [code, setCode] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    if (!/^\d{6}$/.test(code)) {
      setError('Enter the 6-digit code from your email.');
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${API_BASE}/v1/keys/verify`, {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({ request_id:requestId, code }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError((data && data.error && data.error.message) || 'Verification failed.');
        setLoading(false);
        return;
      }
      onVerified(data.api_key, data.tier);
    } catch (err) {
      setError('Network error. Please try again.');
      setLoading(false);
    }
  };

  return (
    <form onSubmit={submit} style={{ maxWidth:440 }}>
      <div style={{
        background:'#F0F9FF', border:'1px solid #BAE6FD',
        borderRadius:10, padding:16, marginBottom:20, fontSize:14,
        lineHeight:1.55, color:'#0C4A6E',
      }}>
        We emailed a 6-digit verification code to <strong>{email}</strong>.
      </div>
      <label style={{ display:'block', fontSize:13, fontWeight:600, color:'#334155', marginBottom:6 }}>
        Verification code
      </label>
      <input
        value={code}
        onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
        placeholder="123456"
        inputMode="numeric"
        style={{
          width:'100%', padding:'12px 16px', border:'1px solid #CBD5E1',
          borderRadius:8, fontSize:20, letterSpacing:'0.3em', textAlign:'center',
          color:'#0F172A', outline:'none', fontFamily:'var(--font-mono)',
          marginBottom:12,
        }}
      />
      {error && (
        <p style={{ fontSize:13, color:'#B91C1C', margin:'0 0 12px' }}>{error}</p>
      )}
      <button
        type="submit" disabled={loading}
        style={{
          width:'100%', padding:'13px 20px', background:'#000080', color:'#FFFFFF',
          border:'none', borderRadius:9, fontSize:15, fontWeight:600,
          cursor: loading ? 'not-allowed' : 'pointer', fontFamily:'var(--font-sans)',
        }}
      >
        {loading ? 'Verifying...' : 'Verify & get key'}
      </button>
    </form>
  );
};

// ── Payment Success View ──

const PaymentSuccess = ({ email }) => (
  <div style={{ maxWidth:520 }}>
    <div style={{
      background:'#F0FDFA', border:'1px solid #99F6E4',
      borderRadius:10, padding:20, marginBottom:20,
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#0D9488" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12"/>
        </svg>
        <span style={{ fontSize:15, fontWeight:700, color:'#0F766E' }}>Payment confirmed</span>
      </div>
      <p style={{ fontSize:14, lineHeight:1.55, color:'#0F766E', margin:0 }}>
        {email ? (
          <span>Your API key is on its way to <strong>{email}</strong>.</span>
        ) : (
          <span>Your API key is on its way by email.</span>
        )}{' '}
        It usually lands within a minute — check spam if you don't see it.
      </p>
    </div>
    <div style={{ display:'flex', gap:12, flexWrap:'wrap' }}>
      <a href="#/docs/api" style={{
        display:'inline-flex', alignItems:'center', gap:8,
        padding:'12px 24px', background:'#000080', color:'#FFFFFF',
        borderRadius:9, textDecoration:'none', fontWeight:600, fontSize:14,
        fontFamily:'var(--font-sans)',
      }}>
        Explore the API docs
      </a>
      <a href="#/account" style={{
        display:'inline-flex', alignItems:'center', gap:8,
        padding:'12px 24px', color:'#000080',
        border:'1px solid rgba(0,0,128,0.20)', background:'transparent',
        borderRadius:9, textDecoration:'none', fontWeight:600, fontSize:14,
        fontFamily:'var(--font-sans)',
      }}>
        Open your dashboard
      </a>
    </div>
  </div>
);

// ── Cancel Notice ──

const CancelNotice = ({ tier }) => (
  <div style={{
    background:'#FFFBEB', border:'1px solid #FDE68A',
    borderRadius:10, padding:14, marginBottom:20,
    fontSize:14, color:'#92400E', maxWidth:440,
  }}>
    Checkout was cancelled — no charge was made. You can restart your{' '}
    <strong>{TIER_INFO[tier].label}</strong> plan below whenever you're ready.
  </div>
);

// ── MCP Add-On Flow ──

const McpAddonFlow = () => {
  const [email, setEmail] = React.useState('');
  const [keyPrefix, setKeyPrefix] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [errorMessage, setErrorMessage] = React.useState(null);

  const inputStyle = {
    width:'100%', padding:'14px 16px', borderRadius:9,
    border:'1px solid #CBD5E1', fontSize:15, fontFamily:'var(--font-sans)',
    color:'#0F172A', outline:'none', boxSizing:'border-box',
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrorMessage(null);
    setLoading(true);
    try {
      const res = await fetch(`${API_BASE}/v1/billing/checkout/mcp`, {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({ email, key_prefix: keyPrefix.trim() }),
      });
      const body = await res.json();
      if (!res.ok) {
        setErrorMessage((body && body.error && body.error.message) || 'Could not start checkout.');
        setLoading(false);
        return;
      }
      window.location.href = body.checkout_url;
    } catch (err) {
      setErrorMessage('Network error. Please try again.');
      setLoading(false);
    }
  };

  return (
    <div style={{ background:'#FFFFFF', minHeight:'100vh' }}>
      <section style={{ padding:'100px 0 80px' }}>
        <div className="container" style={{ maxWidth:560 }}>
          <div style={{ marginBottom:40 }}>
            <div style={{
              display:'inline-flex', alignItems:'center', gap:8,
              padding:'4px 12px', borderRadius:5,
              background:'#7C3AED10', color:'#7C3AED',
              fontSize:12, fontWeight:700, letterSpacing:'0.06em',
              textTransform:'uppercase', fontFamily:'var(--font-mono)',
              marginBottom:16,
            }}>
              MCP add-on
            </div>
            <h1 style={{
              fontSize:'clamp(28px, 3.5vw, 40px)', fontWeight:800,
              color:'#0F172A', lineHeight:1.10, letterSpacing:'-0.02em',
              margin:'0 0 8px',
            }}>
              Add MCP to your subscription
            </h1>
            <p style={{ fontSize:16, lineHeight:1.55, color:'#64748B', margin:0 }}>
              $200 per month. Attaches to an existing Professional or Advanced key —
              included free with Enterprise. Separate 5,000 tool-call monthly allowance.
            </p>
          </div>

          <form onSubmit={handleSubmit} style={{ display:'flex', flexDirection:'column', gap:18, maxWidth:440 }}>
            {errorMessage && (
              <div style={{
                background:'#FEF2F2', border:'1px solid #FECACA',
                borderRadius:10, padding:14,
                fontSize:14, color:'#B91C1C',
              }}>
                {errorMessage}
              </div>
            )}
            <div>
              <label style={{ display:'block', fontSize:13, fontWeight:600, color:'#334155', marginBottom:6 }}>
                Email
              </label>
              <input
                type="email" required value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="you@company.com"
                style={inputStyle}
              />
            </div>
            <div>
              <label style={{ display:'block', fontSize:13, fontWeight:600, color:'#334155', marginBottom:6 }}>
                API key prefix
              </label>
              <input
                required value={keyPrefix}
                onChange={e => setKeyPrefix(e.target.value)}
                placeholder="fpds_tier1_k..."
                style={inputStyle}
              />
              <p style={{ fontSize:13, color:'#94A3B8', margin:'6px 0 0' }}>
                The first 16 characters of your subscription key.
              </p>
            </div>
            <button
              type="submit" disabled={loading}
              style={{
                padding:'14px 24px', borderRadius:9, fontSize:15, fontWeight:600,
                border:'none', cursor: loading ? 'wait' : 'pointer',
                background:'#000080', color:'#FFFFFF', fontFamily:'var(--font-sans)',
                opacity: loading ? 0.7 : 1,
              }}
            >
              {loading ? 'Redirecting to checkout…' : 'Continue to checkout'}
            </button>
            <div style={{fontSize:12, color:'var(--slate-500)', textAlign:'center', lineHeight:1.6}}>
              By continuing you agree to our <a href="/legal/terms" style={{color:'#000080'}}>Terms of Service</a> and{' '}
              <a href="/legal/privacy" style={{color:'#000080'}}>Privacy Policy</a>.
            </div>
          </form>
        </div>
      </section>
    </div>
  );
};

// ── Main Signup Page ──

const SignupFlow = () => {
  const tier = parseTier();
  const info = TIER_INFO[tier];
  const hash = window.location.hash || '';
  const addonMode = hash.includes('addon=mcp');
  const cancelled = hash.includes('status=cancelled');
  const initialStep = hash.includes('status=success')
    ? SIGNUP_STEPS.SUCCESS
    : SIGNUP_STEPS.FORM;
  const [step, setStep] = React.useState(initialStep);
  const [formData, setFormData] = React.useState(null);
  const [requestId, setRequestId] = React.useState(null);
  const [apiKey, setApiKey] = React.useState(null);
  const [apiTier, setApiTier] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [errorMessage, setErrorMessage] = React.useState(null);
  const [interval, setInterval] = React.useState('month');

  const handleFormSubmit = async (data) => {
    setFormData(data);
    setErrorMessage(null);

    if (tier === 'public') {
      // Email-verified free key: request → code by email → verify
      setLoading(true);
      try {
        const res = await fetch(`${API_BASE}/v1/keys/request`, {
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body:JSON.stringify({
            email:data.email,
            name:data.name,
            organization:data.organization,
            intended_use:data.intended_use,
            tier:'public',
          }),
        });
        const body = await res.json();
        if (!res.ok) {
          setErrorMessage((body && body.error && body.error.message) || 'Key request failed.');
          setLoading(false);
          return;
        }
        setRequestId(body.request_id);
        setStep(SIGNUP_STEPS.VERIFY);
      } catch (err) {
        setErrorMessage('Network error. Please try again.');
      }
      setLoading(false);
    } else if (info.stripe) {
      // Self-serve Stripe checkout: Explorer (t05), Professional (tier1), Advanced (tier2)
      setStep(SIGNUP_STEPS.STRIPE);
    } else {
      // Enterprise + Custom: consultation-gated via Calendly
      setStep(SIGNUP_STEPS.CALENDLY);
    }
  };

  const handleVerified = (key, keyTier) => {
    setApiKey(key);
    setApiTier(keyTier);
    setStep(SIGNUP_STEPS.KEY);
  };

  const handleStripeError = (msg) => {
    setErrorMessage(msg);
  };

  const successEmail = hashParam('email') || (formData && formData.email) || '';

  if (addonMode) {
    return <McpAddonFlow/>;
  }

  return (
    <div style={{ background:'#FFFFFF', minHeight:'100vh' }}>
      <section style={{ padding:'100px 0 80px' }}>
        <div className="container" style={{ maxWidth:560 }}>
          <div style={{ marginBottom:40 }}>
            <div style={{
              display:'inline-flex', alignItems:'center', gap:8,
              padding:'4px 12px', borderRadius:5,
              background:`${info.color}10`, color:info.color,
              fontSize:12, fontWeight:700, letterSpacing:'0.06em',
              textTransform:'uppercase', fontFamily:'var(--font-mono)',
              marginBottom:16,
            }}>
              {info.label} plan
            </div>
            <h1 style={{
              fontSize:'clamp(28px, 3.5vw, 40px)', fontWeight:800,
              color:'#0F172A', lineHeight:1.10, letterSpacing:'-0.02em',
              margin:'0 0 8px',
            }}>
              {tier === 'public' ? 'Get your free API key' :
               tier === 'enterprise' ? 'Schedule your onboarding call' :
               tier === 'custom' ? 'Let\u2019s build your plan' :
               `Start your ${info.label} plan`}
            </h1>
            <p style={{
              fontSize:16, lineHeight:1.55, color:'#64748B', margin:0,
            }}>
              {tier === 'public' ? 'No credit card required. Free access to discovery tools.' :
               tier === 'enterprise' ? 'Enterprise access is provisioned after a conversation with our team.' :
               tier === 'custom' ? 'Pick a 30-minute slot and we\u2019ll scope your contract together.' :
               `${info.price} per seat per month. Cancel anytime.`}
            </p>
          </div>

          {step === SIGNUP_STEPS.FORM && (
            <div>
              {cancelled && <CancelNotice tier={tier}/>}
              {errorMessage && (
                <div style={{
                  background:'#FEF2F2', border:'1px solid #FECACA',
                  borderRadius:10, padding:14, marginBottom:20,
                  fontSize:14, color:'#B91C1C', maxWidth:440,
                }}>
                  {errorMessage}
                </div>
              )}
              {info.stripe && (
                <div style={{
                  display:'inline-flex', gap:8, padding:4,
                  background:'#F1F5F9', borderRadius:10, marginBottom:20,
                }}>
                  <button
                    type="button"
                    onClick={() => setInterval('month')}
                    style={{
                      padding:'8px 18px', borderRadius:8, border:'none',
                      fontSize:13, fontWeight:600, cursor:'pointer',
                      fontFamily:'var(--font-sans)',
                      background: interval === 'month' ? '#FFFFFF' : 'transparent',
                      color: interval === 'month' ? '#000080' : '#64748B',
                      boxShadow: interval === 'month' ? '0 1px 3px rgba(0,0,0,0.10)' : 'none',
                    }}
                  >
                    Monthly · {info.price}
                  </button>
                  <button
                    type="button"
                    onClick={() => setInterval('annual')}
                    style={{
                      padding:'8px 18px', borderRadius:8, border:'none',
                      fontSize:13, fontWeight:600, cursor:'pointer',
                      fontFamily:'var(--font-sans)',
                      background: interval === 'annual' ? '#FFFFFF' : 'transparent',
                      color: interval === 'annual' ? '#000080' : '#64748B',
                      boxShadow: interval === 'annual' ? '0 1px 3px rgba(0,0,0,0.10)' : 'none',
                    }}
                  >
                    Annual · save 20%
                  </button>
                </div>
              )}
              <SignupForm tier={tier} onSubmit={handleFormSubmit} loading={loading}/>
            </div>
          )}

          {step === SIGNUP_STEPS.VERIFY && formData && (
            <VerifyCode
              requestId={requestId}
              email={formData.email}
              onVerified={handleVerified}
            />
          )}

          {step === SIGNUP_STEPS.CALENDLY && formData && (
            <CalendlyBooking tier={tier} formData={formData}/>
          )}

          {step === SIGNUP_STEPS.SUCCESS && (
            <PaymentSuccess email={successEmail}/>
          )}

          {step === SIGNUP_STEPS.STRIPE && formData && (
            <StripeRedirect tier={tier} formData={formData} interval={interval} onError={handleStripeError}/>
          )}

          {step === SIGNUP_STEPS.KEY && (
            <KeyDisplay apiKey={apiKey} tier={apiTier || tier}/>
          )}
        </div>
      </section>
    </div>
  );
};

window.SignupFlow = SignupFlow;
