<script lang="ts">
  import { createEventDispatcher, onMount } from 'svelte';

  export let isGenerating = false;
  export let isTauriAvailable = false;
  export let getGpuInfo: (() => Promise<any>) | null = null;
  export let unloadModels: (() => Promise<any>) | null = null;
  export let listVariables: (() => Promise<any>) | null = null;

  const dispatch = createEventDispatcher();

  let input = '';
  type HistoryItem =
  | { type: 'input' | 'output' | 'error' | 'info' | 'success' | 'dim' | 'cyan' | 'magenta' | 'progress-msg'; text: string }
  | { type: 'table'; rows: Array<{ cmd: string; desc: string }> }
  | { type: 'varsTable'; rows: Array<{ id: string; count: number; sample: string }> }
  | { type: 'header'; text: string }
  | { type: 'divider' }
  | { type: 'progress-bar'; percent: number; stage: string }
  | { type: 'prompt-highlight'; variant: 'enhanced' | 'final'; text: string };

  let history: HistoryItem[] = [];
  let suggestions: string[] = [];
  let showSuggestions = false;
  let selectedSuggestion = -1;
  let inputEl: HTMLInputElement;
  let historyEl: HTMLDivElement;

  // Progress state
  let currentProgress = 0;
  let currentStage = '';
  let progressBarIndex = -1;  // Track where our progress bar is in history

  // State
  let currentSeed: number | null = null;
  let currentSize = { width: 1024, height: 1024 };

  // Dynamic prompt variables (loaded from backend)
  let promptVars: string[] = [];

  // Version - will be updated from backend health check
  let VERSION = '0.4.1';
  const commands = ['/help', '/vars', '/enhance', '/seed', '/size', '/gpu', '/unload', '/version', '/changelog', '/quit', '/q'];
  
  // Function to fetch version from backend
  export async function fetchVersion(apiBase: string) {
    try {
      const res = await fetch(`${apiBase}/api/health`, { signal: AbortSignal.timeout(2000) });
      if (res.ok) {
        const data = await res.json();
        if (data.version) {
          VERSION = data.version;
          // Update the header in history if it exists
          history = history.map(item => {
            if (item.type === 'header' && item.text.includes('Z-Explorer v')) {
              return { ...item, text: `⚡ Z-Explorer v${VERSION}` };
            }
            return item;
          });
        }
      }
    } catch (e) {
      // Ignore - keep default version
    }
  }

  async function loadVariables() {
    console.log('📚 [FakeCLI] Loading variables...');
    if (listVariables) {
      try {
        const result = await listVariables();
        console.log('📚 [FakeCLI] Variables result:', result);
        if (result?.success && result.variables) {
          promptVars = result.variables.map((v: any) => v.id);
          console.log('✅ [FakeCLI] Loaded variables for autocomplete:', promptVars);
        } else {
          console.warn('⚠️ [FakeCLI] No variables returned');
        }
      } catch (e) {
        console.error('❌ [FakeCLI] Could not load variables:', e);
      }
    } else {
      console.warn('⚠️ [FakeCLI] listVariables prop not provided');
    }
  }

  onMount(async () => {
    // Welcome message - styled GUI version
    history = [
      { type: 'dim', text: 'Initializing...' },
      { type: 'success', text: '✓ All dependencies available' },
      { type: 'divider' },
      // { type: 'table', rows: [
      //   { cmd: '/help', desc: 'Show this help' },
      //   { cmd: '/vars', desc: 'List available prompt variables' },
      //   { cmd: '/enhance <prompt>', desc: 'Enhance a prompt without generating' },
      //   { cmd: '/seed <number>', desc: 'Set seed for next generation' },
      //   { cmd: '/size <WxH>', desc: 'Set output size (e.g., 1024x1024)' },
      //   { cmd: '/gpu', desc: 'Show GPU memory status' },
      //   { cmd: '/unload', desc: 'Unload models to free GPU memory' },
      //   { cmd: '/quit or /q', desc: 'Exit' },
      // ]},
      //{ type: 'divider' },
      { type: 'cyan', text: '💡 Tips:' },
      { type: 'dim', text: '• Use __variable__ syntax for random substitution (e.g., __animal__)' },
      { type: 'dim', text: '• Missing variables are auto-generated by the local LLM' },
      { type: 'dim', text: '• Add \'>\' to enhance prompt (e.g., \'a cat > make it magical\')' },
      { type: 'dim', text: '• Add batch params with \':\' (e.g., \'prompt : x10,h832,w1216\')' },
    ];

    // Load variables dynamically
    await loadVariables();

    // Focus input
    inputEl?.focus();
  });

  function updateSuggestions() {
    const cursorPos = inputEl?.selectionStart || 0;
    const textBeforeCursor = input.slice(0, cursorPos);

    // Command suggestions
    if (textBeforeCursor.includes('/')) {
      const lastSlash = textBeforeCursor.lastIndexOf('/');
      const partial = textBeforeCursor.slice(lastSlash);
      suggestions = commands.filter(cmd => cmd.startsWith(partial) && cmd !== partial);
      showSuggestions = suggestions.length > 0;
      console.log(`🔍 [Autocomplete] Command suggestions for "${partial}":`, suggestions);
      return;
    }

    // Variable suggestions
    if (textBeforeCursor.includes('__')) {
      const lastVar = textBeforeCursor.lastIndexOf('__');
      const afterVar = textBeforeCursor.slice(lastVar);
      console.log(`🔍 [Autocomplete] Looking for variables matching "${afterVar}"`);
      console.log(`🔍 [Autocomplete] Available promptVars:`, promptVars);
      if ((afterVar.match(/__/g) || []).length === 1) {
        suggestions = promptVars.filter(v => v.startsWith(afterVar) && v !== afterVar);
        showSuggestions = suggestions.length > 0;
        console.log(`🔍 [Autocomplete] Variable suggestions:`, suggestions);
        return;
      }
    }

    showSuggestions = false;
    suggestions = [];
  }

  function applySuggestion(suggestion: string) {
    const cursorPos = inputEl?.selectionStart || 0;
    const textBeforeCursor = input.slice(0, cursorPos);

    if (textBeforeCursor.includes('/')) {
      const lastSlash = textBeforeCursor.lastIndexOf('/');
      input = input.slice(0, lastSlash) + suggestion + input.slice(cursorPos);
    } else if (textBeforeCursor.includes('__')) {
      const lastVar = textBeforeCursor.lastIndexOf('__');
      const afterVar = textBeforeCursor.slice(lastVar);
      input = input.slice(0, lastVar) + suggestion + input.slice(cursorPos);
    }

    showSuggestions = false;
    selectedSuggestion = -1;
    inputEl?.focus();
  }

  function handleKeydown(e: KeyboardEvent) {
    if (showSuggestions) {
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        selectedSuggestion = Math.min(selectedSuggestion + 1, suggestions.length - 1);
        return;
      }
      if (e.key === 'ArrowUp') {
        e.preventDefault();
        selectedSuggestion = Math.max(selectedSuggestion - 1, -1);
        return;
      }
      if (e.key === 'Tab' || e.key === 'Enter') {
        if (selectedSuggestion >= 0) {
          e.preventDefault();
          applySuggestion(suggestions[selectedSuggestion]);
          return;
        }
      }
      if (e.key === 'Escape') {
        showSuggestions = false;
        return;
      }
    }

    if (e.key === 'Enter' && !showSuggestions) {
      submit();
    }
  }

  function parseParams(input: string): { prompt: string; params: any } {
    const params = { count: 1, width: 1024, height: 1024 };

    if (!input.includes(':')) {
      return { prompt: input, params };
    }

    const parts = input.split(':');
    const paramPart = parts[parts.length - 1].trim();

    // Check if it looks like parameters
    if (!/[xhw]\d/.test(paramPart)) {
      return { prompt: input, params };
    }

    const prompt = parts.slice(0, -1).join(':').trim();

    for (const param of paramPart.split(',')) {
      const p = param.trim().toLowerCase();
      if (p.startsWith('x')) params.count = parseInt(p.slice(1)) || 1;
      if (p.startsWith('h')) params.height = parseInt(p.slice(1)) || 1024;
      if (p.startsWith('w')) params.width = parseInt(p.slice(1)) || 1024;
    }

    return { prompt, params };
  }

  function submit() {
    if (!input.trim() || isGenerating) return;

    const trimmed = input.trim();

    // Handle commands
    if (trimmed.startsWith('/')) {
      handleCommand(trimmed);
      input = '';
      return;
    }

    // Parse prompt and parameters
    const { prompt, params } = parseParams(trimmed);

    history = [...history, { type: 'input', text: `>>> ${trimmed}` }];

    if (params.count > 1 || params.width !== 1024 || params.height !== 1024) {
      history = [...history, {
        type: 'info',
        text: `📐 Batch: ${params.count} image(s) @ ${params.width}×${params.height}`
      }];
    }

    // Dispatch to parent - progress messages will come from backend events
    dispatch('generate', { prompt, params, seed: currentSeed });

    // Reset seed after use (like pyros-local)
    currentSeed = null;

    // Keep prompt for iteration
    scrollToBottom();
  }

  function handleCommand(cmd: string) {
    history = [...history, { type: 'input', text: `>>> ${cmd}` }];

    const [command, ...args] = cmd.split(' ');

    switch (command) {
      case '/help':
        history = [...history,
          { type: 'header', text: '📖 Commands' },
          { type: 'table', rows: [
            { cmd: '/help', desc: 'Show this help' },
            { cmd: '/vars', desc: 'List available prompt variables' },
            { cmd: '/enhance <prompt>', desc: 'Enhance a prompt without generating' },
            { cmd: '/seed <number>', desc: 'Set seed for next generation' },
            { cmd: '/size <WxH>', desc: 'Set output size (e.g., 1024x1024)' },
            { cmd: '/gpu', desc: 'Show GPU memory status' },
            { cmd: '/unload', desc: 'Unload models to free GPU memory' },
            { cmd: '/version', desc: 'Show version information' },
            { cmd: '/changelog', desc: 'Show recent changes' },
            { cmd: '/quit or /q', desc: 'Exit' },
          ]},
          { type: 'divider' },
          { type: 'cyan', text: '💡 Tips:' },
          { type: 'dim', text: '• Use __variable__ syntax for random substitution (e.g., __animal__)' },
          { type: 'dim', text: '• Missing variables are auto-generated by the local LLM' },
          { type: 'dim', text: '• Add \'>\' to enhance prompt (e.g., \'a cat > make it magical\')' },
          { type: 'dim', text: '• Add batch params with \':\' (e.g., \'prompt : x10,h832,w1216\')' },
          { type: 'dim', text: '  x<N>=count, h<N>=height, w<N>=width (all optional)' },
        ];
        break;
      case '/vars':
        if (listVariables) {
          history = [...history, { type: 'cyan', text: '📋 Loading variables...' }];
          scrollToBottom();

          listVariables().then((result: any) => {
            if (result?.success && result.variables) {
              const varRows = result.variables.map((v: any) => ({
                id: v.id,
                count: v.count,
                sample: v.sample?.slice(0, 3).join(', ') || ''
              }));
              history = [...history,
                { type: 'header', text: `📋 ${result.count} Variables Available` },
                { type: 'varsTable', rows: varRows },
              ];
              // Update autocomplete
              promptVars = result.variables.map((v: any) => v.id);
            } else {
              history = [...history, { type: 'error', text: '❌ Failed to load variables' }];
            }
            scrollToBottom();
          });
        } else {
          history = [...history,
            { type: 'header', text: '📋 Available Variables' },
            { type: 'divider' },
            ...promptVars.map(v => ({ type: 'magenta' as const, text: `  ${v}` }))
          ];
        }
        break;
      case '/enhance':
        if (args.length > 0) {
          history = [...history,
            { type: 'cyan', text: '🤖 Enhancing prompt with local LLM...' },
            { type: 'dim', text: '(Enhancement will be applied during generation)' },
          ];
        } else {
          history = [...history,
            { type: 'error', text: '❌ Usage: /enhance <prompt>' },
          ];
        }
        break;
      case '/seed':
        if (args.length > 0) {
          const seedVal = parseInt(args[0]);
          if (!isNaN(seedVal) && seedVal >= 0) {
            currentSeed = seedVal;
            history = [...history,
              { type: 'success', text: `✓ Seed set to: ${seedVal}` },
              { type: 'dim', text: '(Will be used for next generation, then reset)' },
            ];
          } else {
            history = [...history,
              { type: 'error', text: '❌ Invalid seed (must be a positive number)' },
            ];
          }
        } else {
          currentSeed = null;
          history = [...history,
            { type: 'cyan', text: '🎲 Seed reset to random' },
          ];
        }
        break;
      case '/size':
        if (args.length > 0) {
          const sizeMatch = args[0].toLowerCase().match(/(\d+)x(\d+)/);
          if (sizeMatch) {
            history = [...history,
              { type: 'success', text: `✓ Size set to: ${sizeMatch[1]}×${sizeMatch[2]}` },
            ];
          } else {
            history = [...history,
              { type: 'error', text: '❌ Invalid size format. Use: /size 1024x1024' },
            ];
          }
        } else {
          history = [...history,
            { type: 'cyan', text: '📐 Current size: 1024×1024' },
          ];
        }
        break;
      case '/gpu':
        if (getGpuInfo) {
          history = [...history, { type: 'cyan', text: '🖥️ Fetching GPU info...' }];
          scrollToBottom();

          getGpuInfo().then((info: any) => {
            if (info?.available) {
              history = [...history,
                { type: 'header', text: '🖥️ GPU Memory Status' },
                { type: 'success', text: `Device: ${info.device_name}` },
                { type: 'info', text: `Allocated: ${info.allocated_gb} GB` },
                { type: 'info', text: `Reserved: ${info.reserved_gb} GB` },
                { type: 'info', text: `Total: ${info.total_gb} GB` },
                { type: 'cyan', text: `Free: ${info.free_gb} GB` },
              ];
            } else {
              history = [...history,
                { type: 'error', text: `❌ ${info?.error || 'GPU not available'}` },
              ];
            }
            scrollToBottom();
          });
        } else {
          history = [...history,
            { type: 'dim', text: '(GPU info not available in demo mode)' },
          ];
        }
        break;
      case '/unload':
        if (unloadModels) {
          history = [...history, { type: 'cyan', text: '🔄 Unloading models...' }];
          scrollToBottom();

          unloadModels().then((result: any) => {
            if (result?.success) {
              const unloaded = [];
              if (result.llm_unloaded) unloaded.push('LLM (Qwen3-4B)');
              if (result.image_model_unloaded) unloaded.push('Image model (Z-Image-Turbo)');
              if (result.cuda_cache_cleared) unloaded.push('CUDA cache');

              if (unloaded.length > 0) {
                history = [...history,
                  { type: 'success', text: '✓ Models unloaded successfully' },
                  { type: 'dim', text: `Unloaded: ${unloaded.join(', ')}` },
                  { type: 'dim', text: '(Models will reload on next generation)' },
                ];
              } else {
                history = [...history,
                  { type: 'info', text: 'ℹ️ No models were loaded' },
                ];
              }
            } else {
              history = [...history,
                { type: 'error', text: '❌ Failed to unload models' },
              ];
            }
            scrollToBottom();
          });
        } else {
          history = [...history,
            { type: 'dim', text: '(Unload not available in demo mode)' },
          ];
        }
        break;
      case '/version':
        history = [...history,
          { type: 'header', text: `⚡ Z-Explorer v${VERSION}` },
          { type: 'dim', text: 'AI Image Generation Without the UI Tax' },
          { type: 'info', text: 'Z-Image-Turbo + Qwen3-4B' },
          { type: 'divider' },
          { type: 'dim', text: 'GitHub: github.com/pyros-projects/z-Explorer' },
        ];
        break;
      case '/changelog':
        history = [...history,
          { type: 'header', text: '📋 Changelog' },
          { type: 'cyan', text: `v${VERSION} - Desktop GUI Integration` },
          { type: 'divider' },
          { type: 'success', text: '✨ Added:' },
          { type: 'dim', text: '• Native desktop app via Tauri with bundled uv binary' },
          { type: 'dim', text: '• Three modes: GUI (default), CLI (--cli), Server (--server)' },
          { type: 'dim', text: '• Progress streaming via Server-Sent Events (SSE)' },
          { type: 'dim', text: '• Masonry gallery layout for generated images' },
          { type: 'dim', text: '• Prompt saved alongside images as .txt files' },
          { type: 'dim', text: '• Variable autocomplete in CLI-style input' },
          { type: 'dim', text: '• /changelog and /version commands' },
          { type: 'divider' },
          { type: 'info', text: '🔄 Changed:' },
          { type: 'dim', text: '• Default mode is now GUI (previously CLI-only)' },
          { type: 'dim', text: '• Server port standardized to 8345' },
          { type: 'divider' },
          { type: 'dim', text: 'Full changelog: github.com/pyros-projects/z-Explorer/blob/main/CHANGELOG.md' },
        ];
        break;
      case '/quit':
      case '/q':
        history = [...history,
          { type: 'cyan', text: '👋 Goodbye! (Close the window to exit)' },
        ];
        break;
      default:
        history = [...history,
          { type: 'error', text: `❌ Unknown command: ${command}` },
          { type: 'dim', text: 'Type /help for available commands' },
        ];
    }

    scrollToBottom();
  }

  function scrollToBottom() {
    setTimeout(() => {
      if (historyEl) {
        historyEl.scrollTop = historyEl.scrollHeight;
      }
    }, 10);
  }

  // Add generated result to history
  export function addResult(text: string, isError = false) {
    history = [...history, { type: isError ? 'error' : 'output', text }];
    scrollToBottom();
  }

  // Stage icons for progress messages
  const stageIcons: Record<string, string> = {
    'starting': '🚀',
    'loading_vars': '📋',
    'substituting': '🔄',
    'var_missing': '⚠️',
    'var_generating': '🤖',
    'var_saved': '💾',
    'enhancing': '✨',
    'enhanced': '💡',
    'phase1_complete': '📝',
    'final_prompt': '📜',
    'llm_unloaded': '🧹',
    'loading_image_model': '🎨',
    'generating_image': '🖼️',
    'diffusion_step': '⚡',
    'generating_steps': '⚡',
    'image_saved': '💾',
    'complete': '✅',
    'error': '❌',
  };
  
  // Stages that shouldn't spam the log (just update progress bar)
  const silentStages = new Set(['diffusion_step', 'generating_steps']);

  // Start a new generation session - adds initial progress bar
  export function startGeneration() {
    console.log('🎬 [FakeCLI] startGeneration() called');
    currentProgress = 0;
    currentStage = 'starting';
    progressBarIndex = history.length;
    history = [...history, { type: 'progress-bar', percent: 0, stage: 'starting' }];
    console.log('📊 [FakeCLI] Progress bar added at index:', progressBarIndex);
    scrollToBottom();
  }

  // Update progress during generation - updates bar AND adds message
  export function updateProgress(percent: number, stage: string, message: string) {
    console.log(`📈 [FakeCLI] updateProgress(${percent}%, ${stage}, "${message}")`);
    currentProgress = percent;
    currentStage = stage;
    
    // Update the progress bar in place
    if (progressBarIndex >= 0 && progressBarIndex < history.length) {
      history[progressBarIndex] = { type: 'progress-bar', percent, stage };
      history = [...history]; // Trigger Svelte reactivity
      console.log(`📊 [FakeCLI] Progress bar updated: ${percent}% - ${stage}`);
    } else {
      console.warn('⚠️ [FakeCLI] Progress bar index invalid:', progressBarIndex);
    }
    
    // Add the message below the progress bar (if meaningful and not a silent stage)
    // Silent stages (like diffusion_step) only update the bar, don't spam the log
    if (message && !silentStages.has(stage)) {
      const icon = stageIcons[stage] || '⚡';
      
      // Special handling for prompts - highlight them!
      if (stage === 'enhanced') {
        history = [...history, { type: 'prompt-highlight', variant: 'enhanced', text: message }];
        console.log(`💡 [FakeCLI] Added enhanced prompt: ${message.substring(0, 50)}...`);
      } else if (stage === 'final_prompt') {
        history = [...history, { type: 'prompt-highlight', variant: 'final', text: message }];
        console.log(`📜 [FakeCLI] Added final prompt: ${message.substring(0, 50)}...`);
      } else {
        history = [...history, { type: 'progress-msg', text: `${icon} ${message}` }];
        console.log(`💬 [FakeCLI] Added progress message: ${icon} ${message}`);
      }
    } else if (silentStages.has(stage)) {
      console.log(`🔇 [FakeCLI] Silent stage, only updating bar: ${stage}`);
    }
    
    scrollToBottom();
  }

  // Finalize progress bar - marks it as complete and keeps it in history
  export function completeGeneration(success: boolean) {
    console.log(`🏁 [FakeCLI] completeGeneration(success=${success})`);
    // Update progress bar to final state
    if (progressBarIndex >= 0 && progressBarIndex < history.length) {
      history[progressBarIndex] = { 
        type: 'progress-bar', 
        percent: 100, 
        stage: success ? 'complete' : 'error' 
      };
      history = [...history];
      console.log('✅ [FakeCLI] Progress bar set to complete');
    }
    
    // Reset tracking but keep the bar in history
    progressBarIndex = -1;
    currentProgress = 0;
    currentStage = '';
    scrollToBottom();
  }

  // Legacy function for backwards compatibility
  export function clearProgress() {
    completeGeneration(true);
  }
</script>

<div class="cli">
  <div class="history" bind:this={historyEl}>
    {#each history as line}
      {#if line.type === 'table'}
        <div class="cmd-table">
          {#each line.rows as row}
            <div class="cmd-row">
              <span class="cmd-name">{row.cmd}</span>
              <span class="cmd-desc">{row.desc}</span>
            </div>
          {/each}
        </div>
      {:else if line.type === 'varsTable'}
        <div class="vars-table">
          {#each line.rows as row}
            <div class="var-row">
              <span class="var-id">{row.id}</span>
              <span class="var-count">({row.count})</span>
              <span class="var-sample">{row.sample}</span>
            </div>
          {/each}
        </div>
      {:else if line.type === 'header'}
        <div class="line header">{line.text}</div>
      {:else if line.type === 'divider'}
        <div class="divider"></div>
      {:else if line.type === 'progress-bar'}
        <div class="progress-container">
          <div class="progress-header">
            <span class="progress-stage">{line.stage.replace(/_/g, ' ')}</span>
            <span class="progress-percent">{line.percent}%</span>
          </div>
          <div class="progress-track">
            <div class="progress-fill" style="width: {line.percent}%">
              <div class="progress-glow"></div>
            </div>
          </div>
        </div>
      {:else if line.type === 'progress-msg'}
        <div class="line progress-msg">{line.text}</div>
      {:else if line.type === 'prompt-highlight'}
        <div class="prompt-highlight {line.variant}">
          <span class="prompt-label">
            {#if line.variant === 'enhanced'}
              💡 Enhanced Prompt
            {:else}
              📜 Final Prompt
            {/if}
          </span>
          <div class="prompt-text">{line.text}</div>
        </div>
      {:else}
        <div class="line {line.type}">{line.text}</div>
      {/if}
    {/each}
  </div>

  <div class="input-area">
    <div class="input-line">
      <span class="prompt-symbol">❯❯❯</span>
      <input
        bind:this={inputEl}
        bind:value={input}
        on:input={updateSuggestions}
        on:keydown={handleKeydown}
        placeholder={isGenerating ? 'Generating...' : 'Enter prompt or /help'}
        disabled={isGenerating}
        spellcheck="false"
        autocomplete="off"
      />
    </div>

    {#if showSuggestions}
      <div class="suggestions">
        {#each suggestions as suggestion, i}
          <button
            class="suggestion"
            class:selected={i === selectedSuggestion}
            on:click={() => applySuggestion(suggestion)}
          >
            {suggestion}
          </button>
        {/each}
      </div>
    {/if}
  </div>
</div>

<style>
  .cli {
    height: 100%;
    display: flex;
    flex-direction: column;
    font-family: var(--font-mono);
    font-size: 13px;
  }

  .history {
    flex: 1;
    overflow-y: auto;
    padding: 12px 16px;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .line {
    white-space: pre-wrap;
    word-break: break-word;
    line-height: 1.5;
  }

  .line.input {
    color: var(--accent-secondary);
  }

  .line.output {
    color: var(--success);
  }

  .line.error {
    color: var(--error);
  }

  .line.info {
    color: var(--text-secondary);
  }

  .line.success {
    color: #4ade80;
    font-weight: 500;
  }

  .line.dim {
    color: var(--text-muted);
    font-size: 12px;
  }

  .line.cyan {
    color: #22d3ee;
    font-weight: 600;
  }

  .line.magenta {
    color: #e879f9;
  }

  .line.header {
    color: #f97316;
    font-size: 16px;
    font-weight: 700;
    padding: 8px 0 4px 0;
  }

  .divider {
    height: 1px;
    background: linear-gradient(90deg, var(--border-color), transparent);
    margin: 8px 0;
  }

  .cmd-table {
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    overflow: hidden;
    margin: 8px 0;
  }

  .cmd-row {
    display: flex;
    padding: 6px 12px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    transition: background 0.15s;
  }

  .cmd-row:last-child {
    border-bottom: none;
  }

  .cmd-row:hover {
    background: rgba(255, 255, 255, 0.03);
  }

  .cmd-name {
    color: #a78bfa;
    font-weight: 600;
    min-width: 160px;
    flex-shrink: 0;
  }

  .cmd-desc {
    color: var(--text-secondary);
  }

  .vars-table {
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    overflow: hidden;
    margin: 8px 0;
    max-height: 300px;
    overflow-y: auto;
  }

  .var-row {
    display: flex;
    padding: 4px 12px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    gap: 12px;
    align-items: baseline;
  }

  .var-row:last-child {
    border-bottom: none;
  }

  .var-row:hover {
    background: rgba(255, 255, 255, 0.03);
  }

  .var-id {
    color: #e879f9;
    font-weight: 600;
    min-width: 200px;
    flex-shrink: 0;
  }

  .var-count {
    color: var(--text-muted);
    font-size: 11px;
    min-width: 40px;
  }

  .var-sample {
    color: var(--text-secondary);
    font-size: 12px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .input-area {
    position: relative;
    border-top: 1px solid var(--border-color);
    background: var(--bg-tertiary);
  }

  .input-line {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
  }

  .prompt-symbol {
    color: var(--accent-primary);
    font-weight: 600;
    font-size: 14px;
  }

  input {
    flex: 1;
    background: none;
    border: none;
    outline: none;
    color: var(--text-primary);
    font-family: inherit;
    font-size: inherit;
    caret-color: var(--accent-primary);
  }

  input::placeholder {
    color: var(--text-muted);
  }

  input:disabled {
    opacity: 0.5;
  }

  .suggestions {
    position: absolute;
    bottom: 100%;
    left: 16px;
    right: 16px;
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    max-height: 200px;
    overflow-y: auto;
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.3);
  }

  .suggestion {
    display: block;
    width: 100%;
    padding: 8px 12px;
    text-align: left;
    background: none;
    border: none;
    color: var(--text-secondary);
    font-family: var(--font-mono);
    font-size: 12px;
    cursor: pointer;
    transition: all 0.1s;
  }

  .suggestion:hover,
  .suggestion.selected {
    background: var(--accent-glow);
    color: var(--text-primary);
  }

  /* Progress Bar Styles */
  .progress-container {
    margin: 12px 0;
    padding: 12px 16px;
    background: linear-gradient(135deg, rgba(124, 58, 237, 0.1), rgba(168, 85, 247, 0.05));
    border: 1px solid rgba(124, 58, 237, 0.3);
    border-radius: 8px;
  }

  .progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .progress-stage {
    color: #a78bfa;
    font-weight: 600;
    font-size: 12px;
    text-transform: capitalize;
  }

  .progress-percent {
    color: #22d3ee;
    font-weight: 700;
    font-size: 14px;
    font-variant-numeric: tabular-nums;
  }

  .progress-track {
    height: 8px;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 4px;
    overflow: hidden;
    position: relative;
  }

  .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #7c3aed, #a855f7, #c084fc);
    border-radius: 4px;
    transition: width 0.3s ease-out;
    position: relative;
    overflow: hidden;
  }

  .progress-glow {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      90deg,
      transparent,
      rgba(255, 255, 255, 0.4),
      transparent
    );
    animation: shimmer 1.5s infinite;
  }

  @keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
  }

  .line.progress-msg {
    color: #94a3b8;
    font-size: 11px;
    padding-left: 8px;
    border-left: 2px solid rgba(124, 58, 237, 0.3);
    margin-left: 4px;
    animation: fadeSlideIn 0.2s ease-out;
  }

  /* Highlighted prompt styles - these should POP! */
  .prompt-highlight {
    margin: 8px 0;
    padding: 12px;
    border-radius: 8px;
    animation: promptPop 0.3s ease-out;
    font-family: 'JetBrains Mono', 'Fira Code', monospace;
  }

  .prompt-highlight.enhanced {
    background: linear-gradient(135deg, rgba(251, 191, 36, 0.15) 0%, rgba(245, 158, 11, 0.1) 100%);
    border: 1px solid rgba(251, 191, 36, 0.4);
    box-shadow: 0 0 20px rgba(251, 191, 36, 0.1), inset 0 1px 0 rgba(251, 191, 36, 0.2);
  }

  .prompt-highlight.final {
    background: linear-gradient(135deg, rgba(34, 197, 94, 0.15) 0%, rgba(16, 185, 129, 0.1) 100%);
    border: 1px solid rgba(34, 197, 94, 0.4);
    box-shadow: 0 0 20px rgba(34, 197, 94, 0.1), inset 0 1px 0 rgba(34, 197, 94, 0.2);
  }

  .prompt-label {
    display: block;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 1px;
    margin-bottom: 6px;
  }

  .prompt-highlight.enhanced .prompt-label {
    color: #fbbf24;
  }

  .prompt-highlight.final .prompt-label {
    color: #22c55e;
  }

  .prompt-text {
    color: #f8fafc;
    font-size: 13px;
    line-height: 1.6;
    word-wrap: break-word;
    white-space: pre-wrap;
  }

  @keyframes promptPop {
    0% {
      opacity: 0;
      transform: translateY(-10px) scale(0.98);
    }
    50% {
      transform: translateY(2px) scale(1.01);
    }
    100% {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }

  @keyframes fadeSlideIn {
    from {
      opacity: 0;
      transform: translateX(-10px);
    }
    to {
      opacity: 1;
      transform: translateX(0);
    }
  }
</style>



