// Five Nodes Hospital — Appointments calendar (week view)
const { useState: useStateAp, useEffect: useEffectAp, useMemo: useMemoAp } = React;

const HOURS = Array.from({ length: 13 }, (_, i) => 8 + i); // 08:00–20:00
const DAYS_KEYS = ['appts.day.sun','appts.day.mon','appts.day.tue','appts.day.wed','appts.day.thu','appts.day.fri','appts.day.sat'];

function startOfWeek(date) {
  const d = new Date(date);
  d.setHours(0,0,0,0);
  const diff = d.getDay(); // Sun=0
  d.setDate(d.getDate() - diff);
  return d;
}
function fmtDate(d) {
  return d.toLocaleDateString('en-US', { day: 'numeric', month: 'short' });
}

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

const Appointments = () => {
  const t = (k) => window.__t ? window.__t(k) : k;
  const [weekStart, setWeekStart] = useStateAp(() => startOfWeek(new Date()));
  const [liveAppts, setLiveAppts] = useStateAp([]);
  const [loading, setLoading] = useStateAp(true);
  const [filter, setFilter] = useStateAp('all'); // all | live | demo
  const [pulseId, setPulseId] = useStateAp(null);
  const pulseRef = React.useRef(null);

  const days = useMemoAp(() => Array.from({ length: 7 }, (_, i) => {
    const d = new Date(weekStart); d.setDate(d.getDate() + i); return d;
  }), [weekStart]);

  // Tutorial popup stashes the freshly-created appointment id and navigates
  // here — pulse-highlight + scroll-into-view the matching card, then clear.
  useEffectAp(() => {
    if (!window.__pulseRowId) return;
    if (liveAppts.some(a => a.id === window.__pulseRowId)) {
      setPulseId(window.__pulseRowId);
      window.__pulseRowId = null;
    }
  }, [liveAppts]);
  useEffectAp(() => {
    if (!pulseId) return;
    if (pulseRef.current) pulseRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
    const t = setTimeout(() => setPulseId(null), 8000);
    return () => clearTimeout(t);
  }, [pulseId]);

  useEffectAp(() => {
    const start = new Date(weekStart).toISOString();
    const end = new Date(weekStart); end.setDate(end.getDate() + 7);
    const endIso = end.toISOString();
    let cancelled = false;
    setLoading(true);
    window.__api.sbGet('hsp_appointments', {
      'select': 'id,patient_name,doctor_name,specialty_code,scheduled_for,duration_min,status',
      'scheduled_for': 'gte.' + start,
      'order': 'scheduled_for.asc', 'limit': '500'
    }).then(rows => {
      if (cancelled) return;
      const inWeek = (rows || []).filter(r => r.scheduled_for < endIso);
      setLiveAppts(inWeek);
    }).catch(e => console.warn('[appts]', e.message))
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [weekStart]);

  // Scatter mock appointments across the Qatar workweek (Sun–Thu) of the
  // visible weekStart, so demo data fills any week the user navigates to —
  // not just today. Round-robin assignment keeps it deterministic per week.
  const mockAppts = useMemoAp(() => {
    const WORK_DAYS = [0, 1, 2, 3, 4]; // Sun..Thu offsets from weekStart
    return (window.__data.todayAppointments || []).map((a, i) => {
      const [hh, mm] = a.time.split(':').map(Number);
      const dayOffset = WORK_DAYS[i % WORK_DAYS.length];
      const d = new Date(weekStart);
      d.setDate(d.getDate() + dayOffset);
      d.setHours(hh, mm, 0, 0);
      return {
        id: 'mock-' + i,
        isMock: true,
        patient_name: a.patient,
        doctor_name: a.doctor,
        specialty_code: a.specialty,
        scheduled_for: d.toISOString(),
        duration_min: 20,
        status: 'booked',
        reason: a.reason
      };
    });
  }, [weekStart]);

  const allAppts = filter === 'live' ? liveAppts : filter === 'demo' ? mockAppts : [...liveAppts, ...mockAppts];

  const stats = useMemoAp(() => {
    const total = allAppts.length;
    const bySpec = {};
    allAppts.forEach(a => { bySpec[a.specialty_code] = (bySpec[a.specialty_code] || 0) + 1; });
    return { total, bySpec };
  }, [allAppts]);

  return (
    <div className="content view">
      <div className="section-head">
        <div>
          <div className="sub">{t('appts.sub.weekOf')} {fmtDate(weekStart)} · {stats.total} {t('appts.sub.appts')} {liveAppts.length > 0 && <> · <span style={{ color: 'var(--accent-deep)' }}>{liveAppts.length} {t('common.live').toLowerCase()}</span></>}</div>
          <h2>{t('appts.title').replace(t('appts.title.em'), '').trim()} <em>{t('appts.title.em')}</em></h2>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn ghost" onClick={() => { const d = new Date(weekStart); d.setDate(d.getDate() - 7); setWeekStart(d); }}>← {t('common.previous')}</button>
          <button className="btn" onClick={() => setWeekStart(startOfWeek(new Date()))}>{t('common.today')}</button>
          <button className="btn ghost" onClick={() => { const d = new Date(weekStart); d.setDate(d.getDate() + 7); setWeekStart(d); }}>{t('common.next')} →</button>
          <div className="pill-tabs">
            <button className={filter === 'all' ? 'active' : ''} onClick={() => setFilter('all')}>{t('common.all')}</button>
            <button className={filter === 'live' ? 'active' : ''} onClick={() => setFilter('live')}>{t('common.live')}</button>
            <button className={filter === 'demo' ? 'active' : ''} onClick={() => setFilter('demo')}>{t('common.demo')}</button>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-body" style={{ padding: 0, overflowX: 'auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '60px repeat(7, 1fr)', minWidth: 900 }}>
            <div style={{ padding: '12px 8px', borderBottom: '1px solid var(--line)' }}></div>
            {days.map((d, i) => {
              const isToday = d.toDateString() === new Date().toDateString();
              return (
                <div key={i} style={{ padding: '12px 8px', borderBottom: '1px solid var(--line)', borderLeft: '1px solid var(--line)', textAlign: 'center', background: isToday ? 'var(--accent-soft)' : 'transparent' }}>
                  <div className="mono" style={{ fontSize: 10, color: isToday ? 'var(--accent-deep)' : 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>{t(DAYS_KEYS[i])}</div>
                  <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4, color: isToday ? 'var(--accent-deep)' : 'var(--fg)' }}>{d.getDate()} {d.toLocaleDateString('en-US', { month: 'short' })}</div>
                </div>
              );
            })}

            {HOURS.map(hour => (
              <React.Fragment key={hour}>
                <div style={{ padding: '4px 8px', borderTop: '1px solid var(--line)', minHeight: 80 }}>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-4)' }}>{String(hour).padStart(2,'0')}:00</div>
                </div>
                {days.map((d, di) => {
                  const slotAppts = allAppts.filter(a => {
                    const ad = new Date(a.scheduled_for);
                    return ad.toDateString() === d.toDateString() && ad.getHours() === hour;
                  });
                  return (
                    <div key={di} style={{ borderTop: '1px solid var(--line)', borderLeft: '1px solid var(--line)', minHeight: 80, padding: 4, position: 'relative', display: 'flex', flexDirection: 'column', gap: 3 }}>
                      {slotAppts.map((a, ai) => {
                        const ad = new Date(a.scheduled_for);
                        const time = ad.toTimeString().slice(0,5);
                        const color = specColor(a.specialty_code);
                        const isPulsing = a.id && a.id === pulseId;
                        return (
                          <div key={a.id || ai}
                            ref={isPulsing ? pulseRef : null}
                            className={isPulsing ? 'appt-card is-pulsing' : 'appt-card'}
                            title={`${time} · ${a.patient_name} → ${a.doctor_name}${a.reason ? ' · ' + a.reason : ''}`}
                            style={{ fontSize: 10.5, padding: '4px 6px', borderRadius: 4, background: color + '22', borderLeft: '2px solid ' + color, color: 'var(--fg)', cursor: 'pointer', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            <div className="mono" style={{ fontSize: 9, color: 'var(--fg-3)' }}>{time}</div>
                            <div style={{ fontWeight: 500 }}>{a.patient_name}</div>
                            <div style={{ color: 'var(--fg-3)', fontSize: 9.5 }}>{a.doctor_name}</div>
                          </div>
                        );
                      })}
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>

      <div style={{ marginTop: 14, display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center' }}>
        <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>{t('appts.legend')}</span>
        {window.__data.specialties.map(s => (
          <span key={s.code} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'var(--fg-2)' }}>
            <span style={{ width: 10, height: 10, borderRadius: 2, background: s.color }} />
            {s.name}
          </span>
        ))}
      </div>
    </div>
  );
};

window.Appointments = Appointments;
