// Planning (calendar), Evaluation forms, Bedside Logbook

// ===================== Planning / Calendar =====================

function getPlanTopics() {
  try {
    const s = localStorage.getItem('lr_supervision_topics');
    if (s) return JSON.parse(s);
  } catch {}
  return window.SUPERVISION_TOPICS || [];
}

const SUPERVISION_TYPES = ['One-on-One','Group','Bedside','Case Conference'];
const SUPERVISION_ACTIVITIES = ['Nursing Round','Nursing Conference','Teaching','Counseling','Problem-solving','Observation','Participation'];

const TH_MONTHS = ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'];

function buddhistYear(y) { return y + 543; }

const svStyle = { width: 'calc(1em)', height: 8, borderRadius: 2, flexShrink: 0 };

const PlanningModal = ({ sv, defaultDate, onClose, onSaved }) => {
  const editing = !!sv;
  const [availTopics] = useState(getPlanTopics);
  const [topicMode, setTopicMode] = useState(() => {
    // If editing and the existing topic doesn't match any known topic → custom mode
    if (sv?.topic) {
      const allTopics = getPlanTopics().flatMap(g => g.topics);
      return allTopics.includes(sv.topic) ? 'select' : 'custom';
    }
    return 'select';
  });
  const [form, setForm] = useState({
    date: sv?.date || defaultDate || new Date().toISOString().slice(0,10),
    time: sv?.time || '09:00',
    type: sv?.type || 'One-on-One',
    topic: sv?.topic || '',
    supervisor: sv?.supervisor || D.STAFF.filter(s => window.isSupervisorRole ? window.isSupervisorRole(s.role) : true)[0]?.id || 'n01',
    supervisee: sv?.supervisee || 'group',
    activity: sv?.activity || 'Nursing Round',
    status: sv?.status || 'scheduled',
  });
  // Multi-supervisee selection (empty = group)
  const [selectedSupervisees, setSelectedSupervisees] = useState(() => {
    if (!sv?.supervisee || sv.supervisee === 'group') return [];
    if (Array.isArray(sv.supervisee)) return sv.supervisee;
    return [sv.supervisee];
  });
  const toggleSupervisee = (id) => setSelectedSupervisees(prev =>
    prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
  );
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.topic.trim()) { setErr('กรุณาระบุหัวข้อการนิเทศ'); return; }
    setSaving(true); setErr('');
    const sveeValue = selectedSupervisees.length === 0 ? 'group'
      : selectedSupervisees.length === 1 ? selectedSupervisees[0]
      : selectedSupervisees;
    const payload = { ...form, supervisee: sveeValue };
    try {
      if (editing) {
        await window.DB.supervisions.update(sv.id, payload);
      } else {
        await window.DB.supervisions.create({
          ...payload,
          id: 'sv-' + Date.now() + '-' + Math.random().toString(36).slice(2,5),
        });
      }
      onSaved();
      onClose();
    } catch (e) {
      setErr(e.message || 'บันทึกไม่สำเร็จ');
      setSaving(false);
    }
  };

  const selectStyle = { width: '100%', padding: '8px 10px', marginTop: 4, border: '1px solid var(--c-border)', borderRadius: 8, background: 'var(--c-surface)', color: 'var(--c-ink)', fontSize: 13 };
  const inputStyle = { ...selectStyle };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 16 }}>
      <div className="card" style={{ width: '100%', maxWidth: 520, maxHeight: '92vh', overflowY: 'auto' }}>
        <div className="card-header">
          <h3>{editing ? 'แก้ไขนัดนิเทศ' : 'นัดการนิเทศใหม่'}</h3>
          <button className="btn btn-sm btn-ghost" style={{ marginLeft: 'auto' }} onClick={onClose}>ยกเลิก</button>
        </div>
        <div className="card-body stack">
          <div className="grid-2">
            <div>
              <label className="muted txt-xs">วันที่</label>
              <input type="date" value={form.date} onChange={e => set('date', e.target.value)} style={inputStyle} />
            </div>
            <div>
              <label className="muted txt-xs">เวลา</label>
              <input type="time" value={form.time} onChange={e => set('time', e.target.value)} style={inputStyle} />
            </div>
          </div>

          <div>
            <label className="muted txt-xs">หัวข้อการนิเทศ</label>
            <select
              value={topicMode === 'custom' ? '__custom__' : (form.topic || '')}
              onChange={e => {
                if (e.target.value === '__custom__') {
                  setTopicMode('custom');
                  set('topic', '');
                } else {
                  setTopicMode('select');
                  set('topic', e.target.value);
                }
              }}
              style={selectStyle}
            >
              <option value="">— เลือกหัวข้อการนิเทศ —</option>
              {availTopics.map(g => (
                <optgroup key={g.group} label={g.group}>
                  {g.topics.map(t => <option key={t} value={t}>{t}</option>)}
                </optgroup>
              ))}
              <option value="__custom__">✏️ พิมพ์เอง...</option>
            </select>
            {topicMode === 'custom' && (
              <input
                value={form.topic}
                onChange={e => set('topic', e.target.value)}
                placeholder="ระบุหัวข้อการนิเทศ..."
                autoFocus
                style={{ ...inputStyle, marginTop: 6, borderColor: 'var(--c-primary)' }}
              />
            )}
          </div>

          <div className="grid-2">
            <div>
              <label className="muted txt-xs">ประเภท</label>
              <select value={form.type} onChange={e => set('type', e.target.value)} style={selectStyle}>
                {SUPERVISION_TYPES.map(t => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <label className="muted txt-xs">วิธีการนิเทศ</label>
              <select value={form.activity} onChange={e => set('activity', e.target.value)} style={selectStyle}>
                {SUPERVISION_ACTIVITIES.map(a => <option key={a}>{a}</option>)}
              </select>
            </div>
          </div>

          <div>
            <label className="muted txt-xs">ผู้นิเทศ</label>
            <select value={form.supervisor} onChange={e => set('supervisor', e.target.value)} style={selectStyle}>
              {D.STAFF.filter(s => window.isSupervisorRole ? window.isSupervisorRole(s.role) : true).map(s => (
                <option key={s.id} value={s.id}>{s.title}{s.name}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="muted txt-xs" style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span>ผู้รับการนิเทศ</span>
              <span style={{ color: 'var(--c-primary)', fontWeight: 600 }}>
                {selectedSupervisees.length === 0 ? 'ทีมพยาบาล (กลุ่ม)' : `เลือก ${selectedSupervisees.length} คน`}
              </span>
            </label>
            <div style={{ border: '1px solid var(--c-border)', borderRadius: 8, marginTop: 4, maxHeight: 180, overflowY: 'auto', background: 'var(--c-surface)' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderBottom: '1px solid var(--c-border-soft)', cursor: 'pointer', background: selectedSupervisees.length === 0 ? 'var(--c-primary-soft)' : 'transparent' }}>
                <input type="checkbox" checked={selectedSupervisees.length === 0}
                  onChange={() => setSelectedSupervisees([])}
                  style={{ accentColor: 'var(--c-primary)', width: 15, height: 15 }} />
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--c-primary)' }}>👥 ทีมพยาบาล (นิเทศกลุ่ม)</span>
              </label>
              {D.STAFF.map(s => {
                const checked = selectedSupervisees.includes(s.id);
                return (
                  <label key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', borderBottom: '1px solid var(--c-border-soft)', cursor: 'pointer', background: checked ? 'var(--c-primary-soft)' : 'transparent' }}>
                    <input type="checkbox" checked={checked} onChange={() => toggleSupervisee(s.id)}
                      style={{ accentColor: 'var(--c-primary)', width: 15, height: 15, flexShrink: 0 }} />
                    <Avatar name={s.name} size={22} />
                    <span className="txt-sm">{s.title}{s.name}</span>
                    <span className="txt-xs muted" style={{ marginLeft: 'auto' }}>{D.levelById(s.level)?.label || s.level}</span>
                  </label>
                );
              })}
            </div>
            {selectedSupervisees.length === 0 && (
              <div className="txt-xs muted" style={{ marginTop: 4 }}>ไม่เลือกรายบุคคล = นิเทศทั้งกลุ่ม</div>
            )}
          </div>

          {editing && (
            <div>
              <label className="muted txt-xs">สถานะ</label>
              <select value={form.status} onChange={e => set('status', e.target.value)} style={selectStyle}>
                <option value="scheduled">กำหนดการ</option>
                <option value="completed">เสร็จสิ้น</option>
                <option value="cancelled">ยกเลิก</option>
              </select>
            </div>
          )}

          {err && <div style={{ background: '#fee2e2', color: '#991b1b', borderRadius: 8, padding: '8px 12px', fontSize: 13 }}>{err}</div>}

          <button className="btn btn-primary btn-lg" style={{ width: '100%' }} onClick={handleSave} disabled={saving}>
            <Icon name="check" size={14} />{saving ? 'กำลังบันทึก…' : editing ? 'บันทึกการแก้ไข' : 'นัดหมายการนิเทศ'}
          </button>
        </div>
      </div>
    </div>
  );
};

const Planning = () => {
  const [, forceUpdate] = useState(0);
  const refresh = () => forceUpdate(n => n + 1);
  const today = new Date().toISOString().slice(0, 10);
  const [viewYear, setViewYear] = useState(() => parseInt(today.slice(0, 4)));
  const [viewMonth, setViewMonth] = useState(() => parseInt(today.slice(5, 7)) - 1); // 0-indexed
  const [selected, setSelected] = useState(null);
  const [modal, setModal] = useState(null); // null | 'new' | supervision-object (edit)
  const [defaultDate, setDefaultDate] = useState('');

  const fmt = d => d.toISOString().slice(0, 10);

  // First Sunday on or before 1st of month
  const firstDay = new Date(viewYear, viewMonth, 1);
  const startOffset = firstDay.getDay(); // 0=Sun
  const calStart = new Date(firstDay);
  calStart.setDate(1 - startOffset);

  // 6 weeks = 42 cells
  const days = Array.from({ length: 42 }, (_, i) => {
    const d = new Date(calStart);
    d.setDate(calStart.getDate() + i);
    return d;
  });

  const supervisions = D.SUPERVISIONS;
  const eventsByDay = {};
  supervisions.forEach(sv => {
    eventsByDay[sv.date] = eventsByDay[sv.date] || [];
    eventsByDay[sv.date].push(sv);
  });

  const prevMonth = () => {
    if (viewMonth === 0) { setViewYear(y => y - 1); setViewMonth(11); }
    else setViewMonth(m => m - 1);
    setSelected(null);
  };
  const nextMonth = () => {
    if (viewMonth === 11) { setViewYear(y => y + 1); setViewMonth(0); }
    else setViewMonth(m => m + 1);
    setSelected(null);
  };

  const scheduled = supervisions.filter(s => s.status === 'scheduled')
    .sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time));

  const thisMonthTotal = supervisions.filter(s => s.date.startsWith(`${viewYear}-${String(viewMonth+1).padStart(2,'0')}`));
  const thisMonthDone  = thisMonthTotal.filter(s => s.status === 'completed');

  return (
    <div className="page">
      <div className="section-h">
        <div>
          <h2>แผนการนิเทศ <span className="variant-pill">{TH_MONTHS[viewMonth]} {buddhistYear(viewYear)}</span></h2>
          <div className="sub">Clinical Supervision Calendar · One-on-One · Group · Bedside Round</div>
        </div>
        <div className="flex">
          <button className="btn btn-primary" onClick={() => { setDefaultDate(''); setModal('new'); }}>
            <Icon name="plus" size={14} />นัดใหม่
          </button>
        </div>
      </div>

      <div className="split">
        <div className="card">
          <div className="card-header" style={{ paddingBottom: 12 }}>
            <button className="icon-btn" onClick={prevMonth}><Icon name="chevronRight" size={14} style={{ transform: 'rotate(180deg)' }} /></button>
            <h3 style={{ flex: 1, textAlign: 'center' }}>{TH_MONTHS[viewMonth]} {buddhistYear(viewYear)}</h3>
            <button className="icon-btn" onClick={nextMonth}><Icon name="chevronRight" size={14} /></button>
          </div>
          <div className="card-body">
            <div className="calendar">
              {['อา','จ','อ','พ','พฤ','ศ','ส'].map(d => <div key={d} className="cal-head">{d}</div>)}
              {days.map((d, i) => {
                const k = fmt(d);
                const evs = eventsByDay[k] || [];
                const isToday = k === today;
                const inMonth = d.getMonth() === viewMonth;
                return (
                  <div
                    key={i}
                    className={`cal-day ${isToday ? 'today' : ''}`}
                    style={{ opacity: inMonth ? 1 : 0.35, cursor: 'pointer' }}
                    onClick={() => { if (inMonth) { setDefaultDate(k); setModal('new'); } }}
                  >
                    <div className="cal-date">{d.getDate()}</div>
                    {evs.slice(0, 3).map(ev => (
                      <div
                        key={ev.id}
                        className={`cal-event ${ev.type === 'Bedside' ? 'bedside' : ev.type === 'Case Conference' ? 'case' : ''}`}
                        onClick={e => { e.stopPropagation(); setSelected(ev); }}
                      >
                        {ev.time} {ev.topic}
                      </div>
                    ))}
                    {evs.length > 3 && <div className="txt-xs muted">+{evs.length - 3} เพิ่ม</div>}
                  </div>
                );
              })}
            </div>
            <div className="flex" style={{ marginTop: 16, gap: 16 }}>
              <span className="flex txt-xs muted">
                <span style={{ ...svStyle, background: 'var(--c-primary-soft)', borderLeft: '3px solid var(--c-primary)' }} />
                One-on-One / Group
              </span>
              <span className="flex txt-xs muted">
                <span style={{ ...svStyle, background: 'var(--c-accent-blue-soft)', borderLeft: '3px solid var(--c-accent-blue)' }} />
                Bedside
              </span>
              <span className="flex txt-xs muted">
                <span style={{ ...svStyle, background: 'var(--c-warn-soft)', borderLeft: '3px solid var(--c-warn)' }} />
                Case Conference
              </span>
            </div>
          </div>
        </div>

        <div className="stack">
          {selected ? (
            <EventDetail
              event={selected}
              onClose={() => setSelected(null)}
              onEdit={() => { setModal(selected); setSelected(null); }}
              onDelete={async () => {
                if (!confirm('ลบนัดนิเทศนี้?')) return;
                await window.DB.supervisions.delete(selected.id);
                setSelected(null);
                refresh();
              }}
              onStatusChange={async (status) => {
                await window.DB.supervisions.updateStatus(selected.id, status);
                setSelected(null);
                refresh();
              }}
            />
          ) : (
            <div className="card">
              <div className="card-header">
                <h3>กำหนดการที่จะมาถึง</h3>
                <span className="sub">· {scheduled.length} รายการ</span>
              </div>
              <div className="card-body" style={{ padding: 0 }}>
                {scheduled.length === 0 && (
                  <div className="txt-sm muted" style={{ padding: 16 }}>ไม่มีนัดที่กำหนดไว้</div>
                )}
                {scheduled.map(sv => (
                  <div key={sv.id} onClick={() => setSelected(sv)} style={{ padding: '12px 16px', borderBottom: '1px solid var(--c-border-soft)', cursor: 'pointer' }}>
                    <div className="flex-between">
                      <div className="mono txt-xs">{sv.date.slice(5)} · {sv.time}</div>
                      <span className={`badge ${sv.type === 'Bedside' ? 'info' : sv.type === 'Case Conference' ? 'warn' : ''}`}>{sv.type}</span>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600, marginTop: 4 }}>{sv.topic}</div>
                    <div className="txt-xs muted" style={{ marginTop: 2 }}>{staffShort(sv.supervisor)} → {sv.supervisee === 'group' ? 'ทีม' : Array.isArray(sv.supervisee) ? `${sv.supervisee.length} คน` : staffShort(sv.supervisee)}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
          <div className="card card-tight">
            <div className="card-header"><h3>นิเทศเดือนนี้</h3></div>
            <div className="card-body">
              <div className="txt-sm">
                <div className="flex-between" style={{ padding: '6px 0' }}><span>ทั้งหมด</span><strong className="mono">{thisMonthTotal.length} รายการ</strong></div>
                <div className="flex-between" style={{ padding: '6px 0' }}><span>เสร็จสิ้น</span><strong className="mono">{thisMonthDone.length}</strong></div>
                <div className="flex-between" style={{ padding: '6px 0' }}><span>คงเหลือ</span><strong className="mono">{thisMonthTotal.length - thisMonthDone.length}</strong></div>
              </div>
              {thisMonthTotal.length > 0 && (
                <div className="progress" style={{ height: 8, marginTop: 8 }}>
                  <span style={{ width: `${Math.round(thisMonthDone.length / thisMonthTotal.length * 100)}%` }} />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {modal && (
        <PlanningModal
          sv={modal === 'new' ? null : modal}
          defaultDate={modal === 'new' ? defaultDate : undefined}
          onClose={() => setModal(null)}
          onSaved={refresh}
        />
      )}
    </div>
  );
};

const EventDetail = ({ event, onClose, onEdit, onDelete, onStatusChange }) => (
  <div className="card" style={{ borderColor: 'var(--c-primary)' }}>
    <div className="card-header">
      <h3>รายละเอียดนิเทศ</h3>
      <button className="btn btn-sm btn-ghost" style={{ marginLeft: 'auto' }} onClick={onClose}>ปิด</button>
    </div>
    <div className="card-body">
      <div className="mono txt-xs muted">{event.date} · {event.time} น.</div>
      <h3 style={{ margin: '6px 0 10px' }}>{event.topic}</h3>
      <div className="flex" style={{ gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
        <span className={`badge ${event.type === 'Bedside' ? 'info' : event.type === 'Case Conference' ? 'warn' : ''}`}>{event.type}</span>
        {event.activity && <span className="badge">{event.activity}</span>}
        <span className={`badge ${event.status === 'completed' ? 'ok' : event.status === 'cancelled' ? '' : 'warn'}`}>{event.status === 'scheduled' ? 'กำหนดการ' : event.status === 'completed' ? 'เสร็จสิ้น' : 'ยกเลิก'}</span>
      </div>

      <div className="stack txt-sm" style={{ marginBottom: 16 }}>
        <div>
          <div className="muted txt-xs">ผู้นิเทศ</div>
          <div className="flex" style={{ marginTop: 4 }}>
            <Avatar name={D.staffById(event.supervisor)?.name || '?'} size={28} />
            <div>
              <strong>{staffName(event.supervisor)}</strong>
              <div className="txt-xs muted">{D.POSITIONS[D.staffById(event.supervisor)?.pos]}</div>
            </div>
          </div>
        </div>
        <div>
          <div className="muted txt-xs">ผู้รับการนิเทศ</div>
          {event.supervisee === 'group' ? (
            <div className="flex" style={{ marginTop: 4 }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--c-primary-soft)', display: 'grid', placeItems: 'center', fontSize: 14, flexShrink: 0 }}>👥</div>
              <div><strong>ทีมพยาบาลห้องคลอด</strong></div>
            </div>
          ) : Array.isArray(event.supervisee) ? (
            <div className="stack" style={{ gap: 6, marginTop: 4 }}>
              {event.supervisee.map(id => {
                const s = D.staffById(id);
                return s ? (
                  <div key={id} className="flex">
                    <Avatar name={s.name} size={26} />
                    <div>
                      <strong className="txt-sm">{s.title}{s.name}</strong>
                      <div className="txt-xs muted">{D.POSITIONS[s.pos]}</div>
                    </div>
                  </div>
                ) : <span key={id} className="txt-xs muted">{id}</span>;
              })}
            </div>
          ) : (
            <div className="flex" style={{ marginTop: 4 }}>
              <Avatar name={D.staffById(event.supervisee)?.name || '?'} size={28} />
              <div>
                <strong>{staffName(event.supervisee)}</strong>
                <div className="txt-xs muted">{D.POSITIONS[D.staffById(event.supervisee)?.pos]}</div>
              </div>
            </div>
          )}
        </div>
      </div>

      {event.status === 'scheduled' && (
        <button className="btn btn-primary" style={{ width: '100%', marginBottom: 8 }}
          onClick={() => onStatusChange('completed')}>
          <Icon name="check" size={14} />บันทึกว่าเสร็จสิ้น
        </button>
      )}
      <div className="flex" style={{ gap: 8 }}>
        <button className="btn" style={{ flex: 1 }} onClick={onEdit}>
          <Icon name="edit" size={14} />แก้ไข
        </button>
        <button className="btn" style={{ color: 'var(--c-danger)' }} onClick={onDelete}>
          ลบ
        </button>
      </div>
    </div>
  </div>
);

// ===================== Evaluation Forms =====================
const Evaluation = ({ readOnly = false }) => {
  const [layout, setLayout] = useState('inline'); // inline | stack
  const [activeForm, setActiveForm] = useState(D.FORMS[0].id);
  const form = D.FORMS.find(f => f.id === activeForm);
  return (
    <div className="page">
      <div className="section-h">
        <div>
          <h2>{readOnly ? 'ผลประเมินที่ได้รับ' : 'Digital Checklist & Evaluation'}</h2>
          <div className="sub">{readOnly ? 'แบบฟอร์มประเมินที่ผู้นิเทศบันทึกไว้สำหรับคุณ · ดูได้อย่างเดียว' : 'แบบฟอร์มประเมินทักษะ · Real-time feedback · 360° Assessment'}</div>
        </div>
        {!readOnly && (
          <div className="flex">
            <div className="tabs">
              <button className={`tab ${layout==='inline'?'active':''}`} onClick={() => setLayout('inline')}>Inline</button>
              <button className={`tab ${layout==='stack'?'active':''}`} onClick={() => setLayout('stack')}>Stacked</button>
            </div>
            <span className="variant-pill">2 layouts</span>
          </div>
        )}
        {readOnly && (
          <span className="badge" style={{ background: 'var(--c-warn-soft)', color: 'var(--c-warn)', border: '1px solid var(--c-warn)', padding: '4px 12px' }}>
            ดูอย่างเดียว
          </span>
        )}
      </div>

      <div className="split">
        <div className="stack">
          <div className="card">
            <div className="card-header">
              <div className="flex" style={{ gap: 8, flexWrap: 'wrap' }}>
                {D.FORMS.map(f => (
                  <button key={f.id} className={`chip ${activeForm === f.id ? 'active' : ''}`} onClick={() => setActiveForm(f.id)}>
                    {f.title}
                  </button>
                ))}
              </div>
            </div>
            <div className="card-body">
              <div className="flex" style={{ alignItems: 'flex-start', marginBottom: 16, gap: 16 }}>
                <div style={{ flex: 1 }}>
                  <h3 style={{ margin: 0 }}>{form.title}</h3>
                  <div className="mono txt-xs muted" style={{ marginTop: 4 }}>{form.en} · Form: {form.id.toUpperCase()}</div>
                </div>
                <div>
                  <div className="muted txt-xs">ผู้รับการประเมิน</div>
                  <div className="flex" style={{ marginTop: 4 }}>
                    <Avatar name="สุขสิริร์" size={28} />
                    <div className="txt-sm"><strong>น.ส.สุขสิริร์ บุญบุตร</strong><div className="txt-xs muted">พยาบาลวิชาชีพ · 1 ปี · Novice</div></div>
                  </div>
                </div>
              </div>
              {layout === 'inline' ? <FormInline form={form} readOnly={readOnly} /> : <FormStack form={form} readOnly={readOnly} />}
            </div>
          </div>
        </div>
        <FormSidebar />
      </div>
    </div>
  );
};

const FormInline = ({ form, readOnly = false }) => {
  const [scores, setScores] = useState({});
  return (
    <>
      {form.sections.map((sec, si) => (
        <div key={si} className="form-section">
          <h4>{sec.title}</h4>
          {sec.items.map((it, ii) => {
            const key = `${si}-${ii}`;
            return (
              <div key={key} className={`check-row ${scores[key] >= 3 ? 'checked' : ''}`}>
                <span className="label">{it}</span>
                <div className="score-pills">
                  {[1,2,3,4,5].map(s => (
                    <button
                      key={s}
                      className={`score-pill ${scores[key] === s ? 'active' : ''}`}
                      data-score={s}
                      onClick={readOnly ? undefined : () => setScores(p => ({ ...p, [key]: s }))}
                      disabled={readOnly}
                      style={readOnly ? { opacity: scores[key] === s ? 1 : 0.3, cursor: 'default' } : undefined}
                    >
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      ))}
      <FormFooter scores={scores} readOnly={readOnly} />
    </>
  );
};

const FormStack = ({ form, readOnly = false }) => {
  const [scores, setScores] = useState({});
  const labels = ['ไม่ผ่าน', 'ต้องปรับปรุง', 'พอใช้', 'ดี', 'ดีเยี่ยม'];
  let n = 0;
  return (
    <>
      {form.sections.map((sec, si) => (
        <div key={si} className="form-section">
          <h4>{sec.title}</h4>
          {sec.items.map((it, ii) => {
            n++;
            const key = `${si}-${ii}`;
            return (
              <div key={key} className="form-stack-item">
                <div className="item-num">ข้อ {String(n).padStart(2, '0')}</div>
                <div className="item-label">{it}</div>
                <div className="rating-row">
                  {[1,2,3,4,5].map(s => (
                    <label key={s} className={scores[key] === s ? 'active' : ''} style={readOnly ? { pointerEvents: 'none', opacity: scores[key] === s ? 1 : 0.3 } : undefined}>
                      <input type="radio" name={`s-${key}`} onClick={readOnly ? undefined : () => setScores(p => ({ ...p, [key]: s }))} disabled={readOnly} />
                      <div className="mono" style={{ fontSize: 16, fontWeight: 700 }}>{s}</div>
                      <div className="txt-xs">{labels[s-1]}</div>
                    </label>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      ))}
      <FormFooter scores={scores} readOnly={readOnly} />
    </>
  );
};

const FormFooter = ({ scores, readOnly = false }) => {
  const vals = Object.values(scores);
  const total = vals.length;
  const a = total ? avg(vals) : 0;
  return (
    <div style={{ marginTop: 24, padding: 16, border: '1px solid var(--c-border)', borderRadius: 10, background: 'var(--c-surface-2)' }}>
      <div className="flex-between" style={{ marginBottom: 12 }}>
        <div>
          <div className="muted txt-xs">คะแนนรวม</div>
          <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'var(--font-mono)' }}>
            {a.toFixed(2)}<span className="muted txt-sm"> / 5.00</span>
          </div>
        </div>
        <div>
          <div className="muted txt-xs">ตอบแล้ว</div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>{total} ข้อ</div>
        </div>
        {a > 0 && <LevelChip level={Math.round(a)} />}
      </div>

      <div className="grid-2" style={{ gap: 12, marginBottom: 12 }}>
        <div style={{ padding: 12, borderRadius: 8, background: 'var(--c-ok-soft)' }}>
          <div className="flex" style={{ marginBottom: 6 }}>
            <Icon name="sparkles" size={14} />
            <strong className="txt-sm" style={{ color: 'var(--c-ok)' }}>จุดแข็ง</strong>
          </div>
          <textarea
            readOnly={readOnly}
            placeholder="เช่น perineal support ดี · สื่อสารกับมารดาชัดเจน..."
            style={{
              width: '100%', minHeight: 64, padding: 8,
              border: '1px solid rgba(0,0,0,0.08)', borderRadius: 6,
              background: readOnly ? 'rgba(0,0,0,0.03)' : 'rgba(255,255,255,0.6)',
              color: 'var(--c-ink)', resize: readOnly ? 'none' : 'vertical', fontSize: 13,
            }}
            defaultValue="EFM baseline อ่านได้แม่นยำ · ตั้งคำถามตรงประเด็น · เตรียมอุปกรณ์ครบ"
          />
        </div>
        <div style={{ padding: 12, borderRadius: 8, background: 'var(--c-warn-soft)' }}>
          <div className="flex" style={{ marginBottom: 6 }}>
            <Icon name="target" size={14} />
            <strong className="txt-sm" style={{ color: 'var(--c-warn)' }}>จุดที่ต้องพัฒนา</strong>
          </div>
          <textarea
            readOnly={readOnly}
            placeholder="เช่น แยก late vs variable decel ยังสับสน · ต้องทบทวน..."
            style={{
              width: '100%', minHeight: 64, padding: 8,
              border: '1px solid rgba(0,0,0,0.08)', borderRadius: 6,
              background: readOnly ? 'rgba(0,0,0,0.03)' : 'rgba(255,255,255,0.6)',
              color: 'var(--c-ink)', resize: readOnly ? 'none' : 'vertical', fontSize: 13,
            }}
            defaultValue="แยก late vs variable decel ยังสับสน · ต้องทบทวน LIONS"
          />
        </div>
      </div>

      <div style={{ marginBottom: readOnly ? 0 : 12 }}>
        <div className="muted txt-xs" style={{ marginBottom: 6 }}>ข้อเสนอแนะแก่ผู้รับการนิเทศ</div>
        <textarea
          readOnly={readOnly}
          placeholder="พิมพ์ข้อเสนอแนะเพิ่มเติม / แผนพัฒนาต่อไป..."
          style={{
            width: '100%', minHeight: 70, padding: 10,
            border: '1px solid var(--c-border)', borderRadius: 8,
            background: readOnly ? 'var(--c-bg)' : 'var(--c-surface)',
            color: 'var(--c-ink)', resize: readOnly ? 'none' : 'vertical', fontSize: 14,
          }}
          defaultValue="แนะนำเข้า session NCPR เดือนหน้า และฝึก EFM strips กับ APN อีก 10 cases"
        />
      </div>
      {!readOnly && (
        <div className="flex" style={{ gap: 8, justifyContent: 'flex-end', alignItems: 'center' }}>
          <span className="muted txt-xs"><Icon name="signature" size={12} /> ลงนามดิจิทัลทั้งสองฝ่ายเมื่อเสร็จสิ้น</span>
          <button className="btn">บันทึกร่าง</button>
          <button className="btn btn-primary">ส่งและขอลายเซ็น</button>
        </div>
      )}
    </div>
  );
};

const FormSidebar = () => (
  <div className="stack">
    <div className="card card-tight">
      <div className="card-header"><h3>ประเมิน 360°</h3></div>
      <div className="card-body">
        <div className="stack txt-sm">
          <div className="flex-between">
            <span className="flex"><Icon name="user" size={14} /> Self-assessment</span>
            <span className="badge ok">ส่งแล้ว</span>
          </div>
          <div className="flex-between">
            <span className="flex"><Icon name="users" size={14} /> Peer review (2)</span>
            <span className="badge warn">1/2</span>
          </div>
          <div className="flex-between">
            <span className="flex"><Icon name="target" size={14} /> Supervisor</span>
            <span className="badge">กำลังประเมิน</span>
          </div>
        </div>
        <div className="divider" />
        <button className="btn btn-sm" style={{ width: '100%' }}>ดูสรุป 360°</button>
      </div>
    </div>
    <div className="card card-tight">
      <div className="card-header"><h3>ประวัติประเมินครั้งก่อน</h3></div>
      <div className="card-body" style={{ padding: 0 }}>
        {[
          { date: '2026-04-22', form: 'ISBAR Handover', score: 3.4, by: 'n08' },
          { date: '2026-04-12', form: 'EFM Cat-II', score: 2.8, by: 'n01' },
          { date: '2026-03-30', form: 'Normal Delivery', score: 3.0, by: 'n04' },
        ].map((h, i) => (
          <div key={i} style={{ padding: '10px 16px', borderBottom: '1px solid var(--c-border-soft)' }}>
            <div className="flex-between">
              <strong className="txt-sm">{h.form}</strong>
              <span className="mono txt-xs">{h.score.toFixed(2)}</span>
            </div>
            <div className="txt-xs muted">{h.date} · โดย {staffShort(h.by)}</div>
          </div>
        ))}
      </div>
    </div>
    <div className="card card-tight" style={{ background: 'var(--c-warn-soft)', borderColor: 'transparent' }}>
      <div className="card-body">
        <strong className="txt-sm" style={{ color: 'var(--c-warn)' }}>⚠ PDPA</strong>
        <div className="txt-xs" style={{ marginTop: 4 }}>ข้อมูลประเมินเป็นความลับ ตามแนวทาง PDPA ใช้เพื่อการพัฒนาบุคลากรเท่านั้น</div>
      </div>
    </div>
  </div>
);

// ===================== Bedside Logbook =====================
const Logbook = ({ role }) => {
  const canEdit = window.isSupervisorRole ? window.isSupervisorRole(role) : false;
  const [creating, setCreating] = useState(false);
  return (
    <div className="page">
      <div className="section-h">
        <div>
          <h2>Bedside Supervision Log</h2>
          <div className="sub">บันทึกการนิเทศหน้างานด้วยแท็บเล็ต · ใช้เวลา &lt; 60 วินาที</div>
        </div>
        <div className="flex">
          <button className="btn"><Icon name="filter" size={14} />ตัวกรอง</button>
          {canEdit && <button className="btn btn-primary" onClick={() => setCreating(true)}><Icon name="plus" size={14} />บันทึกใหม่</button>}
        </div>
      </div>

      <div className="split">
        <div className="card">
          <div className="card-header">
            <h3>บันทึกล่าสุด</h3>
            <span className="sub">· {D.LOGS.length} รายการ · 7 วันที่ผ่านมา</span>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            <table className="t">
              <thead>
                <tr>
                  <th>เวลา</th>
                  <th>ผู้รับการนิเทศ</th>
                  <th>กิจกรรม</th>
                  <th>หัวข้อ</th>
                  <th>คะแนน</th>
                </tr>
              </thead>
              <tbody>
                {D.LOGS.map(lg => (
                  <tr key={lg.id}>
                    <td>
                      <div className="mono txt-xs">{lg.date.slice(5)}</div>
                      <div className="mono txt-xs muted">{lg.time}</div>
                    </td>
                    <td>
                      <div className="flex">
                        <Avatar name={D.staffById(lg.supervisee).name} size={28} />
                        <div>
                          <strong>{D.staffById(lg.supervisee).name}</strong>
                          <div className="txt-xs muted">โดย {staffShort(lg.supervisor)}</div>
                        </div>
                      </div>
                    </td>
                    <td><span className="badge">{lg.activity}</span></td>
                    <td>
                      <div className="txt-sm" style={{ fontWeight: 500 }}>{lg.topic}</div>
                      <div className="txt-xs muted" style={{ maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>“{lg.note}”</div>
                    </td>
                    <td><LevelChip level={lg.score} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {creating ? <LogbookQuickAdd onClose={() => setCreating(false)} /> : <LogbookSidebar />}
      </div>
    </div>
  );
};

const LogbookQuickAdd = ({ onClose }) => {
  const [score, setScore] = useState(null);
  const [activity, setActivity] = useState(null);
  const [supervisee, setSupervisee] = useState(null);
  const supervisees = D.STAFF.filter(s => s.role === 'supervisee');
  return (
    <div className="card" style={{ borderColor: 'var(--c-primary)' }}>
      <div className="card-header">
        <h3>บันทึก Bedside ใหม่</h3>
        <button className="btn btn-sm btn-ghost" style={{ marginLeft: 'auto' }} onClick={onClose}>ยกเลิก</button>
      </div>
      <div className="card-body stack">
        <div>
          <label className="muted txt-xs">ผู้รับการนิเทศ</label>
          <div className="chips" style={{ marginTop: 6 }}>
            {supervisees.slice(0, 7).map(s => (
              <button key={s.id} className={`chip ${supervisee === s.id ? 'active' : ''}`} onClick={() => setSupervisee(s.id)}>
                {s.name.split(' ')[0]}
              </button>
            ))}
          </div>
        </div>
        <div>
          <label className="muted txt-xs">กิจกรรมการนิเทศ (7 ประการ)</label>
          <div className="chips" style={{ marginTop: 6 }}>
            {['Round','Conference','Teaching','Counseling','Problem-solving','Observation','Participation'].map(a => (
              <button key={a} className={`chip ${activity === a ? 'active' : ''}`} onClick={() => setActivity(a)}>{a}</button>
            ))}
          </div>
        </div>
        <div>
          <label className="muted txt-xs">หัวข้อ / Skill</label>
          <input
            placeholder="เช่น ทำคลอดปกติ G1P0..."
            style={{
              width: '100%', padding: 10, marginTop: 6,
              border: '1px solid var(--c-border)', borderRadius: 8,
              background: 'var(--c-surface)', color: 'var(--c-ink)',
            }}
          />
        </div>
        <div>
          <label className="muted txt-xs">คะแนน (0.0 – 5.0)</label>
          <div className="flex" style={{ alignItems: 'center', gap: 12, marginTop: 6 }}>
            <input
              type="range" min="0" max="5" step="0.1"
              value={score ?? 0}
              onChange={e => setScore(parseFloat(e.target.value))}
              style={{ flex: 1, accentColor: 'var(--c-primary)', height: 24 }}
            />
            <input
              type="number" min="0" max="5" step="0.1"
              value={score ?? ''} placeholder="0.0"
              onChange={e => {
                const v = e.target.value === '' ? null : Math.max(0, Math.min(5, parseFloat(e.target.value) || 0));
                setScore(v);
              }}
              style={{
                width: 80, padding: '8px 10px',
                border: '1px solid var(--c-border)', borderRadius: 8,
                background: 'var(--c-surface)', color: 'var(--c-ink)',
                fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 16, textAlign: 'center',
              }}
            />
            <span className="muted mono">/ 5.0</span>
            {score != null && <LevelChip level={Math.round(Math.max(1, score))} />}
          </div>
          <div className="flex" style={{ gap: 4, marginTop: 8, fontSize: 11, color: 'var(--c-ink-muted)' }}>
            {D.LEVELS.map((lv, i) => (
              <div key={lv.id} style={{ flex: 1, textAlign: i === 0 ? 'left' : i === 4 ? 'right' : 'center' }}>
                <strong className="mono">{lv.n}</strong> {lv.label}
              </div>
            ))}
          </div>
        </div>
        <div>
          <label className="muted txt-xs">บันทึกย่อ (Note)</label>
          <textarea
            placeholder="สังเกต/ข้อเสนอแนะแบบสั้น..."
            style={{
              width: '100%', minHeight: 70, padding: 10, marginTop: 6,
              border: '1px solid var(--c-border)', borderRadius: 8,
              background: 'var(--c-surface)', color: 'var(--c-ink)',
              resize: 'vertical', fontSize: 14,
            }}
          />
        </div>
        <button className="btn btn-primary btn-lg" style={{ width: '100%' }}>
          <Icon name="check" size={14} />บันทึก (เวลา ~30 วินาที)
        </button>
      </div>
    </div>
  );
};

const LogbookSidebar = () => (
  <div className="stack">
    <div className="card card-tight">
      <div className="card-header"><h3>7 กิจกรรมการนิเทศ</h3><span className="sub">เดือนนี้</span></div>
      <div className="card-body">
        {[
          { name: 'Round (เยี่ยมตรวจ)', count: 12 },
          { name: 'Conference', count: 4 },
          { name: 'Teaching', count: 9 },
          { name: 'Counseling', count: 6 },
          { name: 'Problem-solving', count: 3 },
          { name: 'Observation', count: 5 },
          { name: 'Participation', count: 8 },
        ].map(a => (
          <div key={a.name} className="flex-between txt-sm" style={{ padding: '6px 0' }}>
            <span>{a.name}</span>
            <strong className="mono">{a.count}</strong>
          </div>
        ))}
      </div>
    </div>
    <div className="card card-tight">
      <div className="card-header"><h3>ผู้รับการนิเทศบ่อย</h3></div>
      <div className="card-body" style={{ padding: 0 }}>
        {D.STAFF.filter(s => s.role === 'supervisee').slice(0, 5).map((s, i) => (
          <div key={s.id} className="flex" style={{ padding: '10px 16px', borderBottom: '1px solid var(--c-border-soft)' }}>
            <Avatar name={s.name} size={28} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="txt-sm" style={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
              <div className="txt-xs muted">{D.POSITIONS[s.pos]}</div>
            </div>
            <strong className="mono">{12 - i * 2}</strong>
          </div>
        ))}
      </div>
    </div>
  </div>
);

Object.assign(window, { Planning, Evaluation, Logbook, PlanningModal });
