// Five Nodes Hospital — Today's patients (operational ops view)
const { useState: useStateT, useEffect: useEffectT } = React;

function statusLabel(key) {
  const t = (k) => window.__t ? window.__t(k) : k;
  const map = {
    scheduled:  { label: t('status.scheduled'),  color: 'var(--fg-3)',         bg: 'var(--bg-soft)' },
    waiting:    { label: t('status.waiting'),    color: 'var(--warn)',         bg: 'rgba(180,83,9,0.12)' },
    checked_in: { label: t('status.checkedIn'),  color: 'var(--accent-deep)',  bg: 'var(--accent-soft)' },
    in_room:    { label: t('status.inRoom'),     color: 'var(--accent-deep)',  bg: 'var(--accent-soft)' },
    completed:  { label: t('status.completed'),  color: 'var(--pos)',          bg: 'rgba(4,120,87,0.12)' },
    no_show:    { label: t('status.noShow'),     color: 'var(--neg)',          bg: 'rgba(185,28,28,0.10)' }
  };
  return map[key] || map.scheduled;
}

function specInfoT(code) {
  const s = (window.__data.specialties || []).find(x => x.code === code);
  return { name: s?.name || code, color: s?.color || 'var(--fg-3)' };
}

const TodayPatients = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  const todayMock = window.__data.todayAppointments || [];
  const [filter, setFilter] = useStateT('all');

  // Optionally augment with live appointments scheduled today
  const [liveToday, setLiveToday] = useStateT([]);
  useEffectT(() => {
    const today = new Date(); today.setHours(0,0,0,0);
    const tom = new Date(today); tom.setDate(tom.getDate() + 1);
    let cancelled = false;
    window.__api.sbGet('hsp_appointments', {
      'select': 'id,patient_name,doctor_name,specialty_code,scheduled_for,status',
      'scheduled_for': 'gte.' + today.toISOString(),
      'order':         'scheduled_for.asc',
      'limit':         '100'
    }).then(rows => {
      if (cancelled) return;
      setLiveToday((rows || []).filter(r => r.scheduled_for < tom.toISOString()).map(r => ({
        time: new Date(r.scheduled_for).toTimeString().slice(0,5),
        patient: r.patient_name,
        doctor: r.doctor_name,
        specialty: r.specialty_code,
        status: r.status === 'booked' ? 'scheduled' : r.status,
        reason: '',
        isLive: true
      })));
    }).catch(e => console.warn('[today]', e.message));
    return () => { cancelled = true; };
  }, []);

  const all = [...liveToday, ...todayMock.map(t => ({ ...t, isLive: false }))]
    .sort((a, b) => a.time.localeCompare(b.time));

  const filtered = filter === 'all' ? all : all.filter(a => a.status === filter);
  const statusCounts = {};
  all.forEach(a => { statusCounts[a.status] = (statusCounts[a.status] || 0) + 1; });

  return (
    <div className="content view">
      <div className="section-head">
        <div>
          <div className="sub">{new Date().toLocaleDateString(window.__lang === 'ar' ? 'ar-QA' : 'en-US', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })} · {all.length} {t('today.sub')}</div>
          <h2>{t('today.title').replace(t('today.title.em'), '').trim()} <em>{t('today.title.em')}</em></h2>
        </div>
        <div className="pill-tabs">
          <button className={filter === 'all' ? 'active' : ''} onClick={() => setFilter('all')}>{t('today.filter.all')} ({all.length})</button>
          <button className={filter === 'waiting' ? 'active' : ''} onClick={() => setFilter('waiting')}>{t('today.filter.waiting')} ({statusCounts.waiting || 0})</button>
          <button className={filter === 'in_room' ? 'active' : ''} onClick={() => setFilter('in_room')}>{t('today.filter.inRoom')} ({statusCounts.in_room || 0})</button>
          <button className={filter === 'completed' ? 'active' : ''} onClick={() => setFilter('completed')}>{t('today.filter.done')} ({statusCounts.completed || 0})</button>
        </div>
      </div>

      <div className="card">
        <div className="card-body flush">
          <div style={{ display: 'grid', gridTemplateColumns: '70px 1fr 1.4fr 130px 120px 100px', padding: '12px 18px', borderBottom: '1px solid var(--line)', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.1em', gap: 10 }}>
            <div>{t('today.col.time')}</div><div>{t('today.col.patient')}</div><div>{t('today.col.doctor')}</div><div>{t('today.col.reason')}</div><div>{t('today.col.status')}</div><div></div>
          </div>
          {filtered.length === 0 && (
            <div style={{ padding: 28, textAlign: 'center', color: 'var(--fg-4)', fontSize: 13 }}>{t('today.empty')}</div>
          )}
          {filtered.map((a, i) => {
            const sp = specInfoT(a.specialty);
            const st = statusLabel(a.status);
            return (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 1.4fr 130px 120px 100px', padding: '14px 18px', borderTop: '1px solid var(--line)', alignItems: 'center', gap: 10, fontSize: 13 }}>
                <div className="mono" style={{ fontWeight: 600 }}>{a.time}</div>
                <div>
                  <div style={{ fontWeight: 500 }}>{a.patient}</div>
                  {a.isLive && <span style={{ display: 'inline-block', fontSize: 8, fontWeight: 700, padding: '1px 5px', borderRadius: 3, background: 'var(--accent-soft)', color: 'var(--accent-deep)', letterSpacing: '0.06em', marginTop: 3 }}>{t('common.live')}</span>}
                </div>
                <div>
                  <div>{a.doctor}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: sp.color }} />
                    {sp.name}
                  </div>
                </div>
                <div style={{ fontSize: 12, color: 'var(--fg-2)' }}>{a.reason || '—'}</div>
                <div>
                  <span style={{ fontSize: 10.5, fontWeight: 600, padding: '4px 10px', borderRadius: 4, background: st.bg, color: st.color, border: '1px solid ' + st.color + '33', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{st.label}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <button className="btn ghost" style={{ padding: '4px 8px' }}><Icon name="more" size={13} /></button>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

window.TodayPatients = TodayPatients;
