{% set linked = payload.linked_clients_page %}
{% set meta = linked.meta %}

<div class="space-y-6">
  <section class="af-card" id="linked-firm-clients-section">
    <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
      <div>
        <h3 class="text-lg font-semibold text-slate-900">Linked Firm Clients</h3>
        <p class="mt-1 text-sm text-slate-500">Firm clients explicitly linked to your consultant profile.</p>
      </div>
      <span id="linked-client-count" class="w-fit rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">
        {{ meta.total }} client{% if meta.total != 1 %}s{% endif %}
      </span>
    </div>

    <div class="mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
      <div class="md:col-span-2 xl:col-span-2">
        <label for="linked-client-search" class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Search</label>
        <input id="linked-client-search" type="search" autocomplete="off"
               placeholder="Client name, code, PAN, GSTIN or group"
               class="w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800 focus:border-brand-500 focus:outline-none focus:ring-2 focus:ring-brand-100">
      </div>
      <div>
        <label for="linked-client-group" class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Group</label>
        <select id="linked-client-group" class="w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800">
          <option value="">All groups</option>
          {% for group in linked.groups %}
          <option value="{{ group.id }}">{{ group.name }}{% if group.code %} ({{ group.code }}){% endif %}</option>
          {% endfor %}
        </select>
      </div>
      <div>
        <label for="linked-client-status" class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Status</label>
        <select id="linked-client-status" class="w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800">
          <option value="active" selected>Active</option>
          <option value="">All statuses</option>
          <option value="inactive">Inactive</option>
        </select>
      </div>
      <div>
        <label for="linked-client-sort" class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Sort</label>
        <select id="linked-client-sort" class="w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-800">
          <option value="client_code" selected>Client code</option>
          <option value="client_name">Client name</option>
          <option value="pan">PAN</option>
          <option value="client_group">Client group</option>
          <option value="status">Status</option>
        </select>
      </div>
    </div>

    <div id="linked-client-scroll-container" class="mt-5 max-h-[540px] overflow-auto rounded-2xl border border-slate-200">
      <table class="min-w-full divide-y divide-slate-200 text-left">
        <thead class="sticky top-0 z-10 bg-slate-50 shadow-sm">
          <tr class="text-xs font-semibold uppercase tracking-wide text-slate-500">
            <th class="whitespace-nowrap px-4 py-3">Code</th>
            <th class="min-w-[300px] px-4 py-3">Client Name</th>
            <th class="whitespace-nowrap px-4 py-3">PAN</th>
            <th class="min-w-[190px] px-4 py-3">Client Group</th>
            <th class="whitespace-nowrap px-4 py-3">Status</th>
          </tr>
        </thead>
        <tbody id="linked-client-table-body" class="divide-y divide-slate-100 bg-white">
          {% for row in linked.rows %}
          {% set client_status = (row.client.status or 'inactive')|lower %}
          <tr class="linked-client-row hover:bg-slate-50"
              data-code="{{ (row.client.client_code or '')|lower|e }}"
              data-name="{{ (row.client.client_name or '')|lower|e }}"
              data-trade-name="{{ (row.client.trade_name or '')|lower|e }}"
              data-pan="{{ (row.client.pan or '')|lower|e }}"
              data-gstin="{{ (row.client.gstin or '')|lower|e }}"
              data-group-id="{{ row.client_group_id or '' }}"
              data-group="{{ (row.client_group_name or '')|lower|e }} {{ (row.client_group_code or '')|lower|e }}"
              data-status="{{ client_status|e }}">
            <td class="whitespace-nowrap px-4 py-3 text-sm font-semibold text-slate-700">{{ row.client.client_code or '-' }}</td>
            <td class="px-4 py-3">
              <div class="font-semibold text-slate-900">{{ row.client.client_name }}</div>
              {% if row.client.trade_name and row.client.trade_name != row.client.client_name %}<div class="text-xs text-slate-500">{{ row.client.trade_name }}</div>{% endif %}
            </td>
            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-700">{{ row.client.pan or '-' }}</td>
            <td class="px-4 py-3 text-sm text-slate-700">
              {% if row.client_group_name %}
                <div class="font-medium">{{ row.client_group_name }}</div>
                {% if row.client_group_code %}<div class="text-xs text-slate-500">{{ row.client_group_code }}</div>{% endif %}
              {% else %}-{% endif %}
            </td>
            <td class="whitespace-nowrap px-4 py-3">
              {% if client_status == 'active' %}
              <span class="rounded-full bg-emerald-100 px-2.5 py-1 text-xs font-semibold text-emerald-700">Active</span>
              {% else %}
              <span class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-semibold text-slate-600">{{ client_status.replace('_',' ').title() }}</span>
              {% endif %}
            </td>
          </tr>
          {% endfor %}
          <tr id="linked-client-empty-row" class="hidden">
            <td colspan="5" class="px-4 py-10 text-center text-sm text-slate-500">No linked firm clients match the selected filters.</td>
          </tr>
        </tbody>
      </table>
    </div>
  </section>

  <section class="af-card">
    <div class="flex items-center justify-between">
      <div>
        <h3 class="text-lg font-semibold text-slate-900">Managed Clients</h3>
        <p class="mt-1 text-sm text-slate-500">Clients maintained separately within the consultant workspace.</p>
      </div>
      <a href="/consultant/managed-clients" class="text-sm font-semibold text-brand-700 hover:underline">View all</a>
    </div>
    <div class="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
      {% for client in payload.managed_clients %}
      <a href="/consultant/managed-clients/{{ client.id }}" class="block rounded-xl border border-slate-200 p-3 hover:bg-slate-50">
        <div class="font-semibold text-slate-900">{{ client.client_name }}</div>
        <div class="text-xs text-slate-500">{{ client.client_code or '-' }} • {{ client.relationship_stage.replace('_',' ').title() }} • {{ client.status.replace('_',' ').title() }}</div>
        <div class="mt-2 text-xs text-slate-600">Conversion: {{ client.conversion_status.replace('_',' ').title() if client.conversion_status else 'Not Requested' }}</div>
      </a>
      {% else %}
      <div class="rounded-2xl border border-dashed border-slate-300 p-6 text-sm text-slate-500 md:col-span-2 xl:col-span-3">No managed clients yet.</div>
      {% endfor %}
    </div>
  </section>
</div>

<script>
(() => {
  const section = document.getElementById('linked-firm-clients-section');
  if (!section || section.dataset.liveFilterReady === 'true') return;
  section.dataset.liveFilterReady = 'true';

  const search = document.getElementById('linked-client-search');
  const group = document.getElementById('linked-client-group');
  const status = document.getElementById('linked-client-status');
  const sort = document.getElementById('linked-client-sort');
  const body = document.getElementById('linked-client-table-body');
  const count = document.getElementById('linked-client-count');
  const empty = document.getElementById('linked-client-empty-row');
  const scrollContainer = document.getElementById('linked-client-scroll-container');
  const rows = Array.from(body.querySelectorAll('.linked-client-row'));
  let timer = null;

  const normalise = (value) => (value || '').toString().trim().toLocaleLowerCase();

  function applyFilters() {
    const query = normalise(search.value);
    const selectedGroup = group.value;
    const selectedStatus = normalise(status.value);
    const sortKey = sort.value;

    const visible = rows.filter((row) => {
      const searchable = [
        row.dataset.code,
        row.dataset.name,
        row.dataset.tradeName,
        row.dataset.pan,
        row.dataset.gstin,
        row.dataset.group
      ].join(' ');
      const matchesSearch = !query || searchable.includes(query);
      const matchesGroup = !selectedGroup || row.dataset.groupId === selectedGroup;
      const matchesStatus = !selectedStatus || row.dataset.status === selectedStatus;
      return matchesSearch && matchesGroup && matchesStatus;
    });

    visible.sort((a, b) => {
      const keyMap = {
        client_code: 'code',
        client_name: 'name',
        pan: 'pan',
        client_group: 'group',
        status: 'status'
      };
      const dataKey = keyMap[sortKey] || 'code';
      return normalise(a.dataset[dataKey]).localeCompare(normalise(b.dataset[dataKey]), undefined, {
        numeric: true,
        sensitivity: 'base'
      });
    });

    rows.forEach((row) => row.classList.add('hidden'));
    visible.forEach((row) => {
      row.classList.remove('hidden');
      body.insertBefore(row, empty);
    });

    empty.classList.toggle('hidden', visible.length !== 0);
    count.textContent = `${visible.length} client${visible.length === 1 ? '' : 's'}`;
    if (scrollContainer) scrollContainer.scrollTop = 0;
  }

  search.addEventListener('input', () => {
    window.clearTimeout(timer);
    timer = window.setTimeout(applyFilters, 250);
  });
  group.addEventListener('change', applyFilters);
  status.addEventListener('change', applyFilters);
  sort.addEventListener('change', applyFilters);

  applyFilters();
})();
</script>
