// ============================================================
// pages-quiz.jsx — Conversational quiz, 9 real questions
// ============================================================

// Quiz questions with dosha weights
const QUIZ_Q = [
  {
    id: 'q1', prompt: 'What is your primary hair or scalp concern?',
    options: [
      ['Dryness, frizz, or brittle hair',             { vata: 2, pitta: 0, kapha: 0 }],
      ['Thinning hair or premature greying',          { vata: 0, pitta: 2, kapha: 0 }],
      ['Excessive oiliness or heavy hair',            { vata: 0, pitta: 0, kapha: 2 }],
      ['Persistent dandruff and itching',             { vata: 1, pitta: 1, kapha: 0 }],
    ],
  },
  {
    id: 'q2', prompt: 'What is your natural hair texture without any products?',
    options: [
      ['Dry, rough, or curly and frizzy',             { vata: 2 }],
      ['Fine, soft, straight — gets oily quickly',   { pitta: 2 }],
      ['Thick, strong, naturally shiny or wavy',      { kapha: 2 }],
    ],
  },
  {
    id: 'q3', prompt: 'How does your scalp feel 48 hours after washing?',
    options: [
      ['Very dry, tight, or flaky',                   { vata: 2 }],
      ['Oily, hot, or sensitive',                     { pitta: 2 }],
      ['Greasy, heavy, or sticky',                    { kapha: 2 }],
    ],
  },
  {
    id: 'q4', prompt: 'Which environment makes you most uncomfortable?',
    options: [
      ['Cold and dry — skin and hair feel parched',   { vata: 2 }],
      ['Hot and humid — sweating and irritation',     { pitta: 2 }],
      ['Cold and damp — heavy or congested feeling',  { kapha: 2 }],
    ],
  },
  {
    id: 'q5', prompt: 'How would you describe your digestion and appetite?',
    options: [
      ['Irregular — I bloat easily or forget to eat', { vata: 2 }],
      ['Strong and intense — I get irritable if I skip meals', { pitta: 2 }],
      ['Slow and steady — I can skip meals without much trouble', { kapha: 2 }],
    ],
  },
  {
    id: 'q6', prompt: 'How are your sleep and energy levels?',
    options: [
      ['Light sleeper — mind tends to race at night', { vata: 2 }],
      ['Moderate — focused but irritable when tired', { pitta: 2 }],
      ['Deep sleeper — heavy feeling, hard to wake',  { kapha: 2 }],
    ],
  },
  {
    id: 'q7', prompt: 'If you have dandruff, how would you describe it?',
    options: [
      ['Small, white, dry flakes that fall onto clothing', { vata: 2 }],
      ['Red patches or a burning sensation on the scalp',  { pitta: 2 }],
      ['Yellowish, sticky flakes that cling to the scalp', { kapha: 2 }],
      ['I do not have dandruff',                           {} ],
    ],
  },
  {
    id: 'q8', prompt: 'When do you notice hair fall the most?',
    options: [
      ['While combing — hair feels brittle and snaps',  { vata: 2 }],
      ['During washing — visible clumps in the drain',  { pitta: 1, vata: 1 }],
      ['On the pillow in the morning',                  { kapha: 2 }],
      ['General thinning across the entire scalp',      { pitta: 2 }],
    ],
  },
  {
    id: 'q9', prompt: 'How often do you experience mental stress or anxiety?',
    options: [
      ['Often — I feel overwhelmed or anxious regularly', { vata: 2 }],
      ['Occasionally — usually around work or deadlines', { pitta: 2 }],
      ['Rarely — I tend to stay relatively calm',         { kapha: 2 }],
    ],
  },
];

function Quiz({ onNav, setResult }) {
  const { t } = useLang();
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState([]);
  const [typing, setTyping] = useState(true);
  const scrollRef = useRef(null);

  const totalSteps = QUIZ_Q.length;
  const progress = (answers.length / totalSteps) * 100;
  const current = QUIZ_Q[step];

  useEffect(() => {
    setTyping(true);
    const timer = setTimeout(() => setTyping(false), 650);
    return () => clearTimeout(timer);
  }, [step]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [answers, typing]);

  const pick = (optIdx) => {
    const [label, weights] = current.options[optIdx];
    const next = [...answers, { qIdx: step, optIdx, label, weights }];
    setAnswers(next);
    if (step + 1 >= totalSteps) {
      const totals = { vata: 0, pitta: 0, kapha: 0 };
      next.forEach(a => {
        for (const k of Object.keys(a.weights || {})) totals[k] = (totals[k] || 0) + a.weights[k];
      });
      const sum = totals.vata + totals.pitta + totals.kapha || 1;
      const pct = {
        vata: Math.round((totals.vata / sum) * 100),
        pitta: Math.round((totals.pitta / sum) * 100),
        kapha: Math.round((totals.kapha / sum) * 100),
      };
      const winner = Object.entries(totals).sort((a, b) => b[1] - a[1])[0][0];
      setResult({ winner, totals, pct });
      return;
    }
    setStep(step + 1);
  };

  const restart = () => { setAnswers([]); setStep(0); setResult(null); };

  return (
    <section className="section page">
      <div className="quiz-shell">
        <div className="quiz-head">
          <span>{t('quiz_header')}</span>
          <span>Q {Math.min(step + 1, totalSteps)} / {totalSteps}</span>
        </div>
        <div className="progress"><div style={{ width: progress + '%' }}/></div>

        <div className="quiz-card" style={{ marginTop: 20, minHeight: 420 }} ref={scrollRef}>
          {answers.map((a, i) => (
            <React.Fragment key={i}>
              <div className="bubble">
                <span className="who">{t('quiz_who_prakriti')}</span>
                {QUIZ_Q[a.qIdx].prompt}
              </div>
              <div className="bubble user">
                <span className="who">{t('quiz_who_you')}</span>
                {a.label}
              </div>
            </React.Fragment>
          ))}

          {step < totalSteps && (
            typing ? (
              <div className="bubble">
                <span className="who">{t('quiz_who_thinking')}</span>
                <div className="typing"><span/><span/><span/></div>
              </div>
            ) : (
              <>
                <div className="bubble">
                  <span className="who">{t('quiz_who_prakriti')}</span>
                  {current.prompt}
                </div>
                <div className="options">
                  {current.options.map(([label], i) => (
                    <button key={i} className="opt" onClick={() => pick(i)}>{label}</button>
                  ))}
                </div>
              </>
            )
          )}
        </div>

        <div className="flex" style={{ justifyContent: 'space-between', marginTop: 12 }}>
          <button className="btn ghost" onClick={restart} style={{ padding: '8px 14px', fontSize: 13 }}>{t('quiz_restart')}</button>
        </div>
      </div>
    </section>
  );
}

function QuizIntro({ onStart }) {
  const { t } = useLang();
  return (
    <section className="page hero" style={{ paddingBottom: 48 }}>
      <Pill>{t('quiz_intro_pill')}</Pill>
      <h1 className="h-display" style={{ marginTop: 16 }}>
        {t('quiz_intro_h1')}<br/><em className="accent">{t('quiz_intro_h1_em')}</em>
      </h1>
      <p className="deck">{t('quiz_intro_desc')}</p>
      <div className="flex" style={{ marginTop: 32 }}>
        <button className="btn accent" onClick={onStart}>{t('quiz_intro_btn')} <span className="arrow">→</span></button>
        <span className="mono">{t('quiz_intro_time')}</span>
      </div>
    </section>
  );
}

function ContactCapture({ result, onNav, onRetake }) {
  const { t } = useLang();
  const winner = result.winner;
  const colorMap = { vata: 'var(--vata)', pitta: 'var(--pitta)', kapha: 'var(--kapha)' };
  const color = colorMap[winner];
  const [form, setForm] = React.useState({ name: '', email: '', phone: '' });
  const [status, setStatus] = React.useState('idle');
  const [errors, setErrors] = React.useState({});
  const update = (k) => (e) => { setForm(f => ({ ...f, [k]: e.target.value })); setErrors(er => ({ ...er, [k]: '' })); };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = t('err_required');
    if (!form.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = t('err_email');
    if (!form.phone.trim() || !/^[+\d\s\-()]{7,15}$/.test(form.phone.trim())) e.phone = t('err_phone');
    return e;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setStatus('sending');
    emailjs.send('service_tz3fb2h', 'template_1xv3bqj', {
      to_email: 'kudeshiyah@gmail.com',
      from_name: form.name,
      from_email: form.email,
      phone: form.phone,
      dosha: winner,
      vata_pct: result.pct.vata,
      pitta_pct: result.pct.pitta,
      kapha_pct: result.pct.kapha,
    }).then(() => setStatus('done')).catch(() => setStatus('error'));
  };

  if (status === 'done') {
    return (
      <section className="section page" style={{ minHeight: '40vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center', maxWidth: 480 }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>🙏</div>
          <h2 className="h-section" style={{ marginBottom: 12 }}>{t('contact_done_title')}</h2>
          <p style={{ color: 'var(--ink-2)', marginBottom: 32 }}>{t('contact_done_sub')}</p>
          <div className="flex" style={{ justifyContent: 'center', gap: 12 }}>
            <button className="btn" onClick={() => onNav(winner)}>{t('contact_read')} {winner.charAt(0).toUpperCase() + winner.slice(1)} →</button>
            <button className="btn ghost" onClick={onRetake}>{t('contact_retake2')}</button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="section page">
      <div style={{ background: color, borderRadius: 16, padding: 'clamp(32px, 5vw, 56px)', maxWidth: 560, margin: '0 auto' }}>
        <Pill variant="dark">{t('contact_pill')}</Pill>
        <h2 className="h-section" style={{ color: 'var(--paper)', fontSize: 'clamp(28px, 4vw, 44px)', marginTop: 16, maxWidth: '20ch' }}>
          {t('contact_h2_1')} <em style={{ fontStyle: 'italic' }}>{t('contact_h2_2')} {winner.charAt(0).toUpperCase() + winner.slice(1)} {t('contact_h2_3')}</em>
        </h2>
        <p style={{ color: 'rgba(255,255,255,0.85)', marginTop: 12, marginBottom: 28 }}>{t('contact_sub')}</p>
        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div>
            <label style={{ color: 'rgba(255,255,255,0.7)', fontSize: 12, display: 'block', marginBottom: 4 }}>{t('contact_name')} <span style={{ color: '#ffb3b3' }}>*</span></label>
            <input type="text" placeholder={t('contact_name_ph')} value={form.name} onChange={update('name')} className={`contact-input${errors.name ? ' contact-input-error' : ''}`} />
            {errors.name && <div style={{ color: '#ffb3b3', fontSize: 12, marginTop: 3 }}>{errors.name}</div>}
          </div>
          <div>
            <label style={{ color: 'rgba(255,255,255,0.7)', fontSize: 12, display: 'block', marginBottom: 4 }}>{t('contact_email')} <span style={{ color: '#ffb3b3' }}>*</span></label>
            <input type="email" placeholder={t('contact_email_ph')} value={form.email} onChange={update('email')} className={`contact-input${errors.email ? ' contact-input-error' : ''}`} />
            {errors.email && <div style={{ color: '#ffb3b3', fontSize: 12, marginTop: 3 }}>{errors.email}</div>}
          </div>
          <div>
            <label style={{ color: 'rgba(255,255,255,0.7)', fontSize: 12, display: 'block', marginBottom: 4 }}>{t('contact_whatsapp')} <span style={{ color: '#ffb3b3' }}>*</span></label>
            <input type="tel" placeholder="+91 ..." value={form.phone} onChange={update('phone')} className={`contact-input${errors.phone ? ' contact-input-error' : ''}`} />
            {errors.phone && <div style={{ color: '#ffb3b3', fontSize: 12, marginTop: 3 }}>{errors.phone}</div>}
          </div>
          <button className="btn" type="submit" disabled={status === 'sending'} style={{ background: 'var(--paper)', color: 'var(--ink)', marginTop: 8 }}>
            {status === 'sending' ? t('contact_sending') : t('contact_submit')}
          </button>
          {status === 'error' && (
            <p style={{ color: 'rgba(255,255,255,0.9)', fontSize: 14, textAlign: 'center' }}>{t('contact_error')}</p>
          )}
        </form>
        <button onClick={onRetake} style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.6)', cursor: 'pointer', fontSize: 13, marginTop: 16, display: 'block' }}>
          {t('contact_retake')}
        </button>
      </div>
    </section>
  );
}

function QuizResult({ result, onNav, onRetake }) {
  const { t } = useLang();
  const winner = result.winner;
  const d = DOSHA_DATA[winner];
  const colorMap = { vata: 'var(--vata)', pitta: 'var(--pitta)', kapha: 'var(--kapha)' };
  const [showContact, setShowContact] = React.useState(false);

  if (showContact) {
    return <ContactCapture result={result} onNav={onNav} onRetake={onRetake} />;
  }

  return (
    <>
      <section className="page" style={{ padding: '56px 32px 24px' }}>
        <Pill variant="accent">{t('result_pill')}</Pill>
      </section>
      <section className="page">
        <div className="result-hero">
          <div>
            <div className="eyebrow">{t('result_your_prakriti')}</div>
            <div className="big-dosha" style={{ color: colorMap[winner] }}>{d.name}</div>
            <p style={{ fontSize: 18, color: 'var(--ink-2)', marginTop: 20, maxWidth: '44ch' }}>{d.desc}</p>
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>{t('result_distribution')}</div>
            <div className="result-dist">
              {['vata', 'pitta', 'kapha'].map(k => (
                <div className="bar" key={k}>
                  <span style={{ fontFamily: 'var(--f-display)', fontSize: 18, textTransform: 'capitalize' }}>{k}</span>
                  <div className="track"><div className="fill" style={{ width: result.pct[k] + '%', background: colorMap[k] }}/></div>
                  <span className="mono">{result.pct[k]}%</span>
                </div>
              ))}
            </div>
            <p className="muted" style={{ marginTop: 24, fontSize: 13 }}>{t('result_dual_note')}</p>
          </div>
        </div>
      </section>

      <section className="section tint page">
        <SectionHead eyebrow={t('result_root_eyebrow')} title={<>{t('result_root_title')} <em className="accent" style={{ color: colorMap[winner] }}>{d.name}</em> {t('result_root_title2')}</>}>
          {d.rootCause}
        </SectionHead>
        <div className="grid-2">
          {d.problems.slice(0, 2).map(([h, p]) => (
            <div key={h} className="card">
              <div className="k">{t('result_common_in')} {d.name}</div>
              <div className="h">{h}</div>
              <p>{p}</p>
            </div>
          ))}
        </div>
      </section>

      <section className="section page">
        <div style={{ background: colorMap[winner], color: 'var(--paper)', borderRadius: 16, padding: 'clamp(32px, 5vw, 64px)' }}>
          <Pill variant="dark">{d.available ? t('result_available_pill') : t('result_launches_pill') + ' ' + d.launch}</Pill>
          <h2 className="h-section" style={{ fontSize: 'clamp(36px, 5vw, 60px)', color: 'var(--paper)', marginTop: 16, maxWidth: '18ch' }}>
            {d.available
              ? <>Your {d.name} Kit <em style={{ fontStyle: 'italic' }}>{t('result_kit_ready')}</em></>
              : <>{d.name} {t('result_kit_launches')} <em style={{ fontStyle: 'italic' }}>{d.launch}.</em></>}
          </h2>
          <p style={{ color: 'rgba(255,255,255,0.85)', marginTop: 18, maxWidth: '54ch' }}>
            {d.available
              ? `${t('result_kits_limit')} ${d.name} ${t('result_kits_limit2')}`
              : t('result_waitlist_msg')}
          </p>
          <div className="flex" style={{ marginTop: 28 }}>
            <button className="btn" style={{ background: 'var(--paper)', color: 'var(--ink)' }} onClick={() => setShowContact(true)}>
              {d.available ? t('result_apply') : t('result_join_waitlist')} <span className="arrow">→</span>
            </button>
            <button className="btn ghost" style={{ borderColor: 'var(--paper)', color: 'var(--paper)' }} onClick={() => onNav(winner)}>
              {t('result_read_about')} {d.name} →
            </button>
          </div>
        </div>
      </section>

      <section className="section page">
        <div className="flex-between">
          <span className="mono">{t('result_not_right')}</span>
          <button className="btn ghost" onClick={onRetake}>{t('result_retake_btn')}</button>
        </div>
      </section>
    </>
  );
}

function QuizPage({ onNav }) {
  const [stage, setStage] = useState('quiz'); // intro | quiz | result
  const [result, setResult] = useState(null);

  useEffect(() => {
    if (result) setStage('result');
  }, [result]);

  if (stage === 'intro') return <QuizIntro onStart={() => setStage('quiz')} />;
  if (stage === 'result' && result) return <QuizResult result={result} onNav={onNav} onRetake={() => { setResult(null); setStage('intro'); }} />;
  return <Quiz onNav={onNav} setResult={setResult} />;
}

Object.assign(window, { QuizPage });
