// pages-start.jsx — Trial onboarding: email + topic → 1,200-token article delivery
// Route: #/start  |  API: /api/trial/signup  /api/trial/status/{id}
'use strict';

const TICKER_ITEMS = [
  'Researching the topic...',
  'Drafting structure...',
  'Adding citations...',
  'Polishing prose...',
  'Sending to your inbox...',
];

function StartPage() {
  const { t, lang } = useT ? useT() : { t: (k) => k, lang: 'en' };

  // Screen state machine
  const [screen, setScreen] = React.useState('form'); // 'form' | 'pending' | 'done'

  // Form fields
  const [email, setEmail] = React.useState('');
  const [topic, setTopic] = React.useState('');
  const [consent, setConsent] = React.useState(false);

  // UI state
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [tickerIndex, setTickerIndex] = React.useState(0);
  const [inboxNote, setInboxNote] = React.useState(false);
  const [revealed, setRevealed] = React.useState(false);
  const [copied, setCopied] = React.useState(false);

  // Trial data returned from backend
  const [trialData, setTrialData] = React.useState(null);

  // Refs (don't trigger re-renders)
  const fingerprintRef = React.useRef('');
  const refCodeRef = React.useRef('');

  // Compute fingerprint + read ?ref= on mount
  React.useEffect(() => {
    try {
      const fp = btoa(
        [
          navigator.userAgent,
          navigator.language,
          window.screen.width + 'x' + window.screen.height,
          Intl.DateTimeFormat().resolvedOptions().timeZone,
        ].join('|')
      ).slice(0, 64);
      fingerprintRef.current = fp;
    } catch (_) {
      fingerprintRef.current = 'anon-' + Math.random().toString(36).slice(2);
    }
    const params = new URLSearchParams(window.location.search);
    refCodeRef.current = params.get('ref') || '';
  }, []);

  // Pending screen: ticker + poll + 30s inbox note
  React.useEffect(() => {
    if (screen !== 'pending') return;

    const tickTimer = setInterval(() => {
      setTickerIndex((i) => (i + 1) % TICKER_ITEMS.length);
    }, 800);

    const pollTimer = trialData?.trial_id
      ? setInterval(async () => {
          try {
            const res = await fetch(
              window.location.origin + '/api/trial/status/' + trialData.trial_id
            );
            if (res.ok) {
              const data = await res.json();
              if (data.article_status === 'done') {
                setScreen('done');
              }
            }
          } catch (_) {}
        }, 5000)
      : null;

    const noteTimer = setTimeout(() => setInboxNote(true), 30000);

    return () => {
      clearInterval(tickTimer);
      if (pollTimer) clearInterval(pollTimer);
      clearTimeout(noteTimer);
    };
  }, [screen, trialData]);

  // Submit handler
  async function handleSubmit(e) {
    e.preventDefault();
    if (!consent) {
      setError('Please check the consent box to continue.');
      return;
    }
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch(window.location.origin + '/api/trial/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email,
          topic,
          fingerprint: fingerprintRef.current,
          consent: true,
          ref: refCodeRef.current || null,
        }),
      });
      if (res.ok) {
        const data = await res.json();
        setTrialData(data);
        setScreen('pending');
      } else if (res.status === 409) {
        setError('This email or device has already used the trial.');
      } else {
        setError('Something went wrong. Please try again.');
      }
    } catch (_) {
      setError('Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  }

  function copyKey() {
    const key = trialData?.api_key || '';
    if (!key) return;
    navigator.clipboard.writeText(key).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  function maskEmail(addr) {
    if (!addr || !addr.includes('@')) return addr || '';
    const [name, domain] = addr.split('@');
    return (name.slice(0, 2) || name) + '••••@' + domain;
  }

  // ─── Shared styles ───────────────────────────────────────────────
  const wrap = {
    background: 'var(--paper)',
    color: 'var(--ink)',
    minHeight: '100vh',
    fontFamily: 'var(--sans)',
  };

  const inputBase = {
    width: '100%',
    padding: '14px 16px',
    border: '2px solid var(--ink)',
    borderRadius: '6px',
    fontSize: '16px',
    fontFamily: 'var(--sans)',
    background: 'var(--paper)',
    color: 'var(--ink)',
    boxSizing: 'border-box',
    outline: 'none',
    display: 'block',
  };

  const primaryBtn = {
    width: '100%',
    padding: '16px',
    background: 'var(--ink)',
    color: 'var(--accent)',
    border: '2px solid var(--ink)',
    borderRadius: '6px',
    fontSize: '16px',
    fontWeight: '700',
    cursor: 'pointer',
    letterSpacing: '0.5px',
    transition: 'opacity 0.15s',
  };

  // ─── SCREEN 1: form ──────────────────────────────────────────────
  if (screen === 'form') {
    return (
      <div style={wrap}>
        <div style={{ maxWidth: 480, margin: '0 auto', padding: '80px 24px 48px' }}>
          <div style={{
            display: 'inline-block',
            background: 'var(--accent)',
            border: '2px solid var(--ink)',
            padding: '4px 12px',
            fontSize: '12px',
            fontWeight: '700',
            letterSpacing: '1px',
            marginBottom: '20px',
            fontFamily: 'var(--mono)',
          }}>
            FREE · 5 MIN
          </div>
          <h1 className="serif" style={{
            fontSize: 'clamp(36px, 5vw, 64px)',
            lineHeight: '0.95',
            margin: '0 0 16px',
          }}>
            Get a cited article in your inbox
          </h1>
          <p style={{ color: 'var(--ink-2)', fontSize: '17px', lineHeight: '1.5', margin: '0 0 32px' }}>
            1,200 tokens. No card. Article in 5 minutes.
          </p>

          <form onSubmit={handleSubmit}>
            <input
              type="email"
              required
              placeholder="you@company.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              style={{ ...inputBase, marginBottom: '12px' }}
            />

            <div style={{ position: 'relative', marginBottom: '4px' }}>
              <textarea
                placeholder="Best CRM for solo founders"
                maxLength={200}
                rows={3}
                value={topic}
                onChange={(e) => setTopic(e.target.value)}
                style={{ ...inputBase, resize: 'vertical' }}
              />
            </div>
            <div style={{ textAlign: 'right', fontSize: '12px', color: 'var(--ink-3)', marginBottom: '20px' }}>
              {topic.length}/200
            </div>

            <label style={{ display: 'flex', alignItems: 'flex-start', gap: '10px', marginBottom: '24px', cursor: 'pointer', fontSize: '14px', lineHeight: '1.4', color: 'var(--ink-2)' }}>
              <input
                type="checkbox"
                required
                checked={consent}
                onChange={(e) => setConsent(e.target.checked)}
                style={{ marginTop: '2px', flexShrink: 0 }}
              />
              <span>I agree to receive my article and occasional updates from ruuapi</span>
            </label>

            {error && (
              <div style={{ color: '#c00', fontSize: '13px', marginBottom: '12px', lineHeight: '1.4' }}>
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={submitting}
              style={{ ...primaryBtn, opacity: submitting ? 0.65 : 1 }}
            >
              {submitting ? '...' : 'GENERATE MY ARTICLE →'}
            </button>
          </form>

          {/* TODO: Phase 4 — Turnstile invisible widget
          <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
          <div class="cf-turnstile" data-sitekey={window.TURNSTILE_SITE_KEY} data-callback="onTurnstileSuccess"></div>
          */}
        </div>
      </div>
    );
  }

  // ─── SCREEN 2: pending / generating ─────────────────────────────
  if (screen === 'pending') {
    return (
      <div style={wrap}>
        <div style={{ textAlign: 'center', padding: '120px 24px 48px', maxWidth: 560, margin: '0 auto' }}>
          <div style={{
            width: 64,
            height: 64,
            borderRadius: '50%',
            background: 'var(--accent)',
            border: '2px solid var(--ink)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto 24px',
            fontSize: 28,
          }}>
            ✓
          </div>
          <h2 className="serif" style={{ fontSize: 'clamp(28px, 4vw, 40px)', margin: '0 0 16px' }}>
            We're generating your article
          </h2>
          <p style={{ color: 'var(--ink-2)', fontFamily: 'var(--mono)', fontSize: '15px', minHeight: '1.4em', transition: 'opacity 0.3s' }}>
            {TICKER_ITEMS[tickerIndex]}
          </p>
          {inboxNote && (
            <p style={{ fontSize: '13px', color: 'var(--ink-3)', marginTop: '32px' }}>
              Check your inbox — we'll email you when ready!
            </p>
          )}
        </div>
      </div>
    );
  }

  // ─── SCREEN 3: done / success ────────────────────────────────────
  return (
    <div style={wrap}>
      <div style={{ maxWidth: 480, margin: '0 auto', padding: '80px 24px 48px', textAlign: 'center' }}>
        <div style={{ fontSize: '48px', marginBottom: '16px' }}>🎉</div>
        <h2 className="serif" style={{ fontSize: 'clamp(28px, 4vw, 40px)', margin: '0 0 8px' }}>
          Article delivered to {maskEmail(email)}
        </h2>

        <div style={{
          border: '2px solid var(--ink)',
          borderRadius: '8px',
          padding: '24px',
          background: 'var(--paper-2, #ebe8df)',
          margin: '28px 0',
          textAlign: 'left',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '10px', fontSize: '14px' }}>
            <span style={{ color: 'var(--ink-2)' }}>Topic</span>
            <span style={{ fontWeight: '600', maxWidth: '60%', textAlign: 'right' }}>{topic}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px', fontSize: '14px' }}>
            <span style={{ color: 'var(--ink-2)' }}>Delivery</span>
            <span style={{ fontWeight: '600' }}>~5 minutes</span>
          </div>

          <div style={{ borderTop: '1px dashed var(--ink-3)', paddingTop: '20px' }}>
            <div style={{ fontSize: '11px', textTransform: 'uppercase', letterSpacing: '1px', color: 'var(--ink-3)', marginBottom: '10px' }}>
              Your API Key
            </div>
            <div style={{ display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' }}>
              <code style={{
                flex: '1 1 160px',
                background: 'var(--ink)',
                color: 'var(--accent)',
                fontFamily: 'var(--mono)',
                fontSize: '13px',
                padding: '10px 12px',
                borderRadius: '4px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}>
                {revealed ? (trialData?.api_key || 'bw_live_...') : 'bw_live_••••••••••••••••'}
              </code>
              <button
                onClick={() => setRevealed((v) => !v)}
                style={{ padding: '8px 12px', border: '1px solid var(--ink)', borderRadius: '4px', background: 'none', cursor: 'pointer', fontSize: '12px', whiteSpace: 'nowrap' }}
              >
                {revealed ? 'Hide' : 'Reveal'}
              </button>
              <button
                onClick={copyKey}
                style={{ padding: '8px 12px', border: '1px solid var(--ink)', borderRadius: '4px', background: 'var(--ink)', color: 'var(--accent)', cursor: 'pointer', fontSize: '12px', fontWeight: '700', whiteSpace: 'nowrap' }}
              >
                {copied ? 'Copied!' : 'Copy'}
              </button>
            </div>
          </div>
        </div>

        <p style={{ fontSize: '13px', color: 'var(--ink-3)', margin: '0 0 24px' }}>
          Check spam if you don't see it. Sender: <strong>info@ndr.ist</strong>
        </p>

        <button
          onClick={() => { window.location.hash = '#/login'; }}
          style={{ ...primaryBtn, marginBottom: '40px' }}
        >
          Register for full account →
        </button>

        <div style={{ textAlign: 'left' }}>
          <h3 style={{ fontSize: '12px', textTransform: 'uppercase', letterSpacing: '1px', color: 'var(--ink-3)', marginBottom: '12px', fontWeight: '700' }}>
            What you can do now
          </h3>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, fontSize: '14px', color: 'var(--ink-2)', lineHeight: '2' }}>
            <li>→ Use the API key — read the docs at <a href="https://ruuapi.com/#/docs" style={{ color: 'var(--ink)', fontWeight: '600' }}>ruuapi.com/docs</a></li>
            <li>→ Run <strong>/audit</strong> — analyze any page for AI visibility</li>
            <li>→ Check <strong>/citation</strong> — track where AI cites you</li>
            <li>→ Share your <strong>/report</strong> — show stakeholders your AI presence</li>
          </ul>
        </div>
      </div>
    </div>
  );
}

window.StartPage = StartPage;
