/* global React, window, Icon */
const { useState: useSchedState, useEffect: useSchedEffect, useMemo: useSchedMemo } = React;

// Circular employee avatar (clickable → profile).
function SchedAvatar({ id, size = 34 }) {
  const [err, setErr] = useSchedState(false);
  const src = (err || !id) ? '/img/avatar-person.svg' : `/faces/${id}.jpg`;
  return <img src={src} alt="" onError={() => setErr(true)}
    onClick={() => id && window.openProfile && window.openProfile(id)} title={id ? 'ดูโปรไฟล์' : ''}
    style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flex: 'none',
      cursor: id ? 'pointer' : 'default', border: '1px solid var(--line)' }} />;
}

// ตารางเวร — weekly grid (employee × 7 days). Click a cell to assign a shift,
// mark a day off, or clear back to the employee's default. Rotating shifts.
function SchedulePage({ role }) {
  const [weekStart, setWeekStart] = useSchedState(() => mondayOf(window.TODAY || todayStr()));
  const [deptFilter, setDeptFilter] = useSchedState('all');
  const [sched, setSched] = useSchedState({});      // { "empId|date": {shift_id, shift_name} }
  const [editing, setEditing] = useSchedState(null); // { empId, date, x, y }
  const canEdit = role === 'admin' || role === 'hr';

  const days = useSchedMemo(() => Array.from({ length: 7 }, (_, i) => addDays(weekStart, i)), [weekStart]);
  const weekEnd = days[6];

  const employees = useSchedMemo(() => {
    const list = window.EMPLOYEES || [];
    return deptFilter === 'all' ? list : list.filter((e) => String(e.department_id) === deptFilter);
  }, [deptFilter, window.EMPLOYEES]);

  const load = async () => {
    const q = new URLSearchParams({ from: weekStart, to: weekEnd });
    if (deptFilter !== 'all') q.set('department_id', deptFilter);
    const r = await fetch('/api/schedule?' + q.toString(), { credentials: 'include' });
    if (r.ok) {
      const d = await r.json();
      const map = {};
      for (const row of d.rows) map[`${row.employee_id}|${row.date}`] = row;
      setSched(map);
    }
  };
  useSchedEffect(() => { load(); }, [weekStart, deptFilter]);

  const assign = async (empId, date, shiftId, clear) => {
    setEditing(null);
    await fetch('/api/schedule', {
      method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ employee_id: empId, date, shift_id: shiftId, clear: !!clear }),
    });
    load();
  };

  const shiftColor = (id) => {
    // distribute palette by shift id for a stable color per shift
    const palette = ['coral', 'primary', 'mint', 'yellow', 'cyan', 'magenta'];
    return palette[(id || 0) % palette.length];
  };

  return (
    <div data-screen-label="Schedule">
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, margin: 0 }}>ตารางเวร / Schedule</h1>
          <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 4 }}>กำหนดกะรายวัน (กะหมุนเวียน) · คลิกช่องเพื่อเลือกกะ / วันหยุด</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="gv-btn no sm" onClick={() => setWeekStart(addDays(weekStart, -7))}><Icon name="chevron-right" size={13} style={{ transform: 'rotate(180deg)' }}/> สัปดาห์ก่อน</button>
          <button className="gv-btn no sm" onClick={() => setWeekStart(mondayOf(todayStr()))}>สัปดาห์นี้</button>
          <button className="gv-btn no sm" onClick={() => setWeekStart(addDays(weekStart, 7))}>สัปดาห์ถัดไป <Icon name="chevron-right" size={13}/></button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 14 }}>
        <span className="gv-chip c-gray">{fmtRange(weekStart, weekEnd)}</span>
        <div style={{ flex: 1 }}/>
        <select className="gv-select" value={deptFilter} onChange={(e) => setDeptFilter(e.target.value)} style={{ maxWidth: 200, width: 'auto' }}>
          <option value="all">ทุกแผนก</option>
          {(window.DEPARTMENTS || []).map((d) => <option key={d.id} value={String(d.id)}>{d.name}</option>)}
        </select>
      </div>

      <div className="gv-card">
        <div style={{ overflowX: 'auto' }}>
          <table className="gv-tbl" style={{ minWidth: 860 }}>
            <thead>
              <tr>
                <th style={{ minWidth: 210, position: 'sticky', left: 0, background: 'var(--surface-2)', zIndex: 1 }}>พนักงาน</th>
                {days.map((d) => {
                  const wd = new Date(d + 'T00:00:00').getDay();
                  const isWeekend = wd === 0 || wd === 6;
                  return (
                    <th key={d} style={{ textAlign: 'center', minWidth: 92, color: isWeekend ? 'var(--coral-ink)' : undefined }}>
                      {['อา','จ','อ','พ','พฤ','ศ','ส'][wd]}<br/>
                      <span className="tnum" style={{ fontSize: 11, fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>{d.slice(8)}/{d.slice(5,7)}</span>
                    </th>
                  );
                })}
              </tr>
            </thead>
            <tbody>
              {employees.length === 0 ? (
                <tr><td colSpan={8}><div className="gv-empty">ไม่มีพนักงาน</div></td></tr>
              ) : employees.map((e) => (
                <tr key={e.id}>
                  <td style={{ position: 'sticky', left: 0, background: 'var(--surface)', zIndex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <SchedAvatar id={e.id}/>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{e.first_name} {e.last_name}</div>
                        <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{e.id}{e.department_name ? ` · ${e.department_name}` : ''}</div>
                      </div>
                    </div>
                  </td>
                  {days.map((d) => {
                    const cell = sched[`${e.id}|${d}`];
                    const isOff = cell && cell.shift_id == null;
                    return (
                      <td key={d} style={{ textAlign: 'center', padding: 6 }}>
                        <button
                          onClick={() => canEdit && setEditing({ empId: e.id, date: d, name: `${e.first_name} ${e.last_name}` })}
                          disabled={!canEdit}
                          style={{
                            width: '100%', minHeight: 36, borderRadius: 10, cursor: canEdit ? 'pointer' : 'default',
                            border: '1px solid var(--line)', fontSize: 11.5, fontWeight: 600, padding: '4px 2px',
                            background: cell ? (isOff ? 'var(--surface-2)' : `var(--${shiftColor(cell.shift_id)}-soft)`) : 'transparent',
                            color: cell ? (isOff ? 'var(--ink-4)' : `var(--${shiftColor(cell.shift_id)}-ink)`) : 'var(--ink-4)',
                          }}>
                          {cell ? (isOff ? 'หยุด' : cell.shift_name) : <span style={{ opacity: 0.4 }}>—</span>}
                        </button>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {editing && (
        <div onClick={() => setEditing(null)} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(15,23,42,.45)', display: 'grid', placeItems: 'center', padding: 20 }}>
          <div className="gv-card" onClick={(ev) => ev.stopPropagation()} style={{ width: 'min(420px,100%)', maxHeight: '90vh', overflow: 'auto' }}>
            <div className="gv-card-h"><b>เลือกกะ — {editing.name}</b></div>
            <div className="gv-card-b">
              <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginBottom: 12 }}>
                วันที่ {new Date(editing.date + 'T00:00:00').toLocaleDateString('th-TH', { weekday: 'long', day: 'numeric', month: 'long' })}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {(window.SHIFTS || []).map((s) => (
                  <button key={s.id} className="gv-btn no" style={{ justifyContent: 'flex-start' }}
                    onClick={() => assign(editing.empId, editing.date, s.id, false)}>
                    <span style={{ width: 10, height: 10, borderRadius: 3, background: `var(--${shiftColor(s.id)})`, marginRight: 8, flex: 'none' }}/>
                    {s.name} <span style={{ fontSize: 11, color: 'var(--ink-4)', marginLeft: 6 }}>{s.start_time}–{s.end_time}</span>
                  </button>
                ))}
                <button className="gv-btn no" style={{ justifyContent: 'flex-start' }}
                  onClick={() => assign(editing.empId, editing.date, null, false)}>
                  <Icon name="x" size={13}/> วันหยุด (off)
                </button>
                <button className="gv-btn ghost" style={{ justifyContent: 'flex-start' }}
                  onClick={() => assign(editing.empId, editing.date, null, true)}>
                  <Icon name="refresh" size={13}/> ใช้ค่าเริ่มต้น (ลบการกำหนด)
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── local date helpers (avoid toISOString UTC shift) ────────────────────────
function todayStr() {
  const d = new Date(); const p = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`;
}
function addDays(date, n) {
  const d = new Date(date + 'T00:00:00'); d.setDate(d.getDate() + n);
  const p = (x) => String(x).padStart(2, '0');
  return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`;
}
function mondayOf(date) {
  const d = new Date(date + 'T00:00:00');
  const wd = d.getDay();                 // 0=Sun..6=Sat
  const diff = wd === 0 ? -6 : 1 - wd;   // back to Monday
  return addDays(date, diff);
}
function fmtRange(a, b) {
  const f = (x) => new Date(x + 'T00:00:00').toLocaleDateString('th-TH', { day: 'numeric', month: 'short' });
  return `${f(a)} – ${f(b)}`;
}

window.SchedulePage = SchedulePage;
