// ════════════════════════════════════════════════════════════════════
// ASSESSMENT · 6-question quiz funnel → personalized recommendation
//
// Goals:
//   1. Segment the visitor (origin, stage, blocker, timeline)
//   2. Output a recommended phase + top 3 pillars + ETA
//   3. Push to Cal.com with pre-filled context (URL params)
//
// Pure client-side. Answers serialize into a hash so refreshes survive
// and the URL can be shared.
// ════════════════════════════════════════════════════════════════════

const Q = [
  {
    id: 'origin',
    prompt: 'Where are you coming from?',
    sub: 'So we know what regulatory bridges to build.',
    options: [
      { v: 'US',     l: 'United States' },
      { v: 'UK',     l: 'United Kingdom' },
      { v: 'EU',     l: 'Elsewhere in Europe' },
      { v: 'TR',     l: 'Turkey' },
      { v: 'ASIA',   l: 'Asia' },
      { v: 'OTHER',  l: 'Somewhere else' },
    ],
  },
  {
    id: 'stage',
    prompt: 'What stage is the company?',
    sub: 'Be honest. We meet you where you are.',
    options: [
      { v: 'IDEA',     l: 'Pre-incorporation / idea stage' },
      { v: 'PRESEED',  l: 'Pre-seed / first funding' },
      { v: 'SEED',     l: 'Seed (raised, building, hiring)' },
      { v: 'A',        l: 'Series A or later' },
      { v: 'BOOT',     l: 'Bootstrapped & profitable' },
    ],
  },
  {
    id: 'incorporated',
    prompt: 'Already incorporated somewhere?',
    sub: '',
    options: [
      { v: 'NO',       l: 'No — greenfield' },
      { v: 'PARENT',   l: 'Yes, parent co exists' },
      { v: 'NL_ALREADY', l: 'Yes, already a Dutch BV' },
    ],
  },
  {
    id: 'team',
    prompt: 'How many people on the team today?',
    sub: '',
    options: [
      { v: 'SOLO',  l: 'Just me' },
      { v: '2_5',   l: '2–5' },
      { v: '6_20',  l: '6–20' },
      { v: '21+',   l: '21 or more' },
    ],
  },
  {
    id: 'blocker',
    prompt: 'What\u2019s the biggest blocker right now?',
    sub: 'Pick the thing keeping you up at night.',
    options: [
      { v: 'VISA',     l: 'Visas, residency, the 30% ruling' },
      { v: 'BANK',     l: 'Banking, entity, compliance' },
      { v: 'FIN',      l: 'Finance ops — close, audit, reporting' },
      { v: 'INV',      l: 'Raising the next round' },
      { v: 'GTM',      l: 'EU go-to-market & sales' },
      { v: 'TALENT',   l: 'Hiring & people ops' },
    ],
  },
  {
    id: 'when',
    prompt: 'When do you want to touch down?',
    sub: 'Months from today.',
    options: [
      { v: 'NOW',   l: 'Already in motion — yesterday' },
      { v: 'SOON',  l: 'Within 1 month' },
      { v: '3M',    l: '1–3 months' },
      { v: '6M',    l: '3–6 months' },
      { v: 'EXP',   l: 'Just exploring' },
    ],
  },
];

// ─── Recommendation engine ────────────────────────────────────────
function recommend(answers) {
  const stagePhase = { IDEA: 'Launch', PRESEED: 'Launch', SEED: 'Accelerate', A: 'Scale', BOOT: 'Accelerate' };
  const sizePhase  = { SOLO: 'Launch', '2_5': 'Launch', '6_20': 'Accelerate', '21+': 'Scale' };

  // Score each phase by stage + team + blocker
  const phaseScore = { Launch: 0, Accelerate: 0, Scale: 0 };
  phaseScore[stagePhase[answers.stage] || 'Launch'] += 2;
  phaseScore[sizePhase[answers.team] || 'Launch'] += 1;
  if (answers.blocker === 'INV' || answers.blocker === 'GTM') phaseScore.Scale += 2;
  if (answers.blocker === 'BANK' || answers.blocker === 'VISA') phaseScore.Launch += 1;
  if (answers.incorporated === 'NL_ALREADY') phaseScore.Accelerate += 1;

  const phase = Object.entries(phaseScore).sort((a, b) => b[1] - a[1])[0][0];

  // Pillar weighting by blocker
  const pillarMap = {
    VISA:   ['Corporate Legal', 'Academy', 'IT'],
    BANK:   ['Corporate Legal', 'Finance', 'IT'],
    FIN:    ['Finance', 'Corporate Legal', 'IT'],
    INV:    ['Investment', 'Finance', 'Corporate Legal'],
    GTM:    ['Sales', 'Marketing', 'Finance'],
    TALENT: ['Academy', 'Corporate Legal', 'IT'],
  };
  const pillars = pillarMap[answers.blocker] || ['Finance', 'Corporate Legal', 'IT'];

  // ETA
  const etaMap = {
    NOW:  '2–4 weeks',
    SOON: '3–5 weeks',
    '3M': '4–8 weeks',
    '6M': '8–12 weeks',
    EXP:  'When you\u2019re ready',
  };
  const eta = etaMap[answers.when] || '4–8 weeks';

  // Headline copy
  const originLine = {
    US: 'US → Netherlands',
    UK: 'UK → Netherlands',
    EU: 'EU intra-European expansion',
    TR: 'Turkey → Netherlands',
    ASIA: 'Asia → Netherlands',
    OTHER: 'International → Netherlands',
  }[answers.origin] || 'International → Netherlands';

  return { phase, pillars, eta, originLine };
}

// ─── Question screen ──────────────────────────────────────────────
function QuestionScreen({ q, value, onChange, idx, total }) {
  return (
    <div
      style={{
        animation: 'qFadeIn 0.6s cubic-bezier(.2,.7,.2,1)',
      }}
    >
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--signal)', marginBottom: 28 }}>
        QUESTION {String(idx + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}
      </div>
      <h2
        className="serif"
        style={{
          fontSize: 'clamp(40px, 6vw, 90px)',
          lineHeight: 0.95,
          letterSpacing: '-0.035em',
          marginBottom: 16,
          maxWidth: '18ch',
        }}
      >
        {q.prompt}
      </h2>
      {q.sub && (
        <p className="serif" style={{ fontSize: 'clamp(18px, 1.6vw, 24px)', fontStyle: 'italic', opacity: 0.7, marginBottom: 40, maxWidth: '46ch' }}>
          {q.sub}
        </p>
      )}
      <div style={{ display: 'grid', gap: 10, maxWidth: 720 }}>
        {q.options.map((o, i) => (
          <button
            key={o.v}
            onClick={() => onChange(o.v)}
            className="serif"
            style={{
              textAlign: 'left',
              padding: '20px 26px',
              border: '1px solid var(--rule)',
              borderColor: value === o.v ? 'var(--signal)' : 'var(--rule)',
              background: value === o.v ? 'var(--signal)' : 'transparent',
              color: value === o.v ? 'var(--paper)' : 'var(--fg)',
              fontSize: 'clamp(20px, 1.8vw, 26px)',
              letterSpacing: '-0.015em',
              cursor: 'pointer',
              transition: 'all 0.2s',
              display: 'flex',
              alignItems: 'center',
              gap: 18,
              fontFamily: 'var(--serif)',
            }}
            onMouseEnter={(e) => {
              if (value !== o.v) e.currentTarget.style.borderColor = 'var(--signal)';
            }}
            onMouseLeave={(e) => {
              if (value !== o.v) e.currentTarget.style.borderColor = '';
            }}
          >
            <span
              className="mono"
              style={{
                fontSize: 10,
                letterSpacing: '0.3em',
                opacity: 0.55,
                minWidth: 24,
              }}
            >
              {String.fromCharCode(65 + i)}
            </span>
            <span>{o.l}</span>
            <span style={{ marginLeft: 'auto', opacity: 0.6 }}>→</span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ─── Result screen ────────────────────────────────────────────────
function ResultScreen({ answers, onRestart }) {
  const r = recommend(answers);

  // Build Cal.com prefill URL params for context
  const calParams = new URLSearchParams({
    name: '',
    email: '',
    notes: `Assessment result — Phase: ${r.phase}. Origin: ${r.originLine}. Stage: ${answers.stage}. Blocker: ${answers.blocker}. ETA: ${r.eta}.`,
  });
  const calUrl = `contact.html?phase=${r.phase}&blocker=${answers.blocker}#book`;

  return (
    <div style={{ animation: 'qFadeIn 0.8s cubic-bezier(.2,.7,.2,1)' }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.3em', color: 'var(--signal)', marginBottom: 28 }}>
        ◆ ASSESSMENT COMPLETE
      </div>
      <h2
        className="serif"
        style={{
          fontSize: 'clamp(56px, 9vw, 160px)',
          lineHeight: 0.9,
          letterSpacing: '-0.04em',
          marginBottom: 50,
          maxWidth: '14ch',
        }}
      >
        Recommended: <em style={{ color: 'var(--signal)' }}>Phase {r.phase}.</em>
      </h2>

      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 0,
          border: '1px solid var(--rule)',
          marginBottom: 60,
        }}
      >
        {[
          { k: 'YOUR PHASE', v: r.phase, sub: 'How we should engage' },
          { k: 'TIME TO LAND', v: r.eta, sub: 'Operational in...' },
          { k: 'ROUTE',     v: r.originLine, sub: 'Your specific bridge' },
        ].map((b, i) => (
          <div
            key={b.k}
            style={{
              padding: '36px 28px',
              borderRight: i < 2 ? '1px solid var(--rule)' : 'none',
            }}
          >
            <div className="mono" style={{ fontSize: 10, color: 'var(--signal)', letterSpacing: '0.3em', marginBottom: 18 }}>
              {b.k}
            </div>
            <div
              className="serif"
              style={{
                fontSize: 'clamp(28px, 3vw, 48px)',
                lineHeight: 1,
                letterSpacing: '-0.025em',
                fontStyle: 'italic',
                marginBottom: 12,
              }}
            >
              {b.v}
            </div>
            <p className="mono" style={{ fontSize: 10, opacity: 0.55, letterSpacing: '0.2em' }}>
              {b.sub}
            </p>
          </div>
        ))}
      </div>

      <div style={{ marginBottom: 60 }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--signal)', letterSpacing: '0.3em', marginBottom: 20 }}>
          ◆ TOP 3 PILLARS FOR YOU
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
          {r.pillars.map((p, i) => (
            <div
              key={p}
              style={{
                padding: '20px 26px',
                border: '1px solid var(--rule)',
                background: i === 0 ? 'var(--ink)' : 'transparent',
                color: i === 0 ? 'var(--paper)' : 'var(--fg)',
                display: 'flex', alignItems: 'baseline', gap: 14,
              }}
            >
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.3em', opacity: 0.6 }}>
                0{i + 1}
              </span>
              <span className="serif" style={{ fontSize: 24, letterSpacing: '-0.02em' }}>
                {p}
              </span>
            </div>
          ))}
        </div>
        <p className="serif" style={{ marginTop: 18, fontSize: 16, fontStyle: 'italic', opacity: 0.7, maxWidth: '60ch' }}>
          We&apos;ll start with these on day one. Other pillars folded in as you grow.
        </p>
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'center' }}>
        <Magnetic strength={0.25}>
          <a className="btn btn-signal" href={calUrl}>
            Book your discovery call <span className="arrow">→</span>
          </a>
        </Magnetic>
        <Magnetic strength={0.25}>
          <a className="btn" href="platform.html">
            See the platform <span className="arrow">↗</span>
          </a>
        </Magnetic>
        <button
          onClick={onRestart}
          className="mono"
          style={{
            fontSize: 11,
            letterSpacing: '0.2em',
            color: 'var(--fg-soft)',
            borderBottom: '1px solid currentColor',
            paddingBottom: 2,
            marginLeft: 'auto',
          }}
        >
          ← RETAKE
        </button>
      </div>

      <p
        className="mono"
        style={{
          marginTop: 60,
          fontSize: 10,
          opacity: 0.45,
          letterSpacing: '0.2em',
          paddingTop: 30,
          borderTop: '1px solid var(--rule)',
        }}
      >
        THIS IS AN INDICATIVE RECOMMENDATION. THE REAL ROADMAP IS BUILT WITH YOU IN THE DISCOVERY CALL.
      </p>
    </div>
  );
}

// ─── Progress bar ─────────────────────────────────────────────────
function QuizProgress({ idx, total }) {
  return (
    <div style={{ position: 'relative', marginBottom: 50 }}>
      <div
        style={{
          height: 2,
          background: 'var(--rule)',
          position: 'relative',
          overflow: 'hidden',
        }}
      >
        <div
          style={{
            position: 'absolute', left: 0, top: 0, bottom: 0,
            width: `${((idx + 1) / total) * 100}%`,
            background: 'var(--signal)',
            transition: 'width 0.6s cubic-bezier(.2,.7,.2,1)',
          }}
        />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
        <span className="mono" style={{ fontSize: 10, opacity: 0.55, letterSpacing: '0.2em' }}>
          REEL · ASSESSMENT
        </span>
        <span className="mono" style={{ fontSize: 10, opacity: 0.55, letterSpacing: '0.2em' }}>
          {Math.round(((idx + 1) / total) * 100)}%
        </span>
      </div>
    </div>
  );
}

// ─── Main page ────────────────────────────────────────────────────
function AssessmentPage() {
  useLenis();
  const [idx, setIdx] = React.useState(-1); // -1 = intro
  const [answers, setAnswers] = React.useState({});
  const [done, setDone] = React.useState(false);

  const total = Q.length;

  const start = () => setIdx(0);

  const answer = (v) => {
    const q = Q[idx];
    setAnswers({ ...answers, [q.id]: v });
    setTimeout(() => {
      if (idx + 1 >= total) setDone(true);
      else setIdx(idx + 1);
    }, 220);
  };

  const back = () => {
    if (done) { setDone(false); return; }
    if (idx > 0) setIdx(idx - 1);
    else setIdx(-1);
  };

  const restart = () => {
    setAnswers({});
    setIdx(-1);
    setDone(false);
    window.scrollTo(0, 0);
  };

  return (
    <>
      <Cursor />
      <PageFrame pageId="assessment" pageLabel="PAGE / ASSESSMENT" />

      <style>{`
        @keyframes qFadeIn {
          from { opacity: 0; transform: translateY(20px); }
          to   { opacity: 1; transform: translateY(0); }
        }
      `}</style>

      <main className="page">
        <section style={{ padding: '8vh 6vw 6vh', borderBottom: '1px solid var(--rule)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 40, alignItems: 'start', marginBottom: 40 }}>
            <div className="eyebrow">90-second Assessment · No email required</div>
            <div className="mono" style={{ fontSize: 11, opacity: 0.55, letterSpacing: '0.2em', textAlign: 'right' }}>
              FREE · INSTANT<br/>
              NO LISTS · NO SPAM
            </div>
          </div>
          <h1
            className="serif"
            style={{
              fontSize: 'clamp(56px, 11vw, 200px)',
              lineHeight: 0.88,
              letterSpacing: '-0.04em',
              maxWidth: '18ch',
            }}
          >
            Where should you <em style={{ color: 'var(--signal)' }}>touch down?</em>
          </h1>
          <p
            className="serif"
            style={{
              fontSize: 'clamp(22px, 2vw, 32px)',
              fontStyle: 'italic',
              marginTop: 36,
              maxWidth: '60ch',
              opacity: 0.85,
              lineHeight: 1.35,
            }}
          >
            Six questions, ninety seconds. We&apos;ll tell you which engagement phase fits, which three pillars matter most, and roughly how fast you can land.
          </p>
        </section>

        <section style={{ padding: '8vh 6vw 16vh', maxWidth: 1400, margin: '0 auto', width: '100%' }}>
          {idx === -1 && !done && (
            <div style={{ animation: 'qFadeIn 0.6s ease-out', maxWidth: 720 }}>
              <p className="serif" style={{ fontSize: 'clamp(22px, 2vw, 30px)', lineHeight: 1.4, fontStyle: 'italic', marginBottom: 40, opacity: 0.85 }}>
                You answer. We map. Nothing leaves your browser until you decide to book.
              </p>
              <Magnetic strength={0.25}>
                <button className="btn btn-signal" onClick={start}>
                  Start the assessment <span className="arrow">→</span>
                </button>
              </Magnetic>
              <div style={{ marginTop: 60, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 30, maxWidth: 720 }}>
                {[
                  { k: '01', l: 'No email gate' },
                  { k: '02', l: 'No lists, no spam' },
                  { k: '03', l: 'Result you can share' },
                ].map((b) => (
                  <div key={b.k}>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--signal)', letterSpacing: '0.3em', marginBottom: 10 }}>{b.k}</div>
                    <p className="serif" style={{ fontSize: 17, fontStyle: 'italic', opacity: 0.78 }}>{b.l}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {idx >= 0 && !done && (
            <div style={{ maxWidth: 980 }}>
              <QuizProgress idx={idx} total={total} />
              <QuestionScreen
                q={Q[idx]}
                value={answers[Q[idx].id]}
                onChange={answer}
                idx={idx}
                total={total}
              />
              <button
                onClick={back}
                className="mono"
                style={{
                  marginTop: 40,
                  fontSize: 11,
                  letterSpacing: '0.2em',
                  color: 'var(--fg-soft)',
                  borderBottom: '1px solid currentColor',
                  paddingBottom: 2,
                }}
              >
                ← BACK
              </button>
            </div>
          )}

          {done && <ResultScreen answers={answers} onRestart={restart} />}
        </section>
      </main>

      <PageFooter />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<AssessmentPage />);
