<script>
  import { fileUrl } from '../lib/api.js'
  import ImageViewer from './ImageViewer.svelte'
  import VideoPlayer from './VideoPlayer.svelte'
  import AudioPlayer from './AudioPlayer.svelte'
  import MarkdownRenderer from './MarkdownRenderer.svelte'
  import TextViewer from './TextViewer.svelte'
  import DocumentCard from './DocumentCard.svelte'
  import ExecutableWarning from './ExecutableWarning.svelte'

  let { files, cxid, password = '' } = $props()

  function getViewer(file) {
    const flags = file.render_flags || 0
    if (flags & 1) return 'image'
    if (flags & 2) return 'video'
    if (flags & 4) return 'audio'
    if (flags & 8) return 'markdown'
    if (flags & 16) return 'text'
    if (flags & 64 || flags & 128) return 'dangerous'
    return 'document'
  }
</script>

<div class="gallery">
  {#each files as file, i (file.idx)}
    {@const viewer = getViewer(file)}
    <div class="item">
      <div class="item-header">
        <span class="item-index">#{i + 1}</span>
        <span class="item-name">{file.name}</span>
      </div>
      {#if viewer === 'image'}
        <ImageViewer src={fileUrl(cxid, file.idx, false, password)} name={file.name} />
      {:else if viewer === 'video'}
        <VideoPlayer src={fileUrl(cxid, file.idx, false, password)} mime={file.mime} />
      {:else if viewer === 'audio'}
        <AudioPlayer src={fileUrl(cxid, file.idx, false, password)} mime={file.mime} />
      {:else if viewer === 'markdown'}
        <MarkdownRenderer src={fileUrl(cxid, file.idx, false, password)} />
      {:else if viewer === 'text'}
        <TextViewer src={fileUrl(cxid, file.idx, false, password)} />
      {:else if viewer === 'dangerous'}
        <ExecutableWarning {file} downloadUrl={fileUrl(cxid, file.idx, true, password)} />
      {:else}
        <DocumentCard {file} downloadUrl={fileUrl(cxid, file.idx, true, password)} />
      {/if}
    </div>
  {/each}
</div>

<style>
  .gallery {
    max-width: 1000px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
  .item {
    background: var(--retro-panel);
    border: 3px solid var(--retro-border);
    box-shadow: 6px 6px 0px var(--retro-shadow);
  }
  .item-header {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    background: #f0f0f0;
    border-bottom: 2px solid var(--retro-border);
  }
  .item-index {
    font-family: 'Press Start 2P', cursive;
    font-size: 0.5rem;
    color: var(--retro-green);
  }
  .item-name {
    font-size: 1rem;
    word-break: break-all;
  }
</style>
