<!-- #region FileList [C:3] [TYPE Component] [SEMANTICS storage, file, table, navigation, explorer] -->
<!-- @BRIEF Component component: components/storage/FileList.svelte -->
<!-- @LAYER UI -->
<!--
@UX_STATE: Loading -> Default

@SEMANTICS: storage, files, list, table
@PURPOSE:   Displays a table of files with metadata and actions.
@LAYER     UI
@RELATION  DEPENDS_ON -> [storageService]

@PROPS:     files (Array) - List of StoredFile objects.
@EVENTS:    ondelete/onnavigate callback props - Raised when a file is deleted or navigation is requested.
-->

<script lang="ts">
  // [SECTION: IMPORTS]
  import { downloadFile } from '../../services/storageService';
  import { t } from '$lib/i18n/index.svelte.js';
  import { addToast } from '$lib/toasts.svelte.js';
  // [/SECTION: IMPORTS]

  let {
    files = [],
    ondelete = () => {},
    onnavigate = () => {},
  } = $props();

  // #region isDirectory:Function [TYPE Function]
  /**
   * @purpose Checks if a file object represents a directory.
   * @pre     file object has mime_type property.
   * @post    Returns boolean.
   * @param   {Object} file - The file object to check.
   * @return  {boolean} True if it's a directory, false otherwise.
   */
  function isDirectory(file) {
    console.log("[isDirectory][Action] Checking file type");
    return file.mime_type === 'directory';
  }
  // #endregion isDirectory:Function

  // #region formatSize:Function [TYPE Function]
  /**
   * @purpose Formats file size in bytes into a human-readable string.
   * @pre     bytes is a number.
   * @post    Returns formatted string.
   * @param   {number} bytes - The size in bytes.
   * @return  {string} Formatted size (e.g., "1.2 MB").
   */
  function formatSize(bytes) {
    console.log(`[formatSize][Action] Formatting ${bytes} bytes`);
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
  // #endregion formatSize:Function

  // #region formatDate:Function [TYPE Function]
  /**
   * @purpose Formats an ISO date string into a localized readable format.
   * @pre     dateStr is a valid date string.
   * @post    Returns localized string.
   * @param   {string} dateStr - The date string to format.
   * @return  {string} Localized date and time.
   */
  function formatDate(dateStr) {
    console.log("[formatDate][Action] Formatting date string");
    return new Date(dateStr).toLocaleString();
  }
  // #endregion formatDate:Function

  // #region handleDownload:Function [TYPE Function]
  /**
   * @purpose Downloads selected file through authenticated API request.
   * @pre     file is a non-directory storage entry with category/path.
   * @post    Browser download starts or user sees toast on failure.
   */
  async function handleDownload(file) {
    try {
      await downloadFile(file.category, file.path, file.name);
    } catch (error) {
      addToast(error?.message || 'Download failed', 'error');
    }
  }
  // #endregion handleDownload:Function
</script>

<!-- [SECTION: TEMPLATE] -->
<div class="overflow-x-auto">
  <table class="min-w-full bg-surface-card border border-border">
    <thead class="bg-surface-muted">
      <tr>
        <th class="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.storage.table.name}</th>
        <th class="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.storage.table.category}</th>
        <th class="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.storage.table.size}</th>
        <th class="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.storage.table.created_at}</th>
        <th class="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">{$t.storage.table.actions}</th>
      </tr>
    </thead>
    <tbody class="divide-y divide-border">
      {#each files as file}
        <tr class="hover:bg-surface-muted">
          <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-text">
            {#if isDirectory(file)}
              <button
                onclick={() => onnavigate(file.path)}
                class="flex items-center text-primary hover:text-primary"
              >
                <svg class="h-5 w-5 mr-2 text-yellow-400" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" />
                </svg>
                {file.name}
              </button>
            {:else}
              <div class="flex items-center">
                <svg class="h-5 w-5 mr-2 text-text-subtle" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                </svg>
                {file.name}
              </div>
            {/if}
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-text-muted capitalize">{file.category}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-text-muted">
            {isDirectory(file) ? '--' : formatSize(file.size)}
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-text-muted">{formatDate(file.created_at)}</td>
          <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
            {#if !isDirectory(file)}
              <button
                type="button"
                onclick={() => handleDownload(file)}
                class="text-primary hover:text-primary mr-4"
              >
                {$t.storage.table.download}
              </button>
            {/if}
            <button
              onclick={() => ondelete({ category: file.category, path: file.path, name: file.name })}
              class="text-destructive hover:text-destructive"
            >
              {$t.storage.table.delete}
            </button>
          </td>
        </tr>
      {:else}
        <tr>
          <td colspan="5" class="px-6 py-10 text-center text-sm text-text-muted">
            {$t.storage.no_files}
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
</div>
<!-- [/SECTION: TEMPLATE] -->


<!-- #endregion FileList -->
