<script lang="ts">
  import { onMount } from "svelte";
  import { get } from "svelte/store";
  import {
    projectContextStore,
    PROJECT_FILE_NAMES,
    type ProjectFile,
  } from "$lib/stores/projectContext";
  import { characterState } from "$lib/stores/character";
  import { claudeStore } from "$lib/stores/claude";

  interface Props {
    onClose: () => void;
    onInject: (content: string) => void;
    workingDirectory: string;
  }

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

  const ALL_FILES: ProjectFile[] = ["PROJECT", "REQUIREMENTS", "ROADMAP", "STATE", "CODEBASE"];

  const contents = $derived(projectContextStore.contents);
  const isLoading = $derived(projectContextStore.isLoading);
  const isSaving = $derived(projectContextStore.isSaving);
  const activeFile = $derived(projectContextStore.activeFile);
  const isMappingCodebase = $derived(projectContextStore.isMappingCodebase);

  let editContent = $state("");
  let hasUnsavedChanges = $state(false);
  let previousCharacterState = $state<string>("idle");

  onMount(() => {
    projectContextStore.loadAll(workingDirectory);
  });

  $effect(() => {
    const file = $activeFile;
    const fileContent = $contents[file];
    if (file === "CODEBASE") {
      editContent = fileContent ?? "";
    } else {
      editContent = fileContent ?? projectContextStore.getTemplate(file);
    }
    hasUnsavedChanges = false;
  });

  // Auto-reload CODEBASE.md when Claude finishes generating it
  $effect(() => {
    const currentState = $characterState;
    if ($isMappingCodebase && previousCharacterState !== "idle" && currentState === "idle") {
      projectContextStore.loadFile("CODEBASE", workingDirectory);
      projectContextStore.finishMapping();
    }
    previousCharacterState = currentState;
  });

  function handleTabSwitch(file: ProjectFile): void {
    projectContextStore.setActiveFile(file);
  }

  function handleUseTemplate(): void {
    editContent = projectContextStore.getTemplate($activeFile);
    hasUnsavedChanges = true;
  }

  function handleInject(): void {
    onInject(editContent);
  }

  async function handleSave(): Promise<void> {
    const saved = await projectContextStore.saveFile($activeFile, editContent, workingDirectory);
    if (saved) {
      hasUnsavedChanges = false;
    }
  }

  function handleTextChange(event: Event): void {
    editContent = (event.target as HTMLTextAreaElement).value;
    hasUnsavedChanges = true;
  }

  function fileExists(file: ProjectFile): boolean {
    return $contents[file] !== null;
  }

  async function handleMapCodebase(): Promise<void> {
    const conversationId = get(claudeStore.activeConversationId);
    if (!conversationId) return;
    await projectContextStore.mapCodebase(workingDirectory, conversationId);
  }
</script>

<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()}
>
  <div
    class="bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] flex flex-col"
    onclick={(e) => e.stopPropagation()}
    onkeydown={(e) => e.stopPropagation()}
    role="dialog"
    aria-labelledby="project-context-title"
    tabindex="-1"
  >
    <!-- Header -->
    <div class="flex items-center justify-between p-6 pb-4 border-b border-[var(--border-color)]">
      <div class="flex items-center gap-3">
        <h2 id="project-context-title" class="text-xl font-semibold text-[var(--text-primary)]">
          Project Context
        </h2>
        {#if $activeFile === "CODEBASE"}
          {#if $isMappingCodebase}
            <span class="text-xs text-[var(--text-tertiary)]">Mapping codebase...</span>
          {:else if $isLoading[$activeFile]}
            <span class="text-xs text-[var(--text-tertiary)]">Loading...</span>
          {:else if fileExists($activeFile)}
            <span
              class="text-xs px-2 py-0.5 rounded-full bg-green-500/20 text-green-400 border border-green-500/30"
            >
              ✓ File exists
            </span>
          {:else}
            <span
              class="text-xs px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 border border-amber-500/30"
            >
              ✗ Not generated
            </span>
          {/if}
        {:else if $isLoading[$activeFile]}
          <span class="text-xs text-[var(--text-tertiary)]">Loading...</span>
        {:else if fileExists($activeFile)}
          <span
            class="text-xs px-2 py-0.5 rounded-full bg-green-500/20 text-green-400 border border-green-500/30"
          >
            ✓ File exists
          </span>
        {:else}
          <span
            class="text-xs px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 border border-amber-500/30"
          >
            ✗ Not created
          </span>
        {/if}
        {#if hasUnsavedChanges}
          <span class="text-xs text-[var(--text-tertiary)] italic">Unsaved changes</span>
        {/if}
      </div>
      <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>

    <!-- Tab bar -->
    <div class="flex border-b border-[var(--border-color)] px-4">
      {#each ALL_FILES as file (file)}
        <button
          onclick={() => handleTabSwitch(file)}
          class="px-4 py-2 text-sm font-medium transition-colors relative {$activeFile === file
            ? 'text-[var(--accent-primary)] border-b-2 border-[var(--accent-primary)] -mb-px'
            : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)]'}"
        >
          {PROJECT_FILE_NAMES[file]}
          {#if !fileExists(file)}
            <span class="ml-1 text-amber-500">•</span>
          {/if}
        </button>
      {/each}
    </div>

    <!-- Editor area -->
    <div class="flex-1 overflow-hidden p-4 min-h-0">
      {#if $activeFile === "CODEBASE" && !fileExists("CODEBASE") && !$isMappingCodebase}
        <!-- CODEBASE not generated yet — show prompt to map -->
        <div class="flex flex-col items-center justify-center h-full gap-4 text-center">
          <div class="text-4xl">🗺️</div>
          <h3 class="text-lg font-semibold text-[var(--text-primary)]">No Codebase Map Yet</h3>
          <p class="text-sm text-[var(--text-secondary)] max-w-md">
            Generate a <span class="font-mono text-xs">CODEBASE.md</span> file by asking Claude to analyse
            this project. Claude will scan the directory structure and create a comprehensive overview
            of the architecture and key components.
          </p>
          <button
            onclick={handleMapCodebase}
            class="px-5 py-2 text-sm btn-trans-gradient rounded-lg transition-colors"
          >
            Map Codebase
          </button>
        </div>
      {:else if $activeFile === "CODEBASE" && $isMappingCodebase}
        <!-- Mapping in progress -->
        <div class="flex flex-col items-center justify-center h-full gap-4 text-center">
          <div class="text-4xl animate-spin">⚙️</div>
          <h3 class="text-lg font-semibold text-[var(--text-primary)]">Mapping Codebase...</h3>
          <p class="text-sm text-[var(--text-secondary)]">
            Claude is analysing the project and writing <span class="font-mono text-xs"
              >CODEBASE.md</span
            >. This will auto-reload when complete.
          </p>
        </div>
      {:else}
        <textarea
          value={editContent}
          oninput={handleTextChange}
          readonly={$activeFile === "CODEBASE"}
          class="w-full h-full min-h-[400px] bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-4 font-mono text-sm text-[var(--text-primary)] resize-none focus:outline-none focus:border-[var(--accent-primary)] leading-relaxed {$activeFile ===
          'CODEBASE'
            ? 'opacity-80 cursor-default'
            : ''}"
          placeholder="File content will appear here..."
          spellcheck="false"
        ></textarea>
      {/if}
    </div>

    <!-- Footer -->
    <div
      class="flex items-center justify-between p-4 pt-2 border-t border-[var(--border-color)] gap-3"
    >
      <div class="text-xs text-[var(--text-tertiary)]">
        <span class="font-mono">{workingDirectory}/{PROJECT_FILE_NAMES[$activeFile]}</span>
      </div>
      <div class="flex items-center gap-2">
        {#if $activeFile === "CODEBASE"}
          <button
            onclick={() => projectContextStore.loadFile("CODEBASE", workingDirectory)}
            disabled={$isLoading.CODEBASE || $isMappingCodebase}
            class="px-3 py-1.5 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Refresh
          </button>
          <button
            onclick={handleMapCodebase}
            disabled={$isMappingCodebase}
            class="px-4 py-1.5 text-sm btn-trans-gradient rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {#if $isMappingCodebase}
              Mapping...
            {:else}
              {fileExists("CODEBASE") ? "Remap Codebase" : "Map Codebase"}
            {/if}
          </button>
        {:else}
          <button
            onclick={handleUseTemplate}
            class="px-3 py-1.5 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded-lg transition-colors"
          >
            Use Template
          </button>
          <button
            onclick={handleInject}
            class="px-3 py-1.5 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded-lg transition-colors"
          >
            Inject into Prompt
          </button>
          <button
            onclick={handleSave}
            disabled={$isSaving[$activeFile]}
            class="px-4 py-1.5 text-sm btn-trans-gradient rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {#if $isSaving[$activeFile]}
              Saving...
            {:else}
              Save
            {/if}
          </button>
        {/if}
      </div>
    </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);
    }
  }

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

  textarea::-webkit-scrollbar {
    width: 8px;
  }

  textarea::-webkit-scrollbar-track {
    background: transparent;
  }

  textarea::-webkit-scrollbar-thumb {
    background-color: var(--border-color);
    border-radius: 4px;
  }

  textarea::-webkit-scrollbar-thumb:hover {
    background-color: var(--accent-primary);
  }
</style>
