// Onboarding flow — email + 3 questions

const Q_LIBRARY = {
  // Default Q copy — overridable via Tweaks
  defaults: {
    q1Title: "What best describes you?",
    q1Sub: "We tailor what you see in the room to your investor profile.",
    q2Title: "Anticipated allocation size?",
    q2Sub: "Used for routing — no commitment.",
    q3Title: "When do you expect to make a decision?",
    q3Sub: "Helps us schedule deeper diligence sessions.",
    cta: "Enter the room",
  },
};

function Onboarding({ tweaks, identity, onComplete, dark, identityKnown }) {
  // identityKnown: server has already confirmed identity (cookie set).
  // Step 1 is the "confirm your details" form for identityKnown visitors,
  // OR the magic-link sign-in form for unauth visitors. Either way, step 1
  // is the *first* interactive surface — we just route to different bodies.
  // When NOT identityKnown, skip the cover and land directly on sign-in.
  const [step, setStep] = React.useState(identityKnown ? 0 : 1);
  const [email, setEmail] = React.useState(identity?.email || "");
  const [name, setName]   = React.useState(identity?.name  || "");
  const [firm, setFirm]   = React.useState(identity?.firm  || "");
  const [a1, setA1] = React.useState(null);
  const [a2, setA2] = React.useState(null);
  const [a3, setA3] = React.useState(null);

  const total = 5;

  const next = () => setStep(s => Math.min(s + 1, total));
  const back = () => setStep(s => Math.max(s - 1, identityKnown ? 0 : 1));

  const finish = () => {
    onComplete({ email, name, firm, a1, a2, a3 });
  };

  const opts1 = ["Family Office", "VC", "Angel"];
  const opts2 = ["< $100K", "$100K – $500K", "$500K – $2M", "$2M+"];
  const opts3 = ["This quarter", "3–6 months", "6–12 months", "Just exploring"];

  // Step 0: cover, Step 1: email, Step 2-4: questions, Step 5: review
  return (
    <div className="onboarding-root" style={{ display: 'flex', minHeight: '100vh', background: 'var(--bg)' }}>
      {/* Left: brand panel */}
      <div className="onboarding-brand-panel" style={{
        flex: '0 0 42%',
        background: dark ? '#0A0A0A' : '#0D0D0D',
        color: '#F5F5F0',
        padding: '48px 56px',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        position: 'relative',
      }}>
        <div>
          <ArbWordmark size={11} variant={tweaks.logoVariant} />
        </div>
        <div>
          <div style={{ fontSize: 44, lineHeight: 1.05, letterSpacing: '-0.03em', fontWeight: 300 }}>
            Safe yields.<br/>
            <span style={{ color: '#D4AF37' }}>Real alpha.</span>
          </div>
        </div>
        <div />
        {/* Corner brackets on dark panel */}
        <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>

      {/* Right: flow */}
      <div className="onboarding-form-panel" style={{ flex: 1, padding: '48px 56px', display: 'flex', flexDirection: 'column' }}>
        {/* Top bar — hide step counter on the sign-in step for unauth visitors */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 48 }}>
          <SectionNum n={step} label={
            step === 0 ? "WELCOME" :
            step === 1 ? (identityKnown ? "CONFIRM_DETAILS" : "SIGN_IN") :
            step === 2 ? "INVESTOR_PROFILE" :
            step === 3 ? "ALLOCATION_INTENT" :
            step === 4 ? "TIMELINE" :
            "CONFIRM"
          } />
          {(identityKnown || step !== 1) && <ProgressDots count={total + 1} active={step} />}
        </div>

        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', maxWidth: 540 }}>
          {step === 0 && <CoverStep onNext={next} identityKnown={identityKnown} identity={identity} />}
          {step === 1 && (
            identityKnown
              ? <ConfirmIdentityStep name={name} setName={setName} firm={firm} setFirm={setFirm} email={email} onNext={next} />
              : <EmailStep email={email} setEmail={setEmail} />
          )}
          {step === 2 && (
            <QuestionStep
              key="q1"
              title={tweaks.q1Title} sub={tweaks.q1Sub}
              options={opts1} value={a1} setValue={setA1}
              onNext={next}
            />
          )}
          {step === 3 && (
            <QuestionStep
              key="q2"
              title={tweaks.q2Title} sub={tweaks.q2Sub}
              options={opts2} value={a2} setValue={setA2}
              onNext={next}
            />
          )}
          {step === 4 && (
            <QuestionStep
              key="q3"
              title={tweaks.q3Title} sub={tweaks.q3Sub}
              options={opts3} value={a3} setValue={setA3}
              onNext={next}
            />
          )}
          {step === 5 && (
            <ReviewStep
              email={email} name={name} firm={firm}
              a1={a1} a2={a2} a3={a3}
              cta={tweaks.cta}
              onSubmit={finish}
            />
          )}
        </div>

        {/* Footer — hide step counter and back button on the sign-in step (no flow yet) */}
        {(identityKnown || step !== 1) && (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 32, paddingTop: 20, borderTop: '1px solid var(--border)' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-tertiary)', letterSpacing: '0.12em' }}>
              STEP {String(step + 1).padStart(2,'0')} / {String(total + 1).padStart(2,'0')}
            </div>
            {step > (identityKnown ? 0 : 1) && (
              <button className="btn btn-ghost btn-sm" onClick={back}>← Back</button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function Stat({ value, label, dark }) {
  return (
    <div>
      <div style={{ fontSize: 22, letterSpacing: '-0.02em', color: dark ? '#F5F5F0' : 'inherit' }}>{value}</div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.12em', color: dark ? 'rgba(245,245,240,0.5)' : 'var(--text-tertiary)', marginTop: 4 }}>{label}</div>
    </div>
  );
}

function ProgressDots({ count, active }) {
  return (
    <div style={{ display: 'flex', gap: 4 }}>
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} style={{
          width: i === active ? 18 : 4,
          height: 2,
          background: i <= active ? 'var(--text-primary)' : 'var(--border)',
          transition: 'width 200ms',
        }} />
      ))}
    </div>
  );
}

function CoverStep({ onNext, identityKnown, identity }) {
  const firmTag = identity?.firm ? identity.firm.toUpperCase() : 'PRE_BOUND';
  return (
    <div className="fade-in">
      <div className="section-num" style={{ marginBottom: 24 }}>
        <span>[ INVITED ]</span>
        {identityKnown && <><span className="div" /><span>{firmTag}</span></>}
      </div>
      <h1 style={{ fontSize: 40, lineHeight: 1.1, letterSpacing: '-0.03em', fontWeight: 400, margin: 0, marginBottom: 20 }}>
        Welcome to the Arb Capital data room.
      </h1>
      <p style={{ fontSize: 16, lineHeight: 1.7, color: 'var(--text-secondary)', marginBottom: 24, maxWidth: 460 }}>
        {identityKnown && identity?.email
          ? <>This invite is bound to <span className="mono" style={{ color: 'var(--text-primary)' }}>{identity.email}</span>. A few quick details and you're in.</>
          : <>You've been invited to review confidential materials for our Series Seed round. A few quick details and you're in.</>}
      </p>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <button className="btn btn-filled btn-lg" onClick={onNext}>
          {identityKnown ? 'Continue →' : 'Begin →'}
        </button>
      </div>
      <div style={{ marginTop: 48, display: 'flex', gap: 24 }}>
        <Reassure label="ENCRYPTED" sub="TLS 1.3" />
        <Reassure label="WATERMARKED" sub="Per-investor" />
      </div>
    </div>
  );
}

function Reassure({ label, sub }) {
  return (
    <div>
      <div style={{ width: 8, height: 8, background: 'var(--gold)', marginBottom: 8 }} />
      <div className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', fontWeight: 700 }}>{label}</div>
      <div className="mono" style={{ fontSize: 9, letterSpacing: '0.08em', color: 'var(--text-tertiary)', marginTop: 2 }}>{sub}</div>
    </div>
  );
}

// Shown after the cover for identityKnown visitors — they confirm or correct
// the name + firm the admin guessed at invite time. Sent to /api/onboarding
// at the end (along with the 3 question answers) so the investor record is
// updated to whatever they typed.
function ConfirmIdentityStep({ name, setName, firm, setFirm, email, onNext }) {
  const canContinue = name.trim().length > 0;
  return (
    <div className="fade-in">
      <h2 style={{ fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, marginBottom: 12 }}>Confirm your details</h2>
      <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 32 }}>
        Signed in as <span className="mono" style={{ color: 'var(--text-primary)' }}>{email}</span>. Confirm your name and firm — we may have guessed wrong from the invite.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Field label="FULL_NAME" required>
          <input className="input" placeholder="Jane Catalano"
                 value={name} onChange={e => setName(e.target.value)}
                 onKeyDown={e => e.key === 'Enter' && canContinue && onNext()}
                 autoFocus />
        </Field>
        <Field label="FIRM">
          <input className="input" placeholder="Latticework Capital"
                 value={firm} onChange={e => setFirm(e.target.value)}
                 onKeyDown={e => e.key === 'Enter' && canContinue && onNext()} />
        </Field>
      </div>
      <div style={{ marginTop: 32, display: 'flex', alignItems: 'center', gap: 16 }}>
        <button className="btn btn-filled btn-lg" disabled={!canContinue}
                style={{ opacity: canContinue ? 1 : 0.4 }}
                onClick={() => canContinue && onNext()}>Continue →</button>
        <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.08em' }}>
          Every page is watermarked with your email above.
        </span>
      </div>
    </div>
  );
}

function EmailStep({ email, setEmail }) {
  // Read remembered credentials. Email pre-fills; invite token enables a
  // one-click sign-in (no email round-trip) so long as the invite is still
  // valid server-side. Both are cleared by "Use a different email".
  const lastEmail = React.useMemo(() => {
    try { return localStorage.getItem('arbcap_last_email') || ''; } catch (e) { return ''; }
  }, []);
  const cachedToken = React.useMemo(() => {
    try { return localStorage.getItem('arbcap_invite_token') || ''; } catch (e) { return ''; }
  }, []);
  const [recognized, setRecognized] = React.useState(!!lastEmail);

  React.useEffect(() => {
    if (lastEmail && !email) setEmail(lastEmail);
  // eslint-disable-next-line
  }, []);

  const [busy, setBusy] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState(null);
  const valid = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email);

  const useDifferentEmail = () => {
    setRecognized(false);
    setEmail('');
    try {
      localStorage.removeItem('arbcap_last_email');
      localStorage.removeItem('arbcap_invite_token');
    } catch (e) {}
  };

  // One-click sign-in: re-redeem the cached invite token. If the server
  // says the invite is expired/revoked, drop the cache and fall back to
  // the email-based magic-link path.
  const signInWithCache = async () => {
    if (busy) return;
    setBusy(true); setError(null);
    try {
      const r = await fetch('/api/invite/redeem', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ token: cachedToken }),
      });
      if (r.ok) {
        // Cookie is set; reload to bootstrap as authenticated.
        window.location.href = window.location.pathname;
        return;
      }
      // Token no good — clear cache and surface the email path.
      try { localStorage.removeItem('arbcap_invite_token'); } catch (e) {}
      const data = await r.json().catch(() => ({}));
      setError(data.error === 'invite_expired' ? 'invite expired'
             : data.error === 'invite_revoked' ? 'access revoked'
             : 'cached invite no longer valid');
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  };

  const sendLink = async () => {
    if (!valid || busy) return;
    setBusy(true); setError(null);
    try {
      const r = await fetch('/api/auth/request-magic-link', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      setSent(true);
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  };

  if (sent) {
    return (
      <div className="fade-in">
        <h2 style={{ fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, marginBottom: 12 }}>Check your inbox</h2>
        <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 24 }}>
          If <span className="mono" style={{ color: 'var(--text-primary)' }}>{email}</span> is on the invite list, a sign-in link is on its way. The link is valid for 30 minutes.
        </p>
        <p style={{ fontSize: 13, color: 'var(--text-tertiary)', lineHeight: 1.6 }}>
          Didn't get it after a minute? Check spam, then{' '}
          <button onClick={() => { setSent(false); useDifferentEmail(); }} style={{ background: 'none', border: 'none', padding: 0, color: 'var(--gold-dark)', textDecoration: 'underline', cursor: 'pointer', fontSize: 13 }}>try a different email</button>.
        </p>
      </div>
    );
  }

  // Returning-user variant: cached identity. Primary action is a one-click
  // sign-in using the stored invite token (no email round-trip). Email-based
  // magic link stays as a secondary fallback.
  if (recognized) {
    return (
      <div className="fade-in">
        <h2 style={{ fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, marginBottom: 12 }}>Welcome back</h2>
        <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 28 }}>
          {cachedToken
            ? <>Sign in as <span className="mono" style={{ color: 'var(--text-primary)' }}>{email}</span> on this device.</>
            : <>We'll send a fresh sign-in link to <span className="mono" style={{ color: 'var(--text-primary)' }}>{email}</span>. One click, valid 30 minutes.</>}
        </p>
        {error && (
          <div style={{ marginBottom: 16, padding: 10, border: '1px solid var(--error)', color: 'var(--error)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>
            {error}
          </div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          {cachedToken ? (
            <>
              <button className="btn btn-filled btn-lg" disabled={busy}
                      style={{ opacity: busy ? 0.4 : 1 }}
                      onClick={signInWithCache}>{busy ? 'Signing in…' : 'Sign in →'}</button>
              <button onClick={sendLink} disabled={busy}
                      style={{ background: 'none', border: 'none', padding: 0, color: 'var(--text-secondary)', textDecoration: 'underline', cursor: 'pointer', fontSize: 13 }}>
                Send a fresh email link instead
              </button>
            </>
          ) : (
            <button className="btn btn-filled btn-lg" disabled={busy}
                    style={{ opacity: busy ? 0.4 : 1 }}
                    onClick={sendLink}>{busy ? 'Sending…' : 'Send sign-in link →'}</button>
          )}
          <button onClick={useDifferentEmail}
                  style={{ background: 'none', border: 'none', padding: 0, color: 'var(--gold-dark)', textDecoration: 'underline', cursor: 'pointer', fontSize: 13 }}>
            Use a different email
          </button>
        </div>
      </div>
    );
  }

  // First-time visitor variant: explicit form.
  return (
    <div className="fade-in">
      <h2 style={{ fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, marginBottom: 12 }}>Sign in</h2>
      <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 32 }}>
        Enter your email and we'll send you a sign-in link. No passwords. Every page you view will be watermarked with this email.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Field label="EMAIL_ADDRESS" required>
          <input className="input" type="email" placeholder="you@firm.com"
                 value={email} onChange={e => setEmail(e.target.value)}
                 onKeyDown={e => e.key === 'Enter' && sendLink()}
                 autoFocus />
        </Field>
      </div>
      {error && (
        <div style={{ marginTop: 16, padding: 10, border: '1px solid var(--error)', color: 'var(--error)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>
          Couldn't send: {error}. Try again in a moment.
        </div>
      )}
      <div style={{ marginTop: 32, display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        <button className="btn btn-filled btn-lg" disabled={!valid || busy}
                style={{ opacity: (valid && !busy) ? 1 : 0.4 }}
                onClick={sendLink}>{busy ? 'Sending…' : 'Send sign-in link →'}</button>
        <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.08em' }}>
          Single-use, expires in 30 minutes.
        </span>
      </div>
    </div>
  );
}

function Field({ label, required, children }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--text-tertiary)', marginBottom: 8 }}>
        {label}{required && <span style={{ color: 'var(--gold-dark)', marginLeft: 6 }}>*</span>}
      </div>
      {children}
    </div>
  );
}

function QuestionStep({ title, sub, options, value, setValue, onNext }) {
  return (
    <div className="fade-in">
      <h2 style={{ fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, marginBottom: 12 }}>{title}</h2>
      <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 32 }}>{sub}</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {options.map((o, i) => (
          <button key={o} className="tile"
            data-selected={value === o}
            onClick={() => setValue(o)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <span className="mono tile-meta">[ {String(i+1).padStart(2,'0')} ]</span>
              <span className="tile-label">{o}</span>
            </div>
            {value === o && <span style={{ color: 'var(--gold-dark)' }}>●</span>}
          </button>
        ))}
      </div>
      <div style={{ marginTop: 32 }}>
        <button className="btn btn-filled btn-lg"
          disabled={!value}
          style={{ opacity: value ? 1 : 0.4 }}
          onClick={() => value && onNext()}>Continue →</button>
      </div>
    </div>
  );
}

function ReviewStep({ email, name, firm, a1, a2, a3, cta, onSubmit }) {
  return (
    <div className="fade-in">
      <h2 style={{ fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, marginBottom: 12 }}>You're in.</h2>
      <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 24 }}>
        Confirm your details and we'll open the room.
      </p>
      <Brackets style={{ background: 'var(--bg-card)', border: '1px solid var(--border)', padding: 24, marginBottom: 24 }}>
        <ReviewRow label="EMAIL" value={email || '—'} />
        <ReviewRow label="NAME" value={name || '—'} />
        <ReviewRow label="FIRM" value={firm || '—'} />
        <ReviewRow label="PROFILE" value={a1 || '—'} />
        <ReviewRow label="ALLOCATION" value={a2 || '—'} />
        <ReviewRow label="TIMELINE" value={a3 || '—'} last />
      </Brackets>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <button className="btn btn-filled btn-lg" onClick={onSubmit}>{cta} →</button>
        <span className="mono" style={{ fontSize: 9, color: 'var(--text-tertiary)', letterSpacing: '0.12em' }}>
          NDA_AGREED · WATERMARK_BOUND
        </span>
      </div>
    </div>
  );
}

function ReviewRow({ label, value, last }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      padding: '10px 0',
      borderBottom: last ? 'none' : '1px solid var(--border)',
    }}>
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--text-tertiary)' }}>{label}</span>
      <span style={{ fontSize: 14 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { Onboarding, Q_LIBRARY });
