// petal-chat.jsx — the Posy conversational check-in flow. Exports PosyChat.
const { useState: useS, useEffect: useE, useRef: useR } = React;

const NURSE = (CFG.NURSE_NAME || 'Posy');
const WELCOME = [
  { id: 'w1', from: 'posy', kind: 'text', text: `Hi ${PEOPLE.patient}, I'm ${NURSE} 🌷` },
  { id: 'w2', from: 'posy', kind: 'text', text: `I'm here to help you tell ${PEOPLE.doctor} how you're feeling. Whenever you're ready, just describe what's going on in your own words — take your time.` },
];

const STARTERS = ['I have a headache', 'My tummy hurts', "I'm exhausted", 'I feel feverish', 'I feel anxious'];

function PosyChat({ user, onOpenDoctor, onOpenHealth, onSignOut }) {
  const isDoctor = user && user.role === 'doctor';
  const draft = loadDraft();
  const [messages, setMessages] = useS(draft ? draft.messages : WELCOME);
  const [phase, setPhase] = useS(draft ? draft.phase : 'intro'); // intro|thinking|awaiting|done
  const [rounds, setRounds] = useS(draft ? draft.rounds : 0);
  const [concern, setConcern] = useS(draft ? draft.concern : '');
  const [qa, setQa] = useS(draft ? draft.qa : []);
  const [severity, setSeverity] = useS(draft ? draft.severity : null);
  const [sid] = useS(draft ? draft.id : uid());
  const [startedAt] = useS(draft ? draft.startedAt : Date.now());
  const [input, setInput] = useS('');
  const scrollRef = useR(null);

  // persist draft (only while a check-in is active, not after done)
  useE(() => {
    if (phase === 'done') { clearDraft(); return; }
    saveDraft({ id: sid, startedAt, messages, phase, rounds, concern, qa, severity });
  }, [messages, phase, rounds, concern, qa, severity]);

  // autoscroll
  useE(() => {
    const el = scrollRef.current;
    if (el) requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; });
  }, [messages, phase]);

  const push = (m) => setMessages(prev => [...prev, { id: uid(), ...m }]);

  async function runPosy(nextMessages, nextRounds) {
    setPhase('thinking');
    const result = await PetalAPI.askPosy(nextMessages, nextRounds);
    if (result.done) {
      push({ from: 'posy', kind: 'text', text: result.reply || "All done — thank you, Maryna. I've sent everything to Nuno. 💛" });
      finalize(result.summary || '');
      setPhase('done');
    } else {
      push({ from: 'posy', kind: 'text', text: result.reply || 'Thank you — a few quick questions.' });
      push({ from: 'posy', kind: 'questions', questions: result.questions, locked: false, answers: null });
      setRounds(nextRounds + 1);
      setPhase('awaiting');
    }
  }

  function sendConcern() {
    const text = input.trim();
    if (!text || phase !== 'intro') return;
    setInput('');
    setConcern(text);
    const next = [...messages, { id: uid(), from: 'maryna', kind: 'text', text }];
    setMessages(next);
    runPosy(next, 0);
  }

  function submitGroup(msgId, questions, finalAnswers, summary, pairs) {
    // lock the group
    setMessages(prev => prev.map(m => m.id === msgId ? { ...m, locked: true, answers: finalAnswers } : m));
    // capture severity from any scale question
    const scaleQ = questions.find(q => q.type === 'scale');
    let nextSev = severity;
    if (scaleQ && finalAnswers[scaleQ.id] != null) { nextSev = finalAnswers[scaleQ.id]; setSeverity(nextSev); }
    const nextQa = [...qa, ...pairs];
    setQa(nextQa);
    const next = [...messages.map(m => m.id === msgId ? { ...m, locked: true, answers: finalAnswers } : m),
      { id: uid(), from: 'maryna', kind: 'answers', text: summary }];
    setMessages(next);
    runPosy(next, rounds);
  }

  function finalize(summaryText) {
    PetalAPI.addSession({
      id: sid, startedAt, status: 'pending',
      concern: concern || (qa[0] && qa[0].answer) || 'Symptom check-in',
      severity, qa, summary: summaryText, doctorNote: '',
    });
  }

  function restart() {
    clearDraft();
    setMessages(WELCOME); setPhase('intro'); setRounds(0);
    setConcern(''); setQa([]); setSeverity(null); setInput('');
  }

  const canType = phase === 'intro';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'linear-gradient(180deg,#FBF4EF 0%,#F7ECE6 100%)' }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '14px 18px',
        borderBottom: `1px solid ${PAL.borderSoft}`, background: 'rgba(251,244,239,0.85)',
        backdropFilter: 'blur(8px)', position: 'relative', zIndex: 5 }}>
        <PosyAvatar size={40} ring />
        <div style={{ lineHeight: 1.15 }}>
          <div style={{ fontFamily: SERIF, fontSize: 22, color: PAL.ink, fontWeight: 500 }}>{NURSE}</div>
          <StatusDot label={phase === 'thinking' ? 'thinking…' : 'here for you'} />
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          {isDoctor && (
            <button onClick={onOpenDoctor} title="Doctor desk" style={{ display: 'flex', alignItems: 'center', gap: 7,
              background: '#fff', border: `1px solid ${PAL.border}`, borderRadius: 999, padding: '7px 13px',
              fontFamily: FONT, fontSize: 13, color: PAL.ink2, cursor: 'pointer', fontWeight: 600, whiteSpace: 'nowrap', flexShrink: 0 }}>
              <span style={{ width: 18, height: 18, borderRadius: '50%', background: PAL.ink, color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700 }}>{PEOPLE.doctor[0]}</span>
              {PEOPLE.doctor}'s desk
            </button>
          )}
          <button onClick={onOpenHealth} title="Health profile" style={{ width: 36, height: 36, borderRadius: '50%',
            background: '#fff', border: `1px solid ${PAL.border}`, cursor: 'pointer', flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <rect x="3.2" y="2.6" width="9.6" height="11.4" rx="2.4" stroke={PAL.mut} strokeWidth="1.5" />
              <rect x="5.6" y="1.6" width="4.8" height="2.4" rx="1.2" fill="#fff" stroke={PAL.mut} strokeWidth="1.5" />
              <path d="M6 8.4h4M6 11h2.6" stroke={PAL.blush} strokeWidth="1.5" strokeLinecap="round" />
            </svg>
          </button>
          <button onClick={onSignOut} title="Sign out" style={{ width: 36, height: 36, borderRadius: '50%',
            background: '#fff', border: `1px solid ${PAL.border}`, color: PAL.mut, cursor: 'pointer', flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15 }}>⏻</button>
        </div>
      </div>

      {/* messages */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '18px 16px 8px',
        display: 'flex', flexDirection: 'column', gap: 12 }}>
        {messages.map((m, i) => {
          const prev = messages[i - 1];
          if (m.from === 'posy') {
            const showAv = !prev || prev.from !== 'posy';
            return (
              <div key={m.id} style={{ display: 'flex', gap: 9, alignItems: 'flex-end' }}>
                <div style={{ width: 30, flexShrink: 0 }}>{showAv ? <PosyAvatar size={30} /> : null}</div>
                {m.kind === 'text'
                  ? <div style={{ background: PAL.card, color: PAL.ink, borderRadius: '20px 20px 20px 7px',
                      padding: '13px 16px', fontSize: 15.5, lineHeight: 1.5, boxShadow: PAL.shadowSoft,
                      border: `1px solid ${PAL.borderSoft}`, maxWidth: '88%' }}>{m.text}</div>
                  : <div style={{ flex: 1, minWidth: 0 }}>
                      <QuizGroup questions={m.questions} locked={m.locked} answers={m.answers}
                        onSubmit={(fa, sum, pairs) => submitGroup(m.id, m.questions, fa, sum, pairs)} />
                    </div>}
              </div>
            );
          }
          return <MarynaBubble key={m.id}>{m.text}</MarynaBubble>;
        })}

        {phase === 'thinking' && (
          <div style={{ display: 'flex', gap: 9, alignItems: 'flex-end' }}>
            <div style={{ width: 30, flexShrink: 0 }}><PosyAvatar size={30} /></div>
            <TypingDots />
          </div>
        )}

        {phase === 'done' && (
          <div style={{ background: '#fff', border: `1px solid ${PAL.borderSoft}`, borderRadius: 20,
            padding: '20px 18px', boxShadow: PAL.shadowSoft, textAlign: 'center', marginTop: 4 }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}><Bloom size={34} /></div>
            <div style={{ fontWeight: 800, fontSize: 17, color: PAL.ink, marginBottom: 4 }}>Sent to {PEOPLE.doctor} 💛</div>
            <div style={{ fontSize: 14, color: PAL.ink2, lineHeight: 1.5, marginBottom: 16 }}>
              Your check-in is saved for {PEOPLE.doctor} to review. Rest up — and come back any time you need to.
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <PillButton onClick={restart}>New check-in</PillButton>
              {isDoctor && <PillButton variant="outline" onClick={onOpenDoctor}>Open {PEOPLE.doctor}'s desk</PillButton>}
            </div>
          </div>
        )}
      </div>

      {/* starter chips */}
      {phase === 'intro' && (
        <div style={{ padding: '4px 14px 6px', display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {STARTERS.map(s => (
            <button key={s} onClick={() => setInput(s)} style={{ border: `1px solid ${PAL.border}`,
              background: 'rgba(255,255,255,0.75)', color: PAL.ink2, borderRadius: 999, padding: '8px 13px',
              fontSize: 13, fontFamily: FONT, cursor: 'pointer' }}>{s}</button>
          ))}
        </div>
      )}

      {/* input bar */}
      <div style={{ padding: '8px 14px 14px' }}>
        {canType ? (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 9, background: '#fff', borderRadius: 24,
            padding: '7px 7px 7px 18px', boxShadow: PAL.shadowSoft, border: `1px solid ${PAL.borderSoft}` }}>
            <textarea value={input} onChange={e => setInput(e.target.value)} rows={1}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendConcern(); } }}
              placeholder="Tell Posy how you feel…"
              style={{ flex: 1, border: 'none', outline: 'none', resize: 'none', fontFamily: FONT, fontSize: 15.5,
                color: PAL.ink, background: 'transparent', maxHeight: 90, lineHeight: 1.4, padding: '8px 0' }} />
            <button onClick={sendConcern} disabled={!input.trim()} style={{ width: 44, height: 44, borderRadius: '50%',
              border: 'none', background: input.trim() ? PAL.blush : PAL.border, color: '#fff', fontSize: 19,
              cursor: input.trim() ? 'pointer' : 'default', flexShrink: 0, transition: 'background .15s' }}>↑</button>
          </div>
        ) : phase === 'awaiting' ? (
          <div style={{ textAlign: 'center', fontSize: 13.5, color: PAL.mut, padding: '10px' }}>
            Answer Posy's questions above to continue ↑
          </div>
        ) : <div style={{ height: 4 }} />}
      </div>
    </div>
  );
}

Object.assign(window, { PosyChat });
