---
import BaseLayout from './BaseLayout.astro';
import SignOutButton from '@/components/admin/SignOutButton.tsx';
import AdminNavIcon from '@/components/admin/AdminNavIcon.astro';
import type { Locale } from '@/data/site';
import type { AuthUser } from '@/lib/auth/types';
import { localizedPath, switchLocalePath, stripLocalePrefix } from '@/i18n/utils';
import { adminNav, type AdminNavGroup } from '@/lib/admin/nav';
import { adminToneStyles, resolveAdminTone } from '@/lib/admin/theme';

export interface AdminBreadcrumb {
  label: string;
  href: string;
}

interface Props {
  locale: Locale;
  title: string;
  user: AuthUser;
  breadcrumbs?: AdminBreadcrumb[];
}

const { locale, title, user, breadcrumbs = [] } = Astro.props;

const dashboardHref = localizedPath(locale, 'admin');
const menuLabel = locale === 'ar' ? 'فتح القائمة' : 'Open menu';
const currentPath = stripLocalePrefix(Astro.url.pathname);
const pageTone = resolveAdminTone(currentPath);
const pageToneStyles = adminToneStyles[pageTone];
const altLocale: Locale = locale === 'ar' ? 'en' : 'ar';
const altHref = switchLocalePath(Astro.url.pathname, altLocale);

function isActive(href: string): boolean {
  const target = stripLocalePrefix(localizedPath(locale, href));
  if (href === 'admin') {
    return currentPath === target;
  }
  return currentPath === target || currentPath.startsWith(`${target}/`);
}
---

<BaseLayout locale={locale} title={title} noindex={true} analytics={false}>
  <div class="drawer lg:drawer-open min-h-screen">
    <input id="admin-drawer" type="checkbox" class="drawer-toggle" autocomplete="off" />

    <div class="drawer-content flex min-h-screen flex-col bg-base-200">
      <header class="flex flex-wrap items-center gap-3 border-b border-base-300 bg-base-100 px-4 py-3 sm:px-6 lg:px-8">
        <label
          for="admin-drawer"
          aria-label={menuLabel}
          class="btn btn-square btn-ghost drawer-button lg:hidden"
        >
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="inline-block h-6 w-6 stroke-current">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
          </svg>
        </label>

        <div class="min-w-0 flex-1">
          {
            breadcrumbs.length > 0 && (
              <nav aria-label="Breadcrumb" class="mb-0.5 flex items-center gap-1 text-xs text-base-content/50">
                <a href={dashboardHref} class="hover:text-base-content/80">
                  {locale === 'ar' ? 'الرئيسية' : 'Home'}
                </a>
                {breadcrumbs.map((crumb) => (
                  <>
                    <span aria-hidden="true">/</span>
                    <a href={crumb.href} class="hover:text-base-content/80">
                      {crumb.label}
                    </a>
                  </>
                ))}
              </nav>
            )
          }
          <h1 class="truncate text-lg font-bold sm:text-xl">{title}</h1>
          <div class={`mt-1.5 h-1 w-12 rounded-full ${pageToneStyles.headerAccent}`} aria-hidden="true"></div>
        </div>

        <div class="flex shrink-0 items-center gap-1.5 sm:gap-2.5">
          <a
            href={localizedPath(locale, '')}
            target="_blank"
            rel="noopener"
            class="btn btn-sm btn-ghost hidden sm:inline-flex"
          >
            {locale === 'ar' ? 'عرض الموقع' : 'View site'}
          </a>
          <a href={altHref} class="btn btn-sm btn-ghost" title={altLocale === 'ar' ? 'العربية' : 'English'}>
            {altLocale === 'ar' ? 'AR' : 'EN'}
          </a>
          <span class="hidden max-w-32 truncate text-sm text-base-content/60 md:inline lg:max-w-none">
            {user.email}
          </span>
          <SignOutButton client:load locale={locale} />
        </div>
      </header>

      <main class="flex-1 p-4 sm:p-6 lg:p-8">
        <slot />
      </main>
    </div>

    <div class="drawer-side z-40 max-lg:z-50">
      <label for="admin-drawer" aria-label={locale === 'ar' ? 'إغلاق القائمة' : 'Close menu'} class="drawer-overlay"></label>
      <aside class="flex min-h-full w-64 flex-col gap-6 border-e border-base-300 bg-base-100 p-6">
        <a href={dashboardHref} class="text-lg font-bold text-primary">
          {locale === 'ar' ? 'لوحة الإدارة' : 'Admin'}
        </a>

        <nav class="flex flex-1 flex-col">
          {
            adminNav.map((entry, index) => {
              if (entry.type === 'link') {
                const active = isActive(entry.href);
                const tone = adminToneStyles[entry.tone];
                const hasGroupsBelow = adminNav.slice(index + 1).some((e) => e.type === 'group');
                return (
                  <>
                    <a
                      href={localizedPath(locale, entry.href)}
                      class={`flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors ${
                        active ? tone.navActive : 'text-base-content/80 hover:bg-base-200'
                      }`}
                    >
                      <AdminNavIcon
                        name={entry.icon}
                        class={`h-5 w-5 shrink-0 ${active ? tone.navIcon : 'opacity-70'}`}
                      />
                      {entry.label[locale]}
                    </a>
                    {hasGroupsBelow && <div class="my-4 border-t border-base-300" aria-hidden="true" />}
                  </>
                );
              }

              const group = entry as AdminNavGroup;
              const groupTone = adminToneStyles[group.tone];
              return (
                <div class={index > 0 ? 'mt-5 first:mt-0' : ''}>
                  <p class="mb-1.5 flex items-center gap-2 px-3 text-[11px] font-semibold uppercase tracking-wider text-base-content/45">
                    <span class={`h-1.5 w-1.5 rounded-full ${groupTone.headerAccent}`} aria-hidden="true"></span>
                    {group.label[locale]}
                  </p>
                  <div class="space-y-0.5">
                    {group.items.map((item) => {
                      const active = isActive(item.href);
                      const tone = adminToneStyles[item.tone];
                      return (
                        <a
                          href={localizedPath(locale, item.href)}
                          class={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                            active
                              ? tone.navActive
                              : 'text-base-content/70 hover:bg-base-200 hover:text-base-content'
                          }`}
                        >
                          <AdminNavIcon
                            name={item.icon}
                            class={`h-5 w-5 shrink-0 ${active ? tone.navIcon : 'opacity-70'}`}
                          />
                          {item.label[locale]}
                        </a>
                      );
                    })}
                  </div>
                </div>
              );
            })
          }
        </nav>
      </aside>
    </div>
  </div>
</BaseLayout>
