// Shifts page — the bot's primary workflow.
// On-duty board, today's clock activity, hours leaderboard, weekly report preview, Sheets sync.

const COMPANIES = [
  { key: 'pl', name: 'Pacific Logistics', color: '#7cffb2', onduty: 8, total: 24, target: 12 },
  { key: 'bu', name: 'Bangkok Underground', color: '#c8a8ff', onduty: 14, total: 38, target: 20 },
  { key: 'sa', name: 'Saint Andrews PD', color: '#5eead4', onduty: 6, total: 18, target: 10 },
  { key: 'hp', name: 'Highway Patrol HQ', color: '#fb7185', onduty: 5, total: 14, target: 8 },
  { key: 'mg', name: 'Mercy General Hospital', color: '#fbbf24', onduty: 3, total: 10, target: 6 },
  { key: 'ym', name: 'Yamamoto Family', color: '#60a5fa', onduty: 2, total: 6, target: 4 },
];

const ON_DUTY = [
  { id: '401123…', name: 'ake', company: 'Pacific Logistics', companyColor: '#7cffb2', since: '08:42', dur: '5h 28m', shift: '#4291' },
  { id: '552901…', name: 'nine', company: 'Bangkok Underground', companyColor: '#c8a8ff', since: '09:12', dur: '4h 58m', shift: '#4288' },
  { id: '661044…', name: 'noi', company: 'Bangkok Underground', companyColor: '#c8a8ff', since: '09:30', dur: '4h 40m', shift: '#4289' },
  { id: '884330…', name: 'pim', company: 'Pacific Logistics', companyColor: '#7cffb2', since: '10:01', dur: '4h 09m', shift: '#4292' },
  { id: '729811…', name: 'tar', company: 'Highway Patrol HQ', companyColor: '#fb7185', since: '11:04', dur: '3h 06m', shift: '#4290' },
  { id: '991028…', name: 'bell', company: 'Saint Andrews PD', companyColor: '#5eead4', since: '11:48', dur: '2h 22m', shift: '#4293' },
  { id: '728112…', name: 'kong', company: 'Bangkok Underground', companyColor: '#c8a8ff', since: '12:15', dur: '1h 55m', shift: '#4294' },
  { id: '102998…', name: 'ploy', company: 'Mercy General Hospital', companyColor: '#fbbf24', since: '12:30', dur: '1h 40m', shift: '#4295' },
];

const CLOCK_EVENTS = [
  { t: '14:10', kind: 'in', user: 'kong', company: 'Bangkok Underground', color: '#c8a8ff', shift: '#4294' },
  { t: '13:52', kind: 'out', user: 'rin', company: 'Saint Andrews PD', color: '#5eead4', dur: '3h 12m' },
  { t: '13:30', kind: 'in', user: 'ploy', company: 'Mercy General Hospital', color: '#fbbf24', shift: '#4295' },
  { t: '13:04', kind: 'out', user: 'mint', company: 'Highway Patrol HQ', color: '#fb7185', dur: '4h 02m' },
  { t: '12:48', kind: 'break', user: 'noi', company: 'Bangkok Underground', color: '#c8a8ff' },
  { t: '12:15', kind: 'in', user: 'kong', company: 'Bangkok Underground', color: '#c8a8ff', shift: '#4294' },
  { t: '11:48', kind: 'in', user: 'bell', company: 'Saint Andrews PD', color: '#5eead4', shift: '#4293' },
  { t: '11:04', kind: 'in', user: 'tar', company: 'Highway Patrol HQ', color: '#fb7185', shift: '#4290' },
  { t: '10:32', kind: 'out', user: 'pao', company: 'Pacific Logistics', color: '#7cffb2', dur: '2h 14m' },
  { t: '10:01', kind: 'in', user: 'pim', company: 'Pacific Logistics', color: '#7cffb2', shift: '#4292' },
];

const HOURS_LB = [
  { rank: 1, name: 'ake', id: '401123…', total: 48.2, days: 7, avg: '6h 53m', target: 40, badge: 'owner' },
  { rank: 2, name: 'nine', id: '552901…', total: 42.6, days: 7, avg: '6h 05m', target: 40 },
  { rank: 3, name: 'noi', id: '661044…', total: 38.1, days: 6, avg: '6h 21m', target: 40 },
  { rank: 4, name: 'pim', id: '884330…', total: 34.8, days: 6, avg: '5h 48m', target: 40 },
  { rank: 5, name: 'tar', id: '729811…', total: 31.4, days: 6, avg: '5h 14m', target: 40 },
  { rank: 6, name: 'bell', id: '991028…', total: 28.9, days: 5, avg: '5h 47m', target: 30 },
  { rank: 7, name: 'kong', id: '728112…', total: 24.1, days: 5, avg: '4h 49m', target: 30 },
  { rank: 8, name: 'ploy', id: '102998…', total: 22.4, days: 5, avg: '4h 29m', target: 30 },
];

// Format milliseconds as "Xh Ym".
function fmtDur(ms) {
  const m = Math.max(0, Math.floor((Number(ms) || 0) / 60000));
  const h = Math.floor(m / 60);
  return `${h}h ${String(m % 60).padStart(2, '0')}m`;
}
// "HH:MM" from an ISO/epoch start time.
function fmtTime(v) {
  if (!v) return '—';
  const d = new Date(typeof v === 'number' ? v : Date.parse(v));
  if (isNaN(d.getTime())) return '—';
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

function PageShifts() {
  const ctx = React.useContext(DashCtx);
  const conn = useConn();
  useRealData(); // re-render on real-data refresh
  const live = (typeof CONN !== 'undefined') && conn.status === 'connected';

  function guildName(id) {
    if (!id) return 'เซิร์ฟเวอร์';
    const g = GUILDS.find((x) => x.id === String(id));
    return g ? g.name : 'เซิร์ฟเวอร์';
  }

  // On-duty board — REAL when connected (empty state if none), mock only when offline.
  const realActive = (REALDATA.shifts && REALDATA.shifts.active) || [];
  const onDuty = live
    ? realActive.map((a) => ({
        id: String(a.userId || ''),
        name: a.displayName || a.username || String(a.userId || ''),
        avatarURL: a.avatarURL || null,
        company: guildName(a.guildId),
        companyColor: 'var(--accent)',
        since: fmtTime(a.startedAt),
        dur: fmtDur(a.elapsedMs),
        shift: '',
      }))
    : ON_DUTY;

  // Weekly leaderboard — REAL when connected (empty state if none), mock only when offline.
  const weekly = (REALDATA.shifts && REALDATA.shifts.weekly) || { users: [], totalShifts: 0, totalMs: 0 };
  const realWeeklyUsers = weekly.users || [];
  const hoursLb = live
    ? realWeeklyUsers
        .slice()
        .sort((a, b) => (b.totalMs || 0) - (a.totalMs || 0))
        .map((u, i) => ({
          rank: i + 1,
          name: u.displayName || u.username || String(u.userId || ''),
          id: String(u.userId || ''),
          avatarURL: u.avatarURL || null,
          total: +(((u.totalMs || 0) / 3600000).toFixed(1)),
          days: u.shifts || 0,
          avg: fmtDur(u.averageMs),
          target: 40,
        }))
    : HOURS_LB;

  // Clock activity — REAL events when connected (empty state if none).
  const realEvents = (REALDATA.shifts && REALDATA.shifts.recentEvents) || [];
  const clockEvents = live
    ? realEvents.map((e) => ({
        t: fmtTime(e.at),
        kind: e.type === 'out' ? 'out' : 'in',
        user: e.displayName || e.username || String(e.userId || ''),
        company: guildName(e.guildId),
        color: 'var(--accent)',
        dur: e.durationMs ? fmtDur(e.durationMs) : undefined,
        shift: '',
      }))
    : CLOCK_EVENTS;

  const totalOnDuty = live ? onDuty.length : COMPANIES.reduce((s, c) => s + c.onduty, 0);
  const totalEmployees = COMPANIES.reduce((s, c) => s + c.total, 0);

  // Real weekly aggregates (for stat cards + report preview)
  const realHours7d = (weekly.totalMs || 0) / 3600000;
  const realShifts = weekly.totalShifts || 0;
  const realWorkers = realWeeklyUsers.length;
  const realAvgH = realWorkers ? realHours7d / realWorkers : 0;

  // last 7 days, hours per day
  const dailyHours = [284, 312, 296, 348, 372, 320, 252];
  const dayLabels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Shifts</h1>
          <div className="page-sub">{live ? `${totalOnDuty} กำลังเข้าเวร · ${realShifts} กะใน 7 วัน · ${realWorkers} คน` : `Duty tracking across ${COMPANIES.length} companies · ${totalOnDuty} on duty now · ${totalEmployees} total`}</div>
        </div>
        <div className="row">
          <button className="btn" disabled={!live} onClick={() => live && REALDATA.doAction('sheetstyle').then(() => toast('ตกแต่ง Google Sheet เรียบร้อย', 'success')).catch((e) => toast('ล้มเหลว: ' + e.message, 'error'))}>Sync to Sheets</button>
          <button className="btn primary" disabled={!live} onClick={() => live && REALDATA.doAction('weeklyreport').then(() => toast('ส่งสรุปรายสัปดาห์แล้ว', 'success')).catch((e) => toast('ล้มเหลว: ' + e.message, 'error'))}>Send weekly report</button>
        </div>
      </div>

      {/* Stat row */}
      <div className="grid grid-4">
        <StatCard label="กำลังเข้าเวร" value={totalOnDuty} delta={live ? 'ตอนนี้' : '+3 since 12:00'} deltaDir="up" spark={[12, 14, 16, 18, 22, 28, 32, 36, 38, 38]}/>
        <StatCard label="ชั่วโมง · 7 วัน" value={live ? Math.round(realHours7d).toLocaleString() : '2,184'} delta={live ? `${realWorkers} คน` : '−4.1% vs prev'} deltaDir={live ? 'up' : 'down'} spark={dailyHours} sparkColor="var(--violet)"/>
        <StatCard label="กะ · 7 วัน" value={live ? realShifts : '42'} delta={live ? `${realActive.length} กำลังเปิด` : '14 still open'} deltaDir="up" spark={[2, 6, 10, 14, 18, 24, 28, 34, 38, 42]}/>
        <StatCard label="เฉลี่ย/คน" value={live ? fmtDur(realWorkers ? (weekly.totalMs / realWorkers) : 0) : '2m ago'} delta={live ? '7 วันล่าสุด' : '187 rows synced today'} deltaDir="up" spark={[20, 24, 18, 28, 32, 30, 38, 42]} sparkColor="var(--info)"/>
      </div>

      {/* Companies board — demo only (bot has no per-company target staffing) */}
      {!live && (
      <Card title="Companies" sub="Live on-duty counts vs target staffing">
        <div className="grid grid-3" style={{ gap: 14 }}>
          {COMPANIES.map((c) => {
            const pct = Math.min(100, (c.onduty / c.target) * 100);
            const hit = c.onduty >= c.target;
            return (
              <div key={c.key} style={{ background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 8, padding: 14 }}>
                <div className="row between">
                  <div className="row">
                    <span style={{ width: 10, height: 10, borderRadius: 3, background: c.color }}/>
                    <span style={{ fontWeight: 600, fontSize: 13 }}>{c.name}</span>
                  </div>
                  <span className="chip mono" style={{ fontSize: 10.5 }}>{c.total} staff</span>
                </div>
                <div style={{ marginTop: 12, display: 'flex', alignItems: 'baseline', gap: 8 }}>
                  <span className="mono" style={{ fontSize: 26, fontWeight: 600, color: hit ? c.color : 'var(--text)' }}>{c.onduty}</span>
                  <span className="muted" style={{ fontSize: 12 }}>/ {c.target} target</span>
                  {hit && <span className="chip solid" style={{ marginLeft: 'auto' }}>met</span>}
                  {!hit && <span className="chip warn" style={{ marginLeft: 'auto' }}>−{c.target - c.onduty}</span>}
                </div>
                <div className="bar-track" style={{ marginTop: 10, height: 5 }}>
                  <div className="bar-fill" style={{ width: `${pct}%`, background: c.color }}/>
                </div>
              </div>
            );
          })}
        </div>
      </Card>
      )}

      {/* On duty + clock activity */}
      <div className="grid grid-12-5">
        <Card title="Currently on duty" sub={`${onDuty.length} people clocked in`} padding={0}>
          <table className="tbl">
            <thead><tr><th>User</th><th>Company</th><th className="num">Clock-in</th><th className="num">Duration</th><th>Shift</th></tr></thead>
            <tbody>
              {onDuty.map((u, i) => (
                <tr key={u.id || i}>
                  <td>
                    <div className="row">
                      {u.avatarURL
                        ? <img src={u.avatarURL} alt="" style={{ width: 24, height: 24, borderRadius: 999, objectFit: 'cover' }}/>
                        : <div style={{ width: 24, height: 24, borderRadius: 999, background: `hsl(${(u.name || '?').charCodeAt(0) * 9} 70% 60%)` }}/>}
                      <div>
                        <div>{u.name}</div>
                        <div className="mono muted" style={{ fontSize: 10.5 }}>{u.id}</div>
                      </div>
                    </div>
                  </td>
                  <td><div className="row" style={{ gap: 6 }}><span style={{ width: 7, height: 7, borderRadius: 999, background: u.companyColor }}/><span style={{ fontSize: 12.5 }}>{u.company}</span></div></td>
                  <td className="num mono">{u.since}</td>
                  <td className="num mono" style={{ color: 'var(--accent)' }}>{u.dur}</td>
                  <td className="mono muted">{u.shift}</td>
                </tr>
              ))}
              {onDuty.length === 0 && (
                <tr><td colSpan={5} style={{ padding: 24, textAlign: 'center', color: 'var(--text-muted)' }}>ไม่มีใครเข้างานอยู่ตอนนี้</td></tr>
              )}
            </tbody>
          </table>
        </Card>

        <Card title="Clock activity" sub="latest events today">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {clockEvents.length === 0 && (
              <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-muted)', fontSize: 12.5 }}>ยังไม่มีกิจกรรมเข้า-ออกงาน</div>
            )}
            {clockEvents.map((e, i) => {
              const meta = {
                in: { label: 'IN', color: 'var(--accent)' },
                out: { label: 'OUT', color: 'var(--text-muted)' },
                break: { label: 'BRK', color: 'var(--warn)' },
              }[e.kind] || { label: 'IN', color: 'var(--accent)' };
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: i < clockEvents.length - 1 ? '1px dashed color-mix(in oklab, var(--border) 60%, transparent)' : 0 }}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', width: 38 }}>{e.t}</span>
                  <span className="chip" style={{ background: `color-mix(in oklab, ${meta.color} 16%, transparent)`, color: meta.color, borderColor: 'transparent', fontFamily: 'var(--font-mono)', fontSize: 10, padding: '1px 6px' }}>{meta.label}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5 }}>{e.user}</div>
                    <div className="ellipsis" style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                      <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: 2, background: e.color, marginRight: 5, verticalAlign: 'middle' }}/>
                      {e.company}
                    </div>
                  </div>
                  {e.dur && <span className="mono muted" style={{ fontSize: 11 }}>{e.dur}</span>}
                  {e.shift && <span className="mono muted" style={{ fontSize: 11 }}>{e.shift}</span>}
                </div>
              );
            })}
          </div>
        </Card>
      </div>

      {/* Weekly hours chart + leaderboard */}
      <div className="grid grid-12-5">
        <Card title="Hours per day" sub="last 7 days · all companies">
          <MiniBars data={dailyHours} highlightIdx={6} height={160}/>
          <div style={{ display: 'flex', justifyContent: 'space-around', color: 'var(--text-dim)', fontSize: 11, marginTop: 8, fontFamily: 'var(--font-mono)' }}>
            {dayLabels.map((d) => <span key={d}>{d}</span>)}
          </div>
        </Card>

        <Card title="Hours leaderboard" sub="last 7 days" padding={0}>
          <table className="tbl">
            <thead><tr><th style={{ width: 36 }}>#</th><th>User</th><th className="num">Hours</th><th></th></tr></thead>
            <tbody>
              {hoursLb.slice(0, 7).map((u) => {
                const pct = (u.total / 50) * 100;
                const hitTarget = u.total >= u.target;
                return (
                  <tr key={u.id || u.rank}>
                    <td className="mono dim">{String(u.rank).padStart(2, '0')}</td>
                    <td>
                      <div className="row">
                        {u.avatarURL
                          ? <img src={u.avatarURL} alt="" style={{ width: 22, height: 22, borderRadius: 999, objectFit: 'cover' }}/>
                          : <div style={{ width: 22, height: 22, borderRadius: 999, background: `hsl(${(u.name || '?').charCodeAt(0) * 9} 70% 60%)` }}/>}
                        <div>
                          <div style={{ fontSize: 12.5 }}>{u.name} {u.badge && <span className="chip warn" style={{ marginLeft: 4, fontSize: 9.5 }}>{u.badge}</span>}</div>
                          <div className="muted" style={{ fontSize: 10.5 }}>avg {u.avg}</div>
                        </div>
                      </div>
                    </td>
                    <td className="num mono" style={{ color: hitTarget ? 'var(--accent)' : 'var(--text)' }}>{u.total}h</td>
                    <td>
                      <div className="bar-track" style={{ width: 80 }}>
                        <div className="bar-fill" style={{ width: `${Math.min(100, pct)}%`, background: hitTarget ? 'var(--accent)' : 'var(--violet)' }}/>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {hoursLb.length === 0 && (
                <tr><td colSpan={4} style={{ padding: 24, textAlign: 'center', color: 'var(--text-muted)' }}>ยังไม่มีข้อมูลชั่วโมงสัปดาห์นี้</td></tr>
              )}
            </tbody>
          </table>
        </Card>
      </div>

      {/* Weekly report preview + sheets sync */}
      <div className="grid grid-12-5">
        <Card title="Weekly report preview" sub="next send · Sunday 20:00 ICT">
          <div style={{ background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 8, padding: 14, fontSize: 12.5 }}>
            <div style={{ fontWeight: 600, marginBottom: 8 }}>📊 Weekly shift report · Week 22 / 2026</div>
            <div className="muted" style={{ marginBottom: 12 }}>May 26 – Jun 1, 2026</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div className="kv" style={{ borderBottom: 0, padding: '4px 0' }}><div className="kv-key">Total hours</div><div className="kv-val mono">{live ? realHours7d.toFixed(1) + 'h' : '2,184h'}</div></div>
              <div className="kv" style={{ borderBottom: 0, padding: '4px 0' }}><div className="kv-key">Shifts closed</div><div className="kv-val mono">{live ? realShifts : '312'}</div></div>
              <div className="kv" style={{ borderBottom: 0, padding: '4px 0' }}><div className="kv-key">Unique workers</div><div className="kv-val mono">{live ? realWorkers : '62'}</div></div>
              <div className="kv" style={{ borderBottom: 0, padding: '4px 0' }}><div className="kv-key">Avg / person</div><div className="kv-val mono">{live ? realAvgH.toFixed(1) + 'h' : '35.2h'}</div></div>
            </div>
            <hr className="sep"/>
            <div style={{ fontWeight: 600, fontSize: 11.5, textTransform: 'uppercase', letterSpacing: 0.04, color: 'var(--text-dim)', marginBottom: 6 }}>Top contributors</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {hoursLb.slice(0, 3).map((u) => (
                <div key={u.id || u.rank} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                  <span>🏅 {u.name}</span><span className="mono">{u.total}h</span>
                </div>
              ))}
            </div>
          </div>
          <div className="row" style={{ marginTop: 10 }}>
            <button className="btn primary" style={{ marginLeft: 'auto' }} disabled={!live} onClick={() => live && REALDATA.doAction('weeklyreport').then(() => toast('ส่งสรุปรายสัปดาห์แล้ว', 'success')).catch((e) => toast('ล้มเหลว: ' + e.message, 'error'))}>Send now</button>
          </div>
        </Card>

        <Card title="Google Sheets sync" sub={SETTINGS.sheets.spreadsheet}>
          <div className="kv"><div className="kv-key">Last sync</div><div className="kv-val">{live ? <span className="chip mono">บันทึกตอน approve คำขอ</span> : <span className="chip solid">2 minutes ago</span>}</div></div>
          <div className="kv"><div className="kv-key">Sheet ID</div><div className="kv-val mono ellipsis" style={{ maxWidth: 260 }}>{SETTINGS.sheets.spreadsheetId}</div></div>
          <div className="kv"><div className="kv-key">Rows synced today</div><div className="kv-val mono">{live ? '—' : '187'}</div></div>
          <div className="kv"><div className="kv-key">Worksheets</div><div className="kv-val">
            <div className="row" style={{ gap: 4, flexWrap: 'wrap' }}>
              <span className="chip mono">Shifts</span>
              <span className="chip mono">Hours</span>
              <span className="chip mono">Companies</span>
              <span className="chip mono">Active</span>
            </div>
          </div></div>
          <div className="row" style={{ marginTop: 12, gap: 8 }}>
            <button className="btn" onClick={() => { const s = SETTINGS.sheets.spreadsheetId; window.open(/^https?:\/\//.test(s) ? s : 'https://docs.google.com/spreadsheets/d/' + s, '_blank'); }}>Open Sheet</button>
            <button className="btn" style={{ marginLeft: 'auto' }} disabled={!live} onClick={() => live && REALDATA.doAction('sheetstyle').then(() => toast('ตกแต่ง Google Sheet เรียบร้อย', 'success')).catch((e) => toast('ล้มเหลว: ' + e.message, 'error'))}>Sync now</button>
          </div>
        </Card>
      </div>
    </div>
  );
}

window.PageShifts = PageShifts;
window.COMPANIES = COMPANIES;
window.ON_DUTY = ON_DUTY;
window.HOURS_LB = HOURS_LB;
