/* ============================================================
   QUIZ - interactive flow. Questions + result narratives live
   in components/quiz-data.jsx (shared with the mobile shell).
   ============================================================ */

const QuizArtboard = () => {
  const SLUG = { P: 'peacekeeper', Pf: 'performer', V: 'vault', F: 'forecaster', D: 'disappearer' };
  const SAVE_KEY = 'etp_quiz_state';
  const saved = (() => {
    try { return JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); } catch (e) { return null; }
  })();
  const [step, setStep] = React.useState((saved && saved.step) || 0);
  const [scores, setScores] = React.useState((saved && saved.scores) || { P: 0, Pf: 0, V: 0, F: 0, D: 0 });
  const [history, setHistory] = React.useState((saved && saved.history) || []);
  const [calib, setCalib] = React.useState((saved && saved.calib) || null);
  const [email, setEmail] = React.useState('');
  const [sendState, setSendState] = React.useState('idle'); // idle | sending
  const [sendResult, setSendResult] = React.useState(null); // null | 'ok' | 'fail'
  const emailValid = /.+@.+\..+/.test(email);

  const total = QUIZ.length;          // 12 scored questions
  const calibStep = total + 1;        // one calibration question
  const gateStep = calibStep + 1;     // email step - the result is delivered by email
  const atResult = step > gateStep;

  // Resume support - the privacy page promises progress is remembered.
  React.useEffect(() => {
    try { localStorage.setItem(SAVE_KEY, JSON.stringify({ step, scores, history, calib })); } catch (e) {}
  }, [step, scores, history, calib]);

  const progress = step === 0 ? 0 : step >= gateStep ? 100 : (step / calibStep) * 100;

  const select = (pattern) => {
    setHistory([...history, { step, pattern, scores }]);
    setScores({ ...scores, [pattern]: scores[pattern] + 1 });
    setStep(step + 1);
  };

  const reset = () => {
    setStep(0);
    setScores({ P: 0, Pf: 0, V: 0, F: 0, D: 0 });
    setHistory([]);
    setCalib(null);
    setSendState('idle');
    setSendResult(null);
    setEmail('');
    try { localStorage.removeItem(SAVE_KEY); } catch (e) {}
  };

  const back = () => {
    if (history.length === 0) return;
    const prev = history[history.length - 1];
    setScores(prev.scores);
    setStep(prev.step);
    setHistory(history.slice(0, -1));
  };

  // Scoring. 12 forced-choice items can't support percentage precision,
  // so the breakdown shows strength bands, not a psychometric profile.
  const sorted = Object.entries(scores).sort((a, b) => b[1] - a[1]);
  const top = sorted[0][0];
  const second = sorted[1][0];
  const nearTie = sorted[0][1] - sorted[1][1] <= 1 && sorted[1][1] > 0;
  const result = PATTERNS[top];
  const band = (v) => (v >= 4 ? 'Strong' : v >= 2 ? 'Present' : 'Quiet');

  const goJoin = (key) => {
    try {
      localStorage.setItem('etp_pattern', SLUG[key] || '');
      localStorage.setItem('etp_secondary', SLUG[second] || '');
      if (email) localStorage.setItem('etp_email', email);
    } catch (e) {}
    window.navTo('/reserve');
  };

  const submitGate = async (e) => {
    e.preventDefault();
    if (!emailValid || sendState === 'sending') return;
    setSendState('sending');
    const r = await window.etpSubscribe(email, { pattern: SLUG[top], secondary: SLUG[second], source: 'quiz' });
    setSendState('idle');
    setSendResult(r.ok ? 'ok' : 'fail');
    setStep(gateStep + 1);
  };

  // Honest delivery banner - never claims an email was sent when it wasn't.
  const sentBanner = sendResult && (
    <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px', background: sendResult === 'ok' ? '#1a6b5a' : '#1c1c1c', color: '#f4f1eb', flexWrap: 'wrap', marginBottom: 8 }}>
      {sendResult === 'ok' ? (
        <><span className="label" style={{ color: '#d4883a' }}>✓ On the list</span><span style={{ fontSize: 14 }}>You're on the founding list as {email}. Here's your result -</span></>
      ) : (
        <><span className="label" style={{ color: '#d4883a' }}>Couldn't confirm</span><span style={{ fontSize: 14 }}>We couldn't confirm you joined the list - your result is here either way. If you want the founding invite, email endthepattern@outlook.com.</span></>
      )}
    </div>
  );

  const disclaimer = (
    <p style={{ fontSize: 13, lineHeight: 1.55, color: '#666', maxWidth: 620, marginTop: 40 }}>
      This result comes from a 12-question self-reflection. It is a map, not a diagnosis - community work that runs alongside therapy, never instead of it. If reading it stirred more than you expected: call or text <a href="tel:988" style={{ color: '#1a6b5a', fontWeight: 600 }}>988</a> (US) or see <a href="https://findahelpline.com" target="_blank" rel="noopener noreferrer" style={{ color: '#1a6b5a', fontWeight: 600 }}>findahelpline.com</a>. This site can wait.
    </p>
  );

  return (
    <div className="etp" style={{ width: '100%', minHeight: '100%', background: '#f4f1eb', display: 'flex', flexDirection: 'column' }}>
      {/* Progress bar */}
      <div style={{ borderBottom: '1px solid #1c1c1c', padding: '20px 56px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 32 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Mark size={24} color="#1a6b5a" />
          <Wordmark size={18} />
        </div>
        <div style={{ flex: 1, height: 4, background: '#d8c9a8', position: 'relative' }}>
          <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, background: '#d4883a', width: `${progress}%`, transition: 'width 0.3s ease' }} />
        </div>
        <div className="label" style={{ minWidth: 90, textAlign: 'right' }}>
          {step === 0 && 'Start'}
          {step > 0 && step <= total && `${step} / ${total}`}
          {step === calibStep && 'Last one'}
          {step === gateStep && 'Almost'}
          {atResult && 'Result'}
        </div>
        <SiteLink to="/" className="label" style={{ color: '#666', textDecoration: 'none' }}>Exit</SiteLink>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '48px 56px' }}>
        {step === 0 && (
          <div style={{ maxWidth: 840 }}>
            <div className="label" style={{ color: '#1a6b5a', marginBottom: 32 }}>● The Pattern Diagnostic - 12 questions, 90 seconds</div>
            <h1 style={{ fontSize: 'clamp(56px, 8vw, 120px)', lineHeight: 0.88, letterSpacing: '-0.025em', marginBottom: 32 }}>
              Which family<br/>pattern is<br/><span style={{ color: '#d4883a' }}>running you?</span>
            </h1>
            <p style={{ fontSize: 19, lineHeight: 1.5, marginBottom: 32, maxWidth: 580 }}>
              Twelve questions about the room you grew up in. Your answers map to one of five inherited survival strategies. Free - your result and printable 3-page dossier appear right here when you finish.
            </p>
            <p style={{ fontSize: 14, lineHeight: 1.5, marginBottom: 16, maxWidth: 540, color: '#666' }}>
              There are no right answers. There are only the answers that are true for you. Go quickly - first answers are usually less edited - and you can go back anytime.
            </p>
            <p style={{ fontSize: 13, lineHeight: 1.5, marginBottom: 40, maxWidth: 540, color: '#666' }}>
              This is a 12-question self-reflection, not a clinical instrument. A map, not a diagnosis.
            </p>
            <button onClick={() => setStep(1)} className="etp-btn etp-btn-orange" style={{ padding: '20px 32px', fontSize: 14 }}>Begin →</button>
          </div>
        )}

        {step > 0 && step <= total && (
          <div style={{ maxWidth: 920, margin: '0 auto', width: '100%' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 32 }}>
              <div className="label" style={{ color: '#1a6b5a' }}>Question {step} of {total}</div>
              {step > 1 && (
                <button onClick={back} className="label" style={{ background: 'none', border: 'none', color: '#666', cursor: 'pointer' }}>← Back</button>
              )}
            </div>
            <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 56px)', lineHeight: 0.98, letterSpacing: '-0.02em', marginBottom: 40 }}>
              {QUIZ[step - 1].q}
            </h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {QUIZ[step - 1].a.map((ans, i) => (
                <button
                  key={i}
                  onClick={() => select(ans.p)}
                  style={{
                    textAlign: 'left',
                    padding: '20px 28px',
                    background: '#ebe6db',
                    color: '#1c1c1c',
                    border: '1px solid #1c1c1c',
                    cursor: 'pointer',
                    fontSize: 17,
                    fontFamily: "'Instrument Sans', sans-serif",
                    transition: 'all 0.15s ease',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 20,
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = '#1c1c1c'; e.currentTarget.style.color = '#f4f1eb'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = '#ebe6db'; e.currentTarget.style.color = '#1c1c1c'; }}
                >
                  <span className="label" style={{ minWidth: 24, opacity: 0.6 }}>{String.fromCharCode(65 + i)}</span>
                  <span>{ans.t}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {step === calibStep && (
          <div style={{ maxWidth: 920, margin: '0 auto', width: '100%' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 32 }}>
              <div className="label" style={{ color: '#1a6b5a' }}>Last one - no scoring, just honesty</div>
              <button onClick={back} className="label" style={{ background: 'none', border: 'none', color: '#666', cursor: 'pointer' }}>← Back</button>
            </div>
            <h2 style={{ fontSize: 'clamp(32px, 4.5vw, 56px)', lineHeight: 0.98, letterSpacing: '-0.02em', marginBottom: 40 }}>
              How much did these questions land?
            </h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                ['very', 'Very - most of them named something real.'],
                ['somewhat', 'Somewhat - some landed, some didn\'t.'],
                ['not', 'Not really - I didn\'t recognize myself in these.'],
              ].map(([val, label], i) => (
                <button
                  key={val}
                  onClick={() => { setCalib(val); setStep(step + 1); }}
                  style={{
                    textAlign: 'left', padding: '20px 28px', background: '#ebe6db', color: '#1c1c1c',
                    border: '1px solid #1c1c1c', cursor: 'pointer', fontSize: 17,
                    fontFamily: "'Instrument Sans', sans-serif", transition: 'all 0.15s ease',
                    display: 'flex', alignItems: 'center', gap: 20,
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = '#1c1c1c'; e.currentTarget.style.color = '#f4f1eb'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = '#ebe6db'; e.currentTarget.style.color = '#1c1c1c'; }}
                >
                  <span className="label" style={{ minWidth: 24, opacity: 0.6 }}>{String.fromCharCode(65 + i)}</span>
                  <span>{label}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {step === gateStep && (
          <div style={{ maxWidth: 720, margin: '0 auto', width: '100%' }}>
            <div className="label" style={{ color: '#1a6b5a', marginBottom: 24 }}>● Your result is ready</div>
            <h1 style={{ fontSize: 'clamp(48px, 6.5vw, 96px)', lineHeight: 0.9, letterSpacing: '-0.025em', marginBottom: 24 }}>
              Your pattern<br/><span style={{ color: '#d4883a' }}>is ready.</span>
            </h1>
            <p style={{ fontSize: 18, lineHeight: 1.5, marginBottom: 32, maxWidth: 560 }}>
              Enter your email to see it - your result and printable dossier appear right here, and you'll get your founding invite the moment doors open.
            </p>
            <form onSubmit={submitGate} style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 20, maxWidth: 560 }}>
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" required style={{ flex: 1, minWidth: 240, padding: '18px 20px', background: '#fff', border: '1px solid #1c1c1c', color: '#1c1c1c', fontSize: 17, fontFamily: 'inherit' }} />
              <button type="submit" disabled={!emailValid || sendState === 'sending'} className="etp-btn etp-btn-orange" style={{ padding: '18px 28px', fontSize: 14, opacity: emailValid && sendState !== 'sending' ? 1 : 0.5 }}>{sendState === 'sending' ? 'One moment…' : 'Show my result →'}</button>
            </form>
            <p style={{ fontSize: 13, lineHeight: 1.5, color: '#666', maxWidth: 560 }}>
              What arrives by email: one invite when founding doors open, and the occasional letter while we build. That's the list. One unsubscribe ends everything. We never sell your data.
            </p>
            <button onClick={() => setStep(calibStep)} className="label" style={{ background: 'none', border: 'none', color: '#666', cursor: 'pointer', marginTop: 24, padding: 0 }}>← Back</button>
          </div>
        )}

        {atResult && calib === 'not' && (
          <div style={{ maxWidth: 760, margin: '0 auto', width: '100%' }}>
            {sentBanner}
            <div className="label" style={{ color: '#1a6b5a', marginBottom: 24 }}>● An honest result</div>
            <h1 style={{ fontSize: 'clamp(48px, 6.5vw, 96px)', lineHeight: 0.9, letterSpacing: '-0.025em', marginBottom: 24 }}>
              Nothing landed<br/><span style={{ color: '#d4883a' }}>cleanly.</span>
            </h1>
            <p style={{ fontSize: 19, lineHeight: 1.55, marginBottom: 16, maxWidth: 620 }}>
              That's a real answer, not a failure. This might not be your work right now - or your pattern might live outside these five. A quiz that can't say "not you" wouldn't mean much when it says "you."
            </p>
            <p style={{ fontSize: 16, lineHeight: 1.6, marginBottom: 40, maxWidth: 620, color: '#333' }}>
              If you're curious anyway, the closest match from your answers was <strong>{result.name}</strong> - read it and see. Or come back when something rings.
            </p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button onClick={() => setCalib('somewhat')} className="etp-btn etp-btn-orange">Show me the closest match →</button>
              <SiteLink to="/patterns" className="etp-btn etp-btn-ghost" style={{ textDecoration: 'none' }}>Browse all five patterns</SiteLink>
              <button onClick={reset} className="etp-btn etp-btn-ghost">Retake</button>
            </div>
            {disclaimer}
          </div>
        )}

        {atResult && calib !== 'not' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 48, alignItems: 'flex-start', maxWidth: 1400, width: '100%', margin: '0 auto' }}>
            {sentBanner}
            {/* Result narrative */}
            <div>
              <div className="label" style={{ color: '#1a6b5a', marginBottom: 24 }}>● Your dominant pattern</div>
              <h1 style={{ fontSize: 'clamp(56px, 7vw, 104px)', lineHeight: 0.86, letterSpacing: '-0.03em', marginBottom: 24 }}>
                {result.name.split(' ')[0]}<br/><span style={{ color: '#d4883a' }}>{result.name.split(' ').slice(1).join(' ')}.</span>
              </h1>
              <p style={{ fontSize: 22, lineHeight: 1.35, marginBottom: 24, maxWidth: 560, fontWeight: 500 }}>
                {result.short}
              </p>
              {nearTie && (
                <p style={{ fontSize: 15, lineHeight: 1.55, marginBottom: 24, maxWidth: 560, color: '#1a6b5a', fontWeight: 500 }}>
                  You're carrying two patterns in almost equal measure - {PATTERNS[top].name} and {PATTERNS[second].name}. We show {PATTERNS[top].name.replace('The ', 'the ')} first; your dossier covers both.
                </p>
              )}
              <p style={{ fontSize: 16, lineHeight: 1.6, marginBottom: 32, maxWidth: 560 }}>
                {result.long}
              </p>

              <p style={{ fontSize: 15, lineHeight: 1.6, marginBottom: 16, maxWidth: 560, color: '#1a6b5a', fontWeight: 500 }}>
                This pattern is not a flaw. It's the intelligence of a kid who solved an impossible room - and it worked. That's why it's still running.
              </p>
              <div className="label" style={{ color: '#1a6b5a', marginBottom: 12 }}>What it costs you</div>
              <ul style={{ listStyle: 'none', padding: 0, marginBottom: 40 }}>
                {result.costs.map((c, i) => (
                  <li key={i} style={{ display: 'flex', gap: 16, padding: '14px 0', borderBottom: '1px solid #d8c9a8', fontSize: 16, lineHeight: 1.5 }}>
                    <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 12, color: '#1a6b5a', paddingTop: 2 }}>0{i + 1}</span>
                    <span>{c}</span>
                  </li>
                ))}
              </ul>

              <div className="label" style={{ color: '#1a6b5a', marginBottom: 12 }}>The work</div>
              <p style={{ fontSize: 16, lineHeight: 1.55, marginBottom: 32, maxWidth: 560 }}>{result.work}</p>

              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <a href={`Dossier.html?pattern=${SLUG[top]}&secondary=${SLUG[second]}`} target="_blank" rel="noopener" className="etp-btn etp-btn-orange" style={{ textDecoration: 'none' }}>Download your dossier ↓</a>
                <button onClick={() => goJoin(top)} className="etp-btn etp-btn-ghost">Reserve a founding seat →</button>
                <button onClick={reset} className="etp-btn etp-btn-ghost">Retake</button>
              </div>
              {disclaimer}
            </div>

            {/* Breakdown + email exchange */}
            <aside style={{ background: '#1c1c1c', color: '#f4f1eb', padding: '36px 32px', border: '1px solid #1c1c1c', position: 'sticky', top: 80 }}>
              <div className="label" style={{ color: '#d4883a', marginBottom: 24 }}>Your full breakdown</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 18, marginBottom: 32 }}>
                {sorted.map(([key, val]) => {
                  const isTop = key === top;
                  return (
                    <div key={key}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                        <span style={{ fontWeight: isTop ? 700 : 500, fontSize: 15, color: isTop ? '#d4883a' : '#f4f1eb' }}>{PATTERNS[key].name}</span>
                        <span className="label" style={{ color: isTop ? '#d4883a' : '#f4f1eb', opacity: isTop ? 1 : 0.7 }}>{isTop ? 'Dominant' : band(val)}</span>
                      </div>
                      <div style={{ height: 4, background: '#444' }}>
                        <div style={{ width: `${Math.round((val / total) * 100)}%`, height: '100%', background: isTop ? '#d4883a' : '#1a6b5a', transition: 'width 0.4s ease' }} />
                      </div>
                    </div>
                  );
                })}
              </div>

              <div style={{ paddingTop: 20, borderTop: '1px solid #444', marginBottom: 24 }}>
                <div className="label" style={{ color: '#d4883a', marginBottom: 12 }}>Most likely secondary</div>
                <div style={{ fontWeight: 700, fontSize: 22, lineHeight: 1, textTransform: 'uppercase', marginBottom: 8 }}>{PATTERNS[second].name}</div>
                <p style={{ fontSize: 13, lineHeight: 1.5, opacity: 0.8 }}>
                  Most pattern breakers carry two. We work the dominant one first - the curriculum addresses both.
                </p>
              </div>

              <div onClick={() => goJoin(top)} style={{ paddingTop: 0, marginTop: 4, padding: '14px 16px', background: '#1a6b5a', color: '#f4f1eb', cursor: 'pointer' }}>
                <div className="label" style={{ color: '#d4883a', marginBottom: 4 }}>● Founding 500 →</div>
                <div style={{ fontSize: 13, lineHeight: 1.45 }}>$24/mo for life for the first 500 members. Reserving costs nothing today - doors open soon.</div>
              </div>
            </aside>
          </div>
        )}
      </div>
    </div>
  );
};

window.QuizArtboard = QuizArtboard;
