// Page: Waitlist (v0 — client-side capture, wire to backend later)
// `side` = 'operator' | 'company' — `lang` = 'en' | 'de'
function WaitlistPage({ go, side, lang }) {
  const isOperator = side === 'operator';
  const isDe = lang === 'de';
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [niche, setNiche] = useState('');
  const [extra, setExtra] = useState('');
  const [marketing, setMarketing] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState('');

  // Localized copy bundle
  const T = isDe ? {
    invalidEmail: 'Bitte gültige E-Mail-Adresse eingeben.',
    onListKicker: 'Sie sind dabei',
    thanks: 'Danke.',
    inTouch: 'Wir melden uns.',
    operatorDone: 'Sobald das Verzeichnis öffnet, sind Sie eine der ersten Personen, die ein Profil anlegen können. Wir schreiben Ihnen, sobald die Listings live gehen.',
    companyDone: 'Sobald das Verzeichnis öffnet, haben Sie als erstes Zugang zu geprüften Anbietern. Wir schreiben Ihnen, sobald wir starten.',
    backHome: 'Zur Startseite',
    browse: 'Vorschau ansehen',
    operatorKicker: 'Für Anbieter',
    companyKicker: 'Für Unternehmen',
    earlyTitle1: 'Sie sind früh dran.',
    earlyTitle2: 'Tragen Sie sich ein.',
    operatorLead: 'Wir öffnen die Anbieter-Profile bald. Lassen Sie uns Ihre E-Mail da, dann können Sie Ihren Profilnamen und Ihre Listings vor dem Ansturm reservieren.',
    companyLead: 'Wir öffnen die Unternehmens-Listings bald. Lassen Sie uns Ihre E-Mail da, dann können Sie vor allen anderen Ihr erstes Anliegen einstellen und mit Anbietern in Kontakt kommen.',
    emailLabel: 'E-Mail',
    emailPlaceholder: 'sie@ihrunternehmen.de',
    nameLabel: isOperator ? 'Ihr Name oder Profilname' : 'Firmenname (optional)',
    namePlaceholder: isOperator ? 'Alex Müller' : 'Annas Friseur',
    nicheLabel: isOperator ? 'Worauf Sie spezialisiert sind (optional)' : 'Ihre Branche (optional)',
    nichePlaceholder: isOperator ? 'KI-Empfang · n8n-Workflows · für Med-Spas' : 'Friseur · Zahnarztpraxis · Klempner',
    extraLabel: isOperator ? 'Sonst noch was, das wir wissen sollten? (optional)' : 'Welches Problem wollen Sie lösen? (optional)',
    extraPlaceholder: isOperator ? 'Tools, Nischen, wie lange Sie schon dabei sind.' : 'Mir entgehen ständig Anrufe, während ich am Kunden bin. Die kommen dann nicht zurück.',
    saving: 'Wird gespeichert…',
    submit: 'Frühzugang sichern',
    back: 'Zurück',
    marketingLabel: 'Ich möchte gelegentlich Updates zu HumansRunIt und KI-Workflows für KMU bekommen (optional).',
    legalPart1: 'Mit dem Absenden willigen Sie ein, dass wir Ihre E-Mail speichern, um Sie zum Start zu benachrichtigen. Mehr in unserer ',
    legalPrivacyLabel: 'Datenschutzerklärung',
    legalPrivacyHref: '/de/privacy',
    legalPart2: '.',
    requiredStar: '*',
  } : {
    invalidEmail: 'Please enter a valid email.',
    onListKicker: "You're on the list",
    thanks: 'Thanks.',
    inTouch: "We'll be in touch.",
    operatorDone: "When we open the directory you'll be one of the first humans to claim a profile. We'll email you the moment listings go live.",
    companyDone: "When the directory opens you'll get first pick of vetted operators. We'll email you the moment we launch.",
    backHome: 'Back to home',
    browse: 'Browse the preview',
    operatorKicker: 'For operators',
    companyKicker: 'For companies',
    earlyTitle1: "You're early.",
    earlyTitle2: 'Get on the list.',
    operatorLead: "We're opening operator profiles soon. Drop your email — we'll let you in early so you can claim your handle and listings before the rush.",
    companyLead: "We're opening company listings soon. Drop your email — we'll let you in early so you can post your first problem and connect with operators before the rush.",
    emailLabel: 'Email',
    emailPlaceholder: 'you@yourbusiness.com',
    nameLabel: isOperator ? 'Your name or handle' : 'Business name (optional)',
    namePlaceholder: isOperator ? 'Alex Chen' : "Anna's Salon",
    nicheLabel: isOperator ? 'What you specialize in (optional)' : 'Your industry (optional)',
    nichePlaceholder: isOperator ? 'AI receptionist · n8n workflows · for med spas' : 'Hair salon · Dental practice · Plumber',
    extraLabel: isOperator ? "Anything we should know? (optional)" : "What problem are you trying to solve? (optional)",
    extraPlaceholder: isOperator ? "Tools, niches, how long you've been at it." : "I keep missing calls during haircuts. Customers don't come back.",
    saving: 'Saving…',
    submit: 'Get my early access',
    back: 'Back',
    marketingLabel: "I'd like occasional updates about HumansRunIt and AI workflows for SMBs (optional).",
    legalPart1: 'By submitting you agree we may store your email to notify you when we launch. See our ',
    legalPrivacyLabel: 'Privacy Policy',
    legalPrivacyHref: '/privacy',
    legalPart2: '.',
    requiredStar: '*',
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!email || !email.includes('@')) {
      setError(T.invalidEmail);
      return;
    }
    setSubmitting(true);
    try {
      const res = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, name, niche, extra, side, lang, marketing, ts: Date.now() }),
      });
      if (!res.ok) {
        console.warn('[waitlist] backend issue — payload:', { email, name, niche, extra, side, lang, marketing });
      }
    } catch (err) {
      console.warn('[waitlist] no backend — payload:', { email, name, niche, extra, side, lang, marketing });
    }
    setSubmitting(false);
    setDone(true);
  };

  if (done) {
    return (
      <section className="section">
        <div className="container" style={{ maxWidth: 640 }}>
          <Kicker>{T.onListKicker}</Kicker>
          <h1 className="display" style={{ marginTop: 16, fontSize: 56, lineHeight: 1.05 }}>
            {T.thanks} <span className="display-serif" style={{ color: 'var(--accent-2)' }}>{T.inTouch}</span>
          </h1>
          <p style={{ fontSize: 18, color: 'var(--ink-2)', marginTop: 24, lineHeight: 1.5 }}>
            {isOperator ? T.operatorDone : T.companyDone}
          </p>
          <div style={{ marginTop: 40, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <button className="btn btn-primary btn-lg" onClick={() => go('home')}>{T.backHome} <Icon.arrow /></button>
            <button className="btn btn-lg" onClick={() => go('browse')}>{T.browse}</button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="section">
      <div className="container" style={{ maxWidth: 720 }}>
        <Kicker num={isOperator ? '01' : '02'}>{isOperator ? T.operatorKicker : T.companyKicker}</Kicker>
        <h1 className="display" style={{ marginTop: 16, fontSize: 64, lineHeight: 1.04, maxWidth: 720 }}>
          {T.earlyTitle1} <br /><span className="display-serif" style={{ color: 'var(--accent-2)' }}>{T.earlyTitle2}</span>
        </h1>
        <p style={{ fontSize: 19, color: 'var(--ink-2)', marginTop: 28, lineHeight: 1.5, maxWidth: 600 }}>
          {isOperator ? T.operatorLead : T.companyLead}
        </p>

        <form onSubmit={onSubmit} style={{ marginTop: 48, display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 540 }}>
          <Field label={T.emailLabel} required requiredStar={T.requiredStar}>
            <input
              className="input"
              type="email"
              placeholder={T.emailPlaceholder}
              value={email}
              onChange={e => setEmail(e.target.value)}
              required
            />
          </Field>

          <Field label={T.nameLabel}>
            <input
              className="input"
              type="text"
              placeholder={T.namePlaceholder}
              value={name}
              onChange={e => setName(e.target.value)}
            />
          </Field>

          <Field label={T.nicheLabel}>
            <input
              className="input"
              type="text"
              placeholder={T.nichePlaceholder}
              value={niche}
              onChange={e => setNiche(e.target.value)}
            />
          </Field>

          <Field label={T.extraLabel}>
            <textarea
              className="input"
              rows={3}
              placeholder={T.extraPlaceholder}
              value={extra}
              onChange={e => setExtra(e.target.value)}
              style={{ resize: 'vertical', minHeight: 84, fontFamily: 'inherit' }}
            />
          </Field>

          {error && (
            <div style={{ color: '#c63b3b', fontSize: 14 }}>{error}</div>
          )}

          <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.5, marginTop: 4, cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={marketing}
              onChange={e => setMarketing(e.target.checked)}
              style={{ marginTop: 3, flexShrink: 0, width: 16, height: 16, accentColor: '#10b981' }}
            />
            <span>{T.marketingLabel}</span>
          </label>

          <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap', marginTop: 8 }}>
            <button className="btn btn-primary btn-lg" type="submit" disabled={submitting}>
              {submitting ? T.saving : T.submit} <Icon.arrow />
            </button>
            <button type="button" className="btn btn-ghost btn-sm" onClick={() => go('home')}>
              {T.back}
            </button>
          </div>

          <p style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 8, lineHeight: 1.5 }}>
            {T.legalPart1}
            <a href={T.legalPrivacyHref} style={{ color: 'var(--accent-2)', textDecoration: 'underline' }}>
              {T.legalPrivacyLabel}
            </a>
            {T.legalPart2}
          </p>
        </form>
      </div>
    </section>
  );
}

function Field({ label, required, requiredStar, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span className="kicker">
        {label} {required && <span style={{ color: 'var(--accent-2)' }}>{requiredStar || '*'}</span>}
      </span>
      {children}
    </label>
  );
}

Object.assign(window, { WaitlistPage });
