{% extends "ui/templates/base/layout.html" %}

{% block content %}
<div class="space-y-6">
  <section class="rounded-3xl bg-gradient-to-r from-brand-700 to-slate-900 p-6 text-white shadow-soft">
    <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
      <div>
        <p class="text-xs font-semibold uppercase tracking-[0.22em] text-brand-100">Client Portal</p>
        <h2 class="mt-2 text-2xl font-semibold">My Compliance Workspace</h2>
        <p class="mt-2 max-w-3xl text-sm text-brand-100">View pending actions, service progress, documents, invoices, payments and firm messages from one clean dashboard.</p>
      </div>
      <div class="flex flex-wrap gap-2">
        {% if client_row %}
        <a href="/client/documents" class="rounded-xl bg-white px-4 py-2 text-sm font-semibold text-brand-700 hover:bg-brand-50">Upload Documents</a>
        <a href="/client/messages" class="rounded-xl border border-white/30 px-4 py-2 text-sm font-semibold text-white hover:bg-white/10">Messages</a>
        <a href="/client/profile" class="rounded-xl border border-white/30 px-4 py-2 text-sm font-semibold text-white hover:bg-white/10">Profile</a>
        {% endif %}
      </div>
    </div>
  </section>

  {% if not client_row %}
  <div class="rounded-2xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-900 shadow-soft">
    We could not find a client master linked to your login email in the current audit firm. Please contact your firm admin to map this login to the correct client record.
  </div>
  {% else %}
  {# Dashboard sections are now part of the unified Client Dashboard submenu. #}

  <section id="client-dashboard-panel"
           data-initial-tab="{{ active_tab|default('overview') }}"
           class="min-h-[240px]">
    <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>

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

    const panel = document.getElementById('client-dashboard-panel');
    if (!panel) return;

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

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

    function setActive(tabName) {
      dashboardLinks.forEach((link) => {
        const active = tabFromLink(link) === tabName;
        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) {
      setActive(tabName);
      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('/client/dashboard/tab/' + encodeURIComponent(tabName), {
          headers: { 'X-Requested-With': 'fetch' }
        });
        if (!response.ok) throw new Error('Tab load failed');

        panel.innerHTML = await response.text();

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

        document.querySelectorAll('[data-uiux-v2-pilot="client"] details[open]').forEach((details) => {
          details.open = false;
        });
      } catch (error) {
        panel.innerHTML = '<div class="rounded-3xl border border-red-200 bg-red-50 p-6 text-sm text-red-700 shadow-soft">Unable to load this dashboard section. Please refresh the page.</div>';
      }
    }

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

    window.addEventListener('popstate', function () {
      const url = new URL(window.location.href);
      loadTab(url.searchParams.get('tab') || 'overview', false);
    });

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