// ForkWelcome — single-screen modal shown when /api/invite/redeem
// detects a new device on an existing invite.
//
// Decides what happens after the visitor types their email by routing
// the call to /api/invite/identify (server-side decides the tier).
// Four terminal states drive the UI:
//
//   ok / owner_resumed  → full reload, bootstrap picks up the session
//   suggest_typo        → inline "Did you mean…?" prompt
//   magic_link_sent     → "Check your inbox" with resend button
//   pending_approval    → cross-firm request queued for admin approval
//   error               → inline error, retry
//
// The screen is rendered in place of the room via app.jsx bootstrap
// (no router; just conditional render).

function ForkWelcome({ tweaks, ownerName, ownerFirm }) {
  // Pre-fill email from localStorage if the visitor was previously
  // seen on a different device. Reduces friction without leaking
  // identity — only the cache on THIS browser is read.
  const cachedEmail = React.useMemo(() => {
    try { return localStorage.getItem('arbcap_last_email') || ''; }
    catch { return ''; }
  }, []);

  const [email, setEmail]     = React.useState(cachedEmail);
  const [name, setName]       = React.useState('');
  const [state, setState]     = React.useState('form'); // form | submitting | suggest_typo | magic_link_sent | error
  const [error, setError]     = React.useState(null);
  const [suggested, setSuggested] = React.useState(null);
  const [sentTo, setSentTo]   = React.useState(null);
  const [resendCount, setResendCount] = React.useState(0);

  const looksLikeEmail = (v) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.trim());
  const valid = looksLikeEmail(email);

  const submit = async ({ emailOverride, skipTypoCheck } = {}) => {
    const targetEmail = (emailOverride || email).trim();
    if (!looksLikeEmail(targetEmail)) {
      setError('Please enter a valid email address.');
      return;
    }
    setState('submitting');
    setError(null);
    try {
      const r = await fetch('/api/invite/identify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          email: targetEmail,
          name: name.trim() || null,
          skip_typo_check: !!skipTypoCheck,
        }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok) {
        setError(data.status || `HTTP ${r.status}`);
        setState('form');
        return;
      }
      if (data.status === 'ok' || data.status === 'owner_resumed') {
        try { localStorage.setItem('arbcap_last_email', targetEmail); } catch {}
        // Server set the session cookie. Reload bootstraps with the
        // new session and lands the visitor in the room.
        window.location.href = '/';
        return;
      }
      if (data.status === 'suggest_typo') {
        setSuggested(data.suggested_email);
        setState('suggest_typo');
        return;
      }
      if (data.status === 'magic_link_sent') {
        setSentTo(data.email || targetEmail);
        setState('magic_link_sent');
        return;
      }
      if (data.status === 'pending_approval') {
        setSentTo(data.email || targetEmail);
        setState('pending_approval');
        return;
      }
      setError(data.status || 'unknown_response');
      setState('form');
    } catch (e) {
      setError(e.message || 'network_error');
      setState('form');
    }
  };

  const acceptSuggestion = () => {
    setEmail(suggested);
    submit({ emailOverride: suggested, skipTypoCheck: false });
  };
  const rejectSuggestion = () => {
    submit({ skipTypoCheck: true });
  };
  const resend = () => {
    setResendCount(c => c + 1);
    submit({ skipTypoCheck: true });
  };

  // ── Brand frame (mirrors onboarding.jsx layout) ────────────────
  return (
    <div className="onboarding-root" style={{ display: 'flex', minHeight: '100vh', background: 'var(--bg)' }}>
      <div className="onboarding-brand-panel" style={{
        flex: '0 0 42%',
        background: '#0D0D0D',
        color: '#F5F5F0',
        padding: '48px 56px',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        position: 'relative',
      }}>
        <div>
          {typeof ArbWordmark === 'function' ? <ArbWordmark size={11} variant={tweaks?.logoVariant} /> : null}
        </div>
        <div>
          <div style={{ fontSize: 38, lineHeight: 1.1, letterSpacing: '-0.02em', fontWeight: 300 }}>
            Welcome.
          </div>
          <div style={{ fontSize: 15, color: 'rgba(245,245,240,0.7)', marginTop: 14, maxWidth: 380, lineHeight: 1.5 }}>
            {ownerName
              ? <>{ownerName}{ownerFirm ? ` (${ownerFirm})` : ''} shared the Arb Capital data room with you.</>
              : <>Someone shared the Arb Capital data room with you.</>}
          </div>
        </div>
        <div />
        <span style={{ position: 'absolute', top: 16, right: 16, width: 12, height: 12, borderTop: '1px solid rgba(212,175,55,0.4)', borderRight: '1px solid rgba(212,175,55,0.4)' }} />
        <span style={{ position: 'absolute', bottom: 16, left: 16, width: 12, height: 12, borderBottom: '1px solid rgba(212,175,55,0.4)', borderLeft: '1px solid rgba(212,175,55,0.4)' }} />
      </div>

      <div className="onboarding-form-panel" style={{
        flex: 1, padding: '48px 56px', display: 'flex', flexDirection: 'column',
        justifyContent: 'center', maxWidth: 560,
      }}>
        {/* Keep the inbox screen mounted during a resend-triggered
            re-submit (sentTo is the marker that we've already passed
            magic_link_sent at least once). Otherwise the form
            briefly flashes back to the email-entry screen between
            the click and the response, which reads as if the link
            never went out — exactly the wrong signal at the moment
            the user is anxious about delivery. */}
        {state === 'pending_approval' ? (
          <ForkPendingApproval requesterEmail={sentTo} ownerName={ownerName} />
        ) : state === 'magic_link_sent' || (state === 'submitting' && sentTo) ? (
          <ForkSentInbox
            sentTo={sentTo}
            resendCount={resendCount}
            onResend={resend}
            resending={state === 'submitting'}
          />
        ) : state === 'suggest_typo' ? (
          <ForkTypoPrompt
            typed={email}
            suggested={suggested}
            onAccept={acceptSuggestion}
            onReject={rejectSuggestion}
          />
        ) : (
          <ForkForm
            email={email} setEmail={setEmail}
            name={name} setName={setName}
            valid={valid}
            submitting={state === 'submitting'}
            error={error}
            onSubmit={() => submit()}
          />
        )}
      </div>
    </div>
  );
}

function ForkForm({ email, setEmail, name, setName, valid, submitting, error, onSubmit }) {
  const submitOnEnter = (e) => { if (e.key === 'Enter' && valid && !submitting) onSubmit(); };
  return (
    <>
      <h1 style={{ fontSize: 34, fontWeight: 400, letterSpacing: '-0.025em', margin: '0 0 8px' }}>
        Continue to the data room
      </h1>
      <p style={{ fontSize: 14, color: 'var(--text-secondary)', maxWidth: 460, lineHeight: 1.55, margin: '0 0 28px' }}>
        Just need your email to route the right materials to you. Every page is watermarked with this email.
      </p>

      <label style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Email</label>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        onKeyDown={submitOnEnter}
        placeholder="you@firm.com"
        autoFocus
        autoComplete="email"
        style={{ marginTop: 6, marginBottom: 18, fontSize: 16 }}
        className="onboarding-input"
      />

      <label style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Name <span style={{ color: 'var(--text-tertiary)', textTransform: 'none', letterSpacing: 0 }}>(optional)</span></label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        onKeyDown={submitOnEnter}
        placeholder="Your name"
        autoComplete="name"
        style={{ marginTop: 6, marginBottom: 24, fontSize: 16 }}
        className="onboarding-input"
      />

      {error && (
        <div style={{ padding: '10px 12px', marginBottom: 16, border: '1px solid var(--error)', color: 'var(--error)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.04em' }}>
          {error === 'no_pending_fork'      ? 'Your welcome link expired. Open the invite link again.'
           : error === 'pending_expired'    ? 'Your welcome link expired. Open the invite link again.'
           : error === 'already_identified' ? 'This invite was already claimed. Open the original invite link.'
           : error === 'invalid_email'      ? 'That doesn\'t look like a valid email address.'
           : error === 'rate_limited'       ? 'Too many attempts. Please wait a few minutes and try again.'
           : error}
        </div>
      )}

      <button
        disabled={!valid || submitting}
        onClick={onSubmit}
        className="btn btn-primary"
        style={{ width: '100%', padding: '14px 0', fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase' }}
      >
        {submitting ? 'CHECKING…' : 'ENTER THE ROOM →'}
      </button>

      <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 18, lineHeight: 1.5 }}>
        If your firm is already in the room, you're in right away. If you're joining from a different organisation, your request is reviewed by our team and we'll email you a sign-in link once it's approved.
      </div>
    </>
  );
}

// Cross-firm request queued for admin approval. No access yet — the
// requester waits for the approval email (sent by api/admin/share-request.js
// once JB approves). Mirrors the mockup signed off with JB (2026-07-02).
function ForkPendingApproval({ requesterEmail, ownerName }) {
  return (
    <>
      <div className="mono" style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        fontSize: 10, color: 'var(--gold-dark)', letterSpacing: '0.14em',
        textTransform: 'uppercase', border: '1px solid var(--gold)',
        padding: '6px 12px', marginBottom: 20,
      }}>
        <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--gold)', display: 'inline-block' }} />
        Awaiting approval
      </div>
      <h1 style={{ fontSize: 28, fontWeight: 400, letterSpacing: '-0.025em', margin: '0 0 16px' }}>
        Request submitted
      </h1>
      <p style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.6, margin: '0 0 14px' }}>
        Thanks. Your request to access the Arb Capital data room has been sent to the team and will be processed shortly.
      </p>
      <p style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.6, margin: '0 0 14px' }}>
        {ownerName ? `${ownerName} shared this room with you. ` : 'This room was shared with you. '}
        Because you're joining from a different organisation, a team member reviews the request before access is granted.
      </p>
      <p style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.6, margin: '0 0 20px' }}>
        Once approved, we'll email a secure sign-in link to{' '}
        <span className="mono" style={{ color: 'var(--text)' }}>{requesterEmail}</span>. You can close this tab in the meantime.
      </p>
      <div style={{ fontSize: 12, color: 'var(--text-tertiary)', borderTop: '1px solid var(--border)', paddingTop: 16, lineHeight: 1.5 }}>
        No access is granted until approval. The sign-in link is single-use and expires 30 minutes after it's sent.
      </div>
    </>
  );
}

function ForkTypoPrompt({ typed, suggested, onAccept, onReject }) {
  return (
    <>
      <div className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.14em', marginBottom: 12 }}>
        CHECK
      </div>
      <h1 style={{ fontSize: 28, fontWeight: 400, letterSpacing: '-0.025em', margin: '0 0 8px' }}>
        Did you mean…?
      </h1>
      <p style={{ fontSize: 14, color: 'var(--text-secondary)', margin: '0 0 24px' }}>
        You entered <span className="mono">{typed}</span>. We noticed it's one character away from a domain we recognise.
      </p>

      <div style={{ padding: 16, border: '1px solid var(--gold)', background: 'rgba(212,175,55,0.06)', marginBottom: 24 }}>
        <div className="mono" style={{ fontSize: 14, color: 'var(--text)' }}>{suggested}</div>
      </div>

      <button onClick={onAccept}
        className="btn btn-primary"
        style={{ width: '100%', padding: '12px 0', marginBottom: 10, fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
        YES, USE THAT →
      </button>
      <button onClick={onReject}
        className="btn btn-ghost"
        style={{ width: '100%', padding: '10px 0', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
        No, what I typed is correct
      </button>
    </>
  );
}

function ForkSentInbox({ sentTo, resendCount, onResend, resending }) {
  const [canResend, setCanResend] = React.useState(false);
  React.useEffect(() => {
    setCanResend(false);
    const t = setTimeout(() => setCanResend(true), 15000); // 15s
    return () => clearTimeout(t);
  }, [resendCount]);
  // Disable the button while the resend request is in flight too,
  // so a panicked double-tap on a phone doesn't fire two POSTs.
  const buttonDisabled = !canResend || resending;
  const buttonLabel = resending
    ? 'Sending…'
    : canResend ? "Didn't get it? Resend" : 'Resend in 15s…';

  return (
    <>
      <div className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.14em', marginBottom: 12 }}>
        CHECK YOUR INBOX
      </div>
      <h1 style={{ fontSize: 28, fontWeight: 400, letterSpacing: '-0.025em', margin: '0 0 16px' }}>
        Sign-in link sent
      </h1>
      <p style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.6, margin: '0 0 24px' }}>
        We've sent a one-click sign-in link to <span className="mono" style={{ color: 'var(--text)' }}>{sentTo}</span>. Open it on this device to enter the data room.
      </p>
      <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 18, lineHeight: 1.5 }}>
        Valid for 30 minutes. Once you use it, you'll stay signed in on this device.
      </div>
      <button
        disabled={buttonDisabled}
        onClick={onResend}
        className="btn btn-ghost"
        style={{ padding: '10px 16px', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
        {buttonLabel}
      </button>
      {resendCount > 0 && (
        <div className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', marginTop: 10 }}>
          Resent {resendCount} time{resendCount === 1 ? '' : 's'}.
        </div>
      )}
    </>
  );
}
