import React, { useState, useRef, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { SEO } from '@/components/seo';
import { SCHEMA_ORG } from '@/constants/seo';
import { Footer } from '@/components/layout/Footer';
import { SkipNav, PageTransitionWrapper } from '@/components/common';
import { X, Volume2, VolumeX, Play } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useBriefModal } from '@/contexts/BriefModalContext';
import Lenis from 'lenis';
import { PREMIUM_EASE, LUXURY_TRANSITIONS } from '@/constants/animations';
import { getPageTransitions } from '@/constants';
import { useNavigationDirection } from '@/contexts/NavigationDirectionContext';
import { useAnimationSession } from '@/contexts/AnimationSessionContext';
import { GoodFitCard } from '@/components/features/GoodFitCard';
import { useIsMobile } from '@/hooks/use-mobile';

/**
 * SEAMLESS LOADING STRATEGY - Expert Pattern
 *
 * Philosophy: Never show empty states. Content appears ready.
 *
 * 1. HOVER-BASED PRELOADING: When user hovers a card, preload that project
 *    - Most users hover before clicking (intent signal)
 *    - By click time, images are usually cached
 *
 * 2. LOADING GATE: Don't open modal until images are ready
 *    - Track which projects have loaded images
 *    - On click: if ready, open immediately; if not, wait briefly
 *    - Max wait time prevents infinite blocking
 *
 * 3. SYNCHRONIZED ANIMATION: Panel + content appear together
 *    - No staged fade-in that shows empty panel
 *    - Everything slides up fully loaded
 *
 * 4. CONSISTENT LENIS SCROLL: Same smooth scroll in modal as page
 */

// Track preload state per project
const preloadedImages = new Set<string>();
const projectsReady = new Set<string>();
const projectLoadCallbacks = new Map<string, (() => void)[]>();

// Preload AND decode a single image - ensures pixels are ready to paint
const preloadImage = async (src: string): Promise<void> => {
  if (preloadedImages.has(src)) return;

  try {
    const img = new Image();
    img.src = src;

    // Wait for both load AND decode - decode() ensures pixels are ready
    await img.decode();
    preloadedImages.add(src);
  } catch {
    // Don't block on errors (404, decode failure, etc.)
    preloadedImages.add(src); // Mark as "handled" to avoid retries
  }
};

// Get all images for a project
const getProjectImages = (project: typeof PROJECTS[0]): string[] => {
  const images = [project.sourceImage];
  project.outputs.forEach(output => {
    if (output.type === 'image') {
      images.push(output.src);
    }
  });
  return images;
};

// Preload all images for a specific project
const preloadProject = async (project: typeof PROJECTS[0]): Promise<void> => {
  if (projectsReady.has(project.id)) return;

  const images = getProjectImages(project);
  await Promise.all(images.map(preloadImage));

  projectsReady.add(project.id);

  // Notify any waiting callbacks
  const callbacks = projectLoadCallbacks.get(project.id) || [];
  callbacks.forEach(cb => cb());
  projectLoadCallbacks.delete(project.id);
};

// Check if project is ready
const isProjectReady = (projectId: string): boolean => {
  return projectsReady.has(projectId);
};

// Wait for project to be ready (with extended timeout for slow networks)
// Increased from 2s to 5s since we now preload on mount and hover
const waitForProject = (project: typeof PROJECTS[0], maxWait = 5000): Promise<void> => {
  if (isProjectReady(project.id)) return Promise.resolve();

  return new Promise((resolve) => {
    const timeout = setTimeout(() => {
      resolve(); // Open anyway after max wait
    }, maxWait);

    const callbacks = projectLoadCallbacks.get(project.id) || [];
    callbacks.push(() => {
      clearTimeout(timeout);
      resolve();
    });
    projectLoadCallbacks.set(project.id, callbacks);

    // Start loading if not already
    preloadProject(project);
  });
};

// Project Data with editorial descriptions
const PROJECTS = [{
  id: 'coffee-campaign',
  editionNumber: '01',
  label: 'Specialty Coffee',
  coverLine: 'A coffee campaign that warms before the first sip',
  category: 'Product + Lifestyle',
  season: 'Winter 2024',
  image: '/portfolio/coffee/hero-1.webp',
  sourceImage: '/portfolio/coffee/product.webp',
  client: 'Nordic Roast',
  logistics: 'None',
  turnaround: '5 days',
  pullQuote: 'One product photo transformed into a complete visual story.',
  description: 'To match the high value of this specialty coffee, I built a story of aristocratic ritual from a single product photo. The resulting aesthetic places the product within a refined environment to communicate its status as a premium luxury good.',
  outputs: [{
    type: 'image',
    src: '/portfolio/coffee/hero-1.webp',
    caption: 'Hero shot — Morning light'
  }, {
    type: 'image',
    src: '/portfolio/coffee/hero-2.webp',
    caption: 'Alternate hero — Soft focus'
  }, {
    type: 'video',
    src: '/portfolio/coffee/video-showcase.mp4',
    caption: 'Motion piece — 15 seconds'
  }, {
    type: 'image',
    src: '/portfolio/coffee/product-action.webp',
    caption: 'In use — The pour'
  }, {
    type: 'image',
    src: '/portfolio/coffee/product-gift.webp',
    caption: 'Gift presentation'
  }, {
    type: 'image',
    src: '/portfolio/coffee/product-preparation.webp',
    caption: 'Process — The craft'
  }]
}, {
  id: 'wool-coat',
  editionNumber: '02',
  label: 'Wool Coat Editorial',
  coverLine: 'Fashion photography without the photoshoot',
  category: 'Fashion / Apparel',
  season: 'Autumn 2024',
  image: '/portfolio/wool-coat/hero-1.webp',
  sourceImage: '/portfolio/wool-coat/product-photo.webp',
  client: 'Vogue Lite',
  logistics: 'None',
  turnaround: '4 days',
  pullQuote: 'The garment speaks. We just gave it a stage.',
  description: 'I expanded a standalone product photo into a visual story defined by heritage and grace. The presence of classical sculpture elevates the presentation to imply that this coat is not just a trend but a timeless element of quiet luxury.',
  outputs: [{
    type: 'image',
    src: '/portfolio/wool-coat/hero-1.webp',
    caption: 'Editorial hero'
  }, {
    type: 'image',
    src: '/portfolio/wool-coat/hero-2.webp',
    caption: 'Portrait close-up'
  }, {
    type: 'image',
    src: '/portfolio/wool-coat/hero-3.webp',
    caption: 'Over-shoulder look'
  }, {
    type: 'image',
    src: '/portfolio/wool-coat/mood-shot.webp',
    caption: 'Classical profile'
  }, {
    type: 'image',
    src: '/portfolio/wool-coat/mood-shot-2.webp',
    caption: 'Lifestyle context'
  }, {
    type: 'image',
    src: '/portfolio/wool-coat/mood-shot-4.webp',
    caption: 'Gallery walk'
  }, {
    type: 'image',
    src: '/portfolio/wool-coat/detail-shot.webp',
    caption: 'Sculpture moment'
  }, {
    type: 'image',
    src: '/portfolio/wool-coat/close-up-action.webp',
    caption: 'Texture detail'
  }]
}];

/**
 * VideoItem - Click-to-Play Video Component
 * Starts WITH SOUND on first play. Shows poster thumbnail.
 */
const VideoItem = ({ src, poster }: { src: string; poster: string }) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false); // Start with sound!
  const videoRef = useRef<HTMLVideoElement>(null);

  const handlePlayToggle = () => {
    if (!videoRef.current) return;

    if (isPlaying) {
      videoRef.current.pause();
      setIsPlaying(false);
    } else {
      // Play with sound from the start
      videoRef.current.muted = false;
      videoRef.current.play().catch(() => {
        // If autoplay with sound blocked, try muted
        if (videoRef.current) {
          videoRef.current.muted = true;
          setIsMuted(true);
          videoRef.current.play();
        }
      });
      setIsPlaying(true);
    }
  };

  const handleSoundToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  const handleEnded = () => {
    setIsPlaying(false);
    if (videoRef.current) {
      videoRef.current.currentTime = 0;
    }
  };

  return (
    <div
      className="relative group cursor-pointer bg-neutral-200"
      onClick={handlePlayToggle}
    >
      {/* Poster image shown when not playing */}
      {!isPlaying && (
        <img
          src={poster}
          alt="Video thumbnail"
          decoding="sync"
          loading="eager"
          className="w-full h-auto max-h-[70vh] lg:max-h-none block"
        />
      )}

      {/* Video element - only visible when playing */}
      <video
        ref={videoRef}
        src={src}
        muted={isMuted}
        playsInline
        preload="metadata"
        onEnded={handleEnded}
        className={`w-full h-auto max-h-[70vh] lg:max-h-none block ${isPlaying ? 'block' : 'hidden'}`}
      />

      {/* Play button overlay */}
      {!isPlaying && (
        <div className="absolute inset-0 flex items-center justify-center bg-black/20 transition-opacity">
          <div className="w-16 h-16 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center shadow-lg">
            <Play size={24} className="text-text-primary ml-1" fill="currentColor" />
          </div>
        </div>
      )}

      {/* Sound toggle - only when playing */}
      {isPlaying && (
        <button
          onClick={handleSoundToggle}
          className="absolute bottom-3 right-3 p-2 bg-black/20 hover:bg-black/40 rounded-full text-white transition-colors backdrop-blur-md"
          aria-label={isMuted ? "Unmute video" : "Mute video"}
        >
          {isMuted ? <VolumeX size={14} /> : <Volume2 size={14} />}
        </button>
      )}

      {/* Video label - only when not playing */}
      {!isPlaying && (
        <span className="absolute bottom-3 left-3 px-2 py-1 bg-black/40 backdrop-blur-sm rounded text-white text-xs font-mono">
          Video
        </span>
      )}
    </div>
  );
};

/**
 * MagazineCover - Project Card
 * Preloads project images on hover for instant modal opening
 */
const MagazineCover = ({
  project,
  onClick,
  isLoading
}: {
  project: typeof PROJECTS[0];
  onClick: () => void;
  isLoading?: boolean;
}) => {
  // Crossfade state — cover image fades in over 400ms once decoded.
  // Until then, the warm paper-tone surface fills the card so the grid
  // is never visually empty, never pixelated, never "loading".
  const [coverLoaded, setCoverLoaded] = useState(false);

  const handleMouseEnter = () => {
    // Start preloading this project's images on hover
    preloadProject(project);
  };

  return (
    <article
      onClick={onClick}
      onMouseEnter={handleMouseEnter}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(); } }}
      tabIndex={0}
      role="button"
      className="group cursor-pointer"
    >
      <div
        className={`relative aspect-[3/4] rounded-md overflow-hidden shadow-lg border border-black/10 transition-all duration-500 ease-out group-hover:-translate-y-2 group-hover:shadow-2xl ${isLoading ? 'pointer-events-none' : ''}`}
        style={{ backgroundColor: 'hsl(var(--surface-alt))' }}
      >
        <img
          src={project.image}
          alt={`${project.label} — ${project.coverLine}. Edition ${project.editionNumber} by Dainn Editions.`}
          width={1100}
          height={1463}
          decoding="async"
          loading="eager"
          fetchPriority="high"
          onLoad={() => setCoverLoaded(true)}
          className="absolute inset-0 w-full h-full object-cover transition-transform duration-700 ease-out group-hover:scale-[1.02]"
          style={{
            opacity: coverLoaded ? 1 : 0,
            transitionProperty: 'transform, opacity',
            transitionDuration: '700ms, 400ms',
            transitionTimingFunction: 'cubic-bezier(0.16, 1, 0.3, 1), cubic-bezier(0.16, 1, 0.3, 1)',
          }}
        />

        <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent pointer-events-none" />

        {/* Loading indicator - subtle ring on card itself */}
        {isLoading && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/30 z-10">
            <div className="w-8 h-8 border-2 border-white/30 border-t-white rounded-full animate-spin" />
          </div>
        )}

        <div className="absolute bottom-0 left-0 right-0 p-4 md:p-6 3xl:p-8 4xl:p-10 space-y-3 3xl:space-y-4 4xl:space-y-5">
          <span className="label-caps-mono !text-white/70">
            {project.category}
          </span>

          <h2 className="font-headline text-2xl md:text-3xl lg:text-4xl 3xl:text-5xl 4xl:text-6xl text-white leading-[1.1]">
            {project.label}
          </h2>

          <p className="font-body text-xs md:text-sm 3xl:text-base 4xl:text-lg text-white/80 max-w-[90%] leading-relaxed">
            {project.coverLine}
          </p>
        </div>

        <div className="absolute top-2 bottom-2 right-0 w-[3px] bg-gradient-to-l from-black/20 to-transparent pointer-events-none" />
      </div>
    </article>
  );
};

/**
 * MODAL ANIMATION - Uses LUXURY_TRANSITIONS for consistency
 *
 * Same animation timing as Brief panel and Mobile Menu.
 * Enter: 0.65s with gradual start, momentum build, graceful deceleration
 * Exit: 0.75s with controlled deceleration, intentional "breath" moment
 */
const MODAL_TRANSITIONS = {
  backdrop: {
    initial: { opacity: 0 },
    animate: { opacity: 1 },
    exit: { opacity: 0 },
    transition: { duration: 0.5, ease: [0.16, 1, 0.3, 1] as const }
  }
};

const Editions: React.FC = () => {
  const { openBriefModal } = useBriefModal();
  const { skipAnimation, markAnimated } = useAnimationSession();
  const shouldAnimate = !skipAnimation('editions-page');
  const [selectedProject, setSelectedProject] = useState<typeof PROJECTS[0] | null>(null);
  const [loadingProjectId, setLoadingProjectId] = useState<string | null>(null);
  const modalScrollRef = useRef<HTMLDivElement>(null);
  const direction = useNavigationDirection();
  const isMobile = useIsMobile();
  const scrollYRef = useRef(0);
  const lenisRef = useRef<Lenis | null>(null);
  const rafIdRef = useRef<number | null>(null);

  // Escape key handler for modal
  useEffect(() => {
    if (!selectedProject) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') closeModal();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  // Mark page as animated after animations complete
  useEffect(() => {
    if (shouldAnimate) {
      const timer = setTimeout(() => {
        markAnimated('editions-page');
      }, 1200);
      return () => clearTimeout(timer);
    }
  }, [shouldAnimate, markAnimated]);

  // Preload first project on mount - most likely to be clicked
  // This runs in background, doesn't block render
  useEffect(() => {
    if (PROJECTS.length > 0) {
      preloadProject(PROJECTS[0]);
      // Also preload second project with slight delay
      const timer = setTimeout(() => {
        if (PROJECTS.length > 1) {
          preloadProject(PROJECTS[1]);
        }
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, []);

  const transitions = getPageTransitions(direction, isMobile);

  // Initialize Lenis for modal scroll (consistent with page scroll)
  useEffect(() => {
    if (!selectedProject || !modalScrollRef.current || isMobile) return;

    // Clean up existing
    if (lenisRef.current) {
      lenisRef.current.destroy();
      lenisRef.current = null;
    }
    if (rafIdRef.current) {
      cancelAnimationFrame(rafIdRef.current);
      rafIdRef.current = null;
    }

    // Initialize after modal animation starts
    const timer = setTimeout(() => {
      if (!modalScrollRef.current) return;

      lenisRef.current = new Lenis({
        wrapper: modalScrollRef.current,
        content: modalScrollRef.current,
        duration: 1.2,
        easing: t => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
        orientation: 'vertical',
        gestureOrientation: 'vertical',
        smoothWheel: true,
        wheelMultiplier: 1,
        touchMultiplier: 2
      });

      function raf(time: number) {
        lenisRef.current?.raf(time);
        rafIdRef.current = requestAnimationFrame(raf);
      }
      rafIdRef.current = requestAnimationFrame(raf);
    }, 200);

    return () => {
      clearTimeout(timer);
      if (rafIdRef.current) {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = null;
      }
      if (lenisRef.current) {
        lenisRef.current.destroy();
        lenisRef.current = null;
      }
    };
  }, [selectedProject, isMobile]);

  // Lock body scroll when modal is open
  useEffect(() => {
    if (selectedProject) {
      const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
      scrollYRef.current = window.scrollY;

      document.documentElement.style.overflow = 'hidden';
      document.body.style.overflow = 'hidden';
      document.body.style.position = 'fixed';
      document.body.style.top = `-${scrollYRef.current}px`;
      document.body.style.left = '0';
      document.body.style.right = '0';
      document.body.style.width = '100%';
      document.body.style.paddingRight = `${scrollbarWidth}px`;

      return () => {
        const savedScrollY = scrollYRef.current;
        document.documentElement.style.overflow = '';
        document.body.style.overflow = '';
        document.body.style.position = '';
        document.body.style.top = '';
        document.body.style.left = '';
        document.body.style.right = '';
        document.body.style.width = '';
        document.body.style.paddingRight = '';
        window.scrollTo({ top: savedScrollY, behavior: 'instant' });
      };
    }
  }, [selectedProject]);

  const closeModal = () => {
    const savedScrollY = scrollYRef.current;
    setSelectedProject(null);

    requestAnimationFrame(() => {
      document.documentElement.style.overflow = '';
      document.body.style.overflow = '';
      document.body.style.position = '';
      document.body.style.top = '';
      document.body.style.left = '';
      document.body.style.right = '';
      document.body.style.width = '';
      document.body.style.paddingRight = '';
      window.scrollTo({ top: savedScrollY, behavior: 'instant' });
    });
  };

  // Loading gate pattern: wait for images before opening modal
  const handleProjectClick = useCallback(async (project: typeof PROJECTS[0]) => {
    // If already ready (from hover preload or mount preload), open immediately
    if (isProjectReady(project.id)) {
      setSelectedProject(project);
      return;
    }

    // Show loading state on card
    setLoadingProjectId(project.id);

    // Wait for images to load (extended timeout for slow networks)
    await waitForProject(project, 5000);

    // Clear loading and open modal
    setLoadingProjectId(null);
    setSelectedProject(project);
  }, []);

  return (
    <>
      <SEO
        page="editions"
        structuredData={[
          SCHEMA_ORG.organization,
          SCHEMA_ORG.breadcrumbs.editions,
        ]}
      />

      <PageTransitionWrapper
        className=""
        transitions={transitions}
      >
        <SkipNav />

        <main className="flex-grow pt-44 pb-24 sm:pt-32 sm:pb-28 md:pt-40 md:pb-36 lg:pt-48 lg:pb-44 xl:pt-56 xl:pb-52 2xl:pt-60 2xl:pb-56 3xl:pt-64 3xl:pb-60 4xl:pt-72 4xl:pb-68 5xl:pt-80 5xl:pb-72">
          <div className="container mx-auto px-4 sm:px-5 md:px-6 3xl:px-8 4xl:px-12">

            {/* Editorial Header */}
            <header className="mb-10 sm:mb-12 md:mb-16 lg:mb-24 3xl:mb-28 4xl:mb-32 max-w-4xl 3xl:max-w-5xl 4xl:max-w-6xl mx-auto text-center flex flex-col items-center">
              <motion.div
                initial={shouldAnimate ? { opacity: 0, y: 12 } : { opacity: 1, y: 0 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: shouldAnimate ? 0.5 : 0, ease: PREMIUM_EASE }}
                className="mb-3 md:mb-4 3xl:mb-5 4xl:mb-6"
              >
                <span className="label-caps">
                  The Collection
                </span>
              </motion.div>

              <motion.h1
                initial={shouldAnimate ? { opacity: 0, y: 20 } : { opacity: 1, y: 0 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: shouldAnimate ? 0.7 : 0, delay: shouldAnimate ? 0.1 : 0, ease: PREMIUM_EASE }}
                className="font-headline text-hero-mobile md:text-hero-desktop 3xl:text-hero-3xl 4xl:text-hero-4xl 5xl:text-hero-5xl text-text-primary mb-5 md:mb-6 3xl:mb-8 4xl:mb-10"
              >
                Selected editions
              </motion.h1>

              <motion.p
                initial={shouldAnimate ? { opacity: 0, y: 16 } : { opacity: 1, y: 0 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: shouldAnimate ? 0.6 : 0, delay: shouldAnimate ? 0.2 : 0, ease: PREMIUM_EASE }}
                className="font-body text-body-mobile md:text-body-desktop 3xl:text-body-3xl 4xl:text-body-4xl text-text-secondary max-w-2xl 3xl:max-w-3xl 4xl:max-w-4xl mx-auto"
              >
                Each edition begins with a single source image and expands into a complete visual campaign.
                No photoshoots. No logistics. Just focused creative direction.
              </motion.p>
            </header>

            {/* Magazine Cover Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-5 sm:gap-6 md:gap-8 lg:gap-10 3xl:gap-12 4xl:gap-14 5xl:gap-16 max-w-6xl mx-auto">
              {PROJECTS.map((project) => (
                <MagazineCover
                  key={project.id}
                  project={project}
                  onClick={() => handleProjectClick(project)}
                  isLoading={loadingProjectId === project.id}
                />
              ))}
            </div>

            {/* Editorial Statement */}
            <motion.div
              initial={shouldAnimate ? { opacity: 0 } : { opacity: 1 }}
              whileInView={shouldAnimate ? { opacity: 1 } : undefined}
              viewport={{ once: true, margin: "-100px" }}
              transition={{ duration: 0.8, ease: PREMIUM_EASE }}
              className="mt-16 sm:mt-20 md:mt-28 3xl:mt-32 4xl:mt-36 max-w-4xl mx-auto px-6"
            >
              <p className="font-headline text-4xl sm:text-5xl md:text-6xl text-text-primary text-center leading-[1.1] tracking-tight">
                Refining every detail to match your true standards.
              </p>
            </motion.div>



            {/* CTA */}
            <div className="mt-14 sm:mt-18 md:mt-24 3xl:mt-28 4xl:mt-32 5xl:mt-40 max-w-5xl 3xl:max-w-6xl 4xl:max-w-7xl 5xl:max-w-[1800px] mx-auto">
              <GoodFitCard />
            </div>

          </div>
        </main>

        <Footer />
      </PageTransitionWrapper>

      {/* Modal Backdrop - No backdrop-blur for performance */}
      <AnimatePresence>
        {selectedProject && (
          <motion.div
            {...MODAL_TRANSITIONS.backdrop}
            onClick={closeModal}
            className="fixed inset-0 bg-black/70 z-[90] touch-none"
          />
        )}
      </AnimatePresence>

      {/* Editorial Magazine Interior Modal */}
      <AnimatePresence>
        {selectedProject && (
          <motion.div
            initial={{ y: '100%', opacity: 1 }}
            animate={{
              y: 0,
              opacity: 1,
              transition: LUXURY_TRANSITIONS.enter
            }}
            exit={{
              y: '100%',
              opacity: 1,
              transition: LUXURY_TRANSITIONS.exit
            }}
            className="fixed inset-0 z-[100] flex items-end lg:items-center justify-center p-0 lg:p-6 pointer-events-none"
          >
            {/* Glass Frame Wrapper - No backdrop-blur for performance */}
            <div
              className="w-full lg:max-w-[92vw] pointer-events-auto lg:p-3 lg:bg-surface/95 lg:border lg:border-border-quiet/30 lg:shadow-2xl"
              style={{ borderRadius: 'calc(1rem + 0.75rem)' }}
            >
              {/* Inner Modal - CSS containment for isolated paint/layout */}
              <div
                className="w-full h-[90vh] lg:h-[85vh] bg-[#f8f7f5] rounded-t-2xl lg:rounded-2xl shadow-2xl lg:shadow-none overflow-hidden flex flex-col border border-black/10 lg:border-0 relative"
                style={{ contain: 'layout paint style' }}
                onWheel={e => e.stopPropagation()}
              >
                {/* Modal Header */}
                <div className="flex items-center justify-between px-6 py-5 md:px-8 md:py-6 3xl:px-10 3xl:py-7 4xl:px-12 4xl:py-8 border-b border-black/10 bg-[#f8f7f5] sticky top-0 z-10">
                  <div className="flex items-center gap-6">
                    <span className="label-caps">
                      Edition №{selectedProject.editionNumber}
                    </span>
                  </div>

                  <div className="flex items-center gap-4">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={closeModal}
                      className="rounded-full hover:bg-black/5 transition-colors duration-200"
                    >
                      <X size={20} />
                    </Button>
                  </div>
                </div>

                {/* Modal Content - Visible immediately (images preloaded) */}
                <div className="flex-grow min-h-0 flex flex-col lg:flex-row overflow-y-auto lg:overflow-hidden overscroll-contain">
                  {/* LEFT SIDE - Source + Info */}
                  <div className="flex-shrink-0 lg:w-[420px] xl:w-[480px] 2xl:w-[520px] 3xl:w-[580px] 4xl:w-[660px] bg-[#f8f7f5] lg:border-r border-black/10 lg:overflow-y-auto">
                    <div className="p-6 lg:p-8 xl:p-10 3xl:p-12 4xl:p-14 lg:sticky lg:top-0 space-y-6 3xl:space-y-8 4xl:space-y-10">
                      {/* Title */}
                      <div className="space-y-3 3xl:space-y-4 4xl:space-y-5">
                        <span className="label-caps">
                          {selectedProject.category}
                        </span>
                        <h1 className="font-headline text-3xl lg:text-4xl xl:text-5xl 3xl:text-6xl 4xl:text-7xl text-text-primary leading-[1.1]">
                          {selectedProject.label}
                        </h1>
                      </div>

                      {/* Source Image */}
                      <div className="relative">
                        <div className="bg-white p-4 rounded-sm shadow-md border border-black/5">
                          <img
                            src={selectedProject.sourceImage}
                            alt={`Source product photograph for ${selectedProject.label} — the single image used as the starting point for this edition.`}
                            decoding="sync"
                            loading="eager"
                            className="w-full rounded-sm"
                          />
                        </div>
                        <span className="absolute -bottom-2 left-4 label-caps bg-[#f8f7f5] px-2">
                          Source
                        </span>
                      </div>

                      {/* Description */}
                      <p className="font-body text-body-mobile md:text-body-desktop 3xl:text-body-3xl 4xl:text-body-4xl text-text-secondary leading-relaxed">
                        {selectedProject.description}
                      </p>

                      {/* CTA - Desktop */}
                      <div className="hidden lg:block pt-6 3xl:pt-8">
                        <Button
                          variant="signal"
                          size="lg"
                          onClick={() => {
                            closeModal();
                            setTimeout(() => openBriefModal(), 300);
                          }}
                          className="w-full text-base 3xl:text-lg"
                        >
                          Start a Brief
                        </Button>
                      </div>
                    </div>
                  </div>

                  {/* RIGHT SIDE - Outputs with Lenis scroll */}
                  <div
                    ref={modalScrollRef}
                    className="bg-[#f0efed] lg:flex-grow lg:min-h-0 lg:overflow-y-auto lg:overscroll-contain"
                  >
                    <div className="px-6 py-6 md:px-8 md:py-8 lg:px-10 lg:py-10 3xl:px-12 3xl:py-12 4xl:px-14 4xl:py-14">
                      <div className="flex flex-col gap-4 lg:grid lg:grid-cols-3 lg:gap-4 3xl:gap-5 4xl:gap-6">
                        {selectedProject.outputs.map((output, idx) => (
                          <div key={idx}>
                            <div className="overflow-hidden rounded-sm 3xl:rounded-md lg:bg-white lg:shadow-md lg:border lg:border-black/5">
                              {output.type === 'video' ? (
                                <VideoItem src={output.src} poster={selectedProject.image} />
                              ) : (
                                <img
                                  src={output.src}
                                  alt={`${selectedProject.label} — ${output.caption ?? `frame ${idx + 1}`}`}
                                  decoding="sync"
                                  loading="eager"
                                  className="w-full h-auto block"
                                />
                              )}
                            </div>
                          </div>
                        ))}
                      </div>

                      {/* Pull Quote */}
                      <div className="py-10 3xl:py-12 4xl:py-14 mt-8 3xl:mt-10 4xl:mt-12 border-t border-black/10">
                        <blockquote className="text-center max-w-xl 3xl:max-w-2xl 4xl:max-w-3xl mx-auto">
                          <p className="font-headline text-subsection-mobile md:text-subsection-desktop 3xl:text-subsection-3xl 4xl:text-subsection-4xl text-text-primary leading-snug">
                            "{selectedProject.pullQuote}"
                          </p>
                        </blockquote>
                      </div>

                      {/* CTA - Mobile */}
                      <div className="lg:hidden text-center pb-6">
                        <Button
                          variant="signal"
                          size="lg"
                          onClick={() => {
                            closeModal();
                            setTimeout(() => openBriefModal(), 300);
                          }}
                          className="px-8"
                        >
                          Start a Brief
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence >
    </>
  );
};

export default Editions;
