<script lang="ts">
  import { api } from '$lib/api';
  import { goto, invalidateAll } from '$app/navigation';
  import { page } from '$app/state';
  import { ShoppingCart, LogOut } from 'lucide-svelte';
  import { clientSession, sessionHydrated } from '$lib/session';

  let { children } = $props();

  const isRootRoute = $derived(page.url.pathname === '/');
  const currentYear = new Date().getFullYear();

  const userName = $derived($clientSession?.name ?? '');
  const userInitials = $derived(
    ($clientSession?.name ?? '')
      .split(' ')
      .slice(0, 2)
      .map((word: string) => word[0])
      .join('')
      .toUpperCase() || '?'
  );

  const navItems = [{ href: '/ordering', label: 'Order Catalogue', icon: ShoppingCart }];

  function isActive(href: string) {
    return href === '/' ? page.url.pathname === '/' : page.url.pathname.startsWith(href);
  }

  async function signOut() {
    try {
      await api.clientLogout();
    } catch {
      // Clearing the local session is the safe fallback.
    } finally {
      clientSession.clear();
      await goto('/', { replaceState: true });
    }
  }

  // Keep the saved session fresh on reload (mirrors the workspace shell).
  let restoredSessionKey = $state<string | null>(null);
  $effect(() => {
    const hydrated = $sessionHydrated;
    const sessionKey = $clientSession ? `${$clientSession.role}:${$clientSession.email}:${$clientSession.user_id ?? ''}` : null;
    if (!hydrated || !sessionKey || restoredSessionKey === sessionKey) {
      return;
    }
    restoredSessionKey = sessionKey;
    api
      .clientSession()
      .then((session) => {
        restoredSessionKey = `${session.role}:${session.email}:${session.user_id ?? ''}`;
        clientSession.set(session);
        return invalidateAll();
      })
      .catch(() => {
        restoredSessionKey = null;
        clientSession.clear();
      });
  });

  // Signed-out customers go back to the sign-in screen; the portal landing is
  // always the catalogue, never the internal dashboard/login root.
  $effect(() => {
    if (!$sessionHydrated) return;
    if (!$clientSession && !isRootRoute) {
      goto('/', { replaceState: true });
    } else if ($clientSession && isRootRoute) {
      goto('/ordering', { replaceState: true });
    }
  });
</script>

<svelte:head>
  <title>Customer Ordering Portal | Hunter Premium Produce</title>
</svelte:head>

{#if !$clientSession}
  {#if isRootRoute}
    {@render children()}
  {:else}
    <div class="loading-screen">
      <p>Returning you to sign in…</p>
    </div>
  {/if}
{:else}
  <div class="portal">
    <aside class="sidebar">
      <div class="brand">
        <span class="brand-mark"><ShoppingCart size={20} strokeWidth={2} /></span>
        <div class="brand-text">
          <span class="brand-name">Hunter Premium Produce</span>
          <span class="brand-sub">Customer Ordering Portal</span>
        </div>
      </div>

      <nav class="nav" aria-label="Customer portal navigation">
        {#each navItems as item}
          {@const Icon = item.icon}
          <a class="nav-row" class:active={isActive(item.href)} href={item.href}>
            <span class="nav-icon"><Icon size={18} strokeWidth={1.85} /></span>
            <span>{item.label}</span>
          </a>
        {/each}
      </nav>

      <div class="sidebar-foot">
        <div class="account">
          <span class="avatar">{userInitials}</span>
          <span class="account-name">{userName}</span>
        </div>
        <button class="signout" type="button" onclick={signOut}>
          <LogOut size={16} strokeWidth={1.9} />
          <span>Sign out</span>
        </button>
        <small class="copyright">&copy; {currentYear} Hunter Premium Produce</small>
      </div>
    </aside>

    <div class="main">
      <header class="topbar">
        <h1>Customer Ordering Portal</h1>
        <div class="topbar-account">
          <span class="avatar small">{userInitials}</span>
          <span class="topbar-name">{userName}</span>
        </div>
      </header>
      <main class="content">
        {@render children()}
      </main>
    </div>
  </div>
{/if}

<style>
  .portal {
    display: grid;
    grid-template-columns: 16rem minmax(0, 1fr);
    min-height: 100vh;
    background: #f4f7f4;
    color: #1f2a24;
  }

  .loading-screen {
    display: grid;
    place-items: center;
    min-height: 100vh;
    color: #5f7266;
    background: #f4f7f4;
  }

  /* ── Sidebar ─────────────────────────────────────────────── */
  .sidebar {
    display: flex;
    flex-direction: column;
    gap: 1.25rem;
    padding: 1.4rem 1.05rem;
    background: #1f3a2c;
    color: #e7efe9;
    position: sticky;
    top: 0;
    height: 100vh;
  }

  .brand {
    display: flex;
    align-items: center;
    gap: 0.7rem;
    padding-bottom: 1.1rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.12);
  }

  .brand-mark {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 2.4rem;
    height: 2.4rem;
    border-radius: 0.8rem;
    background: rgba(255, 255, 255, 0.12);
    color: #fff;
    flex-shrink: 0;
  }

  .brand-text {
    display: flex;
    flex-direction: column;
    min-width: 0;
  }

  .brand-name {
    font-size: 0.98rem;
    font-weight: 700;
    line-height: 1.2;
  }

  .brand-sub {
    font-size: 0.78rem;
    color: rgba(231, 239, 233, 0.7);
  }

  .nav {
    display: grid;
    gap: 0.25rem;
  }

  .nav-row {
    display: flex;
    align-items: center;
    gap: 0.7rem;
    padding: 0.7rem 0.8rem;
    border-radius: 0.75rem;
    color: rgba(231, 239, 233, 0.85);
    text-decoration: none;
    font-size: 0.92rem;
    font-weight: 500;
    transition: background-color 140ms ease, color 140ms ease;
  }

  .nav-row:hover {
    background: rgba(255, 255, 255, 0.08);
    color: #fff;
  }

  .nav-row.active {
    background: #fff;
    color: #1f3a2c;
    font-weight: 600;
  }

  .nav-icon {
    display: inline-flex;
    flex-shrink: 0;
  }

  .sidebar-foot {
    margin-top: auto;
    display: grid;
    gap: 0.75rem;
    padding-top: 1rem;
    border-top: 1px solid rgba(255, 255, 255, 0.12);
  }

  .account {
    display: flex;
    align-items: center;
    gap: 0.6rem;
  }

  .avatar {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 2.1rem;
    height: 2.1rem;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.15);
    color: #fff;
    font-size: 0.78rem;
    font-weight: 700;
    flex-shrink: 0;
  }

  .avatar.small {
    width: 1.85rem;
    height: 1.85rem;
    background: #1f3a2c;
  }

  .account-name {
    font-size: 0.86rem;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .signout {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 0.8rem;
    border: 1px solid rgba(255, 255, 255, 0.18);
    border-radius: 0.7rem;
    background: transparent;
    color: #e7efe9;
    font-size: 0.86rem;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 140ms ease;
  }

  .signout:hover {
    background: rgba(255, 255, 255, 0.1);
  }

  .copyright {
    font-size: 0.7rem;
    color: rgba(231, 239, 233, 0.55);
  }

  /* ── Main ────────────────────────────────────────────────── */
  .main {
    display: flex;
    flex-direction: column;
    min-width: 0;
  }

  .topbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    padding: 1.05rem 1.6rem;
    background: #fff;
    border-bottom: 1px solid rgba(31, 58, 44, 0.1);
    position: sticky;
    top: 0;
    z-index: 5;
  }

  .topbar h1 {
    margin: 0;
    font-size: 1.1rem;
    font-weight: 700;
    color: #1f3a2c;
  }

  .topbar-account {
    display: flex;
    align-items: center;
    gap: 0.55rem;
  }

  .topbar-name {
    font-size: 0.88rem;
    font-weight: 600;
    color: #1f2a24;
  }

  .content {
    flex: 1;
    padding: 1.6rem;
    min-width: 0;
  }

  @media (max-width: 820px) {
    .portal {
      grid-template-columns: 1fr;
    }

    .sidebar {
      position: static;
      height: auto;
      flex-direction: row;
      flex-wrap: wrap;
      align-items: center;
      gap: 0.75rem;
    }

    .brand {
      border-bottom: none;
      padding-bottom: 0;
      flex: 1;
    }

    .nav {
      grid-auto-flow: column;
    }

    .sidebar-foot {
      margin-top: 0;
      border-top: none;
      padding-top: 0;
      grid-auto-flow: column;
      align-items: center;
    }

    .copyright {
      display: none;
    }
  }
</style>
