// petal-quiz.jsx — interactive in-chat question cards (choice / multi / scale / text).
// Exports QuizGroup to window. Manages its own answer state until submitted.
const { useState: useStateQ } = React;

function formatAnswer(q, v) {
  if (q.type === 'scale') return `${v} / ${q.max || 10}`;
  if (q.type === 'multi') return (v && v.length) ? v.join(', ') : '—';
  return (v == null || v === '') ? '—' : String(v);
}

function ChoiceCard({ q, value, onChange, locked }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {(q.options || []).map(o => {
        const on = value === o;
        return (
          <button key={o} disabled={locked} onClick={() => onChange(o)} style={{
            display: 'flex', alignItems: 'center', gap: 11, textAlign: 'left', width: '100%',
            background: on ? PAL.blush : '#fff', color: on ? '#fff' : PAL.ink,
            border: `1.5px solid ${on ? PAL.blush : PAL.border}`, borderRadius: 14,
            padding: '13px 15px', fontSize: 15, fontFamily: FONT, fontWeight: 500,
            cursor: locked ? 'default' : 'pointer', transition: 'all .14s',
          }}>
            <span style={{ width: 18, height: 18, borderRadius: '50%', flexShrink: 0,
              border: `2px solid ${on ? '#fff' : PAL.border}`, background: on ? '#fff' : 'transparent',
              boxShadow: on ? `inset 0 0 0 3px ${PAL.blush}` : 'none' }} />
            {o}
          </button>
        );
      })}
    </div>
  );
}

function MultiCard({ q, value, onChange, locked }) {
  const arr = value || [];
  const toggle = (o) => onChange(arr.includes(o) ? arr.filter(x => x !== o) : [...arr, o]);
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {(q.options || []).map(o => {
        const on = arr.includes(o);
        return (
          <button key={o} disabled={locked} onClick={() => toggle(o)} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            background: on ? PAL.blush : '#fff', color: on ? '#fff' : PAL.ink,
            border: `1.5px solid ${on ? PAL.blush : PAL.border}`, borderRadius: 999,
            padding: '9px 15px', fontSize: 14.5, fontFamily: FONT, fontWeight: 500,
            cursor: locked ? 'default' : 'pointer', transition: 'all .14s',
          }}>
            <span style={{ fontSize: 13, opacity: on ? 1 : 0.35 }}>{on ? '✓' : '+'}</span>{o}
          </button>
        );
      })}
    </div>
  );
}

function ScaleCard({ q, value, onChange, locked }) {
  const min = q.min || 1, max = q.max || 10;
  const v = value == null ? Math.round((min + max) / 2) : value;
  return (
    <div style={{ background: '#fff', border: `1.5px solid ${PAL.border}`, borderRadius: 16, padding: '16px 16px 14px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <span style={{ fontSize: 12.5, color: PAL.mut }}>{q.minLabel || 'Low'}</span>
        <span style={{ fontWeight: 800, color: PAL.deep, fontSize: 17 }}>{v}<span style={{ fontSize: 13, color: PAL.mut, fontWeight: 600 }}> / {max}</span></span>
        <span style={{ fontSize: 12.5, color: PAL.mut }}>{q.maxLabel || 'High'}</span>
      </div>
      <input type="range" min={min} max={max} value={v} disabled={locked}
        onChange={e => onChange(+e.target.value)}
        style={{ width: '100%', accentColor: PAL.blush }} />
    </div>
  );
}

function TextCard({ q, value, onChange, locked }) {
  return (
    <textarea value={value || ''} disabled={locked} onChange={e => onChange(e.target.value)}
      placeholder={q.placeholder || 'Type here…'} rows={2}
      style={{ width: '100%', resize: 'none', border: `1.5px solid ${PAL.border}`, borderRadius: 14,
        padding: '12px 14px', fontSize: 15, fontFamily: FONT, color: PAL.ink, background: '#fff',
        outline: 'none', lineHeight: 1.45 }} />
  );
}

function QuestionBlock({ q, value, onChange, locked }) {
  const Card = { choice: ChoiceCard, multi: MultiCard, scale: ScaleCard, text: TextCard }[q.type] || TextCard;
  return (
    <div>
      <div style={{ fontSize: 15.5, fontWeight: 700, color: PAL.ink, marginBottom: 11, lineHeight: 1.35 }}>{q.label}</div>
      <Card q={q} value={value} onChange={onChange} locked={locked} />
    </div>
  );
}

// the full group: Posy's questions + a submit button
function QuizGroup({ questions, onSubmit, locked, answers: lockedAnswers }) {
  const [answers, setAnswers] = useStateQ({});
  const set = (id, v) => setAnswers(a => ({ ...a, [id]: v }));

  // required = everything except text
  const required = questions.filter(q => q.type !== 'text');
  const ready = required.every(q => {
    const v = answers[q.id];
    if (q.type === 'multi') return v && v.length;
    return v != null && v !== '';
  });

  const submit = () => {
    // ensure scales default to midpoint if untouched
    const final = { ...answers };
    questions.forEach(q => {
      if (q.type === 'scale' && final[q.id] == null) final[q.id] = Math.round(((q.min || 1) + (q.max || 10)) / 2);
    });
    const summary = questions
      .filter(q => !(q.type === 'text' && (!final[q.id])))
      .map(q => `${q.label} — ${formatAnswer(q, final[q.id])}`).join(' · ');
    onSubmit(final, summary, questions.map(q => ({ label: q.label, answer: formatAnswer(q, final[q.id]) })));
  };

  const src = locked ? (lockedAnswers || {}) : answers;

  return (
    <div style={{ background: PAL.blushSofter, border: `1px solid ${PAL.borderSoft}`, borderRadius: 18,
      padding: 16, display: 'flex', flexDirection: 'column', gap: 18, width: '100%' }}>
      {questions.map(q => (
        <QuestionBlock key={q.id} q={q} value={src[q.id]} onChange={v => set(q.id, v)} locked={locked} />
      ))}
      {!locked && (
        <PillButton onClick={submit} disabled={!ready} style={{ marginTop: 2 }}>
          {ready ? 'Send to Posy' : 'Tap your answers above'}
        </PillButton>
      )}
    </div>
  );
}

Object.assign(window, { QuizGroup, formatAnswer });
