// Multi-step eligibility check. The conversion point + validation instrument.

const { useState, useMemo } = React;

const SUPABASE_URL = 'https://uoualarfinsblliazwjr.supabase.co';
const SUPABASE_KEY = 'sb_publishable_lUjwpcPeVyF0HOFUUgOzRA_jwy6siQk';

async function saveLead({ email, answers }) {
  const payload = {
    email,
    product: answers.product ?? null,
    company: answers.company ?? null,
    equity_type: answers.equityType ?? null,
    equity_value: typeof answers.equityValue === 'number' ? answers.equityValue : null,
    income: typeof answers.income === 'number' ? answers.income : null,
    timeline: answers.timeline ?? null,
    city: answers.city ?? null,
    qualifies: (answers.equityValue || 0) >= 750000 && ['now','0_6','6_12'].includes(answers.timeline),
    user_agent: typeof navigator !== 'undefined' ? navigator.userAgent : null,
    referrer: typeof document !== 'undefined' ? document.referrer || null : null,
    raw_answers: answers,
  };
  const res = await fetch(`${SUPABASE_URL}/rest/v1/leads`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      apikey: SUPABASE_KEY,
      Authorization: `Bearer ${SUPABASE_KEY}`,
      Prefer: 'return=minimal',
    },
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new Error(`Supabase ${res.status}: ${await res.text()}`);
}

const STEPS = [
  {
    id: 'product',
    tag: 'What you need',
    q: 'What are you looking for?',
    hint: 'Pick the one closest to your situation.',
    type: 'choice',
    options: [
      { v: 'buy',     label: 'Buy a home' },
      { v: 'refi',    label: 'Refinance' },
      { v: 'loc',     label: 'A line of credit' },
      { v: 'explore', label: 'Just exploring' },
    ],
  },
  {
    id: 'company',
    tag: 'Your company',
    q: 'Where do you work?',
    hint: 'Type your employer. We assess most venture-backed late-stage companies.',
    type: 'text',
    placeholder: 'e.g. Databricks',
  },
  {
    id: 'equityType',
    tag: 'Equity type',
    q: 'What kind of equity do you hold?',
    hint: 'Pick the one that\u2019s most of your stake.',
    type: 'choice',
    options: [
      { v: 'iso',  label: 'ISO' },
      { v: 'nso',  label: 'NSO' },
      { v: 'rsu',  label: 'RSU' },
      { v: 'mix',  label: 'Mix' },
      { v: 'nope', label: 'Not sure' },
    ],
  },
  {
    id: 'equityValue',
    tag: 'Vested equity',
    q: 'How much vested equity do you hold?',
    hint: 'Most-recent 409A or tender price is fine.',
    type: 'choice',
    options: [
      { v: 0,        label: 'Under $500K' },
      { v: 750000,   label: '$500K - $1M' },
      { v: 2000000,  label: '$1M - $3M' },
      { v: 6000000,  label: '$3M - $10M' },
      { v: 15000000, label: '$10M+' },
    ],
  },
  {
    id: 'income',
    tag: 'Cash income',
    q: 'What\u2019s your household income?',
    hint: 'Base salary plus cash bonus. Pre-tax.',
    type: 'choice',
    options: [
      { v: 150000,  label: 'Under $200K' },
      { v: 250000,  label: '$200K - $300K' },
      { v: 400000,  label: '$300K - $500K' },
      { v: 650000,  label: '$500K - $800K' },
      { v: 1000000, label: '$800K+' },
    ],
  },
  {
    id: 'timeline',
    tag: 'Timeline',
    q: 'When do you want to close?',
    hint: 'Real demand has a date on it.',
    type: 'choice',
    options: [
      { v: 'now',     label: 'Actively shopping' },
      { v: '0_6',     label: '0\u20136 months' },
      { v: '6_12',    label: '6\u201312 months' },
      { v: 'explore', label: 'Exploring' },
    ],
  },
  {
    id: 'city',
    tag: 'City',
    q: 'Where are you buying?',
    hint: 'City or metro is enough.',
    type: 'text',
    placeholder: 'e.g. San Francisco',
  },
];

const Option = ({ active, label, onClick }) => (
  <button className="elig-opt" aria-pressed={active} onClick={onClick}>
    <span>{label}</span>
    <span className="check"><Icon.Check/></span>
  </button>
);

const Eligibility = () => {
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const [done, setDone] = useState(false);
  const [email, setEmail] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  const submit = async () => {
    if (!email.includes('@') || submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      await saveLead({ email, answers });
      setSubmitted(true);
    } catch (err) {
      setSubmitError('Something went wrong. Try again or email dan@vestedmortgages.com.');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const safeStep = Math.min(Math.max(step, 0), STEPS.length - 1);
  const current = STEPS[safeStep];
  const isLast = safeStep === STEPS.length - 1;
  const progress = done ? 100 : ((safeStep) / STEPS.length) * 100;

  const filled = useMemo(() => {
    if (!current) return false;
    const v = answers[current.id];
    if (current.type === 'choice') return v !== undefined;
    return typeof v === 'string' && v.trim().length > 0;
  }, [answers, current]);

  const setAnswer = (val) => setAnswers((a) => ({ ...a, [current.id]: val }));

  const next = () => {
    if (!filled) return;
    if (isLast) setDone(true);
    else setStep((s) => Math.min(s + 1, STEPS.length - 1));
  };
  const back = () => {
    if (done) { setDone(false); return; }
    if (step > 0) setStep((s) => s - 1);
  };

  const qualifies = (answers.equityValue || 0) >= 750000 &&
                    ['now','0_6','6_12'].includes(answers.timeline);

  return (
    <section className="section fog" id="elig">
      <div className="container">
        <div className="section-head center">
          <div className="eyebrow">03 / Get on the list</div>
          <h2 className="h2">See if you&rsquo;re a fit.</h2>
          <p className="section-sub">
            A few quick questions. No credit pull, no documents, no
            obligation. If you&rsquo;re at an early-stage startup with only
            unvested equity, this isn&rsquo;t for you yet.
          </p>
        </div>

        <div className="elig-shell">
          <div className="elig-bar">
            <div className="elig-progress">
              <span style={{ width: `${progress}%` }} />
            </div>
            <div className="elig-counter">
              {done ? 'Result' : `${String(step+1).padStart(2,'0')} / ${String(STEPS.length).padStart(2,'0')}`}
            </div>
          </div>

          <div className="elig-body">
            {!done && (
              <React.Fragment>
                <div className="elig-q-tag">{current.tag}</div>
                <h3 className="elig-q">{current.q}</h3>
                <p className="elig-hint">{current.hint}</p>

                {current.type === 'choice' && (
                  <div className={'elig-options' + (current.options.length === 5 ? ' single' : '')}>
                    {current.options.map((o) => (
                      <Option
                        key={String(o.v)}
                        active={answers[current.id] === o.v}
                        label={o.label}
                        onClick={() => { setAnswer(o.v); setTimeout(() => {
                          if (isLast) setDone(true);
                          else setStep((s) => Math.min(s + 1, STEPS.length - 1));
                        }, 140); }}
                      />
                    ))}
                  </div>
                )}

                {current.type === 'text' && (
                  <input
                    className="elig-input"
                    type="text"
                    placeholder={current.placeholder}
                    value={answers[current.id] || ''}
                    onChange={(e) => setAnswer(e.target.value)}
                    onKeyDown={(e) => { if (e.key === 'Enter' && filled) next(); }}
                    autoFocus
                  />
                )}

                <div className="elig-foot">
                  {step > 0 ? (
                    <button className="elig-back" onClick={back}>
                      <Icon.ArrowBack/> Back
                    </button>
                  ) : <span/>}
                  {current.type === 'text' ? (
                    <button className="btn btn-primary" disabled={!filled} onClick={next}
                      style={{ opacity: filled ? 1 : 0.5, pointerEvents: filled ? 'auto' : 'none' }}>
                      {isLast ? 'See my number' : 'Continue'}
                      <Icon.Arrow/>
                    </button>
                  ) : (
                    <span className="elig-skip">Pick one to continue</span>
                  )}
                </div>
              </React.Fragment>
            )}

            {done && !submitted && (
              <div className="elig-result">
                <span className="tag">
                  {qualifies ? 'Looks like a fit' : 'Worth a closer look'}
                </span>
                <h3>You look like a fit for our first cohort.</h3>
                <p className="desc">
                  We&rsquo;re onboarding a small group now. Leave your email
                  and we&rsquo;ll send your full breakdown and your place in
                  line. We&rsquo;ll only reach out if it&rsquo;s actually a
                  fit.
                </p>
                <div className="email-row">
                  <input
                    type="email"
                    placeholder="you@work.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
                    disabled={submitting}
                  />
                  <button
                    className="btn btn-primary"
                    disabled={!email.includes('@') || submitting}
                    onClick={submit}
                    style={{ opacity: email.includes('@') && !submitting ? 1 : 0.5 }}
                  >
                    {submitting ? 'Sending…' : 'Get my breakdown'}
                    <Icon.Arrow/>
                  </button>
                </div>
                {submitError && (
                  <p className="smallprint" style={{marginTop:12, color:'#c1432a'}}>
                    {submitError}
                  </p>
                )}
                <button className="elig-back" style={{marginTop: 24}} onClick={back}>
                  <Icon.ArrowBack/> Adjust answers
                </button>
              </div>
            )}

            {done && submitted && (
              <div className="elig-result thanks">
                <span className="tag">You&rsquo;re in line</span>
                <h3 style={{marginTop:24, fontSize:28, color:'var(--ink)'}}>
                  Check your inbox.
                </h3>
                <p className="desc" style={{marginTop:8}}>
                  We&rsquo;ve queued your breakdown for{' '}
                  <span className="mono" style={{color:'var(--ink)'}}>{email}</span>.
                  If you&rsquo;re a fit, you&rsquo;ll hear from a real human in
                  the next 48 hours.
                </p>
                <button
                  className="btn btn-ghost"
                  style={{marginTop: 32}}
                  onClick={() => {
                    setAnswers({}); setStep(0); setDone(false); setSubmitted(false); setEmail(''); setSubmitError(null);
                  }}
                >
                  Start over
                </button>
              </div>
            )}
          </div>
        </div>

        <p className="smallprint" style={{marginTop:24}}>
          Estimate only · Not a quote, an offer, or a commitment to lend · No credit pull
        </p>
      </div>
    </section>
  );
};

window.Eligibility = Eligibility;
