// quiz.jsx — one-question-per-screen health assessment

const { useState, useEffect } = React;

const QUIZ_QUESTIONS = [
  {
    id: 'concern',
    title: 'What brings you in today?',
    sub: "We'll tailor your assessment based on what you'd like to address.",
    kind: 'choice',
    options: [
      { value: 'ed',    label: 'Erectile difficulties', sub: 'Trouble getting or keeping an erection' },
      { value: 'pe',    label: 'Finishing too quickly', sub: 'Premature ejaculation' },
      { value: 'both',  label: 'Both, honestly',        sub: "ED and PE — I'd like to tackle both" },
      { value: 'desire',label: 'Low desire or arousal', sub: "I'm just not as interested as I used to be" },
    ],
  },
  {
    id: 'frequency',
    title: 'How often does this affect you?',
    sub: "There's no wrong answer — this helps your physician calibrate the right dose.",
    kind: 'choice',
    options: [
      { value: 'rarely',     label: 'Rarely',     sub: 'A handful of times' },
      { value: 'sometimes',  label: 'Sometimes',  sub: 'Once or twice a month' },
      { value: 'often',      label: 'Often',      sub: 'Most weeks' },
      { value: 'always',     label: 'Almost always', sub: 'Nearly every time' },
    ],
  },
  {
    id: 'lifestyle',
    title: 'When would you want it to work?',
    sub: 'This decides whether a daily or on-demand treatment fits your life better.',
    kind: 'choice',
    options: [
      { value: 'planned',    label: 'When I plan for it',  sub: '30–60 minutes ahead is fine' },
      { value: 'spontaneous',label: 'Whenever it happens', sub: "I'd rather be ready, always" },
      { value: 'both',       label: 'A mix of both',       sub: 'Some planned, some spontaneous' },
    ],
  },
  {
    id: 'age',
    title: 'How old are you?',
    sub: 'You must be 18 or older to use HermanRx.',
    kind: 'age',
    min: 18, max: 80, default: 38,
  },
  {
    id: 'history',
    title: 'Have you tried ED medication before?',
    sub: 'Knowing what you\'ve responded to helps your physician choose.',
    kind: 'choice',
    options: [
      { value: 'no',           label: 'No, this would be my first time' },
      { value: 'yes_worked',   label: 'Yes — it worked well' },
      { value: 'yes_partial',  label: 'Yes — it helped, but not enough' },
      { value: 'yes_didnt',    label: "Yes — it didn't work for me" },
    ],
  },
  {
    id: 'conditions',
    title: 'Do any of these apply?',
    sub: 'Select all that apply. Your physician will review these carefully.',
    kind: 'multi',
    options: [
      { value: 'heart',     label: 'Heart disease or chest pain' },
      { value: 'bp',        label: 'High or low blood pressure' },
      { value: 'diabetes',  label: 'Diabetes' },
      { value: 'liver',     label: 'Liver or kidney issues' },
      { value: 'depression',label: 'Depression or anxiety' },
      { value: 'none',      label: 'None of the above', exclusive: true },
    ],
  },
  {
    id: 'meds',
    title: 'Are you currently taking nitrates or alpha-blockers?',
    sub: 'These can interact with ED medication. If you\'re not sure, choose "I\'m not sure" and your physician will follow up.',
    kind: 'choice',
    options: [
      { value: 'no',     label: "No" },
      { value: 'yes',    label: 'Yes' },
      { value: 'unsure', label: "I'm not sure" },
    ],
  },
];

function Quiz({ go }) {
  const QUIZ_STORAGE_KEY = 'hrx_quiz_state';

  // Restore saved state from localStorage on mount
  const initial = (() => {
    try {
      const raw = localStorage.getItem(QUIZ_STORAGE_KEY);
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      // Expire after 14 days
      if (parsed.savedAt && Date.now() - parsed.savedAt > 14 * 24 * 3600 * 1000) return null;
      return parsed;
    } catch { return null; }
  })();

  const [step, setStep] = useState(initial?.step ?? 0);
  const [answers, setAnswers] = useState(initial?.answers ?? {});
  const total = QUIZ_QUESTIONS.length;
  const q = QUIZ_QUESTIONS[step];

  // Persist on every change
  useEffect(() => {
    try {
      localStorage.setItem(QUIZ_STORAGE_KEY, JSON.stringify({
        step, answers, savedAt: Date.now(),
      }));
    } catch {}
  }, [step, answers]);

  const setAnswer = (id, value) => {
    setAnswers(prev => ({ ...prev, [id]: value }));
  };

  const canAdvance = (() => {
    if (!q) return false;
    const v = answers[q.id];
    if (q.kind === 'choice') return !!v;
    if (q.kind === 'multi')  return Array.isArray(v) && v.length > 0;
    if (q.kind === 'age')    return v != null;
    if (q.kind === 'email')  return v && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v);
    return true;
  })();

  const next = () => {
    if (!canAdvance) return;
    if (step < total - 1) setStep(step + 1);
    else {
      // Clear saved state on completion
      try { localStorage.removeItem(QUIZ_STORAGE_KEY); } catch {}
      go('results', { answers });
    }
  };
  const back = () => {
    if (step > 0) setStep(step - 1);
    else go('landing');
  };

  return (
    <main style={{
      minHeight: '100vh',
      background: 'var(--bg)',
      display: 'grid',
      gridTemplateRows: 'auto 1fr auto',
    }}>
      <QuizHeader go={go} step={step} total={total} />
      <div style={{ display: 'grid', placeItems: 'center', padding: '40px 24px 80px' }}>
        <div key={step} className="page-enter" style={{
          width: '100%', maxWidth: 720,
        }}>
          <QuestionView
            q={q}
            value={answers[q.id]}
            onChange={(v) => setAnswer(q.id, v)}
            onAutoAdvance={() => {
              // small delay for visual feedback
              setTimeout(() => {
                if (step < total - 1) setStep(step + 1);
                else go('results', { answers });
              }, 300);
            }}
          />
          {step >= 2 && step < total - 1 && (
            <SaveProgressBanner onSave={(email) => {
              // For prototype: just store the email; production would send it via email/SMS
              try { localStorage.setItem('hrx_quiz_email', email); } catch {}
            }} />
          )}
        </div>
      </div>
      <QuizFooter step={step} total={total} onBack={back} onNext={next} canAdvance={canAdvance} />
    </main>
  );
}

function QuizHeader({ go, step, total }) {
  const pct = ((step) / total) * 100;
  return (
    <header style={{
      borderBottom: '1px solid var(--line)',
      padding: '20px 0',
    }}>
      <div className="container" style={{
        display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 24, alignItems: 'center',
      }}>
        <a href="/" onClick={(e) => { e.preventDefault(); go('landing'); }}
           style={{ display: 'inline-flex', alignItems: 'center', textDecoration: 'none', color: 'inherit', cursor: 'pointer' }}
           aria-label="HermanRx home">
          <HermanLogo size={20} />
        </a>
        <div style={{
          height: 4, background: 'var(--surface)', borderRadius: 4,
          overflow: 'hidden', position: 'relative',
        }}>
          <div style={{
            position: 'absolute', inset: 0, width: pct + '%',
            background: 'var(--accent)',
            transition: 'width .45s cubic-bezier(.2,.7,.2,1)',
          }} />
        </div>
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-mute)',
          letterSpacing: '.04em', minWidth: 56, textAlign: 'right',
        }}>{String(step + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}</div>
      </div>
    </header>
  );
}

function QuizFooter({ step, total, onBack, onNext, canAdvance }) {
  return (
    <footer style={{
      borderTop: '1px solid var(--line)',
      background: 'color-mix(in oklab, var(--bg) 94%, transparent)',
      backdropFilter: 'blur(10px)',
      padding: '16px 0',
    }}>
      <div className="container" style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
      }}>
        <button onClick={onBack} style={btn.ghost}>
          ← Back
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ fontSize: 12, color: 'var(--ink-mute)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <TrustIcon name="lock" size={13} /> Your answers are private and HIPAA-protected.
          </div>
          <button onClick={onNext} disabled={!canAdvance}
                  style={{
                    ...btn.solid,
                    opacity: canAdvance ? 1 : 0.35,
                    cursor: canAdvance ? 'pointer' : 'not-allowed',
                    padding: '12px 22px',
                  }}>
            {step === total - 1 ? 'See my recommendation' : 'Continue'}
            <span style={{ marginLeft: 8 }}>→</span>
          </button>
        </div>
      </div>
    </footer>
  );
}

// ────────────────────────────────────────────────────────────────────────────
//  Question views
// ────────────────────────────────────────────────────────────────────────────
function QuestionView({ q, value, onChange, onAutoAdvance }) {
  return (
    <div>
      <div style={{
        fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase',
        color: 'var(--accent)', marginBottom: 16,
      }}>Health assessment</div>
      <h1 style={{
        fontFamily: 'var(--serif)', fontSize: 'clamp(34px, 4.4vw, 52px)',
        lineHeight: 1.05, letterSpacing: '-.012em',
      }}>{q.title}</h1>
      {q.sub && (
        <p style={{
          marginTop: 14, fontSize: 16, color: 'var(--ink-dim)', lineHeight: 1.55,
          maxWidth: 620,
        }}>{q.sub}</p>
      )}
      <div style={{ marginTop: 36 }}>
        {q.kind === 'choice' && (
          <ChoiceList q={q} value={value} onChange={(v) => { onChange(v); onAutoAdvance(); }} />
        )}
        {q.kind === 'multi' && (
          <MultiList q={q} value={value || []} onChange={onChange} />
        )}
        {q.kind === 'age' && (
          <AgeInput q={q} value={value} onChange={onChange} />
        )}
        {q.kind === 'email' && (
          <EmailInput value={value} onChange={onChange} />
        )}
      </div>
    </div>
  );
}

function ChoiceList({ q, value, onChange }) {
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      {q.options.map(opt => {
        const selected = value === opt.value;
        return (
          <button key={opt.value}
                  onClick={() => onChange(opt.value)}
                  style={{
                    all: 'unset', cursor: 'pointer',
                    display: 'flex', alignItems: 'center', gap: 18,
                    padding: '20px 22px',
                    border: '1px solid',
                    borderColor: selected ? 'var(--accent)' : 'var(--line)',
                    background: selected ? 'color-mix(in oklab, var(--accent) 8%, transparent)' : 'var(--surface)',
                    borderRadius: 'var(--r-md)',
                    transition: 'all .2s ease',
                  }}>
            <div style={{
              width: 22, height: 22, borderRadius: 22,
              border: '1.5px solid', flexShrink: 0,
              borderColor: selected ? 'var(--accent)' : 'var(--line-strong)',
              display: 'grid', placeItems: 'center',
              transition: 'all .2s ease',
            }}>
              {selected && (
                <div style={{ width: 10, height: 10, borderRadius: 10, background: 'var(--accent)' }} />
              )}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 16, fontWeight: 500 }}>{opt.label}</div>
              {opt.sub && (
                <div style={{ marginTop: 3, fontSize: 13, color: 'var(--ink-dim)' }}>{opt.sub}</div>
              )}
            </div>
          </button>
        );
      })}
    </div>
  );
}

function MultiList({ q, value, onChange }) {
  const toggle = (opt) => {
    const isExclusive = opt.exclusive;
    if (isExclusive) {
      onChange(value.includes(opt.value) ? [] : [opt.value]);
      return;
    }
    // Remove exclusive options when picking non-exclusive
    let next = value.filter(v => {
      const o = q.options.find(x => x.value === v);
      return o && !o.exclusive;
    });
    if (next.includes(opt.value)) next = next.filter(v => v !== opt.value);
    else next = [...next, opt.value];
    onChange(next);
  };
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      {q.options.map(opt => {
        const selected = value.includes(opt.value);
        return (
          <button key={opt.value} onClick={() => toggle(opt)}
                  style={{
                    all: 'unset', cursor: 'pointer',
                    display: 'flex', alignItems: 'center', gap: 18,
                    padding: '18px 22px',
                    border: '1px solid',
                    borderColor: selected ? 'var(--accent)' : 'var(--line)',
                    background: selected ? 'color-mix(in oklab, var(--accent) 8%, transparent)' : 'var(--surface)',
                    borderRadius: 'var(--r-md)',
                    transition: 'all .15s ease',
                  }}>
            <div style={{
              width: 22, height: 22, borderRadius: 5,
              border: '1.5px solid', flexShrink: 0,
              borderColor: selected ? 'var(--accent)' : 'var(--line-strong)',
              background: selected ? 'var(--accent)' : 'transparent',
              display: 'grid', placeItems: 'center',
            }}>
              {selected && (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--cta-ink)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M4 12l5 5L20 6"/>
                </svg>
              )}
            </div>
            <div style={{ fontSize: 15.5, fontWeight: 500 }}>{opt.label}</div>
          </button>
        );
      })}
    </div>
  );
}

function AgeInput({ q, value, onChange }) {
  const v = value ?? q.default;
  useEffect(() => { if (value == null) onChange(q.default); }, []); // eslint-disable-line
  return (
    <div style={{
      padding: '40px 32px', background: 'var(--surface)',
      border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
    }}>
      <div style={{
        textAlign: 'center',
        fontFamily: 'var(--serif)', fontSize: 88, lineHeight: 1,
        letterSpacing: '-.02em',
      }}>{v}</div>
      <div style={{
        textAlign: 'center', color: 'var(--ink-mute)', fontSize: 13,
        marginTop: 6, letterSpacing: '.04em',
      }}>years old</div>
      <input type="range" min={q.min} max={q.max} value={v}
             onChange={(e) => onChange(parseInt(e.target.value))}
             style={{
               width: '100%', marginTop: 32, accentColor: 'var(--accent)',
             }} />
      <div style={{
        display: 'flex', justifyContent: 'space-between', fontSize: 12,
        color: 'var(--ink-mute)', marginTop: 8,
      }}>
        <span>{q.min}</span><span>{q.max}+</span>
      </div>
    </div>
  );
}

function EmailInput({ value, onChange }) {
  return (
    <div>
      <input type="email" autoFocus value={value || ''}
             placeholder="you@example.com"
             onChange={(e) => onChange(e.target.value)}
             style={{
               all: 'unset',
               display: 'block', width: '100%',
               padding: '22px 24px',
               background: 'var(--surface)',
               border: '1px solid var(--line)',
               borderRadius: 'var(--r-md)',
               fontFamily: 'var(--serif)',
               fontSize: 32, color: 'var(--ink)',
               boxSizing: 'border-box',
             }} />
      <div style={{
        marginTop: 16, padding: '14px 18px',
        background: 'var(--surface-2)',
        border: '1px solid var(--line)',
        borderRadius: 'var(--r-md)',
        display: 'flex', alignItems: 'center', gap: 12,
        fontSize: 13, color: 'var(--ink-dim)', lineHeight: 1.5,
      }}>
        <TrustIcon name="lock" size={16} />
        Your email is used only to send your treatment plan. HIPAA-encrypted, never sold.
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
//  Recommendation logic (consumed by Results page)
// ────────────────────────────────────────────────────────────────────────────
function recommendFromAnswers(answers) {
  const concern = answers.concern;
  const life = answers.lifestyle;
  const history = answers.history;
  const conditions = answers.conditions || [];

  // Disqualifying: nitrates flagged for follow-up but still recommend (prototype)
  const flags = [];
  if (answers.meds === 'yes') flags.push('Nitrates / alpha-blockers — our medical team will verify safety before dispensing.');
  if (conditions.includes('heart')) flags.push('Cardiac history — our medical team will calibrate dosing carefully.');

  // FITS is the hero for "both" + spontaneous, or for desire concerns
  if (concern === 'both' || concern === 'desire') {
    return {
      primary: 'fits',
      primaryDose: null,
      alternates: ['tadalafil', 'sildenafil'],
      reasoning: concern === 'both'
        ? 'You’re looking to address both ED and finishing too quickly. FITS, our 3-in-1 formulation, was designed for exactly this — a single daily tablet that handles firmness, control, and desire together.'
        : 'You mentioned low desire alongside performance. FITS combines a PDE5 inhibitor with a serotonergic agent and an arousal compound — engineered for the whole picture.',
      flags,
    };
  }

  if (concern === 'pe') {
    return {
      primary: 'sertraline',
      primaryDose: 25,
      alternates: ['fits'],
      reasoning: 'For premature ejaculation, daily low-dose sertraline (25mg) is the most-prescribed off-label option in U.S. men’s health. Clinical studies show it can extend time-to-climax by 2–4×.',
      flags,
    };
  }

  // ED path — choose tadalafil daily vs sildenafil on-demand
  const wantsDaily = life === 'spontaneous' || life === 'both';
  if (wantsDaily) {
    const dose = answers.frequency === 'always' || history === 'yes_partial' ? 5 : 2.5;
    return {
      primary: 'tadalafil',
      primaryDose: dose,
      alternates: ['sildenafil', 'fits'],
      reasoning: `You'd rather be ready whenever the moment happens. A daily ${dose}mg dose of tadalafil (generic Cialis) keeps you primed without planning — the most natural-feeling option for spontaneous intimacy.`,
      flags,
    };
  }

  const dose = answers.frequency === 'always' || history === 'yes_partial' ? 100 : 50;
  return {
    primary: 'sildenafil',
    primaryDose: dose,
    alternates: ['tadalafil', 'fits'],
    reasoning: `You'd like a treatment for planned intimacy. Sildenafil ${dose}mg (generic Viagra) is the gold standard — taken about an hour before, effects last 4–6 hours. No daily commitment.`,
    flags,
  };
}

Object.assign(window, { Quiz, QUIZ_QUESTIONS, recommendFromAnswers });
