<script lang="ts">
  // SPDX-License-Identifier: MIT
  // Settings Panel — VS Code-style sidebar + content layout with search.
  import { onMount } from 'svelte';
  import { SETTINGS_REGISTRY, type SettingsCategory, type SettingEntry } from './settings-registry';
  import AppearanceSettings from './categories/AppearanceSettings.svelte';
  import AgentSettings from './categories/AgentSettings.svelte';
  import SecuritySettings from './categories/SecuritySettings.svelte';
  import ProjectSettings from './categories/ProjectSettings.svelte';
  import OrchestrationSettings from './categories/OrchestrationSettings.svelte';
  import AdvancedSettings from './categories/AdvancedSettings.svelte';
  import ProSettings from './categories/ProSettings.svelte';

  interface Props {
    onClose?: () => void;
  }
  let { onClose }: Props = $props();

  const BASE_CATEGORIES: { id: SettingsCategory; label: string; icon: string }[] = [
    { id: 'appearance', label: 'Appearance', icon: '🎨' },
    { id: 'agents', label: 'Agents', icon: '🤖' },
    { id: 'security', label: 'Security', icon: '🛡' },
    { id: 'projects', label: 'Projects', icon: '📁' },
    { id: 'orchestration', label: 'Orchestration', icon: '🔗' },
    { id: 'advanced', label: 'Advanced', icon: '⚡' },
  ];

  let proAvailable = $state(false);
  let CATEGORIES = $derived(proAvailable
    ? [...BASE_CATEGORIES, { id: 'pro' as SettingsCategory, label: 'Pro', icon: '💎' }]
    : BASE_CATEGORIES);

  let activeCategory = $state<SettingsCategory>('appearance');
  let searchQuery = $state('');
  let searchResults = $derived(searchQuery.length >= 2
    ? SETTINGS_REGISTRY.filter(s => {
        const q = searchQuery.toLowerCase();
        return s.label.toLowerCase().includes(q)
          || s.description.toLowerCase().includes(q)
          || s.keywords.some(k => k.includes(q));
      })
    : []
  );
  let showSearch = $derived(searchQuery.length >= 2);
  let sidebarRef: HTMLElement | undefined = $state();

  function selectCategory(id: SettingsCategory) {
    activeCategory = id;
    searchQuery = '';
  }

  function navigateToResult(entry: SettingEntry) {
    activeCategory = entry.category;
    searchQuery = '';
    requestAnimationFrame(() => {
      const el = document.getElementById(entry.anchorId);
      el?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  }

  function handleSidebarKeydown(e: KeyboardEvent) {
    const idx = CATEGORIES.findIndex(c => c.id === activeCategory);
    if (e.key === 'ArrowDown' && idx < CATEGORIES.length - 1) {
      e.preventDefault();
      selectCategory(CATEGORIES[idx + 1].id);
    } else if (e.key === 'ArrowUp' && idx > 0) {
      e.preventDefault();
      selectCategory(CATEGORIES[idx - 1].id);
    } else if (e.key === 'Escape' && onClose) {
      onClose();
    }
  }

  function handleSearchKeydown(e: KeyboardEvent) {
    if (e.key === 'Escape') {
      if (searchQuery) {
        searchQuery = '';
      } else if (onClose) {
        onClose();
      }
    } else if (e.key === 'Enter' && searchResults.length > 0) {
      navigateToResult(searchResults[0]);
    }
  }

  let searchInput: HTMLInputElement | undefined = $state();
  onMount(() => {
    searchInput?.focus();
    import('../commercial/pro-bridge').then(m => m.proStatus()).then(() => { proAvailable = true; }).catch(() => {});
  });
</script>

<div class="settings-panel" onkeydown={handleSidebarKeydown}>
  <div class="settings-header">
    <span class="settings-title">Settings</span>
    <input
      bind:this={searchInput}
      class="settings-search"
      type="text"
      placeholder="Search settings..."
      bind:value={searchQuery}
      onkeydown={handleSearchKeydown}
      aria-label="Search settings"
    />
    {#if onClose}
      <button class="settings-close" onclick={onClose} aria-label="Close settings">x</button>
    {/if}
  </div>

  {#if showSearch}
    <div class="search-results">
      {#each searchResults.slice(0, 10) as result}
        <button class="search-result" onclick={() => navigateToResult(result)}>
          <span class="sr-label">{result.label}</span>
          {#if result.pro}<span class="sr-pro">Pro</span>{/if}
          <span class="sr-cat">{result.category}</span>
          <span class="sr-desc">{result.description}</span>
        </button>
      {/each}
      {#if searchResults.length === 0}
        <div class="search-empty">No settings match "{searchQuery}"</div>
      {/if}
    </div>
  {:else}
    <div class="settings-body">
      <nav class="settings-sidebar" bind:this={sidebarRef} role="tablist" aria-label="Settings categories">
        {#each CATEGORIES as cat}
          <button
            class="sidebar-item"
            class:active={activeCategory === cat.id}
            onclick={() => selectCategory(cat.id)}
            role="tab"
            aria-selected={activeCategory === cat.id}
          >
            <span class="sidebar-icon">{cat.icon}</span>
            <span class="sidebar-label">{cat.label}</span>
          </button>
        {/each}
      </nav>

      <div class="settings-content" role="tabpanel">
        {#if activeCategory === 'appearance'}
          <AppearanceSettings />
        {:else if activeCategory === 'agents'}
          <AgentSettings />
        {:else if activeCategory === 'security'}
          <SecuritySettings />
        {:else if activeCategory === 'projects'}
          <ProjectSettings />
        {:else if activeCategory === 'orchestration'}
          <OrchestrationSettings />
        {:else if activeCategory === 'advanced'}
          <AdvancedSettings />
        {:else if activeCategory === 'pro'}
          <ProSettings />
        {/if}
      </div>
    </div>
  {/if}
</div>

<style>
  .settings-panel {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: var(--ctp-base);
    color: var(--ctp-text);
  }
  .settings-header {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1rem;
    border-bottom: 1px solid var(--ctp-surface0);
    flex-shrink: 0;
  }
  .settings-title {
    font-weight: 600;
    font-size: 0.875rem;
    color: var(--ctp-subtext0);
    white-space: nowrap;
  }
  .settings-search {
    flex: 1;
    background: var(--ctp-mantle);
    border: 1px solid var(--ctp-surface0);
    border-radius: 0.25rem;
    padding: 0.375rem 0.625rem;
    color: var(--ctp-text);
    font-size: 0.8125rem;
    outline: none;
  }
  .settings-search:focus {
    border-color: var(--ctp-blue);
  }
  .settings-search::placeholder {
    color: var(--ctp-overlay0);
  }
  .settings-close {
    background: none;
    border: none;
    color: var(--ctp-overlay0);
    cursor: pointer;
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
  }
  .settings-close:hover { color: var(--ctp-text); }

  .search-results {
    flex: 1;
    overflow-y: auto;
    padding: 0.5rem;
  }
  .search-result {
    display: flex;
    flex-wrap: wrap;
    align-items: baseline;
    gap: 0.375rem;
    width: 100%;
    padding: 0.5rem 0.75rem;
    background: none;
    border: none;
    border-radius: 0.25rem;
    color: var(--ctp-text);
    cursor: pointer;
    text-align: left;
    font-size: 0.8125rem;
  }
  .search-result:hover { background: var(--ctp-surface0); }
  .sr-label { font-weight: 600; }
  .sr-pro {
    font-size: 0.625rem;
    padding: 0.0625rem 0.25rem;
    background: var(--ctp-peach);
    color: var(--ctp-base);
    border-radius: 0.125rem;
    font-weight: 700;
    text-transform: uppercase;
  }
  .sr-cat {
    font-size: 0.6875rem;
    color: var(--ctp-overlay0);
    margin-left: auto;
  }
  .sr-desc {
    width: 100%;
    font-size: 0.75rem;
    color: var(--ctp-subtext0);
  }
  .search-empty {
    padding: 2rem;
    text-align: center;
    color: var(--ctp-overlay0);
    font-size: 0.8125rem;
  }

  .settings-body {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
  }
  .settings-sidebar {
    display: flex;
    flex-wrap: wrap;
    gap: 0.125rem;
    padding: 0.375rem 0.5rem;
    background: var(--ctp-mantle);
    border-bottom: 1px solid var(--ctp-surface0);
    flex-shrink: 0;
  }
  .sidebar-item {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.3125rem 0.5rem;
    background: none;
    border: none;
    border-radius: 0.25rem;
    color: var(--ctp-subtext0);
    cursor: pointer;
    font-size: 0.75rem;
    transition: background 0.1s, color 0.1s;
  }
  .sidebar-item:hover {
    background: var(--ctp-surface0);
    color: var(--ctp-text);
  }
  .sidebar-item.active {
    color: var(--ctp-blue);
    background: color-mix(in srgb, var(--ctp-blue) 12%, transparent);
  }
  .sidebar-icon { font-size: 0.875rem; }
  .sidebar-label { font-weight: 500; }

  .settings-content {
    flex: 1;
    overflow-y: auto;
    padding: 1rem 1.5rem;
  }
  .category-placeholder {
    color: var(--ctp-subtext0);
  }
  .category-placeholder h2 {
    font-size: 1.125rem;
    font-weight: 600;
    color: var(--ctp-text);
    margin-bottom: 0.5rem;
  }
  .setting-count {
    font-size: 0.75rem;
    color: var(--ctp-overlay0);
    margin-top: 0.25rem;
  }
</style>
