// petal-doctor.jsx — the doctor's review desk: history log + detailed session view.
const { useState: useD, useEffect: useDE } = React;
const NURSE = (CFG.NURSE_NAME || 'Posy');

function fmtDate(ts) {
  const d = new Date(ts);
  return d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' })
    + ' · ' + d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
}
function relDay(ts) {
  const days = Math.floor((Date.now() - ts) / 86400000);
  if (days <= 0) return 'Today';
  if (days === 1) return 'Yesterday';
  if (days < 7) return days + ' days ago';
  return new Date(ts).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
}
function sevMeta(s) {
  if (s == null) return { c: PAL.mut, bg: '#F1ECE8', label: '—' };
  if (s <= 3) return { c: '#4F8A63', bg: '#E6F1E9', label: s + '/10 · mild' };
  if (s <= 6) return { c: '#B6822F', bg: '#F6EEDD', label: s + '/10 · moderate' };
  return { c: PAL.deep, bg: PAL.blushSoft, label: s + '/10 · marked' };
}

function SeverityChip({ s }) {
  const m = sevMeta(s);
  return <span style={{ background: m.bg, color: m.c, borderRadius: 999, padding: '4px 11px',
    fontSize: 12.5, fontWeight: 700, whiteSpace: 'nowrap' }}>{m.label}</span>;
}

function StatusPill({ status }) {
  const pending = status !== 'reviewed';
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 700,
      color: pending ? PAL.deep : '#4F8A63', background: pending ? PAL.blushSoft : '#E6F1E9',
      borderRadius: 999, padding: '4px 10px', whiteSpace: 'nowrap', flexShrink: 0 }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: pending ? PAL.blush : '#4F8A63' }} />
      {pending ? 'To review' : 'Reviewed'}
    </span>
  );
}

// ── list ─────────────────────────────────────────────────────
function DoctorList({ sessions, onOpen, onBack, onSignOut, onOpenHealth }) {
  const pending = sessions.filter(s => s.status !== 'reviewed').length;
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PAL.bg }}>
      <div style={{ padding: '16px 20px 14px', borderBottom: `1px solid ${PAL.borderSoft}`, background: '#fff' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'transparent',
            border: 'none', color: PAL.mut, fontFamily: FONT, fontSize: 13.5, cursor: 'pointer', padding: 0, whiteSpace: 'nowrap' }}>
            ‹ {NURSE} chat
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <button onClick={onOpenHealth} style={{ background: 'transparent', border: 'none', color: PAL.deep,
              fontFamily: FONT, fontSize: 13, fontWeight: 600, cursor: 'pointer', padding: 0, whiteSpace: 'nowrap' }}>Health profile</button>
            <button onClick={onSignOut} style={{ background: 'transparent', border: 'none', color: PAL.mut,
              fontFamily: FONT, fontSize: 13, cursor: 'pointer', padding: 0 }}>Sign out</button>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontFamily: SERIF, fontSize: 26, color: PAL.ink, lineHeight: 1.15, whiteSpace: 'nowrap' }}>{PEOPLE.patient}'s check-ins</div>
            <div style={{ fontSize: 13.5, color: PAL.mut, marginTop: 3 }}>Reviewed by {PEOPLE.doctor}</div>
          </div>
          {pending > 0 && (
            <span style={{ background: PAL.blush, color: '#fff', borderRadius: 999, padding: '5px 12px',
              fontSize: 13, fontWeight: 700 }}>{pending} new</span>
          )}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '14px 16px 24px', display: 'flex', flexDirection: 'column', gap: 11 }}>
        {sessions.length === 0 && (
          <div style={{ textAlign: 'center', color: PAL.mut, padding: '48px 20px', fontSize: 14.5 }}>
            No check-ins yet. When {PEOPLE.patient} completes one, it will appear here.
          </div>
        )}
        {sessions.map(s => (
          <button key={s.id} onClick={() => onOpen(s.id)} style={{ textAlign: 'left', background: '#fff',
            border: `1px solid ${PAL.borderSoft}`, borderRadius: 18, padding: '15px 16px', cursor: 'pointer',
            boxShadow: PAL.shadowSoft, fontFamily: FONT, display: 'flex', flexDirection: 'column', gap: 9 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 12.5, color: PAL.mut }}>{relDay(s.startedAt)}</span>
              <StatusPill status={s.status} />
            </div>
            <div style={{ fontSize: 15.5, color: PAL.ink, lineHeight: 1.4, fontWeight: 500,
              display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
              "{s.concern}"
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <SeverityChip s={s.severity} />
              <span style={{ fontSize: 12.5, color: PAL.mut }}>{s.qa.length} answers</span>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ── detail ───────────────────────────────────────────────────
function SessionDetail({ session, onBack, onChange }) {
  const [note, setNote] = useD(session.doctorNote || '');
  const [saved, setSaved] = useD(true);
  const reviewed = session.status === 'reviewed';

  const saveNote = async () => { await PetalAPI.updateSession(session.id, { doctorNote: note }); setSaved(true); onChange(); };
  const toggleReviewed = async () => {
    await PetalAPI.updateSession(session.id, { status: reviewed ? 'pending' : 'reviewed', doctorNote: note });
    onChange();
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PAL.bg }}>
      <div style={{ padding: '14px 20px 14px', borderBottom: `1px solid ${PAL.borderSoft}`, background: '#fff' }}>
        <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'transparent',
          border: 'none', color: PAL.mut, fontFamily: FONT, fontSize: 13.5, cursor: 'pointer', padding: 0, whiteSpace: 'nowrap' }}>
          ‹ All check-ins
        </button>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 18px 28px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* heading */}
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <SeverityChip s={session.severity} />
            <StatusPill status={session.status} />
            <span style={{ marginLeft: 'auto', fontSize: 12.5, color: PAL.mut }}>{fmtDate(session.startedAt)}</span>
          </div>
          <div style={{ fontFamily: SERIF, fontSize: 22, color: PAL.ink, lineHeight: 1.3 }}>
            "{session.concern}"
          </div>
        </div>

        {/* Posy's summary */}
        {session.summary && (
          <div style={{ background: '#fff', border: `1px solid ${PAL.borderSoft}`, borderLeft: `3px solid ${PAL.blush}`,
            borderRadius: 16, padding: '15px 16px', boxShadow: PAL.shadowSoft }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <Bloom size={16} />
              <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', color: PAL.deep }}>{NURSE}'s summary</span>
            </div>
            <div style={{ fontSize: 14.5, lineHeight: 1.55, color: PAL.ink2 }}>{session.summary}</div>
          </div>
        )}

        {/* structured answers */}
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', color: PAL.mut, margin: '2px 2px 10px' }}>Her answers</div>
          <div style={{ background: '#fff', border: `1px solid ${PAL.borderSoft}`, borderRadius: 16, overflow: 'hidden', boxShadow: PAL.shadowSoft }}>
            {session.qa.map((row, i) => (
              <div key={i} style={{ padding: '13px 16px', borderTop: i ? `1px solid ${PAL.borderSoft}` : 'none' }}>
                <div style={{ fontSize: 13, color: PAL.mut, marginBottom: 3 }}>{row.label}</div>
                <div style={{ fontSize: 15, color: PAL.ink, fontWeight: 600 }}>{row.answer}</div>
              </div>
            ))}
          </div>
        </div>

        {/* doctor note */}
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', color: PAL.mut, margin: '2px 2px 10px' }}>Your notes</div>
          <textarea value={note} onChange={e => { setNote(e.target.value); setSaved(false); }}
            placeholder="Add a private note for the record…" rows={3}
            style={{ width: '100%', resize: 'vertical', border: `1px solid ${PAL.border}`, borderRadius: 14,
              padding: '13px 14px', fontSize: 14.5, fontFamily: FONT, color: PAL.ink, background: '#fff',
              outline: 'none', lineHeight: 1.5 }} />
          {!saved && <div style={{ marginTop: 8 }}><PillButton variant="outline" onClick={saveNote} style={{ fontSize: 14, padding: '10px 16px' }}>Save note</PillButton></div>}
        </div>
      </div>

      {/* sticky action */}
      <div style={{ padding: '12px 18px', borderTop: `1px solid ${PAL.borderSoft}`, background: '#fff' }}>
        <PillButton onClick={toggleReviewed} variant={reviewed ? 'outline' : 'solid'} style={{ width: '100%' }}>
          {reviewed ? '↩ Mark as to-review' : '✓ Mark as reviewed'}
        </PillButton>
      </div>
    </div>
  );
}

function DoctorDesk({ onBack, onSignOut, onOpenHealth }) {
  const [sessions, setSessions] = useD(null); // null = loading
  const [openId, setOpenId] = useD(null);
  const refresh = async () => setSessions(await PetalAPI.listSessions());
  useDE(() => { refresh(); }, []);

  if (sessions === null) {
    return (
      <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: PAL.bg, gap: 12, flexDirection: 'column' }}>
        <div style={{ animation: 'petalspin 2.4s linear infinite' }}><Bloom size={34} /></div>
        <div style={{ fontSize: 13.5, color: PAL.mut }}>Loading check-ins…</div>
      </div>
    );
  }
  const open = sessions.find(s => s.id === openId);
  if (open) return <SessionDetail session={open} onBack={() => { setOpenId(null); refresh(); }} onChange={refresh} />;
  return <DoctorList sessions={sessions} onOpen={setOpenId} onBack={onBack} onSignOut={onSignOut} onOpenHealth={onOpenHealth} />;
}

Object.assign(window, { DoctorDesk });
