<script>
  import { onMount } from "svelte";
  import { get, del, upload } from "../lib/api.js";

  let entries = $state([]);
  let currentPath = $state("");
  let loading = $state(true);
  let uploading = $state(false);
  let fileInput;

  async function browse(path) {
    loading = true;
    currentPath = path;
    const data = await get(`/files/browse?path=${encodeURIComponent(path)}`);
    entries = data?.entries || [];
    loading = false;
  }

  function goUp() {
    const parts = currentPath.split("/").filter(Boolean);
    parts.pop();
    browse(parts.join("/"));
  }

  async function remove(name) {
    if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
    const path = currentPath ? `${currentPath}/${name}` : name;
    await del(`/files/delete?path=${encodeURIComponent(path)}`);
    browse(currentPath);
  }

  function downloadUrl(name) {
    const path = currentPath ? `${currentPath}/${name}` : name;
    return `/api/files/download?path=${encodeURIComponent(path)}`;
  }

  async function handleUpload() {
    const file = fileInput?.files?.[0];
    if (!file) return;
    uploading = true;
    await upload(currentPath, file);
    fileInput.value = "";
    uploading = false;
    browse(currentPath);
  }

  function formatSize(bytes) {
    if (!bytes) return "—";
    const u = ["B", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, i)).toFixed(1) + " " + u[i];
  }

  function fileIcon(name) {
    const ext = name.split(".").pop().toLowerCase();
    if (["jpg", "jpeg", "png", "gif", "webp", "svg"].includes(ext)) return "image";
    if (["mp4", "mkv", "avi", "mov"].includes(ext)) return "video";
    if (["mp3", "flac", "wav", "m4a", "ogg"].includes(ext)) return "audio";
    if (["zip", "tar", "gz", "7z", "rar"].includes(ext)) return "archive";
    if (["py", "js", "ts", "go", "rs", "sh", "yml", "yaml", "json", "md"].includes(ext)) return "code";
    return "file";
  }

  const crumbs = $derived(currentPath.split("/").filter(Boolean));

  onMount(() => browse(""));
</script>

<div class="space-y-5">
  <div class="flex items-center justify-between">
    <div>
      <h1 class="text-2xl font-bold text-surface-900 dark:text-white tracking-tight">Files</h1>
      <p class="text-sm text-surface-400 mt-1">/volume1{currentPath ? "/" + currentPath : ""}</p>
    </div>
    <div class="flex items-center gap-2">
      <input type="file" bind:this={fileInput} onchange={handleUpload} class="hidden" />
      <button
        onclick={() => fileInput.click()}
        class="text-xs font-medium text-primary-600 bg-primary-50 hover:bg-primary-100 px-3 py-1.5 rounded-lg transition-colors disabled:opacity-50"
        disabled={uploading}
      >
        {uploading ? "Uploading..." : "Upload"}
      </button>
    </div>
  </div>

  <!-- Breadcrumbs -->
  <div class="flex items-center gap-1 text-sm flex-wrap">
    <button class="text-primary-600 hover:text-primary-700 font-medium transition-colors" onclick={() => browse("")}>volume1</button>
    {#each crumbs as part, i}
      <svg class="w-3.5 h-3.5 text-surface-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" /></svg>
      <button
        class="text-primary-600 hover:text-primary-700 font-medium transition-colors"
        onclick={() => browse(crumbs.slice(0, i + 1).join("/"))}
      >{part}</button>
    {/each}
    {#if currentPath}
      <button
        class="ml-auto text-xs font-medium text-surface-500 bg-surface-100 dark:bg-surface-700 hover:bg-surface-200 dark:hover:bg-surface-600 px-2.5 py-1 rounded-lg transition-colors flex items-center gap-1"
        onclick={goUp}
      >
        <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M5 10l7-7m0 0l7 7m-7-7v18" /></svg>
        Up
      </button>
    {/if}
  </div>

  <!-- File List -->
  {#if loading}
    <div class="space-y-1">
      {#each Array(8) as _}
        <div class="h-11 rounded-lg bg-surface-100 dark:bg-surface-800 animate-pulse"></div>
      {/each}
    </div>
  {:else}
    <div class="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 shadow-sm overflow-hidden">
      <!-- Header -->
      <div class="grid grid-cols-[1fr_100px_100px] px-4 py-2 text-[11px] font-semibold uppercase tracking-wider text-surface-400 border-b border-surface-100 dark:border-surface-700">
        <span>Name</span>
        <span class="text-right">Size</span>
        <span class="text-right">Actions</span>
      </div>
      <!-- Entries -->
      {#each entries as e}
        <div class="grid grid-cols-[1fr_100px_100px] items-center px-4 py-2.5 hover:bg-surface-50 dark:hover:bg-surface-700 border-b border-surface-100 dark:border-surface-700 last:border-0 transition-colors group">
          {#if e.is_dir}
            <button class="flex items-center gap-2.5 text-sm font-medium text-surface-700 dark:text-surface-200 hover:text-primary-600 transition-colors text-left truncate" onclick={() => browse(currentPath ? `${currentPath}/${e.name}` : e.name)}>
              <svg class="w-4 h-4 text-amber-400 shrink-0" 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>
              {e.name}
            </button>
          {:else}
            <span class="flex items-center gap-2.5 text-sm text-surface-600 dark:text-surface-300 truncate">
              <svg class="w-4 h-4 text-surface-300 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" 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>
              {e.name}
            </span>
          {/if}
          <span class="text-xs text-surface-400 text-right">{e.is_dir ? "—" : formatSize(e.size)}</span>
          <div class="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            {#if !e.is_dir}
              <a href={downloadUrl(e.name)} class="text-[11px] text-primary-500 hover:text-primary-700 font-medium transition-colors">DL</a>
            {/if}
            <button class="text-[11px] text-rose-400 hover:text-rose-600 font-medium transition-colors" onclick={() => remove(e.name)}>Del</button>
          </div>
        </div>
      {/each}
      {#if entries.length === 0}
        <div class="px-4 py-8 text-center text-sm text-surface-400">Empty directory</div>
      {/if}
    </div>
  {/if}
</div>
