<script lang="ts">
  import { goto } from "$app/navigation";
  import { afterNavigate } from "$app/navigation";
  import EmailText from "../../components/EmailText.svelte";
  import type { PermissionMap } from "$lib/permissions";
  import { formatDate } from "$lib/utils";
  import NoResultsMonkey from "../../components/NoResultsMonkey.svelte";
  import AccessDenied from "../../components/AccessDenied.svelte";
  import Pagination from "../../components/Pagination.svelte";
  import "../../styles/companies/companylist.css";

  export let data: {
    permissions: PermissionMap;
    companies: Array<{
      id: string;
      name: string;
      status?: string;
      type?: string;
      createdAt?: string;
      identifier?: string;
      contactEmail?: string;
      [key: string]: unknown;
    }>;
    totalPages: number;
    currentPage: number;
    totalRecords: number;
    search: string;
  };

  $: hasAccess = data.permissions["companies.view"] === true;

  let searchInput = data.search;
  let debounceTimer: ReturnType<typeof setTimeout>;
  let isSearching = false;
  let searchInputEl: HTMLInputElement;
  let searchStartedAt = 0;
  let isUserTyping = false;

  // When navigation completes (results loaded), clear loading & refocus
  // Ensure spinner stays visible for at least 500ms
  afterNavigate(() => {
    const elapsed = Date.now() - searchStartedAt;
    const remaining = Math.max(0, 500 - elapsed);
    setTimeout(() => {
      isSearching = false;
      isUserTyping = false;
      if (searchInputEl && document.activeElement !== searchInputEl) {
        requestAnimationFrame(() => searchInputEl?.focus());
      }
    }, remaining);
  });

  $: currentPage = data.currentPage;
  $: totalPages = data.totalPages;
  $: totalRecords = data.totalRecords;
  $: companies = data.companies;

  function navigateToPage(p: number) {
    const params = new URLSearchParams();
    params.set("page", String(p));
    if (searchInput) params.set("search", searchInput);
    goto(`/companies?${params.toString()}`, { replaceState: true });
  }

  function handleSearch() {
    isUserTyping = true;
    searchStartedAt = Date.now();
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      isSearching = true;
      isUserTyping = false;
      const params = new URLSearchParams();
      params.set("page", "1");
      if (searchInput) params.set("search", searchInput);
      goto(`/companies?${params.toString()}`, {
        replaceState: true,
        keepFocus: true,
        noScroll: true,
      });
    }, 500);
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key === "Enter") {
      isSearching = true;
      isUserTyping = false;
      searchStartedAt = Date.now();
      clearTimeout(debounceTimer);
      const params = new URLSearchParams();
      params.set("page", "1");
      if (searchInput) params.set("search", searchInput);
      goto(`/companies?${params.toString()}`, {
        replaceState: true,
        keepFocus: true,
        noScroll: true,
      });
    }
  }

  function statusClass(status?: string): string {
    if (!status) return "neutral";
    const s = status.toLowerCase();
    if (s === "active") return "active";
    if (s === "inactive" || s === "disabled") return "inactive";
    if (s === "pending") return "pending";
    return "neutral";
  }

  function companyInitials(name: string): string {
    return name
      .split(/\s+/)
      .slice(0, 2)
      .map((w) => w[0])
      .join("")
      .toUpperCase();
  }
</script>

<svelte:head>
  <title>Companies — Project Optima</title>
</svelte:head>

{#if !hasAccess}
  <AccessDenied
    message="You don't have permission to view Companies. Contact your administrator to request access."
  />
{:else}
  <div class="companies-page">
    <div class="companies-pane">
      <!-- Pane header -->
      <div class="pane-header">
        <div class="pane-header-left">
          <h2 class="page-title">Companies</h2>
          {#if totalRecords > 0}
            <span class="result-count"
              >{totalRecords} record{totalRecords === 1 ? "" : "s"}</span
            >
          {/if}
        </div>
        <div class="search-bar">
          <svg
            class="search-icon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
          >
            <circle cx="11" cy="11" r="8" />
            <path d="M21 21l-4.35-4.35" />
          </svg>
          <input
            type="text"
            placeholder="Search companies…"
            bind:this={searchInputEl}
            bind:value={searchInput}
            on:input={handleSearch}
            on:keydown={handleKeydown}
          />
          {#if searchInput}
            <button
              class="search-clear"
              on:click={() => {
                searchInput = "";
                handleSearch();
              }}
              aria-label="Clear search"
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                width="14"
                height="14"
              >
                <path d="M18 6L6 18M6 6l12 12" />
              </svg>
            </button>
          {/if}
        </div>
      </div>

      <!-- Pane body -->
      <div class="pane-body">
        {#if isSearching && !isUserTyping}
          <div class="search-loading-overlay">
            <div class="search-spinner"></div>
          </div>
        {/if}
        {#if companies.length === 0}
          <div class="empty-state">
            <NoResultsMonkey
              message={searchInput
                ? "No companies match your search"
                : "No companies found"}
            />
          </div>
        {:else}
          <div class="card-grid">
            {#each companies as company (company.id)}
              <button
                class="company-card"
                on:click={() => goto(`/companies/${company.id}`)}
                on:keydown={(e) => {
                  if (e.key === "Enter") goto(`/companies/${company.id}`);
                }}
              >
                <!-- Card header: avatar + status -->
                <div class="card-top">
                  <div class="card-avatar">
                    <span class="avatar-initials"
                      >{companyInitials(company.name)}</span
                    >
                  </div>
                  <span
                    class="status-dot {statusClass(company.status)}"
                    title={company.status || "Unknown"}
                  ></span>
                </div>

                <!-- Card body -->
                <div class="card-body">
                  <h3 class="card-name">{company.name}</h3>
                  {#if company.contactEmail}
                    <span class="card-email">
                      <EmailText email={company.contactEmail} />
                    </span>
                  {/if}
                </div>

                <!-- Card meta -->
                <div class="card-meta">
                  {#if company.type}
                    <div class="meta-item">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        class="meta-icon"
                      >
                        <rect
                          x="2"
                          y="7"
                          width="20"
                          height="14"
                          rx="2"
                          ry="2"
                        />
                        <path d="M16 3h-8l-2 4h12z" />
                      </svg>
                      <span>{company.type}</span>
                    </div>
                  {/if}
                  {#if company.identifier || company.id}
                    <div class="meta-item">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        class="meta-icon"
                      >
                        <path d="M4 9h16M4 15h16M10 3L8 21M16 3l-2 18" />
                      </svg>
                      <span class="mono"
                        >{company.identifier ||
                          company.id?.toString().slice(0, 8)}</span
                      >
                    </div>
                  {/if}
                </div>

                <!-- Card footer -->
                <div class="card-footer">
                  {#if company.status}
                    <span class="status-label {statusClass(company.status)}"
                      >{company.status}</span
                    >
                  {/if}
                  {#if formatDate(company.createdAt)}
                    <span class="card-date"
                      >{formatDate(company.createdAt)}</span
                    >
                  {/if}
                </div>

                <!-- Hover arrow -->
                <svg
                  class="card-arrow"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path d="M5 12h14M12 5l7 7-7 7" />
                </svg>
              </button>
            {/each}
          </div>
        {/if}
      </div>

      <!-- Pane footer / Pagination -->
      {#if totalPages > 1}
        <div class="pane-footer">
          <span class="page-info">
            Page {currentPage} of {totalPages}
          </span>
          <Pagination {currentPage} {totalPages} onNavigate={navigateToPage} />
        </div>
      {/if}
    </div>
  </div>
{/if}

<style>
</style>
