{% extends "ui/templates/base/layout.html" %}
{% block content %}
<div class="space-y-6" id="employee-portal-root">
  <section class="overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-soft">
    <div class="bg-gradient-to-r from-brand-700 via-brand-600 to-slate-900 px-6 py-6 text-white">
      <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <p class="text-xs font-semibold uppercase tracking-[0.22em] text-brand-100">My Workspace</p>
          <h2 class="mt-2 text-2xl font-semibold">Employee Portal</h2>
          <p class="mt-2 max-w-3xl text-sm text-brand-100">Punch attendance, view priority work, track HR details, documents, payslips and alerts from one staff workspace.</p>
        </div>
        <div class="flex flex-wrap gap-2">
          {% if employee %}
          <a href="/employee/attendance" class="rounded-xl bg-white px-4 py-2 text-sm font-semibold text-brand-700 hover:bg-brand-50">Punch / Attendance</a>
          <a href="/employee/work" class="rounded-xl border border-white/40 px-4 py-2 text-sm font-semibold text-white hover:bg-white/10">Open Work Board</a>
          {% else %}
          <a href="/employee/register" class="rounded-xl bg-white px-4 py-2 text-sm font-semibold text-brand-700 hover:bg-brand-50">Request Employee Linkage</a>
          {% endif %}
        </div>
      </div>
    </div>
  </section>

  {# Dashboard sections are now part of the unified Staff Dashboard submenu. #}

  <section id="employee-portal-panel"
           data-initial-tab="{{ active_tab }}"
           class="space-y-6">
    <div class="rounded-3xl border border-slate-200 bg-white p-8 text-center text-sm text-slate-500 shadow-soft">Loading dashboard...</div>
  </section>
</div>

<script>
(function () {
  "use strict";

  const panel = document.getElementById('employee-portal-panel');
  if (!panel) return;

  const dashboardLinks = Array.from(document.querySelectorAll(
    '[data-uiux-v2-pilot="staff"] a[href^="/employee/dashboard?tab="]'
  ));

  const groupMap = {
    'overview': 'overview',
    'work': 'work',
    'work-board': 'work',
    'due-today': 'work',
    'overdue': 'work',
    'client-pending': 'work',
    'returned': 'work',
    'documents': 'work',
    'attendance': 'attendance',
    'attendance-details': 'attendance',
    'attendance-punch': 'attendance',
    'attendance-history': 'attendance',
    'hr': 'hr',
    'profile': 'hr',
    'leave': 'hr',
    'payslips': 'hr',
    'offboarding': 'hr',
    'alerts': 'hr',
    'reports': 'reports'
  };

  function tabFromLink(link) {
    try {
      return new URL(link.href, window.location.origin).searchParams.get('tab') || 'overview';
    } catch (error) {
      return 'overview';
    }
  }

  function setActive(tabName) {
    const activeGroup = groupMap[tabName] || tabName || 'overview';
    dashboardLinks.forEach(function (link) {
      const active = tabFromLink(link) === activeGroup;
      link.classList.toggle('bg-brand-50', active);
      link.classList.toggle('text-brand-700', active);
      link.classList.toggle('text-slate-700', !active);
      if (active) {
        link.setAttribute('aria-current', 'page');
      } else {
        link.removeAttribute('aria-current');
      }
    });
  }

  async function loadTab(tabName, pushState) {
    const safeTab = tabName || 'overview';
    setActive(safeTab);
    panel.innerHTML = '<div class="rounded-3xl border border-slate-200 bg-white p-8 text-center text-sm text-slate-500 shadow-soft">Loading...</div>';

    try {
      const response = await fetch('/employee/dashboard/tab/' + encodeURIComponent(safeTab), {
        headers: {'X-Requested-With': 'fetch'}
      });
      if (!response.ok) throw new Error('HTTP ' + response.status);

      panel.innerHTML = await response.text();

      if (pushState) {
        const url = new URL(window.location.href);
        url.searchParams.set('tab', safeTab);
        window.history.pushState({tab: safeTab}, '', url.toString());
      }

      document.querySelectorAll('[data-uiux-v2-pilot="staff"] details[open]').forEach(function (details) {
        details.open = false;
      });

      if (window.EmployeePortalGeo && typeof window.EmployeePortalGeo.bind === 'function') {
        window.EmployeePortalGeo.bind();
      }
    } catch (error) {
      panel.innerHTML = '<div class="rounded-3xl border border-red-200 bg-red-50 p-8 text-center text-sm text-red-700 shadow-soft">Unable to load tab. Please refresh the page.</div>';
    }
  }

  dashboardLinks.forEach(function (link) {
    link.addEventListener('click', function (event) {
      if (window.location.pathname !== '/employee/dashboard') return;
      event.preventDefault();
      loadTab(tabFromLink(link), true);
    });
  });

  window.addEventListener('popstate', function (event) {
    const params = new URLSearchParams(window.location.search);
    loadTab((event.state && event.state.tab) || params.get('tab') || 'overview', false);
  });

  loadTab(panel.dataset.initialTab || 'overview', false);
})();
</script>
{% endblock %}
