<!-- #region DictionaryDetailPage [C:3] [TYPE Page] [SEMANTICS sveltekit, translate, dictionary, editor, import] -->
<script lang="ts">
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { page } from '$app/state';
  import { t, _ } from '$lib/i18n/index.svelte.js';
  import { PageHeader, Button, Card } from '$lib/ui';
  import { addToast } from '$lib/toasts.svelte.js';
  import { dictionaryApi } from '$lib/api/translate.js';

  let dictionaryId = $derived(page.params.id);
  let dictionary = $state(null);
  let entries = $state([]);
  let totalEntries = $state(0);
  let entryPage = $state(1);
  let entryPageSize = 100;

  let state = $state('loading'); // idle | loading | editing | importing | import_preview | import_conflict | saving

  // Edit form for entries
  let editEntryId = $state(null);
  let editForm = $state({ source_term: '', target_term: '', source_language: '', target_language: '', context_notes: '', context_data: null, usage_notes: '' });
  let editContextDataRaw = $state('');

  // Add new entry form
  let showAddForm = $state(false);
  let addForm = $state({ source_term: '', target_term: '', source_language: '', target_language: '', context_notes: '' });
  let isAdding = $state(false);

  // Expanded context rows
  let expandedEntryId = $state(null);
  let expandedEditing = $state(false);
  let expandedContextData = $state('');
  let expandedUsageNotes = $state('');

  // Import
  let showImportForm = $state(false);
  let importContent = $state('');
  let importDelimiter = $state('');
  let importOnConflict = $state('overwrite');
  let importPreview = $state([]);
  let importErrors = $state([]);
  let importResult = $state(null);
  let isImporting = $state(false);

  // Language pair filter
  let filterSourceLanguage = $state('');
  let filterTargetLanguage = $state('');

  let availableSourceLanguages = $derived.by(() => {
    const codes = new Set(entries.map(e => e.source_language).filter(Boolean));
    return Array.from(codes).sort();
  });

  let availableTargetLanguages = $derived.by(() => {
    const codes = new Set(entries.map(e => e.target_language).filter(Boolean));
    return Array.from(codes).sort();
  });

  let filteredEntries = $derived.by(() => {
    if (!filterSourceLanguage && !filterTargetLanguage) return entries;
    return entries.filter(e => {
      if (filterSourceLanguage && e.source_language !== filterSourceLanguage) return false;
      if (filterTargetLanguage && e.target_language !== filterTargetLanguage) return false;
      return true;
    });
  });

  // Delete confirmation
  let deleteEntryId = $state(null);

  async function loadDictionary() {
    state = 'loading';
    try {
      dictionary = await dictionaryApi.getDictionary(dictionaryId);
      await loadEntries();
      state = 'editing';
    } catch (e) {
      state = 'idle';
      addToast(e?.message || _('translate.dictionaries.load_failed'), 'error');
    }
  }

  async function loadEntries() {
    try {
      const res = await dictionaryApi.fetchEntries(dictionaryId, {
        page: entryPage,
        page_size: entryPageSize,
      });
      entries = res.items || [];
      totalEntries = res.total || 0;
    } catch (e) {
      addToast(e?.message || _('translate.dictionaries.load_entries_failed'), 'error');
    }
  }

  // --- Entry CRUD ---

  function startAddEntry() {
    showAddForm = true;
    addForm = { source_term: '', target_term: '', source_language: '', target_language: '', context_notes: '' };
  }

  async function handleAddEntry() {
    if (!addForm.source_term || !addForm.target_term) {
      addToast(_('translate.dictionaries.required_terms'), 'error');
      return;
    }
    isAdding = true;
    state = 'saving';
    try {
      await dictionaryApi.createEntry(dictionaryId, addForm);
      addToast(_('translate.dictionaries.entry_added'), 'success');
      showAddForm = false;
      addForm = { source_term: '', target_term: '', source_language: '', target_language: '', context_notes: '' };
      await loadEntries();
    } catch (e) {
      addToast(e?.message || _('translate.dictionaries.entry_add_failed'), 'error');
    } finally {
      isAdding = false;
      state = 'editing';
    }
  }

  function startEditEntry(entry) {
    editEntryId = entry.id;
    editForm = {
      source_term: entry.source_term,
      target_term: entry.target_term,
      source_language: entry.source_language || '',
      target_language: entry.target_language || '',
      context_notes: entry.context_notes || '',
      context_data: entry.context_data || null,
      usage_notes: entry.usage_notes || '',
    };
    editContextDataRaw = entry.context_data ? JSON.stringify(entry.context_data, null, 2) : '';
  }

  function cancelEditEntry() {
    editEntryId = null;
    editForm = { source_term: '', target_term: '', source_language: '', target_language: '', context_notes: '', context_data: null, usage_notes: '' };
    editContextDataRaw = '';
  }

  async function handleEditEntry() {
    if (!editForm.source_term || !editForm.target_term) {
      addToast(_('translate.dictionaries.required_terms'), 'error');
      return;
    }
    state = 'saving';
    try {
      const payload = { ...editForm };
      // Parse context_data if it's a string
      if (typeof payload.context_data === 'string') {
        try {
          payload.context_data = JSON.parse(payload.context_data);
        } catch {
          payload.context_data = null;
        }
      }
      // Set has_context flag
      payload.has_context = payload.context_data !== null && typeof payload.context_data === 'object';

      // Only include source_language/target_language if non-empty
      if (!payload.source_language) delete payload.source_language;
      if (!payload.target_language) delete payload.target_language;

      await dictionaryApi.updateEntry(dictionaryId, editEntryId, payload);
      addToast(_('translate.dictionaries.entry_updated'), 'success');
      editEntryId = null;
      editForm = { source_term: '', target_term: '', source_language: '', target_language: '', context_notes: '', context_data: null, usage_notes: '' };
      editContextDataRaw = '';
      await loadEntries();
    } catch (e) {
      addToast(e?.message || _('translate.dictionaries.entry_update_failed'), 'error');
    } finally {
      state = 'editing';
    }
  }

  async function handleDeleteEntry(entryId) {
    deleteEntryId = null;
    state = 'saving';
    try {
      await dictionaryApi.deleteEntry(dictionaryId, entryId);
      addToast(_('translate.dictionaries.entry_deleted'), 'success');
      await loadEntries();
    } catch (e) {
      addToast(e?.message || _('translate.dictionaries.entry_delete_failed'), 'error');
    } finally {
      state = 'editing';
    }
  }

  function confirmDeleteEntry(entryId) {
    deleteEntryId = entryId;
  }

  function cancelDeleteEntry() {
    deleteEntryId = null;
  }

  // --- Import ---

  function startImport() {
    showImportForm = true;
    importContent = '';
    importDelimiter = '';
    importOnConflict = 'overwrite';
    importPreview = [];
    importErrors = [];
    importResult = null;
    state = 'importing';
  }

  function cancelImport() {
    showImportForm = false;
    importContent = '';
    importPreview = [];
    importErrors = [];
    importResult = null;
    state = 'editing';
  }

  async function handlePreviewImport() {
    if (!importContent.trim()) {
      addToast(_('translate.dictionaries.paste_content_first'), 'error');
      return;
    }
    isImporting = true;
    try {
      const res = await dictionaryApi.importEntries(dictionaryId, {
        content: importContent,
        delimiter: importDelimiter || null,
        on_conflict: importOnConflict,
        preview_only: true,
      });
      importPreview = res.preview || [];
      importErrors = res.errors || [];
      state = 'import_preview';
    } catch (e) {
      addToast(e?.message || _('translate.dictionaries.preview_failed'), 'error');
    } finally {
      isImporting = false;
    }
  }

  async function handleExecuteImport() {
    isImporting = true;
    try {
      const res = await dictionaryApi.importEntries(dictionaryId, {
        content: importContent,
        delimiter: importDelimiter || null,
        on_conflict: importOnConflict,
        preview_only: false,
      });
      importResult = res;
      importPreview = res.preview || [];
      importErrors = res.errors || [];
      addToast(_('translate.dictionaries.import_complete').replace('{created}', res.created).replace('{updated}', res.updated).replace('{skipped}', res.skipped), 'success');
      state = 'editing';
      showImportForm = false;
      await loadEntries();
    } catch (e) {
      addToast(e?.message || _('translate.dictionaries.import_failed'), 'error');
    } finally {
      isImporting = false;
    }
  }

  // --- Export ---

  function handleExport() {
    const header = 'source_term,target_term,source_language,target_language,context_notes,context_data,usage_notes';
    const rows = entries.map(e =>
      [
        `"${(e.source_term || '').replace(/"/g, '""')}"`,
        `"${(e.target_term || '').replace(/"/g, '""')}"`,
        `"${(e.source_language || '').replace(/"/g, '""')}"`,
        `"${(e.target_language || '').replace(/"/g, '""')}"`,
        `"${(e.context_notes || '').replace(/"/g, '""')}"`,
        `"${(e.context_data ? JSON.stringify(e.context_data).replace(/"/g, '""') : '').replace(/"/g, '""')}"`,
        `"${(e.usage_notes || '').replace(/"/g, '""')}"`,
      ].join(',')
    );
    const csv = [header, ...rows].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${dictionary?.name || 'dictionary'}-entries.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    addToast(_('translate.dictionaries.export_success'), 'info');
  }

  onMount(loadDictionary);
</script>

<div class="mx-auto w-full max-w-6xl space-y-6">
  {#snippet subtitleContent()}
    {#if dictionary}
      <p class="text-sm text-gray-500">
        {dictionary.source_dialect} &rarr; {dictionary.target_dialect}
        {#if dictionary.description}
          &mdash; {dictionary.description}
        {/if}
        &middot; {$t.translate?.dictionaries?.entry_count.replace('{count}', totalEntries)}
      </p>
    {/if}
  {/snippet}

  {#snippet dictActions()}
    {#if state === 'editing'}
      <div class="flex gap-2">
        <Button variant="secondary" size="sm" onclick={startImport}>
          {$t.translate?.dictionaries?.import_csv_tsv}
        </Button>
        <Button variant="secondary" size="sm" onclick={handleExport}>
          {$t.translate?.dictionaries?.export_csv}
        </Button>
        <Button variant="primary" size="sm" onclick={startAddEntry}>
          {$t.translate?.dictionaries?.add_entry}
        </Button>
      </div>
    {/if}
  {/snippet}

  <PageHeader
    title={dictionary?.name || $t.translate?.dictionaries?.loading}
    subtitle={subtitleContent}
    actions={dictActions}
  />

  {#if state === 'loading'}
    <Card padding="md">
      <div class="space-y-3">
        {#each [1, 2, 3] as _}
          <div class="h-12 animate-pulse rounded-md bg-gray-100"></div>
        {/each}
      </div>
    </Card>

  {:else if state === 'importing' || state === 'import_preview'}
    <Card title={$t.translate?.dictionaries?.import_title} padding="md">
      <div class="space-y-4">
        {#if state === 'importing'}
          <div>
            <label for="import-content" class="text-sm font-medium text-gray-700">
              {$t.translate?.dictionaries?.import_content_label}
            </label>
            <textarea
              id="import-content"
              bind:value={importContent}
                placeholder={$t.translate?.dictionaries?.import_content_placeholder}
              class="flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-mono min-h-[200px] mt-1"
            ></textarea>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="import-delimiter" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.import_delimiter}</label>
              <select
                id="import-delimiter"
                bind:value={importDelimiter}
                class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm mt-1"
              >
                <option value="">{$t.translate?.dictionaries?.import_delimiter_auto}</option>
                <option value=",">{$t.translate?.dictionaries?.import_delimiter_comma}</option>
                <option value="\t">{$t.translate?.dictionaries?.import_delimiter_tab}</option>
              </select>
            </div>
            <div>
              <label for="import-conflict" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.import_on_conflict}</label>
              <select
                id="import-conflict"
                bind:value={importOnConflict}
                class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm mt-1"
              >
                <option value="overwrite">{$t.translate?.dictionaries?.import_conflict_overwrite}</option>
                <option value="keep_existing">{$t.translate?.dictionaries?.import_conflict_keep}</option>
                <option value="cancel">{$t.translate?.dictionaries?.import_conflict_cancel}</option>
              </select>
            </div>
          </div>
          <div class="flex gap-3">
            <Button onclick={handlePreviewImport} isLoading={isImporting}>
              {$t.translate?.dictionaries?.import_preview_btn}
            </Button>
            <Button variant="secondary" onclick={cancelImport}>
              {$t.translate?.dictionaries?.import_cancel_btn}
            </Button>
          </div>
        {/if}

        {#if state === 'import_preview'}
          {#if importPreview.length > 0}
            <div class="max-h-64 overflow-y-auto border rounded-md">
              <table class="w-full text-xs">
                <thead class="bg-gray-50 sticky top-0">
                  <tr>
                    <th class="text-left p-2">{$t.translate?.dictionaries?.import_table_line}</th>
                    <th class="text-left p-2">{$t.translate?.dictionaries?.import_table_source}</th>
                    <th class="text-left p-2">{$t.translate?.dictionaries?.import_table_target}</th>
                    <th class="text-left p-2">{$t.translate?.dictionaries?.import_table_src_lang}</th>
                    <th class="text-left p-2">{$t.translate?.dictionaries?.import_table_tgt_lang}</th>
                    <th class="text-left p-2">{$t.translate?.dictionaries?.import_table_context}</th>
                    <th class="text-left p-2">{$t.translate?.dictionaries?.import_table_conflict}</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                  {#each importPreview as row}
                    <tr class={row.is_conflict ? 'bg-amber-50' : ''}>
                      <td class="p-2 text-gray-400">{row.line}</td>
                      <td class="p-2">{row.source_term}</td>
                      <td class="p-2">{row.target_term}</td>
                      <td class="p-2 font-mono">{row.source_language || '—'}</td>
                      <td class="p-2 font-mono">{row.target_language || '—'}</td>
                      <td class="p-2 text-gray-500">
                        {#if row.has_context || row.context_data}
                          <span class="text-blue-600" title={row.context_data ? JSON.stringify(row.context_data) : ''}>{$t.translate?.dictionaries?.import_yes}</span>
                        {:else if row.usage_notes}
                          <span class="text-green-600" title={row.usage_notes}>{$t.translate?.dictionaries?.import_notes}</span>
                        {:else}
                          —
                        {/if}
                      </td>
                      <td class="p-2">
                        {#if row.is_conflict}
                          <span class="text-amber-600">
                            {_('translate.dictionaries.import_existing').replace('{term}', row.existing_target_term)}
                            ({importOnConflict === 'overwrite' ? $t.translate?.dictionaries?.import_will_overwrite : $t.translate?.dictionaries?.import_will_skip})
                          </span>
                        {:else}
                          <span class="text-green-600">{$t.translate?.dictionaries?.import_new}</span>
                        {/if}
                      </td>
                    </tr>
                  {/each}
                </tbody>
              </table>
            </div>
          {/if}

          {#if importErrors.length > 0}
            <div class="bg-destructive-light border border-destructive-light text-red-700 rounded-md p-3 text-xs">
              <p class="font-medium mb-1">{$t.translate?.dictionaries?.import_errors.replace('{count}', importErrors.length)}</p>
              {#each importErrors as err}
                <p>{_('translate.dictionaries.import_error_line').replace('{line}', err.line).replace('{error}', err.error)}</p>
              {/each}
            </div>
          {/if}

          <div class="flex gap-3">
            <Button onclick={handleExecuteImport} isLoading={isImporting}>
              {$t.translate?.dictionaries?.import_execute_btn.replace('{count}', importPreview.length)}
            </Button>
            <Button variant="secondary" onclick={cancelImport}>
              {$t.translate?.dictionaries?.import_cancel_btn}
            </Button>
          </div>
        {/if}
      </div>
    </Card>

  {:else if state === 'editing'}
    {#if showAddForm}
      <Card title={$t.translate?.dictionaries?.add_entry_title} padding="md">
        <div class="space-y-4">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="add-source" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.source_term_required}</label>
              <input
                id="add-source"
                bind:value={addForm.source_term}
                placeholder={$t.translate?.dictionaries?.source_term_placeholder}
                class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm mt-1"
              />
            </div>
            <div>
              <label for="add-target" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.target_term_required}</label>
              <input
                id="add-target"
                bind:value={addForm.target_term}
                placeholder={$t.translate?.dictionaries?.target_term_placeholder}
                class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm mt-1"
              />
            </div>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="add-source-lang" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.source_language_label}</label>
              <input
                id="add-source-lang"
                bind:value={addForm.source_language}
                placeholder={$t.translate?.dictionaries?.source_lang_placeholder}
                class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm mt-1 font-mono"
              />
            </div>
            <div>
              <label for="add-target-lang" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.target_language_label}</label>
              <input
                id="add-target-lang"
                bind:value={addForm.target_language}
                placeholder={$t.translate?.dictionaries?.target_lang_placeholder}
                class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm mt-1 font-mono"
              />
            </div>
          </div>
          <div>
            <label for="add-notes" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.context_notes_label}</label>
            <input
              id="add-notes"
              bind:value={addForm.context_notes}
              placeholder={$t.translate?.dictionaries?.context_notes_placeholder}
              class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm mt-1"
            />
          </div>
          <div class="flex gap-3">
            <Button onclick={handleAddEntry} isLoading={isAdding}>{$t.translate?.dictionaries?.add_entry_btn}</Button>
            <Button variant="secondary" onclick={() => { showAddForm = false; }}>{$t.translate?.dictionaries?.cancel_btn}</Button>
          </div>
        </div>
      </Card>
    {/if}

    {#if entries.length === 0}
      <Card padding="lg">
        <div class="text-center py-8">
          <p class="text-gray-500 mb-4">{$t.translate?.dictionaries?.no_entries}</p>
          <Button onclick={startAddEntry} variant="primary">{$t.translate?.dictionaries?.add_first_entry}</Button>
        </div>
      </Card>
    {:else}
      <Card padding="none">
        {#if availableSourceLanguages.length > 0 || availableTargetLanguages.length > 0}
          <div class="px-3 py-2 bg-gray-50 border-b border-gray-200 flex items-center gap-3 flex-wrap">
            <span class="text-xs font-medium text-gray-500">{$t.translate?.dictionaries?.filter_by_language}</span>
            <select
              bind:value={filterSourceLanguage}
              class="text-xs px-2 py-1 border border-gray-300 rounded bg-white"
            >
              <option value="">{$t.translate?.dictionaries?.filter_all_source}</option>
              {#each availableSourceLanguages as lang}
                <option value={lang}>{lang}</option>
              {/each}
            </select>
            <span class="text-xs text-gray-400">&rarr;</span>
            <select
              bind:value={filterTargetLanguage}
              class="text-xs px-2 py-1 border border-gray-300 rounded bg-white"
            >
              <option value="">{$t.translate?.dictionaries?.filter_all_target}</option>
              {#each availableTargetLanguages as lang}
                <option value={lang}>{lang}</option>
              {/each}
            </select>
            {#if filterSourceLanguage || filterTargetLanguage}
              <button
                onclick={() => { filterSourceLanguage = ''; filterTargetLanguage = ''; }}
                class="text-xs text-primary hover:text-primary-hover"
              >
                {$t.translate?.dictionaries?.filter_clear}
              </button>
              <span class="text-xs text-gray-400">{_('translate.dictionaries.filter_count').replace('{filtered}', filteredEntries.length).replace('{total}', entries.length)}</span>
            {/if}
          </div>
        {/if}
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead class="bg-gray-50 border-b border-gray-200">
              <tr>
                <th class="text-left p-3 text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.translate?.dictionaries?.table_source_term}</th>
                <th class="text-left p-3 text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.translate?.dictionaries?.table_target_term}</th>
                <th class="text-left p-3 text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.translate?.dictionaries?.table_lang}</th>
                <th class="text-left p-3 text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.translate?.dictionaries?.table_context}</th>
                <th class="text-right p-3 text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.translate?.dictionaries?.table_actions}</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
              {#each filteredEntries as entry}
                {#if editEntryId === entry.id}
                  <tr class="bg-primary-light">
                    <td class="p-2">
                      <input
                        bind:value={editForm.source_term}
                        class="flex h-9 w-full rounded border border-blue-300 bg-white px-2 py-1 text-sm"
                      />
                    </td>
                    <td class="p-2">
                      <input
                        bind:value={editForm.target_term}
                        class="flex h-9 w-full rounded border border-blue-300 bg-white px-2 py-1 text-sm"
                      />
                    </td>
                    <td class="p-2">
                      <div class="flex gap-1">
                        <input
                          bind:value={editForm.source_language}
                          placeholder="src"
                          class="flex h-9 w-14 rounded border border-blue-300 bg-white px-1 py-1 text-xs font-mono"
                        />
                        <span class="text-gray-400 self-center text-xs">&rarr;</span>
                        <input
                          bind:value={editForm.target_language}
                          placeholder="tgt"
                          class="flex h-9 w-14 rounded border border-blue-300 bg-white px-1 py-1 text-xs font-mono"
                        />
                      </div>
                    </td>
                    <td class="p-2">
                      <input
                        bind:value={editForm.context_notes}
                        placeholder="notes"
                        class="flex h-9 w-full rounded border border-blue-300 bg-white px-2 py-1 text-sm"
                      />
                    </td>
                    <td class="p-2 text-right">
                      <div class="flex gap-1 justify-end">
                        <Button variant="primary" size="sm" onclick={handleEditEntry}>{$t.translate?.dictionaries?.save_btn}</Button>
                        <Button variant="ghost" size="sm" onclick={cancelEditEntry}>{$t.translate?.dictionaries?.cancel_btn}</Button>
                      </div>
                    </td>
                  </tr>
                {:else}
                  <tr class="hover:bg-gray-50 transition-colors cursor-pointer" onclick={() => {
                    expandedEntryId = expandedEntryId === entry.id ? null : entry.id;
                    expandedEditing = false;
                    if (expandedEntryId !== entry.id) {
                      expandedContextData = entry.context_data ? JSON.stringify(entry.context_data, null, 2) : '';
                      expandedUsageNotes = entry.usage_notes || '';
                    }
                  }}>
                    <td class="p-3 font-medium text-gray-900">{entry.source_term}</td>
                    <td class="p-3 text-gray-700">{entry.target_term}</td>
                    <td class="p-3 text-xs text-gray-400">
                      {#if entry.source_language || entry.target_language}
                        <span class="font-mono text-gray-500">{entry.source_language || '?'} &rarr; {entry.target_language || '?'}</span>
                      {:else}
                        <span class="text-gray-300 italic">—</span>
                      {/if}
                    </td>
                    <td class="p-3 text-xs text-gray-400">
                      <div class="flex items-center gap-1.5">
                        <span>{entry.context_notes || ''}</span>
                        {#if entry.has_context}
                          <span class="inline-flex items-center text-[10px] px-1.5 py-0.5 rounded-full bg-blue-100 text-blue-700">
                            context
                          </span>
                        {/if}
                        {#if entry.usage_notes}
                          <span class="inline-flex items-center text-[10px] px-1.5 py-0.5 rounded-full bg-green-100 text-green-700">
                            notes
                          </span>
                        {/if}
                      </div>
                    </td>
                    <td class="p-3 text-right">
                      {#if deleteEntryId === entry.id}
                        <div class="flex gap-1 justify-end items-center">
                          <span class="text-xs text-red-600">{$t.translate?.dictionaries?.confirm_delete_entry}</span>
                          <Button variant="danger" size="sm" onclick={() => handleDeleteEntry(entry.id)}>{$t.translate?.dictionaries?.delete_entry_btn}</Button>
                          <Button variant="ghost" size="sm" onclick={cancelDeleteEntry}>{$t.translate?.dictionaries?.no_btn}</Button>
                        </div>
                      {:else}
                        <div class="flex gap-1 justify-end">
                          <Button variant="ghost" size="sm" onclick={() => startEditEntry(entry)}>{$t.translate?.dictionaries?.edit_btn}</Button>
                          <Button variant="ghost" size="sm" onclick={() => confirmDeleteEntry(entry.id)}>{$t.translate?.dictionaries?.delete_entry_btn}</Button>
                        </div>
                      {/if}
                    </td>
                  </tr>
                  {#if expandedEntryId === entry.id}
                    <tr class="bg-gray-50">
                      <td colspan="5" class="p-3">
                        <div class="text-xs space-y-3">
                          {#if expandedEditing}
                            <!-- Inline editing mode -->
                            <div>
                              <div class="flex items-center justify-between mb-1">
                                <span class="font-medium text-gray-600">Context data:</span>
                                <div class="flex gap-1">
                                  <button
                                    onclick={async () => {
                                      try {
                                        const updated = await dictionaryApi.updateEntry(dictionaryId, entry.id, {
                                          context_data: expandedContextData ? JSON.parse(expandedContextData) : null,
                                          usage_notes: expandedUsageNotes,
                                          has_context: !!expandedContextData
                                        });
                                        addToast(_('translate.dictionaries.updated_toast'), 'success');
                                        expandedEditing = false;
                                        await loadEntries();
                                      } catch (e) {
                                        addToast(e?.message || _('translate.dictionaries.save_failed_toast'), 'error');
                                      }
                                    }}
                                    class="px-2 py-0.5 text-xs bg-primary text-white rounded hover:bg-primary-hover"
                                  >{$t.translate?.dictionaries?.save_btn}</button>
                                  <button
                                    onclick={() => { expandedEditing = false; }}
                                    class="px-2 py-0.5 text-xs border border-gray-300 text-gray-600 rounded hover:bg-gray-50"
                                  >{$t.translate?.dictionaries?.cancel_btn}</button>
                                </div>
                              </div>
                              <textarea
                                bind:value={expandedContextData}
                                class="w-full px-2 py-1.5 border border-gray-300 rounded text-xs font-mono min-h-[60px]"
                                placeholder={$t.translate?.dictionaries?.json_placeholder}
                              ></textarea>
                            </div>
                            <div>
                              <label class="font-medium text-gray-600">{$t.translate?.dictionaries?.usage_notes_label}</label>
                              <textarea
                                bind:value={expandedUsageNotes}
                                class="w-full px-2 py-1.5 border border-gray-300 rounded text-xs mt-1 min-h-[40px]"
                                placeholder={$t.translate?.dictionaries?.usage_notes_placeholder}
                              ></textarea>
                            </div>
                          {:else}
                            <!-- Display mode (read-only) -->
                            {#if entry.has_context && entry.context_data}
                              <div>
                                <div class="flex items-center justify-between mb-1">
                                <span class="font-medium text-gray-600">{$t.translate?.dictionaries?.context_data_label}</span>
                                  <button
                                    onclick={() => {
                                      expandedEditing = true;
                                      expandedContextData = entry.context_data ? JSON.stringify(entry.context_data, null, 2) : '';
                                      expandedUsageNotes = entry.usage_notes || '';
                                    }}
                                    class="text-xs text-primary hover:text-primary-hover"
                                  >{$t.translate?.dictionaries?.edit_btn}</button>
                                </div>
                                <div class="bg-white border border-gray-200 rounded p-2">
                                  {#if typeof entry.context_data === 'object' && entry.context_data !== null}
                                    <div class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-[11px]">
                                      {#each Object.entries(entry.context_data) as [key, val]}
                                        <span class="font-medium text-gray-500 text-right">{key}:</span>
                                        <span class="text-gray-700">{typeof val === 'object' ? JSON.stringify(val) : String(val)}</span>
                                      {/each}
                                    </div>
                                  {:else}
                                    <pre class="text-[11px] text-gray-600 overflow-x-auto">{JSON.stringify(entry.context_data, null, 2)}</pre>
                                  {/if}
                                </div>
                              </div>
                            {:else}
                              <div class="flex items-center justify-between">
                                <p class="text-gray-400 italic">{$t.translate?.dictionaries?.no_context_data}</p>
                                <button
                                  onclick={() => {
                                    expandedEditing = true;
                                    expandedContextData = '';
                                    expandedUsageNotes = entry.usage_notes || '';
                                  }}
                                  class="text-xs text-primary hover:text-primary-hover"
                                  >{$t.translate?.dictionaries?.add_context}</button>
                              </div>
                            {/if}
                            {#if entry.usage_notes}
                              <div>
                                <span class="font-medium text-gray-600">{$t.translate?.dictionaries?.usage_notes_label}</span>
                                <p class="mt-0.5 text-gray-700">{entry.usage_notes}</p>
                              </div>
                            {:else if expandedEditing}
                              <!-- usage notes editable handled above -->
                            {/if}
                          {/if}
                          {#if entry.context_source}
                            <div class="flex items-center gap-1.5">
                              <span class="font-medium text-gray-600">{$t.translate?.dictionaries?.source_label}</span>
                              <span class="inline-flex items-center text-[10px] px-1.5 py-0.5 rounded-full
                                {entry.context_source === 'auto' ? 'bg-blue-100 text-blue-700' : ''}
                                {entry.context_source === 'auto_with_edits' ? 'bg-amber-100 text-amber-700' : ''}
                                {entry.context_source === 'manual' ? 'bg-green-100 text-green-700' : ''}
                                {entry.context_source === 'bulk' ? 'bg-purple-100 text-purple-700' : ''}
                                {!['auto','auto_with_edits','manual','bulk'].includes(entry.context_source) ? 'bg-gray-100 text-gray-600' : ''}
                              ">{entry.context_source}</span>
                            </div>
                          {/if}
                        </div>
                      </td>
                    </tr>
                  {/if}
                {/if}
              {/each}
            </tbody>
          </table>
        </div>
      </Card>

      {#if totalEntries > entryPageSize}
        <div class="flex justify-center gap-2 pt-4">
          <Button
            variant="secondary"
            size="sm"
            disabled={entryPage <= 1}
            onclick={() => { entryPage--; loadEntries(); }}
          >
            {$t.translate?.dictionaries?.page_previous}
          </Button>
          <span class="text-sm text-gray-500 self-center">
            {_('translate.dictionaries.page_info').replace('{current}', entryPage).replace('{total}', Math.ceil(totalEntries / entryPageSize))}
          </span>
          <Button
            variant="secondary"
            size="sm"
            disabled={entryPage >= Math.ceil(totalEntries / entryPageSize)}
            onclick={() => { entryPage++; loadEntries(); }}
          >
            {$t.translate?.dictionaries?.page_next}
          </Button>
        </div>
      {/if}
    {/if}
  {/if}
</div>

<!-- #endregion DictionaryDetailPage -->
