/* global React, ChromeBlob, ChromeDrop, VideoPH, PhotoPH, MagneticBtn, Arrow, Play, Lightbox, TOURS, ROOMS, DAYS, INCLUDED, BRING, FAQ, TESTIMONIALS, useReveal, openBooking */
const { useState: tState, useEffect: tEffect, useMemo: tMemo } = React;

function TourPage({ tourId, onNav }) {
  const tour = TOURS.find(t => t.id === tourId) || TOURS[1];
  const [selectedRoom, setSelectedRoom] = tState(ROOMS[2]);
  const [activeDay, setActiveDay] = tState(0);
  const [lbOpen, setLbOpen] = tState(false);
  const [lbIdx, setLbIdx] = tState(0);
  const ref = useReveal();

  const galleryItems = tMemo(() => {
    const placeholderLabels = [
      'Welcome dinner · рівень основи', 'Ранок на даху · йога', 'Pool party, день 2',
      'Говерла · схід', 'DJ Kantik · головна ніч', 'Гала-вечеря · open air',
      'Recovery · SPA', 'Farewell bunch',
    ];

    // Collect all available photo URLs: tour.images array, or fall back to single tour.image
    const tourImgs = tour.images && tour.images.length > 0
      ? tour.images
      : (tour.image ? [tour.image] : []);

    // Also include gallery-tab photos that have a real image
    const galTabImgs = (window._GALLERY || []).filter(g => g.image).map(g => g.image);

    // Merge: tour photos first, then gallery-tab extras (de-duped)
    const allImgs = [...tourImgs, ...galTabImgs.filter(u => !tourImgs.includes(u))];

    const padded = [...allImgs];
    while (padded.length < 8) padded.push(null);
    return padded.slice(0, 8).map((src, i) => ({
      label: placeholderLabels[i] || `Фото ${i + 1}`,
      hue: 280 + i * 3,
      src: src || null,
    }));
  }, [tour.images, tour.image]);

  return (
    <div ref={ref} className="page-fade">
      {/* Hero */}
      <section style={{ paddingTop: 'clamp(110px, 14vw, 180px)', paddingBottom: 'clamp(40px, 6vw, 80px)', position: 'relative' }}>
        <div className="blob-layer">
          <div style={{ position: 'absolute', right: '-10%', top: '10%' }}><ChromeBlob shape="drop" size={600} hue={tour.hue} /></div>
          <div style={{ position: 'absolute', left: '-4%', bottom: '-10%' }}><ChromeBlob shape="loop" size={380} hue={tour.hue + 10} /></div>
        </div>
        <div className="container" style={{ position: 'relative' }}>
          <div className="flex gap-3 center" style={{ marginBottom: 20 }}>
            <button onClick={() => onNav('home')} style={{ fontSize: 13, color: 'var(--fg-2)', display: 'inline-flex', alignItems: 'center', gap: 8 }}>← усі тури</button>
            <span style={{ color: 'var(--fg-3)' }}>/</span>
            <span className="mono" style={{ fontSize: 12, color: 'var(--fg-2)' }}>{tour.tag}</span>
          </div>
          <div className="flex gap-3" style={{ flexWrap: 'wrap' }}>
            <span className={`pill ${tour.status === 'sold' ? 'sold' : tour.status === 'open' ? 'open' : 'soon'}`}><span className="dot" /> {tour.statusLabel}</span>
            <span className="pill">{tour.dates}</span>
            <span className="pill">6 днів · 5 ночей</span>
            <span className="pill">до 100 учасників</span>
          </div>
          <h1 className="h-mega reveal is-in mt-6" style={{ fontSize: 'clamp(56px, 8vw, 128px)' }}>
            {tour.month}.<br />
            <em style={{ fontStyle: 'italic', fontWeight: 500 }}>{tour.title}</em>
          </h1>
          <div className="flex between" style={{ alignItems: 'end', flexWrap: 'wrap', gap: 24, marginTop: 32 }}>
            <p style={{ maxWidth: 560, fontSize: 18, color: 'var(--fg-1)' }}>
              {tour.subtitle} — наш найбільший заїзд сезону. Повний buy-out готелю, 100 своїх людей, 6 днів, які запам'ятовуються на все життя.
            </p>
            <div className="flex gap-3">
              <MagneticBtn className="btn btn-primary" onClick={openBooking}>Забронювати місце <span className="arrow"><Arrow /></span></MagneticBtn>
              {tour.teaserUrl && (
                <a className="btn btn-ghost" href={tour.teaserUrl} target="_blank" rel="noopener noreferrer" style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <Play size={12} /> Teaser туру
                </a>
              )}
            </div>
          </div>

          {/* Hero grid: photo (or video placeholder) + stats */}
          <div className="grid mt-16" style={{ gridTemplateColumns: '2fr 1fr', gap: 16 }}>
            {tour.image ? (
              /* Real photo — clean, no play button */
              <div style={{
                aspectRatio: '21 / 10', borderRadius: 'var(--radius)', overflow: 'hidden',
                position: 'relative',
              }}>
                <img src={tour.image} alt={tour.title}
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </div>
            ) : (
              /* No photo yet — video placeholder with play button */
              <VideoPH label="TOUR TEASER · 01:20" aspect="21 / 10">
                <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', zIndex: 2 }}>
                  <button style={{ width: 84, height: 84, borderRadius: 999, background: 'rgba(255,255,255,.95)', color: '#0a0a0d', display: 'grid', placeItems: 'center' }}>
                    <Play size={24} />
                  </button>
                </div>
              </VideoPH>
            )}
            <div className="stack gap-3">
              <div className="card" style={{ padding: 20 }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', letterSpacing: 0.12, textTransform: 'uppercase' }}>Локація</div>
                <div className="h-md mt-4">Буковель, UA</div>
                <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 6 }}>Bukovel Resort · 1080 м</div>
              </div>
              <div className="card" style={{ padding: 20 }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', letterSpacing: 0.12, textTransform: 'uppercase' }}>Від</div>
                <div className="h-md mt-4">€{selectedRoom.price}</div>
                <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 6 }}>{selectedRoom.name} · 6 днів</div>
              </div>
              <div className="card" style={{ padding: 20, background: 'var(--violet)', color: '#fff', borderColor: 'transparent' }}>
                <div className="mono" style={{ fontSize: 10, opacity: .8, letterSpacing: 0.12, textTransform: 'uppercase' }}>Залишилось</div>
                <div className="h-md mt-4">8 місць</div>
                <div style={{ fontSize: 13, opacity: .85, marginTop: 6 }}>розлітаються за 48 годин</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Gallery — only shown when there are real photos */}
      {galleryItems.some(g => g.src) && (
      <section style={{ background: 'var(--bg-1)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div style={{ marginBottom: 48 }}>
            <div className="eyebrow">GALLERY · 01</div>
            <h2 className="h-xl mt-6">Атмосфера<br /><em style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--violet-soft)' }}>туру.</em></h2>
          </div>

          {/* Dynamic photo grid — only real photos, no placeholders */}
          <TourGalleryGrid items={galleryItems.filter(g => g.src)} onOpen={(i) => { setLbIdx(i); setLbOpen(true); }} />
        </div>
      </section>
      )}

      {/* Day by day */}
      <section>
        <div className="container">
          <div className="flex between" style={{ alignItems: 'end', flexWrap: 'wrap', gap: 24 }}>
            <div>
              <div className="eyebrow">PROGRAM · 6 DAYS</div>
              <h2 className="h-xl mt-6">Що на тебе<br /><em style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--violet-soft)' }}>чекає</em> щодня.</h2>
            </div>
            <p style={{ color: 'var(--fg-1)', maxWidth: 420 }}>
              Кожен день — окрема історія. Обирай свою траєкторію: від йоги та ретриту до квадроциклів та нічних сетів.
            </p>
          </div>

          <div className="grid mt-16" style={{ gridTemplateColumns: '0.9fr 2fr', gap: 24, alignItems: 'start' }}>
            <div className="stack" style={{ position: 'sticky', top: 100 }}>
              {DAYS.map((d, i) => (
                <button key={i}
                  onClick={() => setActiveDay(i)}
                  style={{
                    padding: '18px 20px',
                    textAlign: 'left',
                    borderRadius: 16,
                    background: activeDay === i ? 'var(--violet)' : 'transparent',
                    color: activeDay === i ? '#fff' : 'var(--fg-1)',
                    border: '1px solid ' + (activeDay === i ? 'transparent' : 'var(--line)'),
                    marginBottom: 6,
                    transition: 'all .3s var(--ease)',
                  }}>
                  <div className="flex between center">
                    <div>
                      <div className="mono" style={{ fontSize: 10, opacity: .7, letterSpacing: 0.12, textTransform: 'uppercase' }}>{d.day} · {d.date}</div>
                      <div style={{ fontFamily: 'Unbounded', fontWeight: 600, fontSize: 15, marginTop: 4 }}>{d.title}</div>
                    </div>
                    <span style={{ fontSize: 11, opacity: .8 }}>{d.tag}</span>
                  </div>
                </button>
              ))}
            </div>

            <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
              <div style={{ position: 'relative' }}>
                <VideoPH label={`${DAYS[activeDay].day.toUpperCase()} · ${DAYS[activeDay].title.toUpperCase()}`} aspect="21 / 9" style={{ borderRadius: 0 }} />
                <div style={{ position: 'absolute', left: 28, bottom: 24, color: '#fff', zIndex: 2 }}>
                  <div className="mono" style={{ fontSize: 11, opacity: .7, letterSpacing: 0.12, textTransform: 'uppercase' }}>{DAYS[activeDay].day} · {DAYS[activeDay].date}</div>
                  <div style={{ fontFamily: 'Unbounded', fontSize: 36, fontWeight: 700, letterSpacing: '-0.02em', marginTop: 6 }}>{DAYS[activeDay].title}</div>
                </div>
              </div>
              <div style={{ padding: 28 }}>
                {DAYS[activeDay].items.map((it, i) => (
                  <div key={i} className="itinerary-item" style={{ display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 24, padding: '20px 0', borderBottom: i < DAYS[activeDay].items.length - 1 ? '1px solid var(--line)' : 'none', alignItems: 'center' }}>
                    <div className="mono" style={{ fontSize: 14, color: 'var(--violet-soft)', fontWeight: 600 }}>{it.t}</div>
                    <div style={{ fontSize: 16 }}>{it.d}</div>
                    <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--violet)', opacity: .6 }} />
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Rooms */}
      <section id="rooms-section" style={{ background: 'var(--bg-1)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="flex between" style={{ alignItems: 'end', flexWrap: 'wrap', gap: 24 }}>
            <div>
              <div className="eyebrow">ROOMS · 06 ТИПІВ</div>
              <h2 className="h-xl mt-6">Обирай свій<br /><em style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--violet-soft)' }}>простір.</em></h2>
            </div>
            <p style={{ color: 'var(--fg-1)', maxWidth: 420 }}>
              Ми повністю викупляємо готель — тому можемо пропонувати будь-який формат: від Standard до приватних шале.
            </p>
          </div>

          <div className="grid mt-16" style={{ gridTemplateColumns: '1fr 360px', gap: 24, alignItems: 'start' }}>
            <div className="stack gap-4">
              {ROOMS.map((r) => <RoomCard key={r.id} room={r} selected={selectedRoom.id === r.id} onSelect={() => setSelectedRoom(r)} onBook={openBooking} />)}
            </div>
            <BookingPanel tour={tour} room={selectedRoom} onBook={openBooking} />
          </div>
        </div>
      </section>

      {/* Included + bring */}
      <section>
        <div className="container">
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 24 }}>
            <div className="card" style={{ padding: 32 }}>
              <div className="eyebrow">ВКЛЮЧЕНО В ТУР</div>
              <h3 className="h-lg mt-6">Все продумано.</h3>
              <div className="stack gap-3 mt-8">
                {INCLUDED.map((it, i) => (
                  <div key={i} className="flex gap-3" style={{ alignItems: 'start' }}>
                    <span style={{ width: 22, height: 22, borderRadius: 999, background: 'var(--violet)', color: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 2 }}>
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 12l5 5L20 7" strokeLinecap="round" /></svg>
                    </span>
                    <span style={{ fontSize: 15 }}>{it}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="card" style={{ padding: 32, background: 'var(--bg-2)' }}>
              <div className="eyebrow">ЩО ВЗЯТИ З СОБОЮ</div>
              <h3 className="h-lg mt-6">Твій чек-ліст.</h3>
              <div className="stack gap-3 mt-8">
                {BRING.map((it, i) => (
                  <div key={i} className="flex gap-3" style={{ alignItems: 'start' }}>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--violet-soft)', marginTop: 4, letterSpacing: 0.1 }}>0{i+1}</span>
                    <span style={{ fontSize: 15 }}>{it}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Map placeholder */}
      <section style={{ paddingTop: 0 }}>
        <div className="container">
          <div className="card" style={{ padding: 0, overflow: 'hidden', position: 'relative' }}>
            <div style={{
              aspectRatio: '21 / 9',
              background:
                'radial-gradient(40% 60% at 50% 50%, rgba(140,90,255,.25), transparent 70%),' +
                "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='40' height='40'><path d='M0 20h40M20 0v40' stroke='rgba(255,255,255,0.06)' stroke-width='1'/></svg>\")," +
                'linear-gradient(135deg, #111116, #0a0a0d)',
              position: 'relative',
            }}>
              <div style={{ position: 'absolute', top: 24, left: 24 }}>
                <div className="eyebrow" style={{ color: '#fff' }}>ЛОКАЦІЯ · КАРТА</div>
                <h3 className="h-lg mt-4" style={{ color: '#fff' }}>Буковель, Карпати</h3>
                <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', marginTop: 8 }}>48.3648° N, 24.4086° E</div>
              </div>
              <div style={{ position: 'absolute', top: '45%', left: '55%', transform: 'translate(-50%,-50%)' }}>
                <div style={{ width: 18, height: 18, borderRadius: 999, background: 'var(--violet)', boxShadow: '0 0 0 8px rgba(140,90,255,.25), 0 0 0 18px rgba(140,90,255,.12)' }} />
                <div className="mono" style={{ fontSize: 10, color: '#fff', marginTop: 10, whiteSpace: 'nowrap', textAlign: 'center', transform: 'translateX(-40%)' }}>BUKOVEL RESORT</div>
              </div>
              <div style={{ position: 'absolute', bottom: 24, right: 24 }}>
                <button className="btn btn-ghost" style={{ background: 'rgba(255,255,255,.1)', color: '#fff' }}>Відкрити на карті <Arrow size={12} /></button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Testimonials */}
      <section style={{ background: 'var(--bg-1)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="eyebrow">RESIDENTS · KARPATY</div>
          <h2 className="h-xl mt-6">Кажуть<br /><em style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--violet-soft)' }}>учасники.</em></h2>
          <div className="grid mt-16" style={{ gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
            {TESTIMONIALS.slice(0, 3).map((t, i) => (
              <div key={i} className="card" style={{ padding: 28 }}>
                <div className="flex gap-1" style={{ color: 'var(--violet-soft)' }}>★★★★★</div>
                <p className="mt-4" style={{ fontSize: 16, color: 'var(--fg-1)', lineHeight: 1.5 }}>"{t.text}"</p>
                <div className="mt-8 flex gap-3 center">
                  <PhotoPH label="" hue={280 + i * 10} style={{ width: 44, height: 44, aspectRatio: '1/1', borderRadius: 999 }} />
                  <div>
                    <div style={{ fontFamily: 'Unbounded', fontWeight: 600, fontSize: 14 }}>{t.name}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', letterSpacing: 0.12, marginTop: 2 }}>{t.role}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section>
        <div className="container">
          <div className="grid" style={{ gridTemplateColumns: '1fr 1.4fr', gap: 64, alignItems: 'start' }}>
            <div>
              <div className="eyebrow">FAQ</div>
              <h2 className="h-xl mt-6">Найчастіші<br /><em style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--violet-soft)' }}>питання.</em></h2>
              <p className="mt-6" style={{ color: 'var(--fg-2)' }}>Не знайшов відповіді? Пиши в Telegram — відповімо за годину.</p>
            </div>
            <FAQList />
          </div>
        </div>
      </section>

      {/* Final CTA */}
      <section style={{ paddingBottom: 120 }}>
        <div className="container">
          <div className="card" style={{ padding: 'clamp(40px, 6vw, 80px)', background: 'linear-gradient(135deg, var(--violet-deep), var(--violet))', color: '#fff', borderColor: 'transparent', position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', right: -80, top: -80, opacity: .4 }}>
              <ChromeBlob shape="wave" size={500} hue={280} />
            </div>
            <div style={{ position: 'relative', maxWidth: 700 }}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: 0.12, textTransform: 'uppercase', opacity: .8 }}>ГОТОВИЙ?</div>
              <h2 className="h-xl mt-6">Твоє місце чекає.</h2>
              <p className="mt-6" style={{ fontSize: 18, opacity: .9, maxWidth: 520 }}>
                Забронюй {selectedRoom.name.toLowerCase()} за €{selectedRoom.price} і стань частиною найближчого заїзду.
              </p>
              <div className="flex gap-3 mt-8" style={{ flexWrap: 'wrap' }}>
                <MagneticBtn className="btn btn-dark" onClick={openBooking}>Забронювати <span className="arrow" style={{ background: 'rgba(255,255,255,.2)' }}><Arrow /></span></MagneticBtn>
                <button className="btn btn-ghost" style={{ background: 'rgba(255,255,255,.15)', color: '#fff', borderColor: 'rgba(255,255,255,.2)' }} onClick={() => onNav('home')}>← усі тури</button>
              </div>
            </div>
          </div>
        </div>
      </section>

      <Lightbox open={lbOpen} items={galleryItems.filter(g => g.src)} index={lbIdx} onIndex={setLbIdx} onClose={() => setLbOpen(false)} labelPrefix="KARPATY · SERPEN" />
    </div>
  );
}

function GalItem({ idx, items, open, style = {}, badge }) {
  const [hovered, setHovered] = tState(false);
  const item = items[idx] || {};
  return (
    <div
      onClick={() => open(idx)}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        position: 'relative',
        overflow: 'hidden',
        cursor: 'zoom-in',
        width: '100%',
        height: '100%',
        ...style,
      }}
    >
      <PhotoPH
        label=""
        hue={item.hue || 285}
        src={item.src || null}
        style={{
          width: '100%',
          height: '100%',
          borderRadius: 0,
          aspectRatio: 'auto',
          transform: hovered ? 'scale(1.05)' : 'scale(1)',
          transition: 'transform .6s var(--ease)',
        }}
      />
      {/* overlay on hover */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'rgba(5,5,10,.5)',
        opacity: hovered ? 1 : 0,
        transition: 'opacity .35s var(--ease)',
        display: 'flex', alignItems: 'flex-end', padding: 16,
      }}>
        <span style={{
          fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: 0.12,
          textTransform: 'uppercase', color: 'rgba(255,255,255,.9)',
          background: 'rgba(0,0,0,.55)', backdropFilter: 'blur(10px)',
          padding: '5px 10px', borderRadius: 6,
          border: '1px solid rgba(255,255,255,.12)',
          transform: hovered ? 'translateY(0)' : 'translateY(6px)',
          transition: 'transform .4s var(--ease)',
          display: 'inline-block',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '90%',
        }}>{item.label}</span>
      </div>
      {/* zoom icon */}
      <div style={{
        position: 'absolute', top: 12, right: 12,
        width: 30, height: 30, borderRadius: 999,
        background: 'rgba(255,255,255,.18)', backdropFilter: 'blur(10px)',
        border: '1px solid rgba(255,255,255,.22)',
        display: 'grid', placeItems: 'center',
        opacity: hovered ? 1 : 0,
        transform: hovered ? 'scale(1)' : 'scale(0.6)',
        transition: 'opacity .3s var(--ease), transform .35s var(--ease)',
      }}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round">
          <circle cx="11" cy="11" r="8" /><path d="m21 21-4.35-4.35" /><path d="M11 8v6M8 11h6" />
        </svg>
      </div>
      {/* optional badge */}
      {badge && (
        <div style={{
          position: 'absolute', top: 12, left: 12,
          background: 'var(--violet)', color: '#fff',
          fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: 0.12,
          textTransform: 'uppercase', padding: '5px 10px', borderRadius: 999,
          boxShadow: '0 4px 16px -4px var(--violet-glow)',
        }}>{badge}</div>
      )}
    </div>
  );
}

function TourGalleryGrid({ items, onOpen }) {
  const n = items.length;
  if (!n) return null;

  if (n === 1) {
    return (
      <div style={{ height: 480 }}>
        <GalItem idx={0} items={items} open={onOpen}
          style={{ height: '100%', borderRadius: 'var(--radius-lg)' }} />
      </div>
    );
  }

  if (n === 2) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, height: 440 }}>
        <GalItem idx={0} items={items} open={onOpen} style={{ borderRadius: 'var(--radius)' }} />
        <GalItem idx={1} items={items} open={onOpen} style={{ borderRadius: 'var(--radius)' }} />
      </div>
    );
  }

  if (n === 3) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, height: 480 }}>
        <GalItem idx={0} items={items} open={onOpen} style={{ gridRow: '1 / 3', borderRadius: 'var(--radius-lg)' }} />
        <GalItem idx={1} items={items} open={onOpen} style={{ borderRadius: 'var(--radius)' }} />
        <GalItem idx={2} items={items} open={onOpen} style={{ borderRadius: 'var(--radius)' }} />
      </div>
    );
  }

  if (n === 4) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '3fr 2fr 2fr', gridTemplateRows: '1fr 1fr', gap: 10, height: 500 }}>
        <GalItem idx={0} items={items} open={onOpen} style={{ gridRow: '1 / 3', borderRadius: 'var(--radius-lg)' }} />
        <GalItem idx={1} items={items} open={onOpen} style={{ borderRadius: 'var(--radius)' }} />
        <GalItem idx={2} items={items} open={onOpen} style={{ borderRadius: 'var(--radius)' }} />
        <GalItem idx={3} items={items} open={onOpen} style={{ gridColumn: '2 / 4', borderRadius: 'var(--radius)' }} />
      </div>
    );
  }

  // 5+ photos: use masonry-inspired 12-column grid, cap at 8
  const visible = items.slice(0, Math.min(n, 8));
  const layouts = [
    { gridColumn: '1 / 6', gridRow: '1 / 3', borderRadius: 'var(--radius-lg)' },
    { gridColumn: '6 / 9', gridRow: '1', borderRadius: 'var(--radius)' },
    { gridColumn: '9 / 13', gridRow: '1', borderRadius: 'var(--radius)' },
    { gridColumn: '6 / 9', gridRow: '2', borderRadius: 'var(--radius)' },
    { gridColumn: '9 / 13', gridRow: '2', borderRadius: 'var(--radius)' },
    { gridColumn: '1 / 5', gridRow: '3', borderRadius: 'var(--radius)' },
    { gridColumn: '5 / 9', gridRow: '3', borderRadius: 'var(--radius)' },
    { gridColumn: '9 / 13', gridRow: '3', borderRadius: 'var(--radius)' },
  ];
  const rows = visible.length <= 5 ? '260px 260px' : '260px 260px 220px';
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(12, 1fr)',
      gridTemplateRows: rows,
      gap: 10,
    }}>
      {visible.map((_, i) => (
        <GalItem key={i} idx={i} items={visible} open={onOpen} style={layouts[i]} />
      ))}
    </div>
  );
}

function RoomCard({ room, selected, onSelect, onBook }) {
  const [photoIdx, setPhotoIdx] = tState(0);
  // Use real images if available, fall back to placeholder data
  const roomImages = room.images && room.images.length > 0 ? room.images : null;
  const placeholders = [
    { label: `${room.name} · огляд`, hue: room.hue },
    { label: 'ліжко / простір', hue: room.hue + 4 },
    { label: 'ванна кімната', hue: room.hue - 4 },
    { label: 'балкон / вид', hue: room.hue + 8 },
  ];
  return (
    <div className="card" style={{
      padding: 0, overflow: 'hidden',
      border: selected ? '2px solid var(--violet)' : '1px solid var(--line)',
      boxShadow: selected ? '0 20px 60px -20px var(--violet-glow)' : 'none',
      transition: 'all .4s var(--ease)',
    }}>
      <div className="room-card-inner" style={{ display: 'grid', gridTemplateColumns: '360px 1fr' }}>
        <div style={{ position: 'relative' }}>
          <div style={{ aspectRatio: '4/3', position: 'relative' }}>
            {roomImages
              ? <img src={roomImages[photoIdx] || roomImages[0]} alt={room.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              : <PhotoPH label={placeholders[photoIdx].label} hue={placeholders[photoIdx].hue} style={{ borderRadius: 0, height: '100%', aspectRatio: 'auto' }} />
            }
            {room.featured && <span className="pill violet" style={{ position: 'absolute', top: 14, left: 14 }}>★ FOUNDER PICK</span>}
          </div>
          <div style={{ display: 'flex', gap: 4, padding: 8, background: 'var(--bg-card)' }}>
            {(roomImages || placeholders).map((p, i) => (
              <button key={i} onClick={() => setPhotoIdx(i)} style={{ flex: 1, aspectRatio: '4/3', border: i === photoIdx ? '2px solid var(--violet)' : '1px solid var(--line)', borderRadius: 8, overflow: 'hidden', padding: 0 }}>
                {roomImages
                  ? <img src={p} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                  : <PhotoPH label="" hue={p.hue} style={{ borderRadius: 0, height: '100%', aspectRatio: 'auto' }} />
                }
              </button>
            ))}
          </div>
        </div>

        <div style={{ padding: 24, display: 'flex', flexDirection: 'column' }}>
          <div className="flex between" style={{ alignItems: 'start' }}>
            <div>
              <h3 style={{ fontFamily: 'Unbounded', fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>{room.name}</h3>
              <div className="mono mt-2" style={{ fontSize: 11, color: 'var(--fg-2)', letterSpacing: 0.1, textTransform: 'uppercase' }}>{room.capacity} · {room.size}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'Unbounded', fontSize: 26, fontWeight: 700 }}>€{room.price}</div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', marginTop: 2 }}>/ гість · 6 днів</div>
            </div>
          </div>
          <div className="mt-6" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {room.perks.map((p, i) => (
              <div key={i} style={{ fontSize: 13, color: 'var(--fg-1)', display: 'flex', gap: 8, alignItems: 'center' }}>
                <span style={{ width: 5, height: 5, borderRadius: 999, background: 'var(--violet)' }} /> {p}
              </div>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <div className="flex between center mt-8" style={{ paddingTop: 16, borderTop: '1px solid var(--line)', gap: 10, flexWrap: 'wrap' }}>
            <span className="mono" style={{ fontSize: 12, color: room.available <= 2 ? '#ffc860' : 'var(--fg-2)' }}>
              {room.available <= 2 ? '⚠ ' : ''}залишилось {room.available} шт.
            </span>
            <div className="flex gap-2">
              <button
                onClick={onSelect}
                className="btn btn-ghost"
                style={{ padding: '10px 16px', fontSize: 13 }}>
                {selected ? '✓ Обрано' : 'Обрати'}
              </button>
              <button
                onClick={onBook}
                className="btn btn-primary"
                style={{ padding: '10px 18px', fontSize: 13 }}>
                Забронювати <Arrow size={12} />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function BookingPanel({ tour, room, onBook }) {
  return (
    <div style={{ position: 'sticky', top: 100 }}>
      <div className="card" style={{ padding: 24 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--violet-soft)', letterSpacing: 0.12, textTransform: 'uppercase' }}>ПІДСУМОК БРОНЮВАННЯ</div>
        <h3 className="h-md mt-4">{tour.month}. {tour.title}</h3>
        <div className="mono" style={{ fontSize: 12, color: 'var(--fg-2)', marginTop: 4 }}>{tour.dates} · 6 днів</div>

        <div className="mt-8" style={{ padding: '16px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
          <div className="flex between">
            <span style={{ fontSize: 13, color: 'var(--fg-2)' }}>Номер</span>
            <span style={{ fontSize: 13, fontWeight: 600 }}>{room.name}</span>
          </div>
          <div className="flex between mt-4">
            <span style={{ fontSize: 13, color: 'var(--fg-2)' }}>Тип</span>
            <span style={{ fontSize: 13 }}>{room.capacity}</span>
          </div>
          <div className="flex between mt-4">
            <span style={{ fontSize: 13, color: 'var(--fg-2)' }}>Все включено</span>
            <span style={{ fontSize: 13, color: 'var(--violet-soft)' }}>✓ так</span>
          </div>
        </div>

        <div className="flex between mt-6" style={{ alignItems: 'baseline' }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: 0.1 }}>Загалом</span>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: 'Unbounded', fontSize: 32, fontWeight: 800, letterSpacing: '-0.02em' }}>€{room.price}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--fg-2)', marginTop: 2 }}>/ гість</div>
          </div>
        </div>

        <button className="btn btn-primary mt-6" onClick={onBook} style={{ width: '100%', justifyContent: 'center' }}>
          Забронювати · депозит 30% <span className="arrow"><Arrow /></span>
        </button>
        <div className="mono mt-4" style={{ fontSize: 10, color: 'var(--fg-3)', textAlign: 'center', letterSpacing: 0.1 }}>
          Безкоштовна відміна за 45 днів до туру
        </div>
      </div>

      <div className="card mt-4" style={{ padding: 20 }}>
        <div className="flex gap-3 center">
          <div style={{ width: 44, height: 44, borderRadius: 999, background: 'var(--violet)', display: 'grid', placeItems: 'center', color: '#fff' }}>💬</div>
          <div>
            <div style={{ fontFamily: 'Unbounded', fontWeight: 600, fontSize: 14 }}>Є питання?</div>
            <div style={{ fontSize: 12, color: 'var(--fg-2)', marginTop: 2 }}>Пиши засновникам напряму</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FAQList() {
  const [open, setOpen] = tState(0);
  return (
    <div className="stack">
      {FAQ.map((it, i) => (
        <button key={i} onClick={() => setOpen(open === i ? -1 : i)}
          style={{ padding: '24px 0', borderBottom: '1px solid var(--line)', textAlign: 'left', cursor: 'pointer' }}>
          <div className="flex between center">
            <h4 style={{ fontFamily: 'Unbounded', fontWeight: 600, fontSize: 18 }}>{it.q}</h4>
            <span style={{ width: 32, height: 32, borderRadius: 999, border: '1px solid var(--line-strong)', display: 'grid', placeItems: 'center', transition: 'transform .3s var(--ease), background .3s', transform: open === i ? 'rotate(45deg)' : 'none', background: open === i ? 'var(--violet)' : 'transparent', color: open === i ? '#fff' : 'inherit' }}>+</span>
          </div>
          <div style={{ maxHeight: open === i ? 200 : 0, overflow: 'hidden', transition: 'max-height .5s var(--ease), margin-top .3s var(--ease)', marginTop: open === i ? 14 : 0 }}>
            <p style={{ color: 'var(--fg-1)', fontSize: 15, lineHeight: 1.6, maxWidth: 560 }}>{it.a}</p>
          </div>
        </button>
      ))}
    </div>
  );
}

Object.assign(window, { TourPage });
