<script lang="ts">
  import { HELP_PAGES, nextPage, prevPage, isFirstPage, isLastPage } from "./docs/helpPages";
  import DocsGettingStarted from "./docs/DocsGettingStarted.svelte";
  import DocsKeyboardShortcuts from "./docs/DocsKeyboardShortcuts.svelte";
  import DocsChatInput from "./docs/DocsChatInput.svelte";
  import DocsFileEditor from "./docs/DocsFileEditor.svelte";
  import DocsGitPanel from "./docs/DocsGitPanel.svelte";
  import DocsThemeCustomisation from "./docs/DocsThemeCustomisation.svelte";
  import DocsModelConfig from "./docs/DocsModelConfig.svelte";
  import DocsSessionManagement from "./docs/DocsSessionManagement.svelte";
  import DocsTaskLoop from "./docs/DocsTaskLoop.svelte";
  import DocsPanelsTools from "./docs/DocsPanelsTools.svelte";
  import DocsTroubleshooting from "./docs/DocsTroubleshooting.svelte";
  import DocsChangelog from "./docs/DocsChangelog.svelte";

  interface Props {
    onClose: () => void;
  }

  const { onClose }: Props = $props();

  const PAGE_COMPONENTS = [
    DocsGettingStarted,
    DocsKeyboardShortcuts,
    DocsChatInput,
    DocsFileEditor,
    DocsGitPanel,
    DocsThemeCustomisation,
    DocsModelConfig,
    DocsSessionManagement,
    DocsTaskLoop,
    DocsPanelsTools,
    DocsTroubleshooting,
    DocsChangelog,
  ];

  let currentPageIndex = $state(0);

  const currentComponent = $derived(PAGE_COMPONENTS[currentPageIndex]);
  const atFirst = $derived(isFirstPage(currentPageIndex));
  const atLast = $derived(isLastPage(currentPageIndex, HELP_PAGES.length));

  function handleKeydown(event: KeyboardEvent): void {
    const target = event.target as HTMLElement;
    const isInputFocused = target.tagName === "INPUT" || target.tagName === "TEXTAREA";

    if (event.key === "Escape") {
      onClose();
      return;
    }

    if (isInputFocused) return;

    if (event.key === "ArrowRight" || event.key === "ArrowDown") {
      event.preventDefault();
      currentPageIndex = nextPage(currentPageIndex, HELP_PAGES.length);
    } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
      event.preventDefault();
      currentPageIndex = prevPage(currentPageIndex);
    }
  }
</script>

<svelte:window onkeydown={handleKeydown} />

<!-- Backdrop -->
<div
  class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
  onclick={onClose}
  role="button"
  tabindex="0"
  onkeydown={(e) => e.key === "Escape" && onClose()}
>
  <!-- Dialog -->
  <div
    class="bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-lg shadow-xl w-full max-w-3xl h-[80vh] flex flex-col"
    onclick={(e) => e.stopPropagation()}
    onkeydown={(e) => e.stopPropagation()}
    role="dialog"
    aria-labelledby="help-title"
    tabindex="-1"
  >
    <!-- Header -->
    <div
      class="flex items-center justify-between px-6 py-4 border-b border-[var(--border-color)] shrink-0"
    >
      <h2 id="help-title" class="text-lg font-semibold text-[var(--text-primary)]">
        Help & Documentation
      </h2>
      <button
        onclick={onClose}
        class="p-1 text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
        aria-label="Close"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M6 18L18 6M6 6l12 12"
          />
        </svg>
      </button>
    </div>

    <!-- Body: sidebar + content -->
    <div class="flex flex-1 overflow-hidden">
      <!-- Sidebar TOC -->
      <nav
        class="w-44 shrink-0 border-r border-[var(--border-color)] overflow-y-auto py-2"
        aria-label="Documentation pages"
      >
        {#each HELP_PAGES as page, i (page.id)}
          <button
            onclick={() => (currentPageIndex = i)}
            class="w-full text-left px-4 py-2 text-sm transition-colors {i === currentPageIndex
              ? 'bg-[var(--bg-secondary)] text-[var(--accent-primary)] font-medium'
              : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]'}"
            aria-current={i === currentPageIndex ? "page" : undefined}
          >
            {page.title}
          </button>
        {/each}
      </nav>

      <!-- Page content -->
      <div class="flex-1 overflow-y-auto p-6">
        <svelte:component this={currentComponent} />
      </div>
    </div>

    <!-- Footer: prev / page indicator / next -->
    <div
      class="flex items-center justify-between px-6 py-3 border-t border-[var(--border-color)] shrink-0"
    >
      <button
        onclick={() => (currentPageIndex = prevPage(currentPageIndex))}
        disabled={atFirst}
        class="flex items-center gap-1 px-3 py-1.5 text-sm rounded transition-colors
          {atFirst
          ? 'text-[var(--text-tertiary)] cursor-not-allowed'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]'}"
      >
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M15 19l-7-7 7-7"
          />
        </svg>
        Previous
      </button>

      <span class="text-xs text-[var(--text-tertiary)]">
        Page {currentPageIndex + 1} of {HELP_PAGES.length}
      </span>

      <button
        onclick={() => (currentPageIndex = nextPage(currentPageIndex, HELP_PAGES.length))}
        disabled={atLast}
        class="flex items-center gap-1 px-3 py-1.5 text-sm rounded transition-colors
          {atLast
          ? 'text-[var(--text-tertiary)] cursor-not-allowed'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]'}"
      >
        Next
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
        </svg>
      </button>
    </div>
  </div>
</div>

<style>
  [role="dialog"] {
    animation: slideIn 0.2s ease-out;
  }

  @keyframes slideIn {
    from {
      opacity: 0;
      transform: scale(0.95) translateY(10px);
    }
    to {
      opacity: 1;
      transform: scale(1) translateY(0);
    }
  }

  nav {
    scrollbar-width: thin;
    scrollbar-color: var(--border-color) transparent;
  }

  .overflow-y-auto {
    scrollbar-width: thin;
    scrollbar-color: var(--border-color) transparent;
  }
</style>
