// menove-quiz.jsx, the Assessment. Full Greene Climacteric Scale (21 items),
// answers as stones, result as a quiet written read: where you are on the trail.
// Loads after: menove-final (FB, fbTint), menove-site-shared (SiteWordmark),
// menove-v2-core (V2Nav, V2CTA, V2Cairn), menove-v2-sections (V2Finale).

const QZ_ITEMS = [
  { q: 'Your heart beating quickly or strongly', d: 'mind' },
  { q: 'Feeling tense or nervous', d: 'mind' },
  { q: 'Difficulty in sleeping', d: 'mind' },
  { q: 'Feeling excitable', d: 'mind' },
  { q: 'Attacks of anxiety or panic', d: 'mind' },
  { q: 'Difficulty in concentrating', d: 'mind' },
  { q: 'Feeling tired or lacking in energy', d: 'mood' },
  { q: 'Loss of interest in most things', d: 'mood' },
  { q: 'Feeling unhappy or depressed', d: 'mood' },
  { q: 'Crying spells', d: 'mood' },
  { q: 'Irritability', d: 'mood' },
  { q: 'Feeling dizzy or faint', d: 'body' },
  { q: 'Pressure or tightness in your head or body', d: 'body' },
  { q: 'Parts of your body feeling numb or tingling', d: 'body' },
  { q: 'Headaches', d: 'body' },
  { q: 'Muscle and joint pains', d: 'body' },
  { q: 'Loss of feeling in your hands or feet', d: 'body' },
  { q: 'Breathing difficulties', d: 'body' },
  { q: 'Hot flushes', d: 'heat' },
  { q: 'Sweating at night', d: 'heat' },
  { q: 'Loss of interest in sex', d: 'desire' },
];

const QZ_DOMAINS = { mind: 'the mind', mood: 'mood', body: 'the body', heat: 'heat', desire: 'desire' };

const QZ_ANSWERS = [
  { v: 0, l: 'Not at all' },
  { v: 1, l: 'A little' },
  { v: 2, l: 'Quite a bit' },
  { v: 3, l: 'Extremely' },
];

const QZ_SHAPES = [
  '50% 50% 50% 50% / 56% 56% 44% 44%',
  '54% 46% 52% 48% / 58% 56% 44% 42%',
  '66% 34% 56% 44% / 62% 74% 26% 38%',
  '58% 42% 56% 44% / 70% 66% 34% 30%',
];

/* an answer, as a stone that grows with weight */
function QZStone({ v, selected, idx }) {
  const sizes = [[26, 18], [34, 23], [44, 29], [56, 36]];
  const [w, h] = sizes[v];
  const fills = [
    { background: 'transparent', boxShadow: `inset 0 0 0 1.6px ${FB.aub}` },
    { background: fbTint(FB.iris, .55) },
    { background: fbTint(FB.aub, .45) },
    { background: FB.aub },
  ];
  return (
    <span style={{
      display: 'block', width: w, height: h, borderRadius: QZ_SHAPES[idx % 4],
      transform: `rotate(${idx % 2 ? -5 : 4}deg) scale(${selected ? 1.12 : 1})`,
      transition: 'transform .25s ease, box-shadow .25s ease',
      ...fills[v],
      ...(selected ? { boxShadow: `${fills[v].boxShadow || 'inset 0 0 0 0 transparent'}, 0 0 0 5px ${fbTint(FB.iris, .35)}` } : {}),
    }}></span>
  );
}

/* the trail of 21 across the top */
function QZTrail({ answers, current }) {
  return (
    <div style={{ display: 'flex', gap: 7, alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap', maxWidth: 560 }}>
      {QZ_ITEMS.map((_, i) => {
        const done = answers[i] != null;
        const cur = i === current;
        return (
          <span key={i} style={{
            width: cur ? 15 : 11, height: cur ? 10 : 7.5,
            borderRadius: QZ_SHAPES[i % 4],
            background: done ? FB.aub : 'transparent',
            boxShadow: done ? 'none' : `inset 0 0 0 1.3px ${cur ? FB.aub : fbTint(FB.ink, .3)}`,
            transform: `rotate(${i % 2 ? -6 : 5}deg)`,
            transition: 'all .3s ease',
          }}></span>
        );
      })}
    </div>
  );
}

function QZResult({ answers, onRetake }) {
  const total = answers.reduce((a, b) => a + (b || 0), 0);
  const byDomain = {};
  QZ_ITEMS.forEach((it, i) => {
    byDomain[it.d] = byDomain[it.d] || { sum: 0, n: 0 };
    byDomain[it.d].sum += answers[i] || 0; byDomain[it.d].n += 1;
  });
  const loudest = Object.entries(byDomain).map(([d, { sum, n }]) => ({ d, avg: sum / n })).sort((a, b) => b.avg - a.avg)[0];
  const speaking = loudest.avg >= 1 ? QZ_DOMAINS[loudest.d] : null;

  const band = total <= 11 ? {
    tt: 'A mostly level stretch.',
    body: 'Your days are carrying you without much argument right now. That is worth knowing as surely as the harder seasons are; a quiet baseline is the thing every later pattern gets measured against.',
  } : total <= 22 ? {
    tt: 'The trail has begun to climb.',
    body: 'Something is asking for your attention. Not loudly, but often enough to name. This is the stretch where a kept record matters most: changes this size are easy to dismiss from memory and hard to dismiss on paper.',
  } : total <= 33 ? {
    tt: 'You\u2019re on a steep stretch.',
    body: 'What you\u2019re carrying is real, and it\u2019s more than one thing. Days like these deserve better than being re-narrated from memory in a twelve-minute appointment. Start the record; let it do the arguing.',
  } : {
    tt: 'You\u2019re carrying a great deal.',
    body: 'This read says plainly what you may already know: it\u2019s heavy right now. None of it is in your head, and none of it has to be carried unwitnessed. Bring this to someone who can help, and bring a record with you.',
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', maxWidth: 620 }}>
      <div style={{ fontFamily: FB.sans, fontSize: 11.5, letterSpacing: '.32em', textTransform: 'uppercase', fontWeight: 700, color: FB.plum }}>Where you are on the trail</div>
      <div style={{ margin: '26px 0 0' }}><V2Cairn variant="aubergine" size={.5} /></div>
      <h2 style={{ fontFamily: FB.display, fontWeight: 400, fontSize: 'clamp(30px, 4vw, 46px)', lineHeight: 1.12, margin: '26px 0 0', color: FB.ink, textWrap: 'balance' }}>{band.tt}</h2>
      <p style={{ fontFamily: FB.sans, fontSize: 15, lineHeight: 1.75, color: FB.body, margin: '18px 0 0' }}>{band.body}</p>
      {speaking ? (
        <p style={{ fontFamily: FB.display, fontSize: 17, lineHeight: 1.6, color: FB.ink, margin: '14px 0 0' }}>
          Of the five areas, <em>{speaking}</em> is speaking loudest in your answers.
        </p>
      ) : null}
      <div style={{ margin: '30px 0 0' }}><V2CTA big href="/#beta">Request beta access</V2CTA></div>
      <div style={{ display: 'flex', gap: 22, marginTop: 18, fontFamily: FB.sans, fontSize: 12.5, fontWeight: 600 }}>
        <span onClick={onRetake} style={{ color: FB.body, borderBottom: `1.3px solid ${FB.line}`, paddingBottom: 1, cursor: 'pointer' }}>Take it again</span>
      </div>
      <p style={{ fontFamily: FB.sans, fontSize: 11, lineHeight: 1.6, color: FB.soft, margin: '26px 0 0', maxWidth: 460 }}>
        Based on the Greene Climacteric Scale. For information only; this is not a diagnosis, and it never replaces a conversation with your clinician.
      </p>
    </div>
  );
}

function QuizPage() {
  const KEY = 'menove-quiz-v1';
  const saved = (() => { try { return JSON.parse(localStorage.getItem(KEY)) || {}; } catch (e) { return {}; } })();
  const [stage, setStage] = React.useState(saved.stage || 'intro'); // intro | quiz | result
  const [answers, setAnswers] = React.useState(saved.answers || Array(21).fill(null));
  const [current, setCurrent] = React.useState(saved.current || 0);
  const mobile = window.innerWidth < 760;

  React.useEffect(() => {
    try { localStorage.setItem(KEY, JSON.stringify({ stage, answers, current })); } catch (e) {}
  }, [stage, answers, current]);

  const pick = (v) => {
    const next = answers.slice(); next[current] = v;
    setAnswers(next);
    setTimeout(() => {
      if (current < 20) setCurrent(current + 1);
      else setStage('result');
    }, 340);
  };
  const retake = () => { setAnswers(Array(21).fill(null)); setCurrent(0); setStage('intro'); };

  const item = QZ_ITEMS[current];
  return (
    <div style={{ minHeight: '100vh', background: FB.paper, display: 'flex', flexDirection: 'column' }}>
      <V2Nav dark={false} mobile={mobile} page="Assessment" ctaHref="/#beta" />
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: mobile ? '110px 22px 60px' : '120px 54px 60px' }}>

        {stage === 'intro' && (
          <div style={{ display: 'flex', flexDirection: mobile ? 'column' : 'row', alignItems: 'center', gap: mobile ? 34 : '6vw', maxWidth: 1080 }}>
            <div style={{ flex: 1.1 }}>
              <div style={{ fontFamily: FB.sans, fontSize: 11.5, letterSpacing: '.32em', textTransform: 'uppercase', fontWeight: 700, color: FB.plum }}>The assessment · 21 questions</div>
              <h1 style={{ fontFamily: FB.display, fontWeight: 400, fontSize: 'clamp(34px, 4.6vw, 58px)', lineHeight: 1.08, margin: '18px 0 0', color: FB.ink, textWrap: 'balance' }}>
                Where are you on the trail?
              </h1>
              <p style={{ fontFamily: FB.sans, fontSize: 15, lineHeight: 1.75, color: FB.body, margin: '20px 0 0', maxWidth: 520 }}>
                Twenty-one questions, drawn from the Greene Climacteric Scale, the same check-in clinicians have used for decades. It covers the mind, mood, the body, heat, and desire. About five minutes; each answer is a stone.
              </p>
              <div style={{ margin: '28px 0 0', display: 'flex', alignItems: 'center', gap: 18 }}>
                <V2CTA big onClick={() => setStage('quiz')}>Begin</V2CTA>
              </div>
              <p style={{ fontFamily: FB.sans, fontSize: 11, lineHeight: 1.6, color: FB.soft, margin: '22px 0 0', maxWidth: 440 }}>
                For information only, not medical advice, and nothing here is stored or sent anywhere. It stays on this device.
              </p>
            </div>
            {!mobile && (
              <div style={{ flex: 1, borderRadius: 22, overflow: 'hidden', height: 'min(54vh, 480px)' }}>
                <img src={V2A('photos/pages-quiz-stone.jpg')} alt="A stone resting in an open palm" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </div>
            )}
          </div>
        )}

        {stage === 'quiz' && (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'min(5vh, 44px)', width: '100%', maxWidth: 760 }}>
            <QZTrail answers={answers} current={current} />
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: FB.sans, fontSize: 11, letterSpacing: '.26em', textTransform: 'uppercase', fontWeight: 700, color: FB.soft }}>
                {current + 1} of 21 · {QZ_DOMAINS[item.d]}
              </div>
              <h2 style={{ fontFamily: FB.display, fontWeight: 400, fontSize: 'clamp(26px, 3.4vw, 42px)', lineHeight: 1.18, margin: '16px 0 0', color: FB.ink, textWrap: 'balance', maxWidth: 640 }}>
                {item.q}, how much has it troubled you lately?
              </h2>
            </div>
            <div style={{ display: 'flex', gap: mobile ? 18 : 40, alignItems: 'flex-end' }}>
              {QZ_ANSWERS.map((a, i) => (
                <div key={a.v} onClick={() => pick(a.v)} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 13, cursor: 'pointer', minWidth: 70 }}>
                  <div style={{ height: 40, display: 'flex', alignItems: 'flex-end' }}><QZStone v={a.v} idx={current + i} selected={answers[current] === a.v} /></div>
                  <span style={{ fontFamily: FB.sans, fontSize: 12, fontWeight: 700, color: answers[current] === a.v ? FB.ink : FB.body, whiteSpace: 'nowrap' }}>{a.l}</span>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 26, fontFamily: FB.sans, fontSize: 12.5, fontWeight: 600, minHeight: 18 }}>
              {current > 0 && <span onClick={() => setCurrent(current - 1)} style={{ color: FB.body, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 12 }}><path d="M19 12H5M11 18l-6-6 6-6" /></svg>
                Previous
              </span>}
              {answers[current] != null && current < 20 && <span onClick={() => setCurrent(current + 1)} style={{ color: FB.body, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                Next
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 12 }}><path d="M5 12h14M13 6l6 6-6 6" /></svg>
              </span>}
            </div>
          </div>
        )}

        {stage === 'result' && <QZResult answers={answers} onRetake={retake} />}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<QuizPage />);
