<!-- #region DictionariesPage [C:3] [TYPE Page] [SEMANTICS sveltekit, translate, dictionary, crud, term] -->
<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 } from '$lib/ui';
  import { Button } from '$lib/ui';
  import { Card } from '$lib/ui';
  import { addToast } from '$lib/toasts.svelte.js';
  import { dictionaryApi } from '$lib/api/translate.js';

  let state = $state('loading'); // idle | loading | empty | populated | delete_blocked
  let dictionaries = $state([]);
  let total = $state(0);
  let page_size = 20;
  let currentPage = $state(1);
  let showCreateForm = $state(false);
  let createForm = $state({ name: '', source_dialect: '', target_dialect: '', description: '' });
  let isCreating = $state(false);
  let deleteConfirmId = $state(null);

  async function loadDictionaries() {
    state = 'loading';
    try {
      const res = await dictionaryApi.fetchDictionaries({ page: currentPage, page_size });
      dictionaries = res.items || [];
      total = res.total || 0;
      state = dictionaries.length > 0 ? 'populated' : 'empty';
    } catch (e) {
      state = 'empty';
      addToast(e?.message || _('translate.dictionaries.load_failed'), 'error');
    }
  }

  async function handleCreate() {
    if (!createForm.name || !createForm.source_dialect || !createForm.target_dialect) {
      addToast(_('translate.dictionaries.name_required'), 'error');
      return;
    }
    isCreating = true;
    try {
      await dictionaryApi.createDictionary(createForm);
      addToast(_('translate.dictionaries.dict_created'), 'success');
      showCreateForm = false;
      createForm = { name: '', source_dialect: '', target_dialect: '', description: '' };
      currentPage = 1;
      await loadDictionaries();
    } catch (e) {
      addToast(e?.message || _('translate.dictionaries.create_failed'), 'error');
    } finally {
      isCreating = false;
    }
  }

  async function handleDelete(id) {
    deleteConfirmId = null;
    try {
      await dictionaryApi.deleteDictionary(id);
      addToast(_('translate.dictionaries.delete_success'), 'success');
      await loadDictionaries();
    } catch (e) {
      const msg = e?.message || '';
      if (msg.includes('active/scheduled')) {
        state = 'delete_blocked';
        addToast(msg, 'error');
      } else {
        addToast(msg || _('translate.dictionaries.delete_failed'), 'error');
      }
    }
  }

  function openDeleteConfirm(id) {
    deleteConfirmId = id;
  }

  function cancelDelete() {
    deleteConfirmId = null;
  }

  function goToEditor(id) {
    goto(`/translate/dictionaries/${id}`);
  }

  function goToCreate() {
    showCreateForm = true;
  }

  onMount(loadDictionaries);
</script>

<div class="mx-auto w-full max-w-5xl space-y-6">
  {#snippet pageActions()}
    {#if !showCreateForm}
      <Button onclick={goToCreate} variant="primary">
        {$t.translate?.dictionaries?.create}
      </Button>
    {/if}
  {/snippet}

  <PageHeader
    title={$t.translate?.dictionaries?.title}
    actions={pageActions}
  />

  {#if showCreateForm}
    <Card title={$t.translate?.dictionaries?.new_title} padding="md">
      <div class="space-y-4">
        <div>
          <label for="dict-name" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.name} *</label>
          <input
            id="dict-name"
            bind:value={createForm.name}
            placeholder={$t.translate?.dictionaries?.name_placeholder}
            class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm"
          />
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label for="dict-source" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.source_dialect} *</label>
            <input
              id="dict-source"
              bind:value={createForm.source_dialect}
              placeholder={$t.translate?.dictionaries?.source_dialect_placeholder}
              class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm"
            />
          </div>
          <div>
            <label for="dict-target" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.target_dialect} *</label>
            <input
              id="dict-target"
              bind:value={createForm.target_dialect}
              placeholder={$t.translate?.dictionaries?.target_dialect_placeholder}
              class="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm"
            />
          </div>
        </div>
        <div>
          <label for="dict-desc" class="text-sm font-medium text-gray-700">{$t.translate?.dictionaries?.desc}</label>
          <textarea
            id="dict-desc"
            bind:value={createForm.description}
            placeholder={$t.translate?.dictionaries?.desc_placeholder}
            class="flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm min-h-[60px]"
          ></textarea>
        </div>
        <div class="flex gap-3">
          <Button onclick={handleCreate} isLoading={isCreating}>{$t.translate?.common?.create}</Button>
          <Button
            variant="secondary"
            onclick={() => {
              showCreateForm = false;
              createForm = { name: '', source_dialect: '', target_dialect: '', description: '' };
            }}
          >
            {$t.translate?.common?.cancel}
          </Button>
        </div>
      </div>
    </Card>
  {/if}

  {#if state === 'loading'}
    <Card padding="md">
      <div class="space-y-3">
        {#each [1, 2, 3] as _}
          <div class="h-16 animate-pulse rounded-md bg-gray-100"></div>
        {/each}
      </div>
    </Card>
  {:else if state === 'empty'}
    <Card padding="lg">
      <div class="text-center py-8">
        <p class="text-gray-500 mb-4">{$t.translate?.dictionaries?.no_dicts}</p>
        <Button onclick={goToCreate} variant="primary">{$t.translate?.dictionaries?.create_first}</Button>
      </div>
    </Card>
  {:else if state === 'populated'}
    <Card padding="none">
      <div class="divide-y divide-gray-100">
        {#each dictionaries as dict}
          <div class="flex items-center justify-between p-4 hover:bg-gray-50 transition-colors">
            <div class="flex-1 min-w-0">
              <button
                class="text-left"
                onclick={() => goToEditor(dict.id)}
              >
                <h3 class="text-sm font-semibold text-gray-900 hover:text-primary truncate">{dict.name}</h3>
                <p class="text-xs text-gray-500 mt-0.5">
                  {dict.source_dialect} &rarr; {dict.target_dialect}
                  {#if dict.description}
                    &mdash; {dict.description}
                  {/if}
                </p>
                <p class="text-xs text-gray-400 mt-0.5">
                  {$t.translate?.dictionaries?.entry_count.replace('{count}', dict.entry_count ?? 0)}
                  {#if !dict.is_active}
                    <span class="ml-2 text-amber-600">{$t.translate?.dictionaries?.inactive}</span>
                  {/if}
                </p>
              </button>
            </div>
            <div class="flex items-center gap-2 ml-4 shrink-0">
              <Button
                variant="ghost"
                size="sm"
                onclick={() => goToEditor(dict.id)}
              >
                {$t.translate?.common?.edit}
              </Button>
              {#if deleteConfirmId === dict.id}
                <div class="flex items-center gap-1">
                  <span class="text-xs text-red-600">{$t.translate?.dictionaries?.confirm_delete}</span>
                  <Button
                    variant="danger"
                    size="sm"
                    onclick={() => handleDelete(dict.id)}
                  >
                    {$t.translate?.common?.delete}
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onclick={cancelDelete}
                  >
                    {$t.translate?.common?.cancel}
                  </Button>
                </div>
              {:else}
                <Button
                  variant="ghost"
                  size="sm"
                  onclick={() => openDeleteConfirm(dict.id)}
                >
                  {$t.translate?.common?.delete}
                </Button>
              {/if}
            </div>
          </div>
        {/each}
      </div>
    </Card>

    {#if total > page_size}
      <div class="flex justify-center gap-2 pt-4">
        <Button
          variant="secondary"
          size="sm"
          disabled={currentPage <= 1}
          onclick={() => { currentPage--; loadDictionaries(); }}
        >
          {$t.translate?.common?.previous}
        </Button>
        <span class="text-sm text-gray-500 self-center">
          {$t.translate?.dictionaries?.page_info.replace('{current}', currentPage).replace('{total}', Math.ceil(total / page_size))}
        </span>
        <Button
          variant="secondary"
          size="sm"
          disabled={currentPage >= Math.ceil(total / page_size)}
          onclick={() => { currentPage++; loadDictionaries(); }}
        >
          {$t.translate?.common?.next}
        </Button>
      </div>
    {/if}
  {/if}
</div>

<!-- #endregion DictionariesPage -->
