---
/**
 * ThemeSelectorDropdown
 * A dropdown button for desktop that exposes the colour-theme swatches.
 * The mobile menu still uses the flat ThemeSelector component.
 */
import { cn } from '@/lib/cn';

interface Props {
  class?: string;
}

const { class: className } = Astro.props;

// All 13 themes in Tailwind color order
const themes = [
  { id: 'orange',  name: 'Orange',  color: 'oklch(62.5% 0.22  38)'  },
  { id: 'amber',   name: 'Amber',   color: 'oklch(68%   0.19  75)'  },
  { id: 'lime',    name: 'Lime',    color: 'oklch(64%   0.27 130)'  },
  { id: 'emerald', name: 'Emerald', color: 'oklch(62.5% 0.22 160)'  },
  { id: 'teal',    name: 'Teal',    color: 'oklch(62.5% 0.22 190)'  },
  { id: 'cyan',    name: 'Cyan',    color: 'oklch(65%   0.22 200)'  },
  { id: 'sky',     name: 'Sky',     color: 'oklch(67%   0.21 222)'  },
  { id: 'blue',    name: 'Blue',    color: 'oklch(62.5% 0.22 255)'  },
  { id: 'indigo',  name: 'Indigo',  color: 'oklch(60%   0.24 264)'  },
  { id: 'violet',  name: 'Violet',  color: 'oklch(62.5% 0.26 277)'  },
  { id: 'purple',  name: 'Purple',  color: 'oklch(62.5% 0.25 303)'  },
  { id: 'magenta', name: 'Magenta', color: 'oklch(58%   0.28 330)'  },
];
---

<div class={cn('relative theme-dropdown-wrapper', className)}>
  <!-- Trigger button -->
  <button
    type="button"
    id="theme-dropdown-trigger"
    aria-haspopup="true"
    aria-expanded="false"
    aria-label="Select colour theme"
    class={cn(
      'inline-flex items-center gap-1.5 rounded-full border border-border-strong px-2.5 py-1.5',
      'text-foreground-muted hover:text-foreground hover:bg-secondary',
      'transition-colors duration-(--transition-fast)',
      'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2'
    )}
  >
    <!-- Active theme dot -->
    <span
      class="h-3.5 w-3.5 rounded-full block flex-shrink-0"
      style="background-color: var(--color-brand-500)"
      aria-hidden="true"
    />
    <!-- Chevron — inline, rotates on open -->
    <svg
      class="theme-chevron h-3 w-3 flex-shrink-0 transition-transform duration-200"
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2.5"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6"/>
    </svg>
  </button>

  <!-- Dropdown panel -->
  <div
    id="theme-dropdown-panel"
    role="dialog"
    aria-label="Colour theme"
    class={cn(
      'absolute right-0 top-full mt-2 z-50',
      'w-52 rounded-xl border border-border bg-background shadow-lg',
      'p-2.5',
      'hidden'
    )}
  >
    <p class="text-xs font-medium text-foreground-muted mb-2.5 px-0.5">Colour theme</p>
    <div class="grid grid-cols-4 gap-1.5">
      {themes.map((theme) => (
        <button
          type="button"
          class="theme-swatch-dd group flex flex-col items-center gap-1 rounded-lg p-1 hover:bg-secondary transition-colors duration-(--transition-fast) focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          data-theme-id={theme.id}
          aria-label={`${theme.name} theme`}
        >
          <span
            class="h-4 w-4 rounded-full block"
            style={`background-color:${theme.color}`}
          />
          <span class="text-[9px] font-medium text-foreground-muted group-hover:text-foreground leading-none">
            {theme.name}
          </span>
        </button>
      ))}
    </div>
  </div>
</div>

<style>
  .theme-swatch-dd[data-active] {
    background-color: var(--color-secondary);
  }

  .theme-swatch-dd[data-active] span:first-child {
    box-shadow: 0 0 0 2px var(--color-background), 0 0 0 4px var(--color-brand-500);
  }

  .theme-swatch-dd[data-active] span:last-child {
    color: var(--color-foreground);
    font-weight: 600;
  }
</style>

<script>
  const STORAGE_KEY = 'color-theme';
  const DEFAULT_THEME = 'blue';

  function getActiveTheme(): string {
    try {
      return sessionStorage.getItem(STORAGE_KEY) || DEFAULT_THEME;
    } catch {
      return DEFAULT_THEME;
    }
  }

  function setTheme(id: string) {
    document.documentElement.setAttribute('data-theme', id);
    try { sessionStorage.setItem(STORAGE_KEY, id); } catch { /* private mode */ }

    // Update dropdown swatches
    const ddSwatches = document.querySelectorAll<HTMLButtonElement>('.theme-swatch-dd');
    ddSwatches.forEach((btn) => {
      if (btn.dataset.themeId === id) {
        btn.setAttribute('data-active', '');
      } else {
        btn.removeAttribute('data-active');
      }
    });

    // Also sync flat ThemeSelector swatches (mobile menu)
    const flatSwatches = document.querySelectorAll<HTMLButtonElement>('.theme-swatch');
    flatSwatches.forEach((btn) => {
      if (btn.dataset.themeId === id) {
        btn.setAttribute('data-active', '');
      } else {
        btn.removeAttribute('data-active');
      }
    });
  }

  function closeDropdown() {
    const panel = document.getElementById('theme-dropdown-panel');
    const trigger = document.getElementById('theme-dropdown-trigger');
    panel?.classList.add('hidden');
    trigger?.setAttribute('aria-expanded', 'false');
    trigger?.querySelector('.theme-chevron')?.classList.remove('rotate-180');
  }

  function initThemeDropdown() {
    const trigger = document.getElementById('theme-dropdown-trigger');
    const panel = document.getElementById('theme-dropdown-panel');
    if (!trigger || !panel) return;

    // Guard against double-binding
    if (trigger.dataset.dropdownInit) return;
    trigger.dataset.dropdownInit = 'true';

    const active = getActiveTheme();

    // Mark active swatch
    const activeDdSwatches = document.querySelectorAll<HTMLButtonElement>('.theme-swatch-dd');
    activeDdSwatches.forEach((btn) => {
      if (btn.dataset.themeId === active) {
        btn.setAttribute('data-active', '');
      } else {
        btn.removeAttribute('data-active');
      }

      if (!btn.dataset.selectorInit) {
        btn.dataset.selectorInit = 'true';
        btn.addEventListener('click', () => {
          setTheme(btn.dataset.themeId!);
          closeDropdown();
        });
      }
    });

    // Toggle dropdown
    trigger.addEventListener('click', (e) => {
      e.stopPropagation();
      const isOpen = panel.classList.contains('hidden') === false;
      if (isOpen) {
        closeDropdown();
      } else {
        panel.classList.remove('hidden');
        trigger.setAttribute('aria-expanded', 'true');
        trigger.querySelector('.theme-chevron')?.classList.add('rotate-180');
      }
    });

    // Close on outside click
    document.addEventListener('click', (e) => {
      const wrapper = trigger.closest('.theme-dropdown-wrapper');
      if (wrapper && !wrapper.contains(e.target as Node)) {
        closeDropdown();
      }
    });

    // Close on Escape
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') closeDropdown();
    });
  }

  initThemeDropdown();
  document.addEventListener('astro:page-load', initThemeDropdown);
  document.addEventListener('astro:after-swap', initThemeDropdown);
</script>
