---
import '../styles/global.css';
import { SITE } from '../data/site';
import TemplateInfo from '../components/TemplateInfo.astro';
import AnalyticsHead from '../components/AnalyticsHead.astro';

interface Props {
  title?: string;
  description?: string;
  ogImage?: string;
  canonicalUrl?: string;
  noIndex?: boolean;
}

const {
  title,
  description = SITE.description,
  ogImage,
  canonicalUrl,
  noIndex = false,
} = Astro.props;

const base = import.meta.env.BASE_URL;
const pageTitle = title ? `${title} — ${SITE.name} Photography` : `${SITE.name} — ${SITE.role}`;
const ogImageUrl = ogImage ?? `${base}og-image.png`;
const canon = canonicalUrl ?? Astro.url.href;
---

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <AnalyticsHead />
    <meta name="generator" content={Astro.generator} />

    <title>{pageTitle}</title>
    <meta name="description" content={description} />
    {noIndex && <meta name="robots" content="noindex" />}
    <link rel="canonical" href={canon} />

    <!-- Open Graph -->
    <meta property="og:title" content={pageTitle} />
    <meta property="og:description" content={description} />
    <meta property="og:url" content={canon} />
    <meta property="og:type" content="website" />
    <meta property="og:image" content={ogImageUrl} />
    <meta property="og:image:width" content="1200" />
    <meta property="og:image:height" content="630" />
    <meta property="og:site_name" content={`${SITE.name} Photography`} />

    <!-- Twitter -->
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content={pageTitle} />
    <meta name="twitter:description" content={description} />
    <meta name="twitter:image" content={ogImageUrl} />

    <!-- Favicon -->
    <link rel="icon" href={`${base}favicon.svg`} type="image/svg+xml" />
    <!-- Sitemap -->
    <link rel="sitemap" href={`${base}sitemap-index.xml`} />

    <!-- Fonts are self-hosted via @fontsource and bundled by Vite/Astro -->
  </head>
  <body class="min-h-screen bg-white text-ink">
    <slot />
    <TemplateInfo />

    <!-- Lightbox overlay -->
    <div
      id="lightbox"
      class="lightbox-overlay"
      role="dialog"
      aria-modal="true"
      aria-label="Photo lightbox"
      aria-hidden="true"
    >
      <button
        id="lightbox-close"
        class="absolute top-4 right-4 text-white/80 hover:text-white transition-colors p-2 rounded focus:outline-none focus:ring-2 focus:ring-white"
        aria-label="Close lightbox"
        tabindex="-1"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>

      <button
        id="lightbox-prev"
        class="absolute left-4 top-1/2 -translate-y-1/2 text-white/80 hover:text-white transition-colors p-3 rounded focus:outline-none focus:ring-2 focus:ring-white"
        aria-label="Previous photo"
        tabindex="-1"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <polyline points="15 18 9 12 15 6"></polyline>
        </svg>
      </button>

      <button
        id="lightbox-next"
        class="absolute right-4 top-1/2 -translate-y-1/2 text-white/80 hover:text-white transition-colors p-3 rounded focus:outline-none focus:ring-2 focus:ring-white"
        aria-label="Next photo"
        tabindex="-1"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <polyline points="9 18 15 12 9 6"></polyline>
        </svg>
      </button>

      <img
        id="lightbox-img"
        class="lightbox-img"
        src=""
        alt=""
        width="1200"
        height="800"
        aria-hidden="true"
      />
      <p id="lightbox-caption" class="lightbox-caption" aria-live="polite"></p>

      <p class="absolute bottom-4 right-4 text-white/40 text-xs tabular-nums" id="lightbox-counter" aria-live="polite" aria-atomic="true"></p>
    </div>

    <script>
      // ── Lightbox — vanilla JS, zero dependencies ──────────────────────────
      const overlay = document.getElementById('lightbox') as HTMLElement;
      const img = document.getElementById('lightbox-img') as HTMLImageElement;
      const captionEl = document.getElementById('lightbox-caption') as HTMLParagraphElement;
      const counterEl = document.getElementById('lightbox-counter') as HTMLParagraphElement;
      const closeBtn = document.getElementById('lightbox-close') as HTMLButtonElement;
      const prevBtn = document.getElementById('lightbox-prev') as HTMLButtonElement;
      const nextBtn = document.getElementById('lightbox-next') as HTMLButtonElement;

      let photos: { src: string; alt: string; caption?: string }[] = [];
      let currentIndex = 0;
      let triggerElement: HTMLElement | null = null;

      // Collect all gallery images on the page
      function collectPhotos() {
        photos = Array.from(document.querySelectorAll<HTMLElement>('.lightbox-trigger')).map((el) => {
          const imgEl = el.querySelector('img')!;
          return {
            src: el.dataset.lightboxSrc || imgEl.src,
            alt: imgEl.alt || '',
            caption: el.dataset.lightboxCaption || '',
          };
        });
      }

      function setFocusable(enabled: boolean) {
        const buttons = [closeBtn, prevBtn, nextBtn];
        buttons.forEach((btn) => {
          if (enabled) {
            btn.removeAttribute('tabindex');
          } else {
            btn.setAttribute('tabindex', '-1');
          }
        });
      }

      function openLightbox(index: number, opener: HTMLElement) {
        if (photos.length === 0) collectPhotos();
        currentIndex = index;
        triggerElement = opener;
        showPhoto(currentIndex);
        overlay.classList.add('is-open');
        overlay.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';
        setFocusable(true);
        closeBtn.focus();
      }

      function closeLightbox() {
        overlay.classList.remove('is-open');
        overlay.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = '';
        setFocusable(false);
        triggerElement?.focus();
      }

      function showPhoto(index: number) {
        const p = photos[index];
        if (!p) return;
        img.src = p.src;
        img.alt = p.alt;
        captionEl.textContent = p.caption || p.alt;
        counterEl.textContent = `${index + 1} / ${photos.length}`;
        prevBtn.style.display = photos.length <= 1 ? 'none' : '';
        nextBtn.style.display = photos.length <= 1 ? 'none' : '';
      }

      function prevPhoto() {
        currentIndex = (currentIndex - 1 + photos.length) % photos.length;
        showPhoto(currentIndex);
      }

      function nextPhoto() {
        currentIndex = (currentIndex + 1) % photos.length;
        showPhoto(currentIndex);
      }

      // Wire triggers
      document.addEventListener('click', (e) => {
        const trigger = (e.target as HTMLElement).closest<HTMLElement>('.lightbox-trigger');
        if (!trigger) return;
        e.preventDefault();
        if (photos.length === 0) collectPhotos();
        const allTriggers = Array.from(document.querySelectorAll<HTMLElement>('.lightbox-trigger'));
        const idx = allTriggers.indexOf(trigger);
        openLightbox(idx >= 0 ? idx : 0, trigger);
      });

      closeBtn.addEventListener('click', closeLightbox);

      overlay.addEventListener('click', (e) => {
        if (e.target === overlay) closeLightbox();
      });

      prevBtn.addEventListener('click', (e) => { e.stopPropagation(); prevPhoto(); });
      nextBtn.addEventListener('click', (e) => { e.stopPropagation(); nextPhoto(); });

      // Keyboard nav
      document.addEventListener('keydown', (e) => {
        if (!overlay.classList.contains('is-open')) return;
        if (e.key === 'Escape') closeLightbox();
        if (e.key === 'ArrowLeft') prevPhoto();
        if (e.key === 'ArrowRight') nextPhoto();

        // Focus trap
        if (e.key === 'Tab') {
          const focusable = overlay.querySelectorAll<HTMLElement>(
            'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
          );
          const first = focusable[0];
          const last = focusable[focusable.length - 1];
          if (e.shiftKey) {
            if (document.activeElement === first) { e.preventDefault(); last.focus(); }
          } else {
            if (document.activeElement === last) { e.preventDefault(); first.focus(); }
          }
        }
      });
    </script>
  </body>
</html>
