(() => {
  const API = 'api.php';
  const authToken = localStorage.getItem('emp_token') || '';
  const deviceId = localStorage.getItem('device_id') || 'web-browser';

  const fromEl = document.getElementById('teamFrom');
  const toEl = document.getElementById('teamTo');
  const metaEl = document.getElementById('teamMeta');
  const employeesEl = document.getElementById('teamEmployeesList');
  const recordsHeadEl = document.getElementById('recordsHead');
  const listEl = document.getElementById('teamAttendanceList');
  const btnReload = document.getElementById('btnReload');
  const quickRangeBtns = Array.from(document.querySelectorAll('[data-range]'));
  let teamMembers = [];
  let logsByEmployee = {};
  let activeEmployeeId = null;

  function esc(s) {
    return String(s ?? '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  function canShowMapButton(rec) {
    if (String(rec.work_nature || '') !== 'external') return false;
    const lat = Number(rec.latitude);
    const lng = Number(rec.longitude);
    return Number.isFinite(lat) && Number.isFinite(lng) && !(lat === 0 && lng === 0);
  }

  function openMapForRecord(rec) {
    const lat = Number(rec.latitude);
    const lng = Number(rec.longitude);
    if (!Number.isFinite(lat) || !Number.isFinite(lng)) return;
    const url = `https://www.google.com/maps?q=${encodeURIComponent(`${lat},${lng}`)}`;
    window.open(url, '_blank', 'noopener');
  }

  async function editTeamNote(attendanceId, currentNote) {
    const val = window.prompt('تعديل ملاحظات المأمورية', currentNote || '');
    if (val === null) return;
    const note = String(val);
    try {
      const r = await fetch(`${API}?route=${encodeURIComponent(`team/note/${attendanceId}`)}`, {
        method: 'PUT',
        headers: {
          Authorization: 'Bearer ' + authToken,
          'X-Device-ID': deviceId,
          'Content-Type': 'application/json',
          Accept: 'application/json'
        },
        body: JSON.stringify({ note })
      });
      const txt = await r.text();
      let res;
      try { res = JSON.parse(txt); } catch (e) { res = { success: false, message: txt || 'Invalid response' }; }
      if (!res || !res.success) {
        alert(res?.message || 'تعذر تحديث الملاحظة');
        return;
      }
      await loadAttendance();
    } catch (e) {
      alert('تعذر الاتصال بالخادم');
    }
  }

  function setDefaults() {
    const now = new Date();
    const to = now.toISOString().slice(0, 10);
    const from = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
    if (fromEl && !fromEl.value) fromEl.value = from;
    if (toEl && !toEl.value) toEl.value = to;
  }

  function setRange(daysBack) {
    const now = new Date();
    const to = now.toISOString().slice(0, 10);
    const fromDate = new Date(Date.now() - daysBack * 24 * 60 * 60 * 1000);
    const from = fromDate.toISOString().slice(0, 10);
    if (fromEl) fromEl.value = from;
    if (toEl) toEl.value = to;
  }

  function applyQuickRange(kind) {
    if (kind === 'today') setRange(0);
    else if (kind === '7d') setRange(6);
    else setRange(30);
    quickRangeBtns.forEach((b) => b.classList.toggle('active', b.getAttribute('data-range') === kind));
  }

  async function call(route, query = '') {
    const url = `${API}?route=${encodeURIComponent(route)}${query ? `&${query}` : ''}`;
    const r = await fetch(url, {
      method: 'GET',
      headers: {
        Authorization: 'Bearer ' + authToken,
        'X-Device-ID': deviceId,
        Accept: 'application/json'
      }
    });
    const txt = await r.text();
    try {
      return JSON.parse(txt);
    } catch (e) {
      return { success: false, message: txt || 'Invalid response' };
    }
  }

  async function loadManagerMeta() {
    const res = await call('team/manager-meta');
    if (!res || !res.success || !res.data) {
      metaEl.textContent = 'تعذر تحميل بيانات المشرف.';
      return false;
    }
    const hasTeam = !!res.data.has_team;
    const ids = Array.isArray(res.data.team_member_ids) ? res.data.team_member_ids : [];
    teamMembers = Array.isArray(res.data.team_members) ? res.data.team_members : [];
    const count = ids.length;
    metaEl.textContent = hasTeam ? `عدد أعضاء الفريق: ${count}` : 'لا يوجد أعضاء فريق مُخصصين لك.';
    return hasTeam;
  }

  function groupLogsByEmployee(logs) {
    const out = {};
    for (const r of logs) {
      const id = Number(r.employee_id || 0);
      if (!id) continue;
      if (!out[id]) out[id] = [];
      out[id].push(r);
    }
    Object.keys(out).forEach((id) => {
      out[id].sort((a, b) => String(b.timestamp || '').localeCompare(String(a.timestamp || '')));
    });
    return out;
  }

  function renderEmployeesList() {
    if (!teamMembers.length) {
      employeesEl.innerHTML = '<div class="msg">لا يوجد أعضاء فريق.</div>';
      return;
    }
    employeesEl.innerHTML = teamMembers.map((m) => {
      const id = Number(m.id || 0);
      const total = (logsByEmployee[id] || []).length;
      const active = activeEmployeeId === id ? ' active' : '';
      return `
        <button class="employee-btn${active}" data-emp-id="${id}">
          <div class="emp-name">${esc(m.name || '—')}</div>
          <div class="emp-sub">${esc(m.employee_code || '')}${m.job_title ? ` • ${esc(m.job_title)}` : ''}</div>
          <div class="emp-sub">عدد السجلات: ${total}</div>
        </button>
      `;
    }).join('');

    employeesEl.querySelectorAll('.employee-btn').forEach((btn) => {
      btn.addEventListener('click', () => {
        const id = Number(btn.getAttribute('data-emp-id') || 0);
        if (!id) return;
        activeEmployeeId = id;
        renderEmployeesList();
        renderActiveEmployeeLogs();
      });
    });
  }

  function renderActiveEmployeeLogs() {
    if (!activeEmployeeId) {
      listEl.innerHTML = '<div class="msg">اختر موظفًا لعرض السجلات.</div>';
      recordsHeadEl.textContent = 'سجلات الموظف';
      return;
    }
    const member = teamMembers.find((m) => Number(m.id) === Number(activeEmployeeId));
    const logs = logsByEmployee[activeEmployeeId] || [];
    recordsHeadEl.textContent = member ? `سجلات: ${member.name}` : 'سجلات الموظف';

    if (!logs.length) {
      listEl.innerHTML = '<div class="msg">لا توجد سجلات لهذا الموظف ضمن الفترة المحددة.</div>';
      return;
    }

    let lastDay = '';
    const chunks = [];
    for (const r of logs) {
      const rawTs = String(r.timestamp || '');
      const day = rawTs.slice(0, 10);
      if (day && day !== lastDay) {
        chunks.push(`<div class="day-title">${esc(day)}</div>`);
        lastDay = day;
      }
      const type = r.type === 'check_in' ? 'حضور' : 'انصراف';
      const typeIcon = r.type === 'check_in' ? '↑' : '↓';
      const time = esc(rawTs.replace('T', ' ').slice(0, 16));
      const note = r.visit_details || r.notes || '';
      const showMap = canShowMapButton(r);
      chunks.push(`
        <div class="record">
          <div class="record-top">
            <div>
              <div class="record-type">${typeIcon} ${type}</div>
              <div class="record-time">${time}</div>
            </div>
            <div class="badge">${r.distance_meters != null ? `${Math.round(Number(r.distance_meters))} م` : '—'}</div>
          </div>
          <div class="record-note">${note ? `ملاحظات المأمورية: ${esc(note)}` : 'ملاحظات المأمورية: —'}</div>
          <div class="record-actions">
            ${showMap ? `<button class="btn-sm accent btn-open-map" data-lat="${esc(r.latitude)}" data-lng="${esc(r.longitude)}">📍 تحديد الموقع</button>` : ''}
            <button class="btn-sm warn btn-edit-note" data-id="${Number(r.id || 0)}" data-note="${esc(note)}">✎ تعديل الملاحظة</button>
          </div>
        </div>
      `);
    }
    listEl.innerHTML = chunks.join('');
    listEl.querySelectorAll('.btn-open-map').forEach((btn) => {
      btn.addEventListener('click', () => {
        const lat = Number(btn.getAttribute('data-lat'));
        const lng = Number(btn.getAttribute('data-lng'));
        openMapForRecord({ latitude: lat, longitude: lng, work_nature: 'external' });
      });
    });
    listEl.querySelectorAll('.btn-edit-note').forEach((btn) => {
      btn.addEventListener('click', () => {
        const id = Number(btn.getAttribute('data-id') || 0);
        const noteRaw = btn.getAttribute('data-note') || '';
        const noteTxt = noteRaw
          .replace(/&lt;/g, '<')
          .replace(/&gt;/g, '>')
          .replace(/&quot;/g, '"')
          .replace(/&#39;/g, "'")
          .replace(/&amp;/g, '&');
        if (id > 0) editTeamNote(id, noteTxt);
      });
    });
  }

  async function loadAttendance() {
    if (!authToken) {
      window.location.href = 'login.html';
      return;
    }

    setDefaults();
    const from = fromEl?.value || '';
    const to = toEl?.value || '';

    listEl.innerHTML = '<div class="msg">جارٍ التحميل...</div>';
    const qs = `from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
    const res = await call('team/attendance', qs);
    if (!res || !res.success || !res.data) {
      listEl.innerHTML = `<div class="msg err">${esc(res?.message || 'حدث خطأ')}</div>`;
      return;
    }

    const logs = Array.isArray(res.data.logs) ? res.data.logs : [];
    logsByEmployee = groupLogsByEmployee(logs);

    if (!teamMembers.length && Array.isArray(res.data.team_member_ids)) {
      teamMembers = res.data.team_member_ids.map((id) => ({ id, name: `موظف #${id}` }));
    }

    if (!activeEmployeeId && teamMembers.length) {
      activeEmployeeId = Number(teamMembers[0].id || 0) || null;
    }
    renderEmployeesList();
    renderActiveEmployeeLogs();
  }

  async function init() {
    if (!authToken) {
      window.location.href = 'login.html';
      return;
    }
    setDefaults();
    const hasTeam = await loadManagerMeta();
    if (!hasTeam) {
      employeesEl.innerHTML = '<div class="msg">لا يوجد أعضاء فريق.</div>';
      listEl.innerHTML = '<div class="msg">لا يوجد بيانات لعرضها.</div>';
      return;
    }
    renderEmployeesList();
    await loadAttendance();
  }

  btnReload?.addEventListener('click', loadAttendance);
  quickRangeBtns.forEach((btn) => {
    btn.addEventListener('click', async () => {
      const kind = btn.getAttribute('data-range') || '30d';
      applyQuickRange(kind);
      await loadAttendance();
    });
  });
  init();
})();
