<!-- #region DocPreview [C:3] [TYPE Component] [SEMANTICS llm, documentation, preview, review, dataset] -->
<!-- @BRIEF Component component: components/llm/DocPreview.svelte -->
<!-- @LAYER UI -->
<!--
@UX_STATE: Loading -> Default
 
@PURPOSE: UI component for previewing generated dataset documentation before saving.
@LAYER UI
@RELATION DEPENDS_ON -> [LLMAnalysisPlugin]
-->

<script lang="ts">
  import { t } from '$lib/i18n/index.svelte.js';

  /** @type {Object} */
  let {
    documentation = null,
    content = "",
    type = 'markdown',
    format = 'text',
    onSave = async () => {},
    onCancel = () => {},
  } = $props();

  let previewDoc = $derived(documentation || content);

  let isSaving = $state(false);

  async function handleSave() {
    isSaving = true;
    try {
      await onSave(documentation);
    } catch (err) {
      console.error("Save failed", err);
    } finally {
      isSaving = false;
    }
  }
</script>

{#if previewDoc}
  <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
      <h3 class="text-lg font-semibold mb-4">{$t.llm.doc_preview_title}</h3>
      
      <div class="flex-1 overflow-y-auto mb-6 prose prose-sm max-w-none border rounded p-4 bg-gray-50">
        <h4 class="text-md font-bold text-gray-800 mb-2">{$t.llm.dataset_desc}</h4>
        <p class="text-gray-700 mb-4 whitespace-pre-wrap">{previewDoc.description || 'No description generated.'}</p>

        <h4 class="text-md font-bold text-gray-800 mb-2">{$t.llm.column_doc}</h4>
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-100">
            <tr>
              <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Column</th>
              <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Description</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200">
            {#each Object.entries(previewDoc.columns || {}) as [name, desc]}
              <tr>
                <td class="px-3 py-2 text-sm font-mono text-gray-900">{name}</td>
                <td class="px-3 py-2 text-sm text-gray-700">{desc}</td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>

      <div class="flex justify-end gap-3">
        <button 
          class="px-4 py-2 border rounded hover:bg-gray-50"
          onclick={onCancel}
          disabled={isSaving}
        >
          {$t.llm.cancel}
        </button>
        <button 
          class="px-4 py-2 bg-primary text-white rounded hover:bg-primary-hover disabled:opacity-50"
          onclick={handleSave}
          disabled={isSaving}
        >
          {isSaving ? $t.llm.applying : $t.llm.apply_doc}
        </button>
      </div>
    </div>
  </div>
{/if}

<!-- #endregion DocPreview -->
