<script lang="ts">
  import { onDestroy } from 'svelte';
  import ImagePreviewModal from '$lib/components/ui/ImagePreviewModal.svelte';
  import { getAuthenticatedMediaUrl } from '$lib/matrix';
  import { formatFileSize } from '../utils';
  import type { MediaInfo } from '$lib/matrix/types';

  interface Props {
    type: 'image' | 'video' | 'audio' | 'file';
    media: MediaInfo;
    altText?: string;
  }

  let { type, media, altText = '' }: Props = $props();

  let mediaUrl = $state<string | null>(null);
  let isLoading = $state(true);
  let showPreview = $state(false);

  // Load authenticated media URL
  $effect(() => {
    if (media?.url) {
      isLoading = true;
      getAuthenticatedMediaUrl(media.url)
        .then((url) => {
          mediaUrl = url;
          isLoading = false;
        })
        .catch(() => {
          mediaUrl = media?.httpUrl || null;
          isLoading = false;
        });
    }
  });

  // Cleanup blob URLs
  onDestroy(() => {
    if (mediaUrl?.startsWith('blob:')) {
      URL.revokeObjectURL(mediaUrl);
    }
  });
</script>

{#if type === 'image'}
  {#if isLoading}
    <div class="w-48 h-32 bg-dark/50 rounded-lg animate-pulse flex items-center justify-center">
      <span class="text-light/30 text-sm">Loading...</span>
    </div>
  {:else if mediaUrl}
    <button
      class="block max-w-md cursor-pointer"
      onclick={() => (showPreview = true)}
    >
      <img
        src={mediaUrl}
        alt={altText}
        class="rounded-lg max-h-80 object-contain bg-dark/50 hover:opacity-90 transition-opacity"
        style="max-width: 100%;"
      />
    </button>
  {/if}
{:else if type === 'video' && mediaUrl}
  <video
    src={mediaUrl}
    controls
    class="rounded-lg max-w-md max-h-80 bg-dark/50"
  >
    <track kind="captions" />
  </video>
{:else if type === 'audio' && mediaUrl}
  <audio src={mediaUrl} controls class="w-full max-w-md">
    <track kind="captions" />
  </audio>
{:else if type === 'file'}
  <a
    href={mediaUrl || '#'}
    download={media.filename}
    class="flex items-center gap-3 px-4 py-3 bg-dark/50 rounded-lg hover:bg-dark/70 transition-colors max-w-sm"
  >
    <svg
      class="w-8 h-8 text-primary shrink-0"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
    >
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14,2 14,8 20,8" />
    </svg>
    <div class="min-w-0">
      <p class="text-light truncate">{media.filename || altText}</p>
      <p class="text-xs text-light/50">{formatFileSize(media.size)}</p>
    </div>
  </a>
{/if}

{#if showPreview && mediaUrl}
  <ImagePreviewModal
    src={mediaUrl}
    alt={altText}
    onClose={() => (showPreview = false)}
  />
{/if}
