// Supabase integration — syncs live data into globals after app loads
const _SB_URL = 'https://yocbmctgcpscvzosqafv.supabase.co';
const _SB_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlvY2JtY3RnY3BzY3Z6b3NxYWZ2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzE4MDMwMTQsImV4cCI6MjA4NzM3OTAxNH0.LzR9sPz1chQXq8_GYRrI9mPEDmhqxbH2o6HXyepTztw';

(function () {
  try {
    window.__sb = supabase.createClient(_SB_URL, _SB_KEY);
  } catch (e) {
    console.warn('[GH] Supabase init failed — using local seed data', e);
  }
})();

const _POS_ROLE = {
  'Boss': 'boss', 'Owner': 'boss', 'Manager': 'boss', 'Director': 'boss',
  'Production Manager': 'production_manager', 'Production': 'production_manager',
  'Accountant': 'accountant', 'Finance': 'accountant',
};

function _mapEmployee(e) {
  const full = (e.first_name + ' ' + e.last_name).trim();
  return {
    id: String(e.id),
    full_name: full,
    email: e.email || '',
    role: _POS_ROLE[e.position] || 'employee',
    status: e.status || 'active',
    department: e.department || '',
    salary: e.salary || 0,
    phone: e.phone || '',
    join_date: e.hire_date || '',
    tenure_display_mode: 'months',
    emergency_contact: e.emergency_contact || '',
    initials: ((e.first_name||'?')[0] + (e.last_name||'?')[0]).toUpperCase(),
    avatar_url: e.photo_url || (typeof employeeAvatarUrl === 'function' ? employeeAvatarUrl(full) : ''),
    blood_type: e.blood_type || '',
    national_id: e.national_id || '',
    gender: e.gender || '',
    date_of_birth: e.date_of_birth || '',
    contract_type: e.contract_type || 'fullTime',
    address: e.address || '',
  };
}

async function __syncFromSupabase() {
  const sb = window.__sb;
  if (!sb) return;

  try {
    const { data: emps } = await sb.from('employees').select('*').order('id');
    if (emps && emps.length) {
      const mapped = emps.map(_mapEmployee);
      window.EMPLOYEES = mapped;
      window.__EMPLOYEES_BASE = mapped.map(e => ({ ...e }));
      if (window.__hydrateEmployees) window.__hydrateEmployees();
    }
  } catch (e) { console.warn('[GH] employees sync failed', e); }

  try {
    const { data: deps } = await sb.from('deposits').select('*').order('date', { ascending: false });
    if (deps) {
      window.DEPOSITS = deps.map(d => ({
        id: String(d.id),
        amount: d.amount || 0,
        bank: d.bank_name || '',
        account: d.account_number || '',
        deposit_date: d.date || '',
        reference: d.reference || '',
        deposited_by: d.deposited_by || '',
        notes: d.notes || '',
        created_at: d.created_at || '',
      }));
    }
  } catch (e) { console.warn('[GH] deposits sync failed', e); }

  try {
    const { data: leaves } = await sb.from('leave_requests').select('*').order('created_at', { ascending: false });
    if (leaves) {
      window.LEAVES = leaves.map(l => ({
        id: String(l.id),
        employee_id: String(l.employee_id),
        type: l.type || 'annual',
        start: l.start_date || '',
        end: l.end_date || '',
        status: l.status || 'pending',
        note: l.notes || '',
        approved_by: l.approved_by || '',
        created_at: l.created_at || '',
      }));
    }
  } catch (e) { console.warn('[GH] leave_requests sync failed', e); }

  try {
    const { data: warns } = await sb.from('warnings').select('*').order('created_at', { ascending: false });
    if (warns) {
      window.WARNINGS = warns.map(w => ({
        id: String(w.id),
        employee_id: String(w.employee_id),
        type: w.type || 'verbal',
        reason: w.reason || '',
        issued_by: w.issued_by || '',
        date: w.date || '',
        notes: w.notes || '',
        created_at: w.created_at || '',
      }));
    }
  } catch (e) { console.warn('[GH] warnings sync failed', e); }

  window.dispatchEvent(new CustomEvent('gh-admin-data'));
}

window.__syncFromSupabase = __syncFromSupabase;

// Sync once the page is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => setTimeout(__syncFromSupabase, 800));
} else {
  setTimeout(__syncFromSupabase, 800);
}
