// Hristi Accommodation — booking-focused homepage
// No-build stack: CDN React + in-browser Babel. Content lives in rooms-data.js.
const { useState, useEffect, useRef, useMemo } = React;

// Google Maps — pinned to the exact location of Villa „Hristi" (from the
// owner's Google Maps link). Coordinates: 41.063593, 20.8025131.
const MAP_COORDS = '41.063593,20.8025131';
const MAP_EMBED_URL = `https://www.google.com/maps?q=${MAP_COORDS}&z=17&output=embed`;
const MAP_DIR_URL = `https://www.google.com/maps/dir/?api=1&destination=${MAP_COORDS}`;

// ---------- i18n helper ----------
window.t = (val, lang) => {
  if (val == null) return '';
  if (typeof val === 'string') return val;
  if (typeof val === 'object' && val[lang] != null) return val[lang];
  return '';
};

// ---------- Reveal on scroll ----------
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { el.classList.add('in'); io.disconnect(); }
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

// ---------- Inline icons (replaces lucide-react) ----------
function Icon({ name, className }) {
  const p = { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
    strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', className };
  switch (name) {
    case 'arrow':   return (<svg {...p}><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>);
    case 'expand':  return (<svg {...p}><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>);
    case 'check':   return (<svg {...p}><polyline points="20 6 9 17 4 12"/></svg>);
    case 'chevron': return (<svg {...p}><polyline points="9 18 15 12 9 6"/></svg>);
    case 'clock':   return (<svg {...p}><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>);
    case 'home':    return (<svg {...p}><path d="M3 9.5 12 3l9 6.5"/><path d="M5 10v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V10"/></svg>);
    case 'mail':    return (<svg {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 5L2 7"/></svg>);
    case 'pin':     return (<svg {...p}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0Z"/><circle cx="12" cy="10" r="3"/></svg>);
    case 'menu':    return (<svg {...p}><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg>);
    case 'phone':   return (<svg {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"/></svg>);
    case 'star':    return (<svg {...p} fill="currentColor" stroke="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>);
    case 'leaf':    return (<svg {...p}><path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z"/><path d="M2 21c0-3 1.85-5.36 5.08-6"/></svg>);
    case 'coffee':  return (<svg {...p}><path d="M18 8h1a4 4 0 0 1 0 8h-1"/><path d="M2 8h16v9a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4Z"/><line x1="6" y1="1" x2="6" y2="4"/><line x1="10" y1="1" x2="10" y2="4"/><line x1="14" y1="1" x2="14" y2="4"/></svg>);
    case 'car':     return (<svg {...p}><path d="M5 13l1.6-4.8A2 2 0 0 1 8.5 7h7a2 2 0 0 1 1.9 1.2L19 13"/><path d="M3 13h18v4h-2"/><path d="M7 17H3v-4"/><line x1="9" y1="17" x2="15" y2="17"/><circle cx="7.5" cy="17.5" r="1.6"/><circle cx="16.5" cy="17.5" r="1.6"/></svg>);
    case 'cash':    return (<svg {...p}><rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="2.5"/><line x1="5.5" y1="12" x2="5.5" y2="12"/><line x1="18.5" y1="12" x2="18.5" y2="12"/></svg>);
    case 'no-smoke': return (<svg {...p}><circle cx="12" cy="12" r="9"/><line x1="5.6" y1="5.6" x2="18.4" y2="18.4"/></svg>);
    case 'bed':     return (<svg {...p}><path d="M2 5v14"/><path d="M2 9h16a4 4 0 0 1 4 4v6"/><path d="M2 17h20"/><path d="M6 9V7a1 1 0 0 1 1-1h5a1 1 0 0 1 1 1v2"/></svg>);
    case 'sofa':    return (<svg {...p}><path d="M5 11V8a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v3"/><path d="M3 14a2 2 0 0 1 4 0v2h10v-2a2 2 0 0 1 4 0v3a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1Z"/><line x1="6" y1="19" x2="6" y2="21"/><line x1="18" y1="19" x2="18" y2="21"/></svg>);
    case 'kitchen': return (<svg {...p}><path d="M6 3v6a2 2 0 0 0 4 0V3"/><line x1="8" y1="9" x2="8" y2="21"/><path d="M16 3c-1.6 0-2.5 2-2.5 4.5S14.4 12 16 12"/><line x1="16" y1="3" x2="16" y2="21"/></svg>);
    case 'balcony': return (<svg {...p}><circle cx="12" cy="6" r="2.5"/><line x1="3" y1="13" x2="21" y2="13"/><line x1="5" y1="13" x2="5" y2="21"/><line x1="10" y1="13" x2="10" y2="21"/><line x1="14" y1="13" x2="14" y2="21"/><line x1="19" y1="13" x2="19" y2="21"/></svg>);
    case 'view':    return (<svg {...p}><circle cx="17" cy="7" r="2"/><path d="M3 19l5-6 4 4 3-3 6 5"/><line x1="2" y1="19" x2="22" y2="19"/></svg>);
    case 'droplet': return (<svg {...p}><path d="M12 3s6 5.7 6 10a6 6 0 0 1-12 0c0-4.3 6-10 6-10Z"/></svg>);
    case 'snow':    return (<svg {...p}><line x1="12" y1="3" x2="12" y2="21"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="5.6" y1="5.6" x2="18.4" y2="18.4"/><line x1="18.4" y1="5.6" x2="5.6" y2="18.4"/></svg>);
    case 'tv':      return (<svg {...p}><rect x="2" y="5" width="20" height="13" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/></svg>);
    case 'wifi':    return (<svg {...p}><path d="M5 12.5a10 10 0 0 1 14 0"/><path d="M8.5 15.5a5 5 0 0 1 7 0"/><line x1="12" y1="19" x2="12.01" y2="19"/></svg>);
    case 'linens':  return (<svg {...p}><rect x="4" y="5" width="16" height="14" rx="2"/><line x1="4" y1="10" x2="20" y2="10"/><line x1="9" y1="5" x2="9" y2="10"/></svg>);
    case 'hairdryer': return (<svg {...p}><path d="M14 6H7a3.5 3.5 0 0 0 0 7h7l4 2V4Z"/><line x1="9" y1="13" x2="8" y2="20"/></svg>);
    case 'fridge':  return (<svg {...p}><rect x="6" y="2" width="12" height="20" rx="2"/><line x1="6" y1="10" x2="18" y2="10"/><line x1="9" y1="5" x2="9" y2="7.5"/><line x1="9" y1="13" x2="9" y2="16"/></svg>);
    case 'family':  return (<svg {...p}><path d="M16 19v-1a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v1"/><circle cx="9" cy="7" r="3"/><path d="M22 19v-1a4 4 0 0 0-3-3.87"/><path d="M16 4.13a4 4 0 0 1 0 7.75"/></svg>);
    case 'laptop':  return (<svg {...p}><rect x="4" y="5" width="16" height="11" rx="1.5"/><line x1="2" y1="20" x2="22" y2="20"/></svg>);
    case 'x':       return (<svg {...p}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>);
    case 'instagram': return (<svg {...p}><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>);
    case 'whatsapp':  return (<svg {...p} fill="currentColor" stroke="none"><path d="M.057 24l1.687-6.163a11.867 11.867 0 0 1-1.587-5.945C.16 5.335 5.495 0 12.05 0a11.82 11.82 0 0 1 8.413 3.488 11.82 11.82 0 0 1 3.48 8.414c-.003 6.557-5.338 11.892-11.893 11.892a11.9 11.9 0 0 1-5.688-1.448L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884a9.86 9.86 0 0 0 1.512 5.26l-.999 3.648 3.776-.99zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414z"/></svg>);
    default: return null;
  }
}

// Pick a line icon for a free-text amenity, matching English or Macedonian.
function amenityIcon(text) {
  const s = (text || '').toLowerCase();
  const has = (...keys) => keys.some(k => s.includes(k));
  if (has('living', 'дневна')) return 'sofa';
  if (has('bed', 'кревет', 'sofa', 'софа')) return 'bed';
  if (has('kitchen', 'кујна')) return 'kitchen';
  if (has('balcony', 'балкон')) return 'balcony';
  if (has('terrace', 'тераса')) return 'leaf';
  if (has('view', 'поглед')) return 'view';
  if (has('shower', 'туш')) return 'droplet';
  if (has('bath', 'бања')) return 'droplet';
  if (has('hair', 'фен')) return 'hairdryer';
  if (has('air', 'клима')) return 'snow';
  if (has('wi-fi', 'wifi')) return 'wifi';
  if (has('tv', 'тв')) return 'tv';
  if (has('linen', 'постелнина')) return 'linens';
  if (has('refriger', 'fridge', 'фрижидер')) return 'fridge';
  if (has('coffee', 'tea', 'кафе', 'чај')) return 'coffee';
  if (has('family', 'деца', 'семеј')) return 'family';
  if (has('work', 'работ', 'desk')) return 'laptop';
  return 'check';
}

// ---------- Gradient placeholder (becomes a real photo later) ----------
function Photo({ className = '', gradient, image, children, onClick }) {
  const style = image ? { backgroundImage: `url('${image}')` } : { background: gradient };
  return (
    <div
      className={'photo ' + (image ? '' : 'is-gradient ') + (onClick ? 'clickable ' : '') + className}
      style={style}
      onClick={onClick}
      role={onClick ? 'button' : undefined}
      tabIndex={onClick ? 0 : undefined}
      onKeyDown={onClick ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(e); } } : undefined}
    >
      {children}
    </div>
  );
}

// ---------- Header ----------
function Header({ lang, setLang, onNav, onBook, hidden }) {
  const S = window.STRINGS;
  const [open, setOpen] = useState(false);
  const [activeId, setActiveId] = useState('');
  const go = (id) => { setOpen(false); onNav(id); };
  const book = () => { setOpen(false); onBook(); };

  const links = [
    { id: 'rooms',   label: S.nav.rooms },
    { id: 'about',   label: S.nav.place },
    { id: 'gallery', label: S.nav.gallery },
    { id: 'reviews', label: S.nav.guests },
  ];

  // Highlight the nav link for whichever section is centered in the viewport
  useEffect(() => {
    const els = links.map(l => document.getElementById(l.id)).filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setActiveId(e.target.id); });
    }, { rootMargin: '-45% 0px -50% 0px', threshold: 0 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <header className={'hd' + (hidden && !open ? ' hd-hidden' : '')}>
      <div className="hd-bar">
        <button className="hd-logo" onClick={() => onNav('top')}>
          <span className="hd-mark"><img src="assets/logo.png" alt="Hristi"/></span>
          <span className="hd-name">Hristi Accommodation<small>{t(S.nav.sub, lang)}</small></span>
        </button>

        <nav className="hd-nav">
          {links.map(l => <button key={l.id} className={'hd-link' + (activeId === l.id ? ' active' : '')} onClick={() => onNav(l.id)}>{t(l.label, lang)}</button>)}
        </nav>

        <div className="hd-right">
          <div className="hd-lang" role="group" aria-label="Language">
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
            <button className={lang === 'mk' ? 'active' : ''} onClick={() => setLang('mk')}>МК</button>
          </div>
          <button className="btn-amber" onClick={onBook}>{t(S.nav.book, lang)}</button>
          <button className="hd-burger" onClick={() => setOpen(o => !o)} aria-label={open ? t(S.nav.close, lang) : t(S.nav.menu, lang)} aria-expanded={open}>
            <Icon name={open ? 'x' : 'menu'}/>
          </button>
        </div>
      </div>

      <div className={'hd-mobile' + (open ? ' open' : '')}>
        {links.map(l => <button key={l.id} onClick={() => go(l.id)}>{t(l.label, lang)}</button>)}
        <div className="hd-lang" role="group" aria-label="Language" style={{ alignSelf: 'start' }}>
          <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          <button className={lang === 'mk' ? 'active' : ''} onClick={() => setLang('mk')}>МК</button>
        </div>
        <button className="btn-amber" onClick={book}>{t(S.nav.book, lang)}</button>
      </div>
    </header>
  );
}

// ---------- Hero ----------
function Hero({ lang, onBook, onNav }) {
  const S = window.STRINGS.hero;
  return (
    <section className="hero" id="top">
      <div className="hero-blob b1"/>
      <div className="hero-blob b2"/>
      <div className="hero-grid">
        <div className="hero-copy">
          <h1>{t(S.title, lang)}</h1>
          <p className="hero-sub">{t(S.sub, lang)}</p>
          <div className="hero-cta">
            <button className="btn-amber" onClick={onBook}>{t(S.cta, lang)} <Icon name="arrow"/></button>
            <button className="btn-ghost" onClick={() => onNav('rooms')}>{t(S.explore, lang)}</button>
          </div>
        </div>
        <div className="hero-photos">
          <Photo className="hp-main" image="assets/ohrid-sunset-rays.jpg"/>
          <div className="hp-col">
            <Photo image="assets/ohrid-lake-day.jpg"/>
            <Photo image="assets/ohrid-sunset-golden.jpg"/>
          </div>
        </div>
      </div>
      <div className="hero-fade"/>
    </section>
  );
}

// ---------- About ----------
function About({ lang }) {
  const S = window.STRINGS.about;
  const ref = useReveal();
  return (
    <section className="sec" id="about">
      <div className="about-grid reveal" ref={ref}>
        <div>
          <div className="elabel">{t(S.eyebrow, lang)}</div>
          <h2 className="about-h">{t(S.heading, lang)}</h2>
        </div>
        <div className="about-body">
          <p className="about-lede">{t(S.body, lang)}</p>
          <div className="about-cards">
            {S.reasons.map((r, i) => (
              <div className="about-card" key={i}>
                <Icon name={r.icon} className="ic"/>
                <h3>{t(r.title, lang)}</h3>
                <p>{t(r.copy, lang)}</p>
              </div>
            ))}
          </div>
          <div className="about-arrange">
            <span className="about-arrange-label">{lang === 'en' ? 'And whenever you need it, just ask' : 'И кога ќе ви затреба, само прашајте'}</span>
            <div className="about-arrange-items">
              <div className="about-arrange-item">
                <span className="ix"><Icon name="coffee"/></span>
                <div><strong>{lang === 'en' ? 'Breakfast' : 'Појадок'}</strong>
                  <span>{lang === 'en' ? 'We can arrange it for your stay.' : 'Можеме да го средиме за вашиот престој.'}</span></div>
              </div>
              <div className="about-arrange-item">
                <span className="ix"><Icon name="car"/></span>
                <div><strong>{lang === 'en' ? 'Transport' : 'Превоз'}</strong>
                  <span>{lang === 'en' ? 'Pickup from the airport or bus station.' : 'Превоз од аеродром или автобуска.'}</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Rooms ----------
function Rooms({ lang, onRoom, onBookRoom }) {
  const S = window.STRINGS.rooms;
  const rooms = window.ROOMS;
  const [active, setActive] = useState(0);
  const room = useMemo(() => rooms[active], [active]);
  const features = (t(room.amenities, lang) || []).slice(0, 4);
  const cardRef = useRef(null);
  const selectRoom = (i) => {
    setActive(i);
    if (window.innerWidth < 900 && cardRef.current) {
      setTimeout(() => cardRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' }), 60);
    }
  };

  return (
    <section className="sec rooms" id="rooms">
      <div className="rooms-top">
        <div>
          <div className="elabel">{t(S.eyebrow, lang)}</div>
          <h2 className="rooms-h">{t(S.heading, lang)}</h2>
        </div>
        <p className="rooms-sub">{t(S.sub, lang)}</p>
      </div>

      <div className="rooms-body">
        <div className="room-pick">
          {rooms.map((r, i) => (
            <button key={r.slug} className={'room-tab' + (active === i ? ' active' : '')} onClick={() => selectRoom(i)}>
              <div className="room-tab-top">
                <span className="room-tab-for">{t(r.bestFor, lang)}</span>
                <Icon name="chevron" className="room-tab-chev"/>
              </div>
              <div className="room-tab-name">{t(r.name, lang)}</div>
              <div className="room-tab-meta">{r.sleeps ? (lang === 'en' ? 'Sleeps ' : 'Спие ') + r.sleeps + ' · ' : ''}{t(r.side, lang)}</div>
            </button>
          ))}
        </div>

        <div className="room-card2" ref={cardRef} style={{ scrollMarginTop: '90px' }}>
          <Photo gradient={room.gradient} image={room.images[0] && room.images[0].image} onClick={() => onRoom(room.slug)} className=""/>
          <div className="room-card2-body">
            <div>
              <div className="room-tone">{t(room.tone, lang)}</div>
              <h3>{t(room.name, lang)}</h3>
              <p className="room-desc">{t(room.description, lang)}</p>
              <button className="room-req" onClick={() => onBookRoom(room.slug)}>{t(S.request, lang)} <Icon name="arrow"/></button>
              <div>
                <button className="room-view" onClick={() => onRoom(room.slug)}>{t(S.view, lang)} →</button>
              </div>
            </div>
            <div className="room-incl">
              <div className="room-incl-h">{t(S.included, lang)}</div>
              <ul>
                {features.map((f, i) => (
                  <li key={i}><span className="tick"><Icon name="check"/></span>{f}</li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Gallery ----------
function Gallery({ lang }) {
  const S = window.STRINGS.gallery;
  const items = window.GALLERY;
  const [i, setI] = useState(0);
  const cur = items[i];
  return (
    <section className="sec" id="gallery">
      <div className="gal-top">
        <div>
          <div className="elabel">{t(S.eyebrow, lang)}</div>
          <h2 className="gal-h">{t(S.heading, lang)}</h2>
        </div>
        <p className="gal-sub">{t(S.sub, lang)}</p>
      </div>

      <div className="gal-stage">
        <Photo className="gal-main" gradient={cur.gradient} image={cur.image}>
          <div className="gal-main-cap">
            <div className="k">{String(i + 1).padStart(2, '0')} / {String(items.length).padStart(2, '0')}</div>
            <div className="t">{t(cur.label, lang)}</div>
          </div>
        </Photo>

        <div className="gal-film">
          {items.map((g, idx) => (
            <button key={idx} className={'gal-thumb' + (idx === i ? ' active' : '')} onClick={() => setI(idx)} aria-label={t(g.label, lang)}>
              <Photo gradient={g.gradient} image={g.image}/>
              <div className="gal-thumb-dim"/>
              <div className="gal-thumb-cap"><div className="t">{t(g.label, lang)}</div></div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Reviews (rotating 3-up carousel) ----------
function Reviews({ lang }) {
  const S = window.STRINGS.reviews;
  const ref = useReveal();
  const all = window.REVIEWS;
  const total = all.length;
  const shown = Math.min(3, total);
  const [start, setStart] = useState(0);
  const [paused, setPaused] = useState(false);

  // Auto-advance one review every 5.5s (window of 3 wraps around); pause on hover
  useEffect(() => {
    if (total <= shown || paused) return;
    const id = setInterval(() => setStart(s => (s + 1) % total), 5500);
    return () => clearInterval(id);
  }, [total, shown, paused]);

  const visible = Array.from({ length: shown }, (_, k) => ({ r: all[(start + k) % total], key: (start + k) % total }));

  return (
    <section className="sec reviews" id="reviews">
      <div className="rev-blob"/>
      <div className="rev-inner reveal" ref={ref}>
        <div className="elabel light">{t(S.eyebrow, lang)}</div>
        <h2 className="rev-h">{t(S.heading, lang)}</h2>
        <div className="rev-grid" key={start} onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
          {visible.map(({ r, key }, i) => (
            <article className="rev-card" style={{ animationDelay: (i * 0.08) + 's' }} key={key}>
              <div className="rev-stars">{[0,1,2,3,4].map(n => <Icon key={n} name="star"/>)}</div>
              <p className="rev-quote">“{t(r.quote, lang)}”</p>
              <div className="rev-foot">
                <div>
                  <div className="nm">{r.author}</div>
                  <div className="or">{lang === 'en' ? 'via' : 'преку'} {t(r.origin, lang)}</div>
                </div>
                <Icon name="leaf"/>
              </div>
            </article>
          ))}
        </div>
        {total > shown && (
          <div className="rev-dots">
            {all.map((_, i) => (
              <button key={i} className={'rev-dot' + (i === start ? ' active' : '')} onClick={() => setStart(i)} aria-label={`Review set ${i + 1}`}/>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

// ---------- Booking + Contact + Footer ----------
function BookSection({ lang, preselectRoom, onClearPreselect }) {
  const S = window.STRINGS.book;
  const C = window.STRINGS.contact;
  const F = window.STRINGS.footer;
  // status: idle | whatsapp | instagram
  const [status, setStatus] = useState('idle');
  const [igBody, setIgBody] = useState('');
  const [copied, setCopied] = useState(false);
  const formRef = useRef(null);
  const [room, setRoom] = useState(preselectRoom || '');
  const [arrive, setArrive] = useState('');
  const today = useMemo(() => new Date().toISOString().split('T')[0], []);
  useEffect(() => { if (preselectRoom) { setRoom(preselectRoom); setStatus('idle'); } }, [preselectRoom]);

  // After the request is copied, give the guest ~2.5s to read the paste steps,
  // then take them straight to our Instagram DM.
  useEffect(() => {
    if (status !== 'instagram') return;
    const id = setTimeout(() => { window.location.href = 'https://ig.me/m/hristiaccommodation'; }, 2500);
    return () => clearTimeout(id);
  }, [status]);

  const roomName = (slug) => { const r = window.ROOMS.find(x => x.slug === slug); return r ? t(r.name, lang) : (lang === 'en' ? 'Any available room' : 'Било која слободна соба'); };

  const composeBody = (d) => {
    const L = (en, mk) => lang === 'en' ? en : mk;
    const breakfast = d.get('breakfast') === 'yes' ? L('Yes, please', 'Да, ве молам') : L('No', 'Не');
    const rideMap = {
      airport: L('Airport pickup', 'Превоз од аеродром'),
      bus:     L('Bus station pickup', 'Превоз од автобуска'),
      other:   L('Yes, see note', 'Да, види белешка'),
    };
    const transport = rideMap[d.get('transport')] || L('No', 'Не');
    return [
      L('New availability request from the Hristi website', 'Ново барање за достапност од веб-страницата на Христи'),
      '',
      L('Arrival', 'Пристигање') + ': ' + (d.get('arrival') || '-'),
      L('Departure', 'Заминување') + ': ' + (d.get('departure') || '-'),
      L('Guests', 'Гости') + ': ' + (d.get('guests') || '-'),
      L('Room', 'Соба') + ': ' + roomName(d.get('room')),
      L('Breakfast', 'Појадок') + ': ' + breakfast,
      L('Transport', 'Превоз') + ': ' + transport,
      L('Name', 'Име') + ': ' + (d.get('name') || '-'),
      L('Email or phone', 'Е-пошта или телефон') + ': ' + (d.get('contact') || '-'),
      L('Note', 'Белешка') + ': ' + (d.get('note') || '-'),
    ].join('\n');
  };

  // Both paths reuse the same formatted request. WhatsApp accepts the whole
  // message in the link, so we open it right away. Instagram can't pre-fill a DM,
  // so we copy the text and show the paste instructions FIRST — opening Instagram
  // is a separate, deliberate tap, so the guest reads what to do before they leave.
  const send = (channel) => {
    const form = formRef.current;
    if (!form.reportValidity()) return;            // enforce the required fields first
    const body = composeBody(new FormData(form));
    if (channel === 'whatsapp') {
      const num = C.phone.replace(/\D/g, '');
      window.open(`https://wa.me/${num}?text=${encodeURIComponent(body)}`, '_blank', 'noopener');
    } else {
      try { navigator.clipboard && navigator.clipboard.writeText(body); setCopied(true); } catch (err) {}
      setIgBody(body);
    }
    setStatus(channel);
    if (onClearPreselect) onClearPreselect();
  };

  const openInstagram = () => { window.location.href = 'https://ig.me/m/hristiaccommodation'; };
  const copyAgain = () => { try { navigator.clipboard && navigator.clipboard.writeText(igBody); setCopied(true); } catch (err) {} };
  const reset = () => { setStatus('idle'); setCopied(false); };

  const done = status === 'whatsapp' || status === 'instagram';

  return (
    <section className="sec book" id="book">
      <div className="book-grid">
        <div className="book-left">
          <div className="elabel">{t(S.eyebrow, lang)}</div>
          <h2 className="book-h">{t(S.heading, lang)}</h2>
          <p className="book-sub">{t(S.sub, lang)}</p>

          <div className="book-info" id="contact">
            <div><Icon name="clock"/> {t(S.quick, lang)}</div>
            <a href={`mailto:${C.email}`}><Icon name="mail"/> {C.email}</a>
            <a href={`tel:${C.phone.replace(/\s/g, '')}`}><Icon name="phone"/> {C.phone}</a>
            <a href={MAP_DIR_URL} target="_blank" rel="noopener noreferrer"><Icon name="pin"/> {t(C.address, lang).replace(/\n/g, ', ')} · {lang === 'en' ? 'Get directions' : 'Насоки'}</a>
          </div>

          <div className="book-know">
            <div className="book-know-h">{lang === 'en' ? 'Good to know' : 'Корисно да се знае'}</div>
            <ul>
              <li><Icon name="clock"/> {lang === 'en' ? 'Check-in 2–5 pm · Check-out by 11 am' : 'Пријавување 14–17 ч · Одјавување до 11 ч'}</li>
              <li><Icon name="cash"/> {lang === 'en' ? 'Cash only' : 'Само готовина'}</li>
              <li><Icon name="no-smoke"/> {lang === 'en' ? 'No smoking indoors' : 'Не се пуши во затворен простор'}</li>
            </ul>
          </div>

          <div className="book-socials">
            {C.social.map(s => <a key={s.name} href={s.url} target="_blank" rel="noopener noreferrer">{s.name}</a>)}
          </div>
        </div>

        <div className="book-card">
          {done ? (
            <div className="book-success">
              <div className="ic">✓</div>
              <h3>{status === 'instagram'
                ? (lang === 'en' ? 'Your request is copied ✓' : 'Вашето барање е копирано ✓')
                : (lang === 'en' ? 'Almost there. Press send' : 'Уште малку. Притиснете испрати')}</h3>
              <p>{status === 'instagram'
                ? (lang === 'en' ? 'Taking you to our Instagram now… when the chat opens, long-press the message box, choose Paste, and hit send. We reply quickly.' : 'Ве носиме до нашиот Instagram… кога ќе се отвори разговорот, држете на полето за порака, изберете Залепи и притиснете испрати. Брзо одговараме.')
                : (lang === 'en' ? 'We opened WhatsApp with your request filled in. Just press send and it comes straight to us.' : 'Отворивме WhatsApp со пополнето барање. Само притиснете испрати и пораката доаѓа директно кај нас.')}</p>
              {status === 'instagram' && (
                <div className="ig-actions">
                  <button className="ig-open" onClick={openInstagram}><Icon name="instagram"/> {lang === 'en' ? 'Open Instagram now' : 'Отвори Instagram веднаш'}</button>
                  <button className="copy-again" onClick={copyAgain}>{copied ? (lang === 'en' ? 'Copied ✓' : 'Копирано ✓') : (lang === 'en' ? 'Copy request again' : 'Копирај повторно')}</button>
                </div>
              )}
              <button className="book-again" onClick={reset}>{t(S.again, lang)}</button>
            </div>
          ) : (
            <form className="book-form2" ref={formRef} onSubmit={e => e.preventDefault()}>
              <div className="book-card-kick" style={{ gridColumn: '1 / -1' }}>
                <div className="k">{t(S.cardKicker, lang)}</div>
                <div className="t">{t(S.cardTitle, lang)}</div>
              </div>
              <label>{t(S.arrive, lang)}<input type="date" name="arrival" required min={today} value={arrive} onChange={e => setArrive(e.target.value)}/></label>
              <label>{t(S.depart, lang)}<input type="date" name="departure" required min={arrive || today}/></label>
              <label>{t(S.guests, lang)}
                <select name="guests" defaultValue="2">
                  <option value="1">1</option><option value="2">2</option>
                  <option value="3">3</option><option value="4">4</option><option value="5">5+</option>
                </select>
              </label>
              <label>{t(S.room, lang)}
                <select name="room" value={room} onChange={e => setRoom(e.target.value)}>
                  <option value="">{t(S.any, lang)}</option>
                  {window.ROOMS.map(r => <option key={r.slug} value={r.slug}>{t(r.name, lang)}</option>)}
                </select>
              </label>
              <label>{lang === 'en' ? 'Breakfast' : 'Појадок'}
                <select name="breakfast" defaultValue="">
                  <option value="">{lang === 'en' ? 'No, thanks' : 'Не, благодарам'}</option>
                  <option value="yes">{lang === 'en' ? 'Yes, please add it' : 'Да, додадете'}</option>
                </select>
              </label>
              <label>{lang === 'en' ? 'Need a ride?' : 'Потребен превоз?'}
                <select name="transport" defaultValue="">
                  <option value="">{lang === 'en' ? 'No, thanks' : 'Не, благодарам'}</option>
                  <option value="airport">{lang === 'en' ? 'Airport pickup' : 'Од аеродром'}</option>
                  <option value="bus">{lang === 'en' ? 'Bus station pickup' : 'Од автобуска'}</option>
                  <option value="other">{lang === 'en' ? 'Other (tell us below)' : 'Друго (напишете подолу)'}</option>
                </select>
              </label>
              <label className="full">{t(S.name, lang)}<input type="text" name="name" required placeholder={lang === 'en' ? 'First and last name' : 'Име и презиме'}/></label>
              <label className="full">{t(S.email, lang)}<input type="text" name="contact" required placeholder={lang === 'en' ? 'name@email.com or phone number' : 'е-пошта или телефон'}/></label>
              <label className="full">{t(S.note, lang)}<textarea name="note" rows="4" placeholder={lang === 'en' ? 'Arrival time, questions, room preference…' : 'Време на пристигнување, прашања, преференца…'}/></label>
              <div className="book-actions">
                <button type="button" className="submit wa" onClick={() => send('whatsapp')}>
                  <Icon name="whatsapp"/> {lang === 'en' ? 'Send via WhatsApp' : 'Испрати преку WhatsApp'}
                </button>
                <button type="button" className="submit ig" onClick={() => send('instagram')}>
                  <Icon name="instagram"/> {lang === 'en' ? 'Send via Instagram' : 'Испрати преку Instagram'}
                </button>
              </div>
              <p className="book-note">{lang === 'en' ? 'Pick whichever you use. Your dates and details travel with the message, and we reply quickly.' : 'Изберете што користите. Датумите и деталите одат заедно со пораката, а ние брзо одговараме.'}</p>
            </form>
          )}
        </div>
      </div>

      <div className="book-map">
        <div className="book-map-bar">
          <span><Icon name="pin"/> {t(C.address, lang).replace(/\n/g, ', ')}</span>
          <a href={MAP_DIR_URL} target="_blank" rel="noopener noreferrer">{lang === 'en' ? 'Get directions →' : 'Насоки →'}</a>
        </div>
        <iframe
          title={lang === 'en' ? 'Map to Hristi Accommodation' : 'Мапа до Hristi Accommodation'}
          src={MAP_EMBED_URL}
          loading="lazy"
          referrerPolicy="no-referrer-when-downgrade"
          allowFullScreen
        />
      </div>

      <div className="footer">
        <span>{t(F.rights, lang)}</span>
        <span>{t(F.tag, lang)}</span>
      </div>
    </section>
  );
}

// ---------- Lightbox (click a photo to view it full-size) ----------
function Lightbox({ images, index, lang, onClose, setIndex }) {
  const count = images.length;
  const go = (dir) => setIndex((index + dir + count) % count);
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowRight') go(1);
      else if (e.key === 'ArrowLeft') go(-1);
    };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  });
  const cur = images[index];
  return (
    <div className="lb" onClick={onClose}>
      <button className="lb-close" onClick={onClose} aria-label={t(window.STRINGS.nav.close, lang)}>×</button>
      {count > 1 && <button className="lb-nav lb-prev" onClick={(e) => { e.stopPropagation(); go(-1); }} aria-label="Previous">‹</button>}
      <figure className="lb-stage" onClick={(e) => e.stopPropagation()}>
        <img className="lb-img" src={cur.image} alt={t(cur.label, lang)} />
        <figcaption className="lb-cap">
          <span className="lb-label">{t(cur.label, lang)}</span>
          {count > 1 && <span className="lb-count">{index + 1} / {count}</span>}
        </figcaption>
      </figure>
      {count > 1 && <button className="lb-nav lb-next" onClick={(e) => { e.stopPropagation(); go(1); }} aria-label="Next">›</button>}
    </div>
  );
}

// ---------- Room detail ----------
function RoomDetail({ slug, lang, onBack, onBookRoom }) {
  const [lbIndex, setLbIndex] = useState(null);
  const room = window.ROOMS.find(r => r.slug === slug);
  const S = window.STRINGS.detail;
  if (!room) return <div className="rd-wrap"><button className="rd-back" onClick={onBack}>← {t(S.back, lang)}</button></div>;
  return (
    <div className="rd-wrap">
      <button className="rd-back" onClick={onBack}><span className="arrow">←</span> {t(S.back, lang)}</button>

      <div className="rd-hero">
        <div>
          <div className="rd-num">{lang === 'en' ? 'Room' : 'Соба'} {room.number}</div>
          <h1 className="rd-name">{t(room.name, lang).split(' ').map((w, i, a) => i === a.length - 1 ? <em key={i}>{w}</em> : <span key={i}>{w} </span>)}</h1>
          <p className="rd-teaser">{t(room.teaser, lang)}</p>
        </div>
        <div>
          <p style={{ fontFamily: 'var(--font-heading)', fontSize: '1.3rem', lineHeight: 1.5, color: 'var(--muted)', fontStyle: 'italic', margin: 0, letterSpacing: '-0.01em', maxWidth: '44ch' }}>
            {t(room.description, lang)}
          </p>
        </div>
      </div>

      <div className="rd-facts">
        <div className="rd-fact"><div className="k">{lang === 'en' ? 'Bed' : 'Кревет'}</div><div className="v">{t(room.bed, lang)}</div></div>
        <div className="rd-fact"><div className="k">{lang === 'en' ? 'Floor' : 'Кат'}</div><div className="v">{t(room.floor, lang)}</div></div>
        <div className="rd-fact"><div className="k">{lang === 'en' ? 'Side' : 'Страна'}</div><div className="v">{t(room.side, lang)}</div></div>
        {room.sleeps && <div className="rd-fact"><div className="k">{lang === 'en' ? 'Sleeps' : 'Спие'}</div><div className="v">{room.sleeps}</div></div>}
      </div>

      <div className="rd-gallery">
        {room.images.map((im, i) => (
          <Photo key={i} gradient={im.gradient} image={im.image} onClick={im.image ? () => setLbIndex(i) : undefined}>
            <span className="lbl">{t(im.label, lang)}</span>
            {im.image && <span className="photo-zoom" aria-hidden="true"><Icon name="expand"/></span>}
          </Photo>
        ))}
      </div>

      {lbIndex !== null && (
        <Lightbox
          images={room.images}
          index={lbIndex}
          lang={lang}
          onClose={() => setLbIndex(null)}
          setIndex={setLbIndex}
        />
      )}

      <div className="rd-body">
        <div>
          <h3 className="rd-section-title">{t(S.about, lang)}</h3>
          <p className="rd-description">{t(room.description, lang)}</p>
          <div className="rd-arrange">
            <span className="ix"><Icon name="coffee"/></span>
            <span className="ix"><Icon name="car"/></span>
            <p>{lang === 'en'
              ? 'Breakfast and transport from the airport or bus station can be arranged. Just ask us.'
              : 'Појадок и превоз од аеродром или автобуска можат да се организираат. Само прашајте нè.'}</p>
          </div>
        </div>
        <div>
          <h3 className="rd-section-title">{t(S.inside, lang)}</h3>
          <ul className="rd-amen">{t(room.amenities, lang).map((a, i) => <li key={i}><Icon name={amenityIcon(a)} className="rd-amen-ic"/> {a}</li>)}</ul>
        </div>
      </div>

      <div className="rd-cta-row">
        <button className="rd-cta" onClick={() => onBookRoom(room.slug)}>{t(S.book, lang)} <Icon name="arrow"/></button>
      </div>
    </div>
  );
}

// ---------- App ----------
function App() {
  const [lang, setLang] = useState(() => localStorage.getItem('hristi_lang') || 'en');
  const [view, setView] = useState({ name: 'home', slug: null });
  const [preselectRoom, setPreselectRoom] = useState('');
  const [navHidden, setNavHidden] = useState(false);
  const lastY = useRef(0);

  useEffect(() => { localStorage.setItem('hristi_lang', lang); document.documentElement.lang = lang; }, [lang]);

  // Hide the header once scrolled past the hero; reveal again when scrolling up
  // (or back within the hero) so navigation stays reachable.
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      if (view.name !== 'home') { setNavHidden(false); lastY.current = y; return; }
      const hero = document.getElementById('top');
      const heroBottom = hero ? hero.getBoundingClientRect().bottom : 0;
      if (heroBottom > 80) setNavHidden(false);                 // still in the hero → always show
      else if (y > lastY.current + 4) setNavHidden(true);       // scrolling down past hero → hide
      else if (y < lastY.current - 4) setNavHidden(false);      // scrolling up → reveal
      lastY.current = y;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [view.name]);

  const navTo = (id) => {
    if (view.name !== 'home') {
      setView({ name: 'home', slug: null });
      setTimeout(() => {
        const el = document.getElementById(id);
        if (el) window.scrollTo({ top: el.offsetTop - 80, behavior: 'smooth' });
        else window.scrollTo({ top: 0, behavior: 'smooth' });
      }, 40);
      return;
    }
    if (id === 'top') { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 80, behavior: 'smooth' });
  };

  const goRoom = (slug) => { setView({ name: 'room', slug }); setTimeout(() => window.scrollTo({ top: 0 }), 30); };
  const back = () => {
    setView({ name: 'home', slug: null });
    setTimeout(() => { const el = document.getElementById('rooms'); if (el) window.scrollTo({ top: el.offsetTop - 80 }); }, 40);
  };
  const goBookRoom = (slug) => {
    setPreselectRoom(slug);
    setView({ name: 'home', slug: null });
    setTimeout(() => { const el = document.getElementById('book'); if (el) window.scrollTo({ top: el.offsetTop - 80, behavior: 'smooth' }); }, 60);
  };

  return (
    <div>
      <Header lang={lang} setLang={setLang} onNav={navTo} onBook={() => navTo('book')} hidden={navHidden}/>
      {view.name === 'home' ? (
        <main>
          <Hero lang={lang} onBook={() => navTo('book')} onNav={navTo}/>
          <About lang={lang}/>
          <Rooms lang={lang} onRoom={goRoom} onBookRoom={goBookRoom}/>
          <Gallery lang={lang}/>
          <Reviews lang={lang}/>
          <BookSection lang={lang} preselectRoom={preselectRoom} onClearPreselect={() => setPreselectRoom('')}/>
        </main>
      ) : (
        <main>
          <RoomDetail slug={view.slug} lang={lang} onBack={back} onBookRoom={goBookRoom}/>
        </main>
      )}
    </div>
  );
}

Object.assign(window, { App });
