/* ============================================================
   Villa 44 Badulla — THIS IS YOUR CHANCE: EXPERIENCE SRI LANKA
   Cinematic Scroll-Driven Interactive React 18 Component
   Inspired by https://searic.rotaract3220.org/
   ============================================================ */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ── Experience Destinations Database (6 Curated Cinematic Chapters) ── */
const EXPERIENCE_DESTINATIONS = [
  {
    id: 'highlands',
    number: '01',
    category: 'highlands',
    categoryLabel: 'The Highlands',
    title: 'Misty Ridges & Ceylon Tea Estates',
    subtitle: 'THE HIGHLANDS',
    tagline: 'Misty mornings. Endless tea estates. Crisp mountain air.',
    description: 'Awaken to emerald slopes veiled in morning mist. Wander through century-old colonial tea estates where Ceylon tea leaves glisten under the gentle dawn sun, framed by the majestic silhouettes of the Uva range.',
    distance: 'On your doorstep · 10–30 min from Villa 44',
    elevation: '1,050 – 1,890 m',
    bestTime: '06:00 AM – 09:30 AM (Golden Dawn Mist)',
    highlights: ['Centuries-old tea plantations', 'Panoramic Uva valley vistas', 'Cool mountain breeze & birdsong', 'Exclusive artisan tea tasting'],
    poster: 'images/tea.jpg',
    videoSrc: 'https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/hike.mp4',
    detailStory: 'The highlands surrounding Villa 44 are home to some of the world\'s finest single-origin tea terroirs. Stroll through the tea trails of Badulla and Bandarawela, witness skilled tea pluckers amidst the morning dew, and savor fresh high-grown brew overlooking endless green horizons.',
    conciergeNote: 'Our private chauffeur will arrange a sunrise tea estate walk followed by a warm Ceylon breakfast basket prepared by our private chef.'
  },
  {
    id: 'waterfalls',
    number: '02',
    category: 'waterfalls',
    categoryLabel: 'Cascading Waters',
    title: 'Dunhinda & Highland Cascades',
    subtitle: 'WATERFALLS',
    tagline: 'Follow the sound of cascading water through the hills.',
    description: 'Feel the thunderous roar and cool spray of Dunhinda Falls — known as the "Smoky Falls" of Sri Lanka — where river waters plunge 64 meters into a lush jungle gorge surrounded by pristine biodiversity.',
    distance: '20 min drive from Villa 44',
    elevation: '640 m cascade gorge',
    bestTime: '08:30 AM – 11:30 AM (Bright Sunshine & Rainbows)',
    highlights: ['Dunhinda "Smoky" Falls', 'Turquoise natural rock pools', 'Jungle canopy nature walk', 'Diyaluma & Ravana Falls day routes'],
    poster: 'images/dunhinda_falls.jpg',
    videoSrc: 'https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/pearl.mp4',
    detailStory: 'Fed by the Badulu Oya, Dunhinda Falls creates an ethereal misty cloud that drifts through dense forest valleys. Follow the scenic 1.5 km pathway accompanied by native monkeys, wild butterflies, and the tranquil sounds of untouched nature.',
    conciergeNote: 'Combine Dunhinda Falls with a refreshing dip at nearby natural stream cascades, accompanied by a custom chilled picnic prepared by Villa 44.'
  },
  {
    id: 'railway',
    number: '03',
    category: 'railways',
    categoryLabel: 'The Iconic Journey',
    title: 'Nine Arches Bridge & Blue Train',
    subtitle: 'THE JOURNEY',
    tagline: 'Scenic roads, winding railways and unforgettable views.',
    description: 'Traverse the legendary British-era viaduct in Demodara and watch the iconic bright blue train curve gracefully through misty jungle valleys and emerald hills in a timeless portrait of highland romance.',
    distance: '35 min scenic drive from Villa 44',
    elevation: '1,041 m',
    bestTime: '09:20 AM / 11:45 AM / 03:30 PM (Train Passings)',
    highlights: ['Demodara 9 Arches Viaduct', 'Scenic train crossing photo-spots', 'Hidden jungle walking trails', 'Historic Demodara spiral railway loop'],
    poster: 'images/nine_arch_bridge.jpg',
    videoSrc: 'https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/177127-856658451_tiny.mp4',
    detailStory: 'Commissioned in 1921 and built entirely of stone, brick, and cement without a single piece of steel, the Nine Arches Bridge stands as one of Sri Lanka\'s most photogenic and celebrated engineering masterpieces.',
    conciergeNote: 'We provide VIP timing schedules for train passages so you capture cinematic photographs without the crowded peak rush.'
  },
  {
    id: 'wildlife',
    number: '04',
    category: 'wildlife',
    categoryLabel: 'Wild Sri Lanka',
    title: 'Untamed Sanctuaries & Cloud Forests',
    subtitle: 'WILD SRI LANKA',
    tagline: 'Discover the untamed side of the island.',
    description: 'Venture into the mystical plains of Horton Plains and nearby wild sanctuaries. Encounter sambar deer grazing in misty grasslands, endemic highland birdlife, and wild elephants roaming ancient island corridors.',
    distance: '1.5 – 2.5 hrs scenic day expedition',
    elevation: '2,100 m plateau',
    bestTime: '06:00 AM (Clear View of World\'s End)',
    highlights: ['Horton Plains "World\'s End" sheer cliff', 'Baker\'s Waterfall forest loop', 'Wild elephant habitat corridors', 'Endemic cloud forest bird species'],
    poster: 'images/horton_plains.jpg',
    videoSrc: 'https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/246461_tiny.mp4',
    detailStory: 'From windswept montane grasslands to dense rainforest fringes, Sri Lanka is a global biodiversity hotspot. Explore the dramatic 880-meter vertical drop of World\'s End, where southern coastal plains unfold far beneath the cloud cover.',
    conciergeNote: 'Our concierge arranges private 4x4 safari and national park permits with experienced local naturalist trackers.'
  },
  {
    id: 'culture',
    number: '05',
    category: 'culture',
    categoryLabel: 'Sacred Soul & Heritage',
    title: 'Ancient Shrines & Timeless Traditions',
    subtitle: 'THE CULTURE',
    tagline: 'Experience the warmth, rhythm and soul of Sri Lanka.',
    description: 'Immerse yourself in over two millennia of sacred heritage — from the historic Muthiyangana Raja Maha Viharaya and 16th-century Bogoda wooden bridge to Adam\'s Peak sunrise pilgrimages and traditional Kandyan drumbeats.',
    distance: '15–40 min to key local heritage sites',
    elevation: '680 – 2,243 m',
    bestTime: 'Sunrise Puja & Twilight Chants',
    highlights: ['Muthiyangana Sacred Temple', '16th Century Bogoda Wooden Bridge', 'Kandyan drumming & cultural dance', 'Warm highland village hospitality'],
    poster: 'images/adams_peak.jpg',
    videoSrc: 'https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/culture.mp4',
    detailStory: 'Sri Lanka\'s cultural tapestry is woven with spiritual warmth, ancient rock art, and monastic sanctuaries nestled quietly within mountain forests. Experience authentic blessings, intricate wood architecture, and genuine island smiles.',
    conciergeNote: 'Private guided cultural walks with respectful temple attire guidelines and private tuk-tuk transfers arranged upon request.'
  },
  {
    id: 'peaks',
    number: '06',
    category: 'peaks',
    categoryLabel: 'Sunsets & Horizons',
    title: 'Ella Rock & Namunukula Ridge',
    subtitle: 'PEAKS & SUNSETS',
    tagline: 'Where dramatic mountain crests meet golden skies.',
    description: 'Scale the scenic heights of Ella Rock and Namunukula Peak, where golden hour paints the mountain folds in warm amber hues and the starry hill-country night sky unfolds in crystal clarity.',
    distance: '30–45 min to hiking trailheads',
    elevation: '1,320 – 2,036 m',
    bestTime: '04:30 PM – 06:45 PM (Sunset Golden Hour)',
    highlights: ['Ella Rock sheer gap panorama', 'Namunukula 9-peak mountain crest', 'Little Adam\'s Peak gentle climb', 'Astrophotography & sunset verandas'],
    poster: 'images/ella_rock.jpg',
    videoSrc: 'https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/hospitality.mp4',
    detailStory: 'Rising prominently over the Badulla valley, Namunukula stands as the guardian peak of the province. Sunset over Ella Gap offers one of the most celebrated vistas in Asia, casting golden rays through dramatic cloud formations.',
    conciergeNote: 'Return from your sunset hike to a roaring bonfire and bespoke candlelit lawn dinner on Villa 44\'s private terrace.'
  }
];

/* ── Category Filters ── */
const CATEGORIES = [
  { key: 'all', label: 'All Experiences' },
  { key: 'highlands', label: 'Highlands' },
  { key: 'waterfalls', label: 'Waterfalls' },
  { key: 'railways', label: 'Railways' },
  { key: 'wildlife', label: 'Wildlife' },
  { key: 'culture', label: 'Culture & Sacred' },
  { key: 'peaks', label: 'Peaks & Sunsets' }
];

/* ============================================================
   Subcomponent: CinematicVideo
   Robust Autoplaying Video Element with Controls & Fallbacks
   ============================================================ */
function CinematicVideo({ src, poster, className, controls = false, autoPlay = true, isHero = false }) {
  const videoRef = useRef(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(true);
  const [isLoaded, setIsLoaded] = useState(false);

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

    video.muted = true;
    const playPromise = video.play();
    if (playPromise !== undefined) {
      playPromise
        .then(() => setIsPlaying(true))
        .catch(() => {
          video.muted = true;
          video.play().then(() => setIsPlaying(true)).catch(() => {});
        });
    }
  }, [src]);

  const toggleSound = (e) => {
    e.stopPropagation();
    if (!videoRef.current) return;
    const nextMuted = !videoRef.current.muted;
    videoRef.current.muted = nextMuted;
    setIsMuted(nextMuted);
  };

  const togglePlay = (e) => {
    e.stopPropagation();
    if (!videoRef.current) return;
    if (videoRef.current.paused) {
      videoRef.current.play();
      setIsPlaying(true);
    } else {
      videoRef.current.pause();
      setIsPlaying(false);
    }
  };

  return (
    <div className={`cinematic-video-wrap ${className || ''}`}>
      <img
        src={poster}
        alt="Video backdrop"
        className={`cinematic-poster-img ${isLoaded ? 'cinematic-poster-faded' : ''}`}
        loading="lazy"
      />
      <video
        ref={videoRef}
        src={src}
        poster={poster}
        autoPlay={autoPlay}
        loop
        muted={isMuted}
        playsInline
        preload="auto"
        crossOrigin="anonymous"
        onCanPlay={() => setIsLoaded(true)}
        className={`cinematic-video-element ${isLoaded ? 'cinematic-video-ready' : ''}`}
      />
      {controls && (
        <div className="cinematic-video-controls" onClick={(e) => e.stopPropagation()}>
          <button
            type="button"
            className="cinematic-control-btn"
            onClick={togglePlay}
            aria-label={isPlaying ? 'Pause video' : 'Play video'}
            title={isPlaying ? 'Pause' : 'Play'}
          >
            {isPlaying ? (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                <rect x="6" y="4" width="4" height="16" rx="1" />
                <rect x="14" y="4" width="4" height="16" rx="1" />
              </svg>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                <polygon points="5 3 19 12 5 21 5 3" />
              </svg>
            )}
          </button>
          <button
            type="button"
            className="cinematic-control-btn"
            onClick={toggleSound}
            aria-label={isMuted ? 'Unmute video' : 'Mute video'}
            title={isMuted ? 'Unmute Sound' : 'Mute Sound'}
          >
            {isMuted ? (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" />
                <line x1="23" y1="9" x2="17" y2="15" />
                <line x1="17" y1="9" x2="23" y2="15" />
              </svg>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" />
                <path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07" />
              </svg>
            )}
          </button>
        </div>
      )}
    </div>
  );
}

/* ============================================================
   Subcomponent: HeroVideoTrio
   Signature 3-Video Layout from https://searic.rotaract3220.org/
   ============================================================ */
function HeroVideoTrio({ onSelectChapter }) {
  return (
    <div className="exp-hero-trio-wrapper">
      <div className="exp-hero-trio-container">
        {/* Video 1 (Left): Demodara Nine Arches Viaduct */}
        <div
          className="exp-hero-video-card exp-hero-side exp-hero-left"
          onClick={() => onSelectChapter('railway')}
          role="button"
          tabIndex={0}
          aria-label="Experience Nine Arches Bridge and Highland Railway"
        >
          <CinematicVideo
            src="https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/177127-856658451_tiny.mp4"
            poster="https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/Ancient.webp"
          />
          <div className="exp-hero-scrim"></div>
          <div className="exp-hero-info">
            <span className="exp-hero-badge">✦ 01 · ICONIC RAILWAYS</span>
            <h4 className="exp-hero-title">Nine Arches &amp; Blue Train</h4>
            <p className="exp-hero-desc">British-era viaduct in Demodara</p>
          </div>
          <div className="exp-hero-hover-indicator">
            <span>Explore Route</span>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <polyline points="9 18 15 12 9 6" />
            </svg>
          </div>
        </div>

        {/* Video 2 (Center): Tall Hero Spotlight Feature */}
        <div
          className="exp-hero-video-card exp-hero-center"
          onClick={() => onSelectChapter('waterfalls')}
          role="button"
          tabIndex={0}
          aria-label="Experience Sri Lanka Cinematic Spotlight"
        >
          <CinematicVideo
            src="https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/ticket.mp4"
            poster="images/dining.jpg"
            controls={true}
            isHero={true}
          />
          <div className="exp-hero-scrim exp-hero-scrim-center"></div>
          <div className="exp-hero-center-content">
            <div className="exp-hero-live-pill">
              <span className="exp-live-pulse-dot"></span>
              <span className="exp-live-text">CINEMATIC SRI LANKA</span>
            </div>
            <h3 className="exp-hero-center-heading">The Sanctuary Beyond Villa 44</h3>
            <p className="exp-hero-center-tagline">
              From misty tea ridges &amp; roaring waterfalls to wild elephant corridors
            </p>
          </div>
        </div>

        {/* Video 3 (Right): Untamed Wildlife & Cloud Forests */}
        <div
          className="exp-hero-video-card exp-hero-side exp-hero-right"
          onClick={() => onSelectChapter('wildlife')}
          role="button"
          tabIndex={0}
          aria-label="Experience Wild Sri Lanka & Sanctuaries"
        >
          <CinematicVideo
            src="https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/246461_tiny.mp4"
            poster="https://pub-2dd8b455cfa4473a847d652148f88c45.r2.dev/Safari.webp"
          />
          <div className="exp-hero-scrim"></div>
          <div className="exp-hero-info">
            <span className="exp-hero-badge">✦ 02 · WILD SANCTUARIES</span>
            <h4 className="exp-hero-title">Cloud Forests &amp; Safari</h4>
            <p className="exp-hero-desc">Horton Plains &amp; highland wildlife</p>
          </div>
          <div className="exp-hero-hover-indicator">
            <span>Explore Route</span>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <polyline points="9 18 15 12 9 6" />
            </svg>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   Subcomponent: ExperienceMediaCard
   Destination Chapter Card with Smooth Video Playback
   ============================================================ */
function ExperienceMediaCard({ destination, index, total, isActive, onSelect }) {
  const cardRef = useRef(null);
  const videoRef = useRef(null);
  const [videoLoaded, setVideoLoaded] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);

  useEffect(() => {
    const cardEl = cardRef.current;
    if (!cardEl || typeof IntersectionObserver === 'undefined') {
      if (videoRef.current) {
        videoRef.current.muted = true;
        videoRef.current.play().catch(() => {});
      }
      return;
    }

    const playbackObserver = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          const vid = videoRef.current;
          if (!vid) return;

          if (entry.isIntersecting) {
            vid.muted = true;
            const playPromise = vid.play();
            if (playPromise !== undefined) {
              playPromise
                .then(() => setIsPlaying(true))
                .catch(() => setIsPlaying(false));
            }
          } else {
            vid.pause();
            setIsPlaying(false);
          }
        });
      },
      { threshold: 0.25 }
    );

    playbackObserver.observe(cardEl);
    return () => playbackObserver.disconnect();
  }, []);

  return (
    <article
      ref={cardRef}
      className={`exp-card ${isActive ? 'exp-card-active' : ''}`}
      data-category={destination.category}
      tabIndex={0}
      role="button"
      aria-label={`Explore ${destination.title}`}
      onClick={() => onSelect(destination)}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          onSelect(destination);
        }
      }}
    >
      {/* Visual Media Frame */}
      <div className="exp-media-frame">
        <img
          src={destination.poster}
          alt={destination.title}
          className={`exp-poster-img ${videoLoaded && isPlaying ? 'exp-poster-faded' : ''}`}
          loading={index < 2 ? 'eager' : 'lazy'}
        />

        <video
          ref={videoRef}
          className={`exp-video-player ${videoLoaded && isPlaying ? 'exp-video-visible' : ''}`}
          loop
          muted
          playsInline
          preload="auto"
          crossOrigin="anonymous"
          onCanPlay={() => setVideoLoaded(true)}
          src={destination.videoSrc}
        />

        <div className="exp-media-scrim-top"></div>
        <div className="exp-media-scrim-bottom"></div>

        {/* Top Badges */}
        <div className="exp-card-header-row">
          <div className="exp-num-badge">
            <span className="exp-num-accent">✦</span>
            <span className="exp-num-text">{destination.number}</span>
          </div>
          <div className="exp-category-badge">
            <span>{destination.categoryLabel}</span>
          </div>
        </div>

        {/* Live Play Status */}
        <div className="exp-live-indicator">
          <span className={`exp-pulse-dot ${isPlaying ? 'exp-pulse-active' : ''}`}></span>
          <span className="exp-live-label">{isPlaying ? 'CINEMATIC' : 'EXPLORE'}</span>
        </div>
      </div>

      {/* Card Content */}
      <div className="exp-card-body">
        <div className="exp-meta-row">
          <span className="exp-distance-tag">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 2a8 8 0 00-8 8c0 5.25 8 12 8 12s8-6.75 8-12a8 8 0 00-8-8z" />
              <circle cx="12" cy="10" r="3" />
            </svg>
            {destination.distance}
          </span>
          <span className="exp-elevation-tag">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M8 3l4 8 5-5 5 15H2L8 3z" />
            </svg>
            {destination.elevation}
          </span>
        </div>

        <div className="exp-chapter-tag">{destination.subtitle}</div>
        <h3 className="exp-card-title">{destination.title}</h3>
        <p className="exp-quote-tagline">“{destination.tagline}”</p>
        <p className="exp-card-desc">{destination.description}</p>

        {/* Signature Highlights */}
        <div className="exp-highlights-list">
          {destination.highlights.slice(0, 3).map((item, i) => (
            <span key={i} className="exp-highlight-chip">
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                <polyline points="20 6 9 17 4 12" />
              </svg>
              {item}
            </span>
          ))}
        </div>

        {/* Action Button */}
        <div className="exp-card-action">
          <button
            type="button"
            className="exp-btn-discover"
            aria-label={`View itinerary and tips for ${destination.title}`}
          >
            <span>Discover Route</span>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <line x1="5" y1="12" x2="19" y2="12" />
              <polyline points="12 5 19 12 12 19" />
            </svg>
          </button>
        </div>
      </div>
    </article>
  );
}

/* ============================================================
   Subcomponent: ExperienceDetailModal
   ============================================================ */
function ExperienceDetailModal({ destination, onClose }) {
  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleKeyDown);
    document.body.style.overflow = 'hidden';

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  if (!destination) return null;

  return (
    <div className="exp-modal-backdrop" onClick={onClose} role="dialog" aria-modal="true">
      <div className="exp-modal-card" onClick={(e) => e.stopPropagation()}>
        <button
          type="button"
          className="exp-modal-close-btn"
          onClick={onClose}
          aria-label="Close dialog"
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        </button>

        <div className="exp-modal-media-col">
          <video
            src={destination.videoSrc}
            poster={destination.poster}
            autoPlay
            loop
            muted
            playsInline
            className="exp-modal-video"
          />
          <div className="exp-modal-scrim"></div>
          <div className="exp-modal-badge-row">
            <span className="exp-modal-num">{destination.number}</span>
            <span className="exp-modal-cat">{destination.categoryLabel}</span>
          </div>
        </div>

        <div className="exp-modal-content-col">
          <div className="exp-modal-header">
            <span className="exp-modal-kicker">{destination.subtitle}</span>
            <h2 className="exp-modal-title">{destination.title}</h2>
            <p className="exp-modal-tagline">“{destination.tagline}”</p>
          </div>

          <div className="exp-modal-stats-grid">
            <div className="exp-stat-box">
              <span className="exp-stat-lbl">Distance</span>
              <span className="exp-stat-val">{destination.distance}</span>
            </div>
            <div className="exp-stat-box">
              <span className="exp-stat-lbl">Elevation</span>
              <span className="exp-stat-val">{destination.elevation}</span>
            </div>
            <div className="exp-stat-box">
              <span className="exp-stat-lbl">Best Timing</span>
              <span className="exp-stat-val">{destination.bestTime}</span>
            </div>
          </div>

          <div className="exp-modal-body-text">
            <h4>The Experience Story</h4>
            <p>{destination.detailStory}</p>
          </div>

          <div className="exp-modal-concierge-box">
            <div className="exp-concierge-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
              </svg>
            </div>
            <div className="exp-concierge-text">
              <h5>Villa 44 Private Concierge Touch</h5>
              <p>{destination.conciergeNote}</p>
            </div>
          </div>

          <div className="exp-modal-actions-row">
            <a
              href={`https://wa.me/94762128396?text=${encodeURIComponent('Hello Villa 44 Concierge, I would like to arrange an itinerary for ' + destination.title)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="exp-btn-whatsapp-inquire"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
              </svg>
              <span>Arrange Tour with Concierge</span>
            </a>
            <button type="button" className="exp-btn-close-modal" onClick={onClose}>
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   Main Component: ExperienceSriLankaApp
   ============================================================ */
function ExperienceSriLankaApp() {
  const [activeCategory, setActiveCategory] = useState('all');
  const [selectedDestination, setSelectedDestination] = useState(null);

  const filteredDestinations = useMemo(() => {
    if (activeCategory === 'all') return EXPERIENCE_DESTINATIONS;
    return EXPERIENCE_DESTINATIONS.filter((d) => d.category === activeCategory);
  }, [activeCategory]);

  const handleHeroSelect = useCallback((key) => {
    const dest = EXPERIENCE_DESTINATIONS.find((d) => d.id === key) || EXPERIENCE_DESTINATIONS[0];
    setSelectedDestination(dest);
  }, []);

  return (
    <div className="exp-experience-wrapper">
      {/* Visual Bridge */}
      <div className="exp-transition-bridge">
        <div className="exp-bridge-line"></div>
        <div className="exp-bridge-tag">
          <span className="exp-bridge-sparkle">✦</span>
          <span>BEYOND VILLA 44 SANCTUARY</span>
          <span className="exp-bridge-sparkle">✦</span>
        </div>
        <div className="exp-bridge-line"></div>
      </div>

      <div className="exp-ambient-bg">
        <div className="exp-ambient-glow exp-ambient-glow-1"></div>
        <div className="exp-ambient-glow exp-ambient-glow-2"></div>
        <div className="exp-ambient-glow exp-ambient-glow-3"></div>
        <div className="exp-ambient-pattern"></div>
      </div>

      <div className="exp-content-container">
        {/* Section Header */}
        <header className="exp-header-container">
          <p className="exp-section-kicker">✦ AN INVITATION TO WONDER ✦</p>
          <h2 className="exp-heading-primary">THIS IS YOUR CHANCE</h2>
          <h3 className="exp-heading-highlight">EXPERIENCE SRI LANKA</h3>
          <p className="exp-header-description">
            “From misty mountains and endless tea estates to cascading waterfalls, ancient trails and unforgettable journeys — discover the Sri Lanka beyond Villa 44.”
          </p>
        </header>

        {/* Signature SEARIC 3-Video Trio Showcase */}
        <HeroVideoTrio onSelectChapter={handleHeroSelect} />

        {/* Interactive Chapters Header & Filters */}
        <div className="exp-subheading-wrap">
          <div className="exp-subheading-line"></div>
          <h4 className="exp-subheading-text">CURATED HIGHLAND EXPEDITIONS</h4>
          <div className="exp-subheading-line"></div>
        </div>

        {/* Filter Pills */}
        <div className="exp-filter-pills-row" role="tablist" aria-label="Experience Categories">
          {CATEGORIES.map((cat) => (
            <button
              key={cat.key}
              type="button"
              role="tab"
              aria-selected={activeCategory === cat.key}
              className={`exp-pill-btn ${activeCategory === cat.key ? 'exp-pill-active' : ''}`}
              onClick={() => setActiveCategory(cat.key)}
            >
              {cat.label}
            </button>
          ))}
        </div>

        {/* Destination Cards Grid */}
        <div className="exp-cards-grid-container">
          <div className="exp-cards-grid">
            {filteredDestinations.map((dest, idx) => (
              <ExperienceMediaCard
                key={dest.id}
                destination={dest}
                index={idx}
                total={filteredDestinations.length}
                isActive={false}
                onSelect={(d) => setSelectedDestination(d)}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Detail Modal */}
      {selectedDestination && (
        <ExperienceDetailModal
          destination={selectedDestination}
          onClose={() => setSelectedDestination(null)}
        />
      )}
    </div>
  );
}

/* ── Mount React Component ─────────────────────────────────── */
const expRootEl = document.getElementById('experience-sri-lanka-root');
if (expRootEl && typeof ReactDOM !== 'undefined') {
  ReactDOM.createRoot(expRootEl).render(React.createElement(ExperienceSriLankaApp));
}
