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

const { useState, useMemo } = React;

const track = (event, props) => {
  if (typeof window !== 'undefined' && window.posthog && typeof window.posthog.capture === 'function') {
    window.posthog.capture(event, props);
  }
};

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

// Explorers self-select as not-yet-ready, so they never "qualify" as a hot lead.
// A real line needs real, in-the-money vested equity and a near-term need for cash.
function computeQualifies(answers) {
  // The use-case never gates qualification. A real line needs real, in-the-money
  // vested equity and a near-term need for cash, nothing else.
  return (answers.equityValue || 0) >= 750000 &&
         ['now', '0_6', '6_12'].includes(answers.timeline);
}

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: null,
    qualifies: computeQualifies(answers),
    user_agent: typeof navigator !== 'undefined' ? navigator.userAgent : null,
    referrer: typeof document !== 'undefined' ? document.referrer || null : null,
    raw_answers: { site: 'vested-equity', ...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: 'company',
    tag: 'Your company',
    q: 'Where do you work?',
    hint: 'Type your employer. We work with most venture-backed late-stage companies.',
    type: 'text',
    placeholder: 'e.g. Databricks',
  },
  {
    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: 50000,    label: 'Under $100K' },
      { v: 100000,   label: '$100K - $250K' },
      { v: 250000,   label: '$250K - $500K' },
      { v: 750000,   label: '$500K - $1M' },
      { v: 2000000,  label: '$1M - $3M' },
      { v: 6000000,  label: '$3M - $10M' },
      { v: 15000000, label: '$10M+' },
    ],
  },
  {
    id: 'timeline',
    tag: 'Timeline',
    q: 'When might you want to draw?',
    hint: 'A rough sense is fine, no date required.',
    type: 'choice',
    options: [
      { v: 'now',     label: 'Right now' },
      { v: '0_6',     label: '0–6 months' },
      { v: '6_12',    label: '6–12 months' },
      { v: 'explore', label: 'Just exploring' },
    ],
  },
  {
    // Research only. Open-ended, optional, and never gates qualification.
    id: 'product',
    tag: 'Optional',
    q: 'Anything prompting this?',
    hint: 'Totally optional. Your line works for anything; this just helps us tailor your estimate.',
    type: 'text',
    optional: true,
    placeholder: 'e.g. a tax bill, exercising options, a home… or skip',
  },
];

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 [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  const submit = async () => {
    if (!email.includes('@') || submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    track('lead_submit_clicked', { qualifies: computeQualifies(answers) });
    try {
      await saveLead({ email, answers });
      if (typeof window !== 'undefined' && window.posthog && typeof window.posthog.identify === 'function') {
        window.posthog.identify(email, { email, ...answers, qualifies: computeQualifies(answers) });
      }
      track('lead_submitted', { qualifies: computeQualifies(answers), ...answers });
      try { window.sessionStorage && window.sessionStorage.setItem('vested.equity.lead.email', email); } catch (e) {}
      window.location.assign('/thanks');
    } catch (err) {
      track('lead_submit_failed', { message: err && err.message });
      setSubmitError('Something went wrong. Try again or email info@vestedequity.com.');
      console.error(err);
      setSubmitting(false);
    }
  };

  const steps = STEPS;
  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) => {
    if (Object.keys(a).length === 0) track('quiz_started', { first_question: current.id });
    return { ...a, [current.id]: val };
  });

  const next = () => {
    if (!filled && !current.optional) return;
    track('quiz_step_answered', { step_id: current.id, value: answers[current.id], step_index: safeStep });
    if (isLast) { track('quiz_completed', { qualifies: computeQualifies(answers), ...answers }); setDone(true); }
    else setStep((s) => Math.min(s + 1, steps.length - 1));
  };
  const skip = () => {
    track('quiz_step_skipped', { step_id: current.id, step_index: safeStep });
    setAnswers((a) => { const next = { ...a }; delete next[current.id]; return next; });
    if (isLast) { track('quiz_completed', { qualifies: computeQualifies(answers) }); 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 = computeQualifies(answers);

  return (
    <section className="section fog" id="elig">
      <div className="container">
        <div className="section-head center">
          <div className="eyebrow">05 / Get on the list</div>
          <h2 className="h2">See your line.</h2>
          <p className="section-sub">
            Three quick questions and your email, about 30 seconds. No credit
            pull, no documents, no obligation.
          </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(() => {
                          track('quiz_step_answered', { step_id: current.id, value: o.v, step_index: safeStep });
                          if (isLast) { track('quiz_completed', { qualifies: computeQualifies({ ...answers, [current.id]: o.v }), ...answers, [current.id]: o.v }); 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' ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                      {current.optional && (
                        <button className="elig-back" onClick={skip}>Skip</button>
                      )}
                      <button className="btn btn-primary"
                        disabled={!filled && !current.optional}
                        onClick={next}
                        style={{ opacity: (filled || current.optional) ? 1 : 0.5, pointerEvents: (filled || current.optional) ? 'auto' : 'none' }}>
                        {isLast ? 'See my line' : 'Continue'}
                        <Icon.Arrow/>
                      </button>
                    </div>
                  ) : (
                    <span className="elig-skip">Pick one to continue</span>
                  )}
                </div>
              </React.Fragment>
            )}

            {done && (
              <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 estimated line 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 line estimate'}
                    <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>
            )}

          </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;
