/* global window */
// FaceInTime data layer — wires the /api/bootstrap response onto window
// globals the page modules read.

window.DEPARTMENTS = [];
window.SHIFTS = [];
window.LEAVE_TYPES = [];
window.DEVICES = [];
window.EMPLOYEES = [];
window.HOLIDAYS = [];
window.ATTENDANCE_TODAY = [];
window.RECENT_SCANS = [];
window.SETTINGS = {};
window.CURRENT_USER = null;
window.AI_ENABLED = false;
window.TODAY = null;
window.PENDING_LEAVES = 0;
// หน่วยงาน (ลูกค้า) ที่ล็อกอินอยู่ — ข้อมูลแต่ละหน่วยงานแยกฐานข้อมูลกัน
window.TENANT = null;
// ตั้งค่าเมื่อผู้ดูแลส่วนกลางกำลังเข้าดูระบบของลูกค้า
window.IMPERSONATOR = null;
window.IS_PLATFORM = false;

// Pages copied from FaceCheck still read window.PEOPLE — keep that name pointed
// at the new EMPLOYEES list so they don't break while we port them.
window.PEOPLE = window.EMPLOYEES;

function fmtTime(d) {
  const pad = (n) => String(n).padStart(2, '0');
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
function fmtDate(d) {
  const pad = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
}
window.fmtTime = fmtTime;
window.fmtDate = fmtDate;

const THEME_COLOR_HEX = {
  coral: '#FB6F50', primary: '#4F46E5', indigo: '#4F46E5',
  mint: '#10B981', magenta: '#EC4899', cyan: '#06B6D4', yellow: '#F5C518',
};
function applyTheme(s) {
  if (!s) return;
  const root = document.documentElement;
  const hex = THEME_COLOR_HEX[s.theme_primary];
  if (hex) root.style.setProperty('--primary', hex);
  if (s.theme_font_size) root.style.fontSize = `${parseInt(s.theme_font_size, 10) || 14}px`;
  if (s.theme_mode) root.dataset.theme = s.theme_mode;
}
window.applyTheme = applyTheme;

async function refreshData() {
  try {
    const r = await fetch('/api/bootstrap', { credentials: 'include' });
    if (!r.ok) return null;
    const d = await r.json();
    window.DEPARTMENTS    = d.departments        || [];
    window.SHIFTS         = d.shifts             || [];
    window.LEAVE_TYPES    = d.leave_types        || [];
    window.DEVICES        = d.devices            || [];
    window.EMPLOYEES      = d.employees          || [];
    window.PEOPLE         = window.EMPLOYEES;     // alias for ported pages
    window.HOLIDAYS       = d.holidays_this_year || [];
    window.ATTENDANCE_TODAY = d.attendance_today || [];
    window.RECENT_SCANS   = d.recent_scans       || [];
    window.SETTINGS       = d.settings           || {};
    window.CURRENT_USER   = d.me                 || null;
    window.AI_ENABLED     = !!d.ai_enabled;
    window.TODAY          = d.today              || null;
    window.PENDING_LEAVES = d.pending_leaves_count || 0;
    window.TENANT         = d.tenant             || null;
    window.IMPERSONATOR   = d.impersonator       || null;
    window.IS_PLATFORM    = !!d.platform;
    applyTheme(window.SETTINGS);
    return d;
  } catch (e) {
    console.warn('refreshData failed:', e.message);
    return null;
  }
}
window.refreshData = refreshData;

// ── Live WebSocket scan stream ──────────────────────────────────────────────
function buildScanStream() {
  const subs = new Set();
  let ws = null;
  let reconnectTimer = null;

  function normaliseScan(msg) {
    const dept = window.DEPARTMENTS.find((d) => d.id === msg.department_id) || null;
    const emp = window.EMPLOYEES.find((p) => p.id === msg.employee_id) || null;
    return {
      id: `LOG-${msg.log_id || Date.now()}`,
      employeeId: msg.employee_id,
      employee: emp,
      employee_name: msg.employee_name,
      device_id: msg.device_id,
      device_name: msg.device_name,
      department: dept,
      type: msg.direction || null,   // 'in' (first scan of day) | 'out'
      time: msg.timestamp ? new Date(msg.timestamp) : new Date(),
      confidence: msg.confidence || 0,
      snapshot_url: msg.snapshot_url || null,
      photo_url: msg.photo_url || null,
      daily: msg.daily || null,
      is_known: !!msg.is_known,
    };
  }

  function connect() {
    // ผู้ดูแลส่วนกลางไม่ได้ผูกกับหน่วยงานใด จึงไม่มีสตรีมการสแกนให้ฟัง
    // (ถ้าไม่กันไว้ จะพยายามต่อใหม่ทุก 2 วินาทีไม่รู้จบ)
    if (window.IS_PLATFORM) return;
    try {
      const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
      ws = new WebSocket(`${proto}//${location.host}/ws`);
      ws.onmessage = (ev) => {
        let msg;
        try { msg = JSON.parse(ev.data); } catch (_) { return; }
        if (msg.type === 'scan') {
          const scan = normaliseScan(msg);
          for (const fn of subs) try { fn(scan); } catch (e) { console.warn('scan sub error:', e); }
        }
        if (msg.type === 'init') {
          refreshData();
        }
      };
      ws.onclose = () => {
        ws = null;
        reconnectTimer = setTimeout(connect, 2000);
      };
      ws.onerror = () => { try { ws.close(); } catch (_) {} };
    } catch (e) {
      console.warn('ws connect failed:', e);
      reconnectTimer = setTimeout(connect, 2000);
    }
  }
  window.dataReady && window.dataReady.then(() => connect());

  return {
    subscribe(fn) {
      subs.add(fn);
      return () => subs.delete(fn);
    },
    get connected() { return ws && ws.readyState === 1; },
  };
}

// Ported pages (device/settings/report) expect a useDataVersion() hook that
// re-renders when bootstrap data refreshes. Provide a minimal version: a counter
// that bumps on the 'faceintime:data' event (fired after refreshData()).
window.useDataVersion = function useDataVersion() {
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    const h = () => setV((x) => x + 1);
    window.addEventListener('faceintime:data', h);
    return () => window.removeEventListener('faceintime:data', h);
  }, []);
  return v;
};

window.dataReady = refreshData();
window.scanStream = buildScanStream();
