<!-- #region DictionaryDetailPage [C:3] [TYPE Page] [SEMANTICS sveltekit, translate, dictionary, editor, import] -->
<!-- @ingroup Routes -->
<!-- @BRIEF Dictionary detail page — renders DictionaryDetailModel state. -->
<!-- @LAYER Page -->
<!-- @RELATION BINDS_TO -> [DictionaryDetailModel] -->
<script lang="ts">
  import { page } from '$app/state';
  import { t } from '$lib/i18n/index.svelte.js';
  import { DictionaryDetailModel } from '$lib/models/DictionaryDetailModel.svelte';

  const m = new DictionaryDetailModel();

  $effect(() => {
    const id = page.params.id;
    if (id) { m.dictionaryId = id; m.loadDictionary(); }
  });

  function goBack() { window.history.back(); }
</script>

<div class="max-w-7xl mx-auto px-4 py-6">
  <button onclick={goBack} class="flex items-center gap-2 text-text-muted hover:text-text mb-4 text-sm">
    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 12H5M12 19l-7-7 7-7"/></svg>
    {$t.common?.back}
  </button>

  {#if m.isLoading}
    <div class="space-y-3">{#each Array(5) as _}<div class="h-8 bg-surface-muted rounded animate-pulse"></div>{/each}</div>
  {:else if m.dictionary}
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold text-text">{m.dictionary.name as string}</h1>
        <p class="text-sm text-text-muted mt-1">{m.dictionary.description as string || $t.translate?.dictionaries?.no_description}</p>
      </div>
      <div class="flex gap-2">
        <button class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover text-sm" onclick={() => { m.showAddForm = true; }}>+ {$t.translate?.dictionaries?.add_entry}</button>
        <button class="px-4 py-2 border border-border-strong rounded-lg hover:bg-surface-muted text-sm" onclick={() => { m.showImportForm = true; }}>{$t.translate?.dictionaries?.import_csv}</button>
      </div>
    </div>

    <!-- Add form -->
    {#if m.showAddForm}
      <div class="bg-surface-card border border-border rounded-lg p-4 mb-4">
        <h3 class="text-sm font-semibold mb-3">{$t.translate?.dictionaries?.new_entry}</h3>
        <div class="grid grid-cols-2 gap-3 mb-3">
          <input placeholder={$t.translate?.dictionaries?.source_term_placeholder || 'Source term'} bind:value={m.addForm.source_term} class="px-3 py-2 border border-border-strong rounded text-sm" />
          <input placeholder={$t.translate?.dictionaries?.target_term_placeholder || 'Target term'} bind:value={m.addForm.target_term} class="px-3 py-2 border border-border-strong rounded text-sm" />
          <select bind:value={m.addForm.source_language} class="px-3 py-2 border border-border-strong rounded text-sm">
            <option value="und">—</option>
            {#each m.languageOptions as opt}
              <option value={opt.code}>{opt.name} ({opt.code})</option>
            {/each}
          </select>
          <select bind:value={m.addForm.target_language} class="px-3 py-2 border border-border-strong rounded text-sm">
            <option value="und">—</option>
            {#each m.languageOptions as opt}
              <option value={opt.code}>{opt.name} ({opt.code})</option>
            {/each}
          </select>
        </div>
        <input placeholder={$t.translate?.dictionaries?.context_notes_placeholder || 'Context notes'} bind:value={m.addForm.context_notes} class="w-full px-3 py-2 border border-border-strong rounded text-sm mb-3" />
        <label class="flex items-center gap-2 text-sm mb-3">
          <input type="checkbox" bind:checked={m.addForm.is_regex} class="rounded border-border-strong" />
          <span>{$t.translate?.dictionaries?.regex_pattern || 'Regex pattern'}</span>
        </label>
        <div class="flex justify-end gap-2">
          <button class="px-3 py-1.5 border rounded hover:bg-surface-muted text-sm" onclick={() => { m.showAddForm = false; }}>{$t.common?.cancel}</button>
          <button class="px-3 py-1.5 bg-primary text-white rounded hover:bg-primary-hover text-sm" onclick={() => m.addEntry()} disabled={m.isAdding}>{m.isAdding ? $t.common?.saving : $t.translate?.dictionaries?.save}</button>
        </div>
      </div>
    {/if}

    <!-- Import form -->
    {#if m.showImportForm}
      <div class="bg-surface-card border border-border rounded-lg p-4 mb-4">
        <h3 class="text-sm font-semibold mb-3">{$t.translate?.dictionaries?.import_entries}</h3>
        <textarea placeholder={$t.translate?.dictionaries?.paste_csv || 'Paste CSV content...'} bind:value={m.importContent} class="w-full px-3 py-2 border border-border-strong rounded text-sm font-mono" rows="6"></textarea>
        <div class="grid grid-cols-2 gap-3 mt-3 mb-3">
          <input placeholder={$t.translate?.dictionaries?.delimiter || 'Delimiter (default: tab)'} bind:value={m.importDelimiter} class="px-3 py-2 border border-border-strong rounded text-sm" />
          <select bind:value={m.importOnConflict} class="px-3 py-2 border border-border-strong rounded text-sm">
            <option value="overwrite">{$t.translate?.dictionaries?.conflict_overwrite}</option>
            <option value="skip">{$t.translate?.dictionaries?.conflict_skip}</option>
          </select>
        </div>
        {#if m.importErrors.length > 0}
          <div class="mb-3 text-sm text-destructive bg-destructive-light rounded px-3 py-2">{#each m.importErrors as err}<div>{err}</div>{/each}</div>
        {/if}
        {#if m.appState === 'import_preview' && m.importPreview.length > 0}
          <div class="text-xs text-text-muted mb-1">{$t.translate?.dictionaries?.preview_count?.replace('{count}', String(m.importPreview.length))}</div>
          <div class="max-h-40 overflow-auto border border-border rounded mb-3">
            <table class="min-w-full text-xs"><thead class="bg-surface-muted"><tr><th class="px-2 py-1 text-left">{$t.translate?.dictionaries?.import_table_source || 'Source'}</th><th class="px-2 py-1 text-left">{$t.translate?.dictionaries?.import_table_target || 'Target'}</th></tr></thead>
            <tbody class="divide-y divide-border">{#each m.importPreview as row}<tr><td class="px-2 py-1">{(row as Record<string,unknown>).source_term || (row as Record<string,unknown>).source || '-'}</td><td class="px-2 py-1">{(row as Record<string,unknown>).target_term || (row as Record<string,unknown>).target || '-'}</td></tr>{/each}</tbody></table>
          </div>
        {/if}
        <div class="flex justify-end gap-2">
          <button class="px-3 py-1.5 border rounded hover:bg-surface-muted text-sm" onclick={() => { m.showImportForm = false; m.appState = 'idle'; }}>{$t.common?.cancel}</button>
          <button class="px-3 py-1.5 border rounded hover:bg-surface-muted text-sm" onclick={() => m.previewImport()}>{$t.translate?.dictionaries?.preview}</button>
          <button class="px-3 py-1.5 bg-primary text-white rounded hover:bg-primary-hover text-sm" onclick={() => m.executeImport()} disabled={m.isImporting || m.importContent.length === 0}>{m.isImporting ? $t.common?.saving : $t.translate?.dictionaries?.import_btn}</button>
        </div>
      </div>
    {/if}

    <!-- Filter -->
    <div class="mb-4 flex gap-2 items-center">
      <select bind:value={m.filterSourceLanguage} class="px-3 py-2 border border-border-strong rounded-lg text-sm w-48">
        <option value="">{$t.translate?.dictionaries?.filter_language || 'Filter source language'}</option>
        {#each m.languageOptions as opt}
          <option value={opt.code}>{opt.name} ({opt.code})</option>
        {/each}
      </select>
      <button class="px-3 py-1.5 bg-primary text-white rounded text-sm hover:bg-primary-hover" onclick={() => { m.entryPage = 1; m.loadEntries(); }}>{$t.common?.search}</button>
    </div>

    <!-- Entries table -->
    <div class="bg-surface-card border border-border rounded-lg overflow-hidden">
      <table class="min-w-full divide-y divide-border text-sm">
        <thead class="bg-surface-muted"><tr>
          <th class="px-4 py-3 text-left text-xs font-semibold text-text-muted uppercase">{$t.translate?.dictionaries?.source_term}</th>
          <th class="px-4 py-3 text-left text-xs font-semibold text-text-muted uppercase">{$t.translate?.dictionaries?.target_term}</th>
          <th class="px-4 py-3 text-left text-xs font-semibold text-text-muted uppercase">{$t.translate?.dictionaries?.languages}</th>
          <th class="px-4 py-3 text-right text-xs font-semibold text-text-muted uppercase">{$t.common?.actions}</th>
        </tr></thead>
        <tbody class="divide-y divide-border">
          {#each m.entries as entry (entry.id)}
            <!-- Edit row -->
            {#if m.editEntryId === entry.id && m.appState !== 'loading'}
              <tr class="bg-primary-light">
                <td class="px-4 py-2"><input bind:value={m.editForm.source_term} class="w-full px-2 py-1 border border-border-strong rounded text-sm" /></td>
                <td class="px-4 py-2"><input bind:value={m.editForm.target_term} class="w-full px-2 py-1 border border-border-strong rounded text-sm" /></td>
                <td class="px-4 py-2"><div class="flex gap-1 items-center">
                  <select bind:value={m.editForm.source_language} class="w-24 px-1 py-1 border border-border-strong rounded text-xs">
                    <option value="">—</option>
                    {#each m.languageOptions as opt}
                      <option value={opt.code}>{opt.code}</option>
                    {/each}
                  </select>
                  <span class="text-text-subtle text-xs">→</span>
                  <select bind:value={m.editForm.target_language} class="w-24 px-1 py-1 border border-border-strong rounded text-xs">
                    <option value="">—</option>
                    {#each m.languageOptions as opt}
                      <option value={opt.code}>{opt.code}</option>
                    {/each}
                  </select>
                </div></td>
                <td class="px-4 py-2 text-right"><div class="flex gap-1 justify-end">
                  <button class="px-3 py-1 bg-success text-white rounded text-xs hover:bg-success-hover" onclick={() => m.saveEntry()} disabled={m.isSaving}>✓</button>
                  <button class="px-3 py-1 border rounded text-xs hover:bg-surface-muted" onclick={() => m.cancelEdit()}>×</button>
                </div></td>
              </tr>
              {#if m.appState !== 'loading'}
                <tr class="bg-primary-light"><td colspan="4" class="px-4 py-2 space-y-1">
                  <input placeholder={$t.translate?.dictionaries?.context_notes} bind:value={m.editForm.context_notes} class="w-full px-2 py-1 border border-border-strong rounded text-xs" />
                  <textarea placeholder={$t.translate?.dictionaries?.context_data_json || 'Context data (JSON)'} bind:value={m.editContextDataRaw} class="w-full px-2 py-1 border border-border-strong rounded text-xs font-mono" rows="3"></textarea>
                  <label class="flex items-center gap-2 text-xs">
                    <input type="checkbox" bind:checked={m.editForm.is_regex} class="rounded border-border-strong" />
                    <span>{$t.translate?.dictionaries?.regex_pattern || 'Regex pattern'}</span>
                  </label>
                </td></tr>
              {/if}
            <!-- Expanded view -->
            {:else if m.expandedEntryId === entry.id}
              <tr class="hover:bg-surface-muted cursor-pointer" onclick={() => m.toggleExpand(entry.id)}>
                <td class="px-4 py-2 font-medium text-text">{entry.source_term}</td>
                <td class="px-4 py-2 text-text">{entry.target_term}</td>
                <td class="px-4 py-2 text-xs text-text-muted">{entry.source_language || '-'} → {entry.target_language || '-'}</td>
                <td class="px-4 py-2 text-right"><span class="text-text-subtle text-xs">▾</span></td>
              </tr>
              <tr><td colspan="4" class="px-4 py-3 bg-surface-page text-sm space-y-1">
                {#if entry.context_notes}<div><span class="text-text-muted text-xs">{$t.translate?.dictionaries?.context_notes}:</span> {entry.context_notes}</div>{/if}
                {#if entry.context_data}<div><span class="text-text-muted text-xs">{$t.translate?.dictionaries?.context_data}:</span> <code class="text-xs">{JSON.stringify(entry.context_data)}</code></div>{/if}
                <div class="flex gap-2 mt-2">
                  <button class="px-2 py-0.5 text-xs text-primary hover:underline" onclick={(e) => { e.stopPropagation(); m.startEdit(entry); }}>{$t.common?.edit}</button>
                  <button class="px-2 py-0.5 text-xs text-destructive hover:underline" onclick={(e) => { e.stopPropagation(); m.deleteEntry(entry.id); }}>{$t.common?.delete}</button>
                </div>
              </td></tr>
            <!-- Normal row -->
            {:else}
              <tr class="hover:bg-surface-muted cursor-pointer" onclick={() => m.toggleExpand(entry.id)}>
                <td class="px-4 py-2 font-medium text-text">{entry.source_term}{#if entry.is_regex} <span class="text-xs px-1 py-0.5 bg-accent text-white rounded ml-1">regex</span>{/if}</td>
                <td class="px-4 py-2 text-text">{entry.target_term}</td>
                <td class="px-4 py-2 text-xs text-text-muted">{entry.source_language || '-'} → {entry.target_language || '-'}</td>
                <td class="px-4 py-2 text-right"><div class="flex gap-1 justify-end" onclick={(e) => e.stopPropagation()}>
                  <button class="px-2 py-0.5 text-xs text-primary hover:underline" onclick={() => m.startEdit(entry)}>{$t.common?.edit}</button>
                  <button class="px-2 py-0.5 text-xs text-destructive hover:underline" onclick={() => m.deleteEntry(entry.id)}>{$t.common?.delete}</button>
                </div></td>
              </tr>
            {/if}
          {/each}
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <div class="flex items-center justify-between mt-4">
      <span class="text-sm text-text-muted">{$t.translate?.dictionaries?.total_entries?.replace('{count}', String(m.totalEntries))}</span>
      <div class="flex gap-2">
        <button class="px-3 py-1 text-sm border rounded disabled:opacity-50" disabled={m.entryPage <= 1} onclick={() => { m.entryPage--; m.loadEntries(); }}>{$t.common?.previous}</button>
        <button class="px-3 py-1 text-sm border rounded disabled:opacity-50" disabled={m.entryPage * 50 >= m.totalEntries} onclick={() => { m.entryPage++; m.loadEntries(); }}>{$t.common?.next}</button>
      </div>
    </div>
  {/if}
</div>
<!-- #endregion DictionaryDetailPage -->
