---
import { ENABLE_LIGHTBOX } from '@/consts'
import * as interfaces from '../../lib/interfaces'
import { filePath } from '../../lib/blog-helpers'
import Caption from './Caption.astro'
import fslightbox from 'fslightbox'

export interface Props {
  block: interfaces.Block
}

const { block }: Props = Astro.props

if (!block.Image) {
  return null
}

let image = ''
if (block.Image.External) {
  image = block.Image.External.Url
} else if (block.Image.File?.Url) {
  image = filePath(new URL(block.Image.File.Url))
}

const altText = block.Image.Caption?.map(c => c.Text.Content).join('') || 'Image'
---

<figure class="image">
  {
    image && (
      <div class="image-wrapper">
        <div class="image-container">
          {ENABLE_LIGHTBOX ? (
            <a data-fslightbox href={image} data-type="image" class="lightbox-link">
              <img 
                src={image} 
                alt={altText}
                loading="lazy" 
                decoding="async"
                class="image-content"
              />
            </a>
          ) : (
            <img 
              src={image} 
              alt={altText}
              loading="lazy" 
              decoding="async"
              class="image-content"
            />
          )}
        </div>
        <Caption richTexts={block.Image.Caption} />
      </div>
    )
  }
</figure>

<style>
  .image {
    display: flex;
    margin: 1rem auto;
    max-width: 100%;
  }
  
  .image-wrapper {
    margin: 0 auto;
    max-width: 100%;
  }
  
  .image-container {
    position: relative;
    overflow: hidden;
    border-radius: 0.5rem;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }
  
  .image-container:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  .lightbox-link {
    display: block;
    cursor: zoom-in;
  }
  
  .image-content {
    display: block;
    max-width: 100%;
    height: auto;
    width: 100%;
    object-fit: cover;
    transition: opacity 0.3s ease;
  }
  
  .image-content[loading="lazy"] {
    background: linear-gradient(90deg, 
      hsl(var(--muted)) 0%, 
      hsl(var(--muted) / 0.8) 50%, 
      hsl(var(--muted)) 100%
    );
    background-size: 200% 100%;
    animation: shimmer 1.5s infinite;
  }
  
  @keyframes shimmer {
    0% {
      background-position: -200% 0;
    }
    100% {
      background-position: 200% 0;
    }
  }
  
  @media (max-width: 768px) {
    .image {
      margin: 0.75rem auto;
    }
    
    .image-container:hover {
      transform: none;
      box-shadow: none;
    }
  }
</style>
