// ════════════════════════════════════════════════════════════════
//  หน้าสถานะทีมงาน (Agent Status Board) — 9 agents · 3 ทีม
//  แสดงว่าแต่ละ agent กำลังทำอะไรอยู่ในระบบ · แก้ไขสถานะ/งาน · มี activity log
// ════════════════════════════════════════════════════════════════

window.AgentManager = window.AgentManager || (function () {
  const KEY = 'syk-agents-v1';
  const LOG_KEY = 'syk-agents-log-v1';
  const listeners = new Set();

  const ROSTER = [
    // ── ทีมวิศวกรรมโยธา ──
    { id: 'civil-lead',       team: 'civil',   th: 'หัวหน้าวิศวกรโยธา',     en: 'Lead Civil Engineer',  icon: '👷‍♂️', lead: true,
      duty: 'ประเมินภาพรวมงานโยธา จัดลำดับงาน ประสานข้ามฝ่าย' },
    { id: 'civil-tester',     team: 'civil',   th: 'วิศวกรโยธา–ทดสอบระบบ',  en: 'QA Civil Engineer',    icon: '🧪',
      duty: 'ทดสอบ flow ใช้งานจริง end-to-end หา bug/UX' },
    { id: 'civil-researcher', team: 'civil',   th: 'วิศวกรโยธา–จัดหาข้อมูล', en: 'Research Civil Eng.',  icon: '📚',
      duty: 'ค้นคว้ามาตรฐาน วสท./มยผ. ราคากลาง สูตรค่า K' },
    // ── ทีม IT ──
    { id: 'it-lead',          team: 'it',      th: 'หัวหน้าฝ่าย IT',         en: 'IT Lead',              icon: '💻', lead: true,
      duty: 'รับ feedback วางแผนแก้ มอบหมาย ตรวจก่อนปิด' },
    { id: 'computer-engineer',team: 'it',      th: 'วิศวกรคอมพิวเตอร์',      en: 'Systems Engineer',     icon: '🛠️',
      duty: 'ออกแบบสถาปัตยกรรม/data flow ก่อนเขียนโค้ด' },
    { id: 'programmer',       team: 'it',      th: 'โปรแกรมเมอร์',           en: 'Developer',            icon: '⌨️',
      duty: 'เขียน/แก้โค้ดจริง deploy' },
    // ── ทีมการเงิน & กฎหมาย ──
    { id: 'finance-manager',  team: 'finance', th: 'ผจก.บัญชี-การเงิน',      en: 'Finance Manager',      icon: '💰', lead: true,
      duty: 'ตรวจเบิกจ่าย วิเคราะห์รายรับ-รายจ่าย ภาษี' },
    { id: 'accountant',       team: 'finance', th: 'นักบัญชี',               en: 'Accountant',           icon: '🧾',
      duty: 'ทดลองเบิกเงิน ทำบัญชี กระทบยอด' },
    { id: 'legal-manager',    team: 'finance', th: 'ผจก.กฎหมาย',            en: 'Legal Manager',        icon: '⚖️', lead: true,
      duty: 'ตรวจสัญญา เงื่อนไข ความถูกต้องตามกฎหมาย' },
    // ── ฝ่ายประเมินราคา & จัดซื้อ (The Golden Triangle: QS + Procurement) ──
    { id: 'qs-procurement-lead', team: 'estimating', th: 'หัวหน้าฝ่ายประเมินราคา-จัดซื้อ', en: 'Lead QS & Procurement', icon: '📐', lead: true,
      duty: 'คุมทีมถอดแบบ-เสนอราคา-จัดซื้อ ให้ต้นทุน+เวลาสอดคล้องแผน PM' },
    { id: 'quantity-surveyor',   team: 'estimating', th: 'วิศวกรประมาณราคา (QS)',         en: 'Quantity Surveyor',    icon: '📏',
      duty: 'ถอดแบบสถาปัตย์/โครงสร้าง/ระบบ · ทำใบเสนอราคา (ฉบับลูกค้า+margin / ฉบับคอนโทรลภายใน)' },
    { id: 'procurement-officer', team: 'estimating', th: 'จนท.จัดซื้อฝ่ายก่อสร้าง',        en: 'Procurement Officer',  icon: '🛒',
      duty: 'หา supplier · เปรียบเทียบราคา · เจรจาต่อรอง · สั่งซื้อวัสดุเข้าหน้างานทันตามแผน PM' },
  ];

  function loadStates() { try { return JSON.parse(localStorage.getItem(KEY) || '{}'); } catch { return {}; } }
  function saveStates(o) { localStorage.setItem(KEY, JSON.stringify(o)); listeners.forEach(fn => { try { fn(); } catch {} }); }
  function loadLog() { try { return JSON.parse(localStorage.getItem(LOG_KEY) || '[]'); } catch { return []; } }
  function saveLog(a) { localStorage.setItem(LOG_KEY, JSON.stringify(a.slice(0, 60))); }

  return {
    TEAMS: {
      civil:      { th: 'ทีมวิศวกรรมโยธา', en: 'Civil Engineering', icon: '🏗️', color: '#6f86ff' },
      it:         { th: 'ทีม IT',          en: 'IT',                icon: '💻', color: '#c89858' },
      finance:    { th: 'ทีมการเงิน & กฎหมาย', en: 'Finance & Legal', icon: '⚖️', color: '#22c55e' },
      estimating: { th: 'ฝ่ายประเมินราคา & จัดซื้อ', en: 'QS & Procurement', icon: '📐', color: '#f472b6' },
    },
    STATUS: {
      idle:      { th: 'ว่าง',        en: 'Idle',      dot: '⚪', color: '#9ca3af' },
      working:   { th: 'กำลังทำงาน',  en: 'Working',   dot: '🟢', color: '#22c55e' },
      reviewing: { th: 'กำลังตรวจ',   en: 'Reviewing', dot: '🟡', color: '#fbbf24' },
      waiting:   { th: 'รอข้อมูล',    en: 'Waiting',   dot: '🔵', color: '#6f86ff' },
      blocked:   { th: 'ติดปัญหา',    en: 'Blocked',   dot: '🔴', color: '#ef4444' },
      done:      { th: 'เสร็จงาน',    en: 'Done',      dot: '✅', color: '#4ade80' },
    },
    roster() { return ROSTER; },
    list() {
      const st = loadStates();
      return ROSTER.map(a => ({ ...a, ...(st[a.id] || { status: 'idle', task: '', updated_at: null }) }));
    },
    get(id) { return this.list().find(a => a.id === id); },
    update(id, patch) {
      const st = loadStates();
      const prev = st[id] || {};
      const next = { ...prev, ...patch, updated_at: new Date().toISOString() };
      st[id] = next;
      saveStates(st);
      // log
      const meta = ROSTER.find(a => a.id === id);
      const log = loadLog();
      log.unshift({ id, name: meta?.th || id, icon: meta?.icon || '🤖', status: next.status, task: next.task || '', at: next.updated_at });
      saveLog(log);
    },
    log() { return loadLog(); },
    clearLog() { saveLog([]); listeners.forEach(fn => { try { fn(); } catch {} }); },
    subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
    // เติมสถานะเริ่มต้นครั้งแรก (สะท้อนงานล่าสุดที่ทำในระบบ)
    seedIfEmpty() {
      if (localStorage.getItem(KEY)) return;
      const seed = {
        'civil-lead':       { status: 'done',     task: 'ออกแบบ schedule งวดงาน + dependency + S-Curve ถ่วงน้ำหนัก' },
        'civil-researcher': { status: 'done',     task: 'รวบรวมราคากลาง กรมบัญชีกลาง/สพฐ. 183 รายการ' },
        'civil-tester':     { status: 'reviewing',task: 'ทดสอบ flow ตั้งเบิก + อัปเดต progress หน้างาน' },
        'it-lead':          { status: 'working',  task: 'ดูแล deploy + แก้ปัญหา cache/บันทึกรูป localStorage' },
        'computer-engineer':{ status: 'working',  task: 'ออกแบบ schedule engine + ฐานราคาอ้างอิงผูก cost code' },
        'programmer':       { status: 'working',  task: 'แก้ปุ่มอัพเดตบันทึกไม่ได้ + รูปแบบวันที่ ค.ศ.' },
        'finance-manager':  { status: 'waiting',  task: 'รอตรวจใบตั้งเบิกลูกค้า/ผู้รับเหมาย่อย' },
        'accountant':       { status: 'idle',     task: '' },
        'legal-manager':    { status: 'done',     task: 'ตรวจสัญญา + เงื่อนไขแนบเอกสารลงนามก่อนขึ้นสถานะ' },
        'qs-procurement-lead': { status: 'working', task: 'ออกแบบ Golden Triangle: เชื่อม QS + จัดซื้อ + PM' },
        'quantity-surveyor':   { status: 'working', task: 'วางระบบใบเสนอราคา 2 ฉบับ (ลูกค้า+margin / คอนโทรลภายใน)' },
        'procurement-officer': { status: 'waiting', task: 'รอ BOQ อนุมัติ เพื่อเปรียบเทียบราคา supplier' },
      };
      const st = {};
      const now = new Date().toISOString();
      Object.entries(seed).forEach(([id, v]) => { st[id] = { ...v, updated_at: now }; });
      localStorage.setItem(KEY, JSON.stringify(st));
    },
  };
})();

function AgentStatusPage({ lang }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  const [, force] = React.useState(0);
  const [editing, setEditing] = React.useState(null);
  React.useEffect(() => {
    window.AgentManager.seedIfEmpty();
    force(x => x + 1);
    const unsub = window.AgentManager.subscribe(() => force(x => x + 1));
    const iv = setInterval(() => force(x => x + 1), 5000);
    return () => { unsub(); clearInterval(iv); };
  }, []);

  const M = window.AgentManager;
  const agents = M.list();
  const teams = M.TEAMS;
  const STATUS = M.STATUS;
  const log = M.log();

  const counts = agents.reduce((acc, a) => { acc[a.status] = (acc[a.status] || 0) + 1; return acc; }, {});
  const ago = (iso) => {
    if (!iso) return T('ยังไม่เริ่ม', 'never');
    const s = Math.floor((Date.now() - new Date(iso)) / 1000);
    if (s < 60) return T('เมื่อสักครู่', 'just now');
    if (s < 3600) return `${Math.floor(s / 60)} ${T('นาทีก่อน', 'min ago')}`;
    if (s < 86400) return `${Math.floor(s / 3600)} ${T('ชม.ก่อน', 'h ago')}`;
    return `${Math.floor(s / 86400)} ${T('วันก่อน', 'd ago')}`;
  };

  return (
    <div className="anim-fadein">
      <PageHeader
        title={T('สถานะทีมงาน (Agents)', 'Agent Status Board')}
        subtitle={T('9 ผู้เชี่ยวชาญ · 3 ทีม — ติดตามว่าตอนนี้แต่ละคนกำลังทำอะไร', '9 agents across 3 teams')}
      />

      {/* Summary bar */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8, marginBottom: 14 }}>
        {Object.entries(STATUS).map(([k, s]) => (
          <div key={k} style={{ padding: '8px 10px', background: 'var(--bg-2)', borderRadius: 8, textAlign: 'center', borderTop: `2px solid ${s.color}` }}>
            <div style={{ fontSize: 18, fontWeight: 700, fontFamily: 'var(--font-mono)' }}>{counts[k] || 0}</div>
            <div style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>{s.dot} {T(s.th, s.en)}</div>
          </div>
        ))}
      </div>

      {/* Teams */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14, marginBottom: 14 }} className="agents-grid">
        {Object.entries(teams).map(([tk, team]) => (
          <div key={tk} className="card" style={{ borderTop: `3px solid ${team.color}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span style={{ fontSize: 18 }}>{team.icon}</span>
              <h3 className="h2" style={{ margin: 0, fontSize: 15 }}>{T(team.th, team.en)}</h3>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {agents.filter(a => a.team === tk).map(a => {
                const st = STATUS[a.status] || STATUS.idle;
                return (
                  <div key={a.id} onClick={() => setEditing(a)}
                    style={{ padding: '10px 12px', background: 'var(--bg-2)', borderRadius: 8, cursor: 'pointer', borderLeft: `3px solid ${st.color}` }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontSize: 18 }}>{a.icon}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 700, fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6 }}>
                          {T(a.th, a.en)} {a.lead && <span style={{ fontSize: 8.5, padding: '1px 5px', borderRadius: 4, background: 'rgba(200,152,88,0.18)', color: 'var(--gold-soft, #c89858)' }}>LEAD</span>}
                        </div>
                        <div style={{ fontSize: 9.5, color: 'var(--ink-faint, #888)', fontFamily: 'var(--font-mono)' }}>@{a.id}</div>
                      </div>
                      <span style={{ fontSize: 10.5, fontWeight: 700, color: st.color, whiteSpace: 'nowrap' }}>{st.dot} {T(st.th, st.en)}</span>
                    </div>
                    <div style={{ fontSize: 11, color: a.task ? 'var(--ink)' : 'var(--ink-mute)', marginTop: 6, lineHeight: 1.5 }}>
                      {a.task ? `📌 ${a.task}` : `${T('หน้าที่', 'Duty')}: ${a.duty}`}
                    </div>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-faint, #888)', marginTop: 3 }}>
                      {T('อัปเดต', 'updated')} {ago(a.updated_at)} · {T('คลิกเพื่อแก้', 'click to edit')}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      {/* Activity log */}
      <div className="card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <div className="micro">📡 {T('กิจกรรมล่าสุด', 'Recent activity')}</div>
          {log.length > 0 && (
            <button className="btn btn-sm btn-ghost" onClick={() => { if (confirm(T('ล้างประวัติ?', 'Clear log?'))) M.clearLog(); }} style={{ color: 'var(--rose)' }}>
              {T('ล้าง', 'Clear')}
            </button>
          )}
        </div>
        {log.length === 0 ? (
          <div style={{ fontSize: 12, color: 'var(--ink-mute)', textAlign: 'center', padding: 16 }}>{T('ยังไม่มีกิจกรรม — อัปเดตสถานะ agent เพื่อเริ่มบันทึก', 'No activity yet')}</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4, maxHeight: 280, overflowY: 'auto' }}>
            {log.map((e, i) => {
              const st = STATUS[e.status] || STATUS.idle;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px', background: 'var(--bg-2)', borderRadius: 6, fontSize: 11.5 }}>
                  <span>{e.icon}</span>
                  <span style={{ fontWeight: 600, minWidth: 110 }}>{e.name}</span>
                  <span style={{ color: st.color, fontWeight: 700, whiteSpace: 'nowrap' }}>{st.dot} {T(st.th, st.en)}</span>
                  <span style={{ flex: 1, color: 'var(--ink-mute)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.task}</span>
                  <span style={{ color: 'var(--ink-faint, #888)', fontSize: 10, whiteSpace: 'nowrap' }}>{ago(e.at)}</span>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {editing && <AgentEditModal agent={editing} lang={lang} onClose={() => setEditing(null)}
        onSave={(patch) => { window.AgentManager.update(editing.id, patch); setEditing(null); }} />}
    </div>
  );
}

function AgentEditModal({ agent, lang, onClose, onSave }) {
  const T = (th, en) => (lang === 'th' ? th : en);
  const STATUS = window.AgentManager.STATUS;
  const [status, setStatus] = React.useState(agent.status || 'idle');
  const [task, setTask] = React.useState(agent.task || '');

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }} onClick={onClose}>
      <div className="card" style={{ maxWidth: 440, width: '100%' }} onClick={(e) => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <span style={{ fontSize: 24 }}>{agent.icon}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{T(agent.th, agent.en)}</div>
            <div style={{ fontSize: 10.5, color: 'var(--ink-mute)', fontFamily: 'var(--font-mono)' }}>@{agent.id}</div>
          </div>
          <button onClick={onClose} className="btn btn-sm btn-ghost" style={{ fontSize: 18 }}>×</button>
        </div>

        <label className="micro" style={{ display: 'block', marginBottom: 6 }}>{T('สถานะ', 'Status')}</label>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6, marginBottom: 14 }}>
          {Object.entries(STATUS).map(([k, s]) => (
            <button key={k} onClick={() => setStatus(k)}
              style={{ padding: '8px 6px', borderRadius: 7, cursor: 'pointer', fontSize: 11, fontWeight: 600,
                border: `1.5px solid ${status === k ? s.color : 'var(--line)'}`,
                background: status === k ? s.color + '22' : 'var(--bg-2)',
                color: status === k ? s.color : 'var(--ink-soft)' }}>
              {s.dot} {T(s.th, s.en)}
            </button>
          ))}
        </div>

        <label className="micro" style={{ display: 'block', marginBottom: 6 }}>{T('กำลังทำอะไรอยู่ (งานปัจจุบัน)', 'Current task')}</label>
        <textarea value={task} onChange={(e) => setTask(e.target.value)} rows={3}
          placeholder={agent.duty}
          style={{ width: '100%', padding: '9px 11px', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 6, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit', resize: 'vertical', marginBottom: 14 }} />

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button onClick={() => onSave({ status: 'idle', task: '' })} className="btn btn-ghost" style={{ marginRight: 'auto', color: 'var(--ink-mute)' }}>{T('เคลียร์', 'Reset')}</button>
          <button onClick={onClose} className="btn btn-ghost">{T('ยกเลิก', 'Cancel')}</button>
          <button onClick={() => onSave({ status, task })} className="btn-primary"
            style={{ background: 'var(--gold-soft, #c89858)', color: '#1a1208', fontWeight: 700, border: 'none', padding: '8px 18px', borderRadius: 6, cursor: 'pointer' }}>
            💾 {T('บันทึก', 'Save')}
          </button>
        </div>
      </div>
    </div>
  );
}

window.AgentStatusPage = AgentStatusPage;
