/* global React, L */
// 'sFontaine 1: one-page site for the gîte, in a rounded listing-page layout:
// hero (text + video) and a photo row, the gîte, prices + calendar with a booking card, reviews, map, area, host, FAQ.
// Colours: forest / terracotta / cream (CSS variables and classes live in index.html).
// Reads window.VALMOREL (valmorel-data.js + content/*.json); every text exists in fr, en and nl.

const { useState, useRef, useEffect, useContext, useCallback } = React;
const V_ALPINE = window.VALMOREL;
const trA = window.tr;
// CMS texts may hold links as [words](https://...): shown underlined, opening in a new tab. Only web, mail and phone links.
// A bare https:// address becomes a link too (a trailing full stop or comma stays text).
// Enters typed in the CMS show as line breaks (pre-line).
const linkify = (s) => <span style={{ whiteSpace: 'pre-line' }}>{String(s ?? '').trim().split(/(\[[^\]]+\]\((?:https?:\/\/|mailto:|tel:)[^)\s]+\)|https?:\/\/[^\s<]*[^\s<.,;:!?)])/).map((part, i) => {
  if (!(i % 2)) return part;
  const [, words, href] = part.match(/^\[(.+)\]\((.+)\)$/) || [, part, part];
  return <a key={i} className="vm-text-link" href={href} target="_blank" rel="noopener noreferrer">{words}</a>;
})}</span>;
const esc = (s) => String(s).replace(/[&<>"]/g, c => `&#${c.charCodeAt(0)};`); // CMS text inside HTML strings (map labels)

const LightboxCtx = React.createContext(null);

// Placeholder colours for photo slots that have no photo yet
const TONES = ['warm', 'cream', 'forest'];
const TONE = {
  warm:   { bg: '#e8dcc4', stripe: 'rgba(120,90,60,0.10)', text: '#8a7050' },
  forest: { bg: '#3a4a37', stripe: 'rgba(255,255,255,0.06)', text: '#a8b8a3' },
  cream:  { bg: '#efe7d6', stripe: 'rgba(120,90,60,0.08)', text: '#9a8166' },
};
const stripes = (t, gap = 14) => `repeating-linear-gradient(135deg, ${t.stripe} 0 2px, transparent 2px ${gap}px)`;

const LOCALE = { fr: 'fr-FR', en: 'en-GB', nl: 'nl-NL' };
const fmtEur = (p, lang) => p.toLocaleString(LOCALE[lang], {
  style: 'currency', currency: 'EUR', minimumFractionDigits: p % 1 ? 2 : 0, maximumFractionDigits: 2 });
const fmtOne = (v, lang) => v.toLocaleString(LOCALE[lang], { minimumFractionDigits: 1, maximumFractionDigits: 1 });
const telHref = (phone) => 'tel:' + phone.replace(/[^+\d]/g, '');

// Holds the width of the longest translation, so switching language doesn't shift the layout
function StableText({ k, lang }) {
  return (
    <span style={{ display: 'inline-grid', justifyItems: 'center' }}>
      {['fr', 'en', 'nl'].map(l => (
        <span key={l} style={{ gridArea: '1 / 1', visibility: l === lang ? 'visible' : 'hidden' }}>{trA(V_ALPINE.i18n[k], l)}</span>
      ))}
    </span>
  );
}

// Phone layout switch for the few things CSS can't do (calendar months); the rest is in index.html
const MOBILE_Q = '(max-width: 760px)';
function useMobile() {
  const [m, setM] = useState(() => window.matchMedia(MOBILE_Q).matches);
  useEffect(() => {
    const mq = window.matchMedia(MOBILE_Q);
    const on = () => setM(mq.matches);
    mq.addEventListener('change', on);
    return () => mq.removeEventListener('change', on);
  }, []);
  return m;
}

const scrollToId = (id) => {
  const el = document.getElementById(id);
  if (!el) return;
  window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 96, behavior: 'smooth' });
};

// ─── ICONS (1-stroke, currentColor) ─────────────────────────────────────
const IconA = {
  check: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/>
    </svg>
  ),
  wifi: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
      <path d="M5 12.5a10 10 0 0 1 14 0"/><path d="M8 15.5a6 6 0 0 1 8 0"/><circle cx="12" cy="18.5" r="1" fill="currentColor"/>
    </svg>
  ),
  garage: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 10 12 4l9 6v10H3z"/><path d="M6 14h12M6 18h12"/>
    </svg>
  ),
  ski: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
      <path d="m4 18 16-6M5 20l14-5"/><path d="m9 11 4-7M11 13l4-7"/>
    </svg>
  ),
  boot: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round">
      <path d="M8 4h4v10l5 3 2 4H5v-3l3-2z"/>
    </svg>
  ),
  terrace: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
      <path d="M3 19h18M5 19V9l7-5 7 5v10"/><path d="M10 19v-5h4v5"/>
    </svg>
  ),
  view: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round">
      <path d="m3 18 5-7 4 5 3-4 6 8z"/><circle cx="17" cy="6" r="2"/>
    </svg>
  ),
  kitchen: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round">
      <rect x="5" y="3" width="14" height="18" rx="1"/><path d="M5 10h14M9 6h2M9 14h6M9 17h6"/>
    </svg>
  ),
  dish: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
      <ellipse cx="12" cy="14" rx="9" ry="3"/><path d="M3 14v4c0 1.5 4 3 9 3s9-1.5 9-3v-4"/>
    </svg>
  ),
  wash: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
      <rect x="4" y="3" width="16" height="18" rx="1"/><circle cx="12" cy="14" r="4"/><circle cx="8" cy="6.5" r=".5" fill="currentColor"/>
    </svg>
  ),
  linen: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round">
      <path d="M3 11h18v9H3z"/><path d="M3 11V7l9-3 9 3v4"/><path d="M12 4v7"/>
    </svg>
  ),
  smoke: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="2.5" fill="currentColor"/>
    </svg>
  ),
  heat: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
      <path d="M12 3c-2 3 2 4 0 7s2 4 0 7"/><path d="M7 6c-1.5 2 1.5 3 0 5s1.5 3 0 5M17 6c-1.5 2 1.5 3 0 5s1.5 3 0 5"/>
    </svg>
  ),
};

// Interface icons
const svg = (d, w = 16, extra = {}) => (
  <svg width={w} height={w} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"
       strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" {...extra}>{d}</svg>
);
const Ico = {
  globe: svg(<><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 2.7 3.8 5.7 3.8 9s-1.3 6.3-3.8 9c-2.5-2.7-3.8-5.7-3.8-9S9.5 5.7 12 3z"/></>, 18),
  menu: svg(<path d="M4 7h16M4 12h16M4 17h16"/>, 18),
  close: svg(<path d="M6 6l12 12M18 6L6 18"/>, 18),
  grid: svg(<><rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><rect x="14" y="14" width="6" height="6" rx="1"/></>, 16),
  left: svg(<path d="m15 18-6-6 6-6"/>, 16),
  right: svg(<path d="m9 18 6-6-6-6"/>, 16),
  down: svg(<path d="m6 9 6 6 6-6"/>, 16),
  copy: svg(<><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V6a2 2 0 0 1 2-2h8"/></>, 14),
  check: svg(<path d="m5 12 5 5 9-10"/>, 14),
  out: svg(<path d="M7 17 17 7M8 7h9v9"/>, 14),
  arrow: svg(<path d="M5 12h14M13 6l6 6-6 6"/>, 14),
  route: svg(<><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M19 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"/></>, 16),
  star: <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2.5l2.9 6.1 6.6.8-4.9 4.6 1.3 6.6L12 17.3l-5.9 3.3 1.3-6.6-4.9-4.6 6.6-.8z"/></svg>,
  play: <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style={{ marginLeft: 3 }}><path d="M8 5v14l11-7z"/></svg>,
};

// ─── PHOTO — real photo or a placeholder; opens the lightbox when idx is set ──
function PhotoA({ src, idx, label, tone = 'warm', ratio, radius = 12, showLabel }) {
  const open = useContext(LightboxCtx);
  const t = TONE[tone] || TONE.warm;
  const realSrc = src || (idx !== undefined && V_ALPINE.photos.gallery[idx]?.photo);
  const clickable = idx !== undefined && !!open;
  return (
    <div className={clickable ? 'vm-clickable' : undefined}
         role={clickable ? 'button' : undefined} tabIndex={clickable ? 0 : undefined} aria-label={clickable ? label : undefined}
         onClick={clickable ? () => open(idx) : undefined}
         onKeyDown={clickable ? (e) => e.key === 'Enter' && open(idx) : undefined}
         style={{ position: 'relative', overflow: 'hidden', borderRadius: radius, aspectRatio: ratio,
                  height: ratio ? undefined : '100%', background: t.bg, backgroundImage: realSrc ? 'none' : stripes(t),
                  cursor: clickable ? 'pointer' : 'default' }}>
      {realSrc && <img className="vm-photo-img" src={realSrc} alt={label || ''} loading="lazy" decoding="async" draggable={false}/>}
      {label && (!realSrc || showLabel) && (
        <span style={{ position: 'absolute', left: 12, ...(realSrc ? { bottom: 12 } : { top: 12 }), padding: '4px 10px', borderRadius: 999,
                       background: realSrc ? 'rgba(255,252,247,0.92)' : 'transparent', color: realSrc ? '#2d3e2c' : t.text,
                       font: '600 12px/1.3 "Manrope", sans-serif', pointerEvents: 'none' }}>{label}</span>
      )}
    </div>
  );
}

// Owner photo, or initials while there is none
function Avatar({ size = 48 }) {
  const c = V_ALPINE.contact, src = V_ALPINE.photos.owner;
  const initials = c.name.split(/\s+/).map(w => w[0]).join('').slice(0, 2);
  return src
    ? <img src={src} alt={c.name} style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }}/>
    : <span aria-hidden="true" style={{ width: size, height: size, borderRadius: '50%', background: 'var(--ink)', color: 'var(--bg)',
                                        display: 'grid', placeItems: 'center', flexShrink: 0,
                                        font: `600 ${Math.round(size * 0.36)}px/1 "Fraunces", serif` }}>{initials}</span>;
}

// ─── HEADER ─────────────────────────────────────────────────────────────
function TopBarA({ lang, setLang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [active, setActive] = useState('top');
  const [scrolled, setScrolled] = useState(false);
  const [menu, setMenu] = useState(null); // 'nav' | 'lang' | null
  const go = (id) => { setMenu(null); scrollToId(id); };
  const flag = (kids) => <svg width="22" height="16" viewBox="0 0 22 16" aria-hidden="true" style={{ borderRadius: 3, flexShrink: 0, boxShadow: '0 0 0 1px rgba(45,62,44,0.12)' }}>{kids}</svg>;
const FLAGS = {
  fr: flag(<><rect width="22" height="16" fill="#fff"/><rect width="7.33" height="16" fill="#0055a4"/><rect x="14.67" width="7.33" height="16" fill="#ef4135"/></>),
  nl: flag(<><rect width="22" height="16" fill="#fff"/><rect width="22" height="5.33" fill="#ae1c28"/><rect y="10.67" width="22" height="5.33" fill="#21468b"/></>),
  en: flag(<><rect width="22" height="16" fill="#012169"/><path d="M0 0l22 16M22 0 0 16" stroke="#fff" strokeWidth="3.2"/><path d="M0 0l22 16M22 0 0 16" stroke="#c8102e" strokeWidth="1.2"/><path d="M11 0v16M0 8h22" stroke="#fff" strokeWidth="5"/><path d="M11 0v16M0 8h22" stroke="#c8102e" strokeWidth="3"/></>),
};
const LANGS = [['fr', FLAGS.fr, 'Français'], ['en', FLAGS.en, 'English'], ['nl', FLAGS.nl, 'Nederlands']];
  const navItems = [
    { k: 'nav_overview', id: 'top' },
    { k: 'nav_house',    id: 'le-gite' },
    { k: 'nav_reviews',  id: 'avis' },
    { k: 'nav_location', id: 'localisation' },
    { k: 'nav_area',     id: 'le-domaine' },
    { k: 'nav_faq',      id: 'faq' },
    { k: 'nav_host',     id: 'hote' },
  ];

  // Which section is under the header (ids in page order), and a soft blur once scrolled
  useEffect(() => {
    const ids = ['top', 'le-gite', 'reserver', 'avis', 'localisation', 'le-domaine', 'faq', 'hote'];
    const onScroll = () => {
      let current = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top <= 120) current = id;
      }
      // At the very bottom the last section can't reach the header line; mark it anyway
      if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2) current = ids[ids.length - 1];
      setActive(current);
      setScrolled(window.scrollY > 8);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    if (!menu) return;
    const onKey = (e) => e.key === 'Escape' && setMenu(null);
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [menu]);

  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, boxShadow: scrolled ? '0 2px 16px rgba(45,62,44,0.08)' : 'none', transition: 'box-shadow .2s',
                     background: scrolled ? 'rgba(245,241,234,0.92)' : 'var(--bg)',
                     backdropFilter: scrolled ? 'saturate(1.4) blur(14px)' : 'none',
                     WebkitBackdropFilter: scrolled ? 'saturate(1.4) blur(14px)' : 'none' }}>
      {menu && <div onClick={() => setMenu(null)} style={{ position: 'fixed', inset: 0 }}/>}
      <div className="vm-wrap" style={{ position: 'relative', height: 72, display: 'flex', alignItems: 'center',
                                        justifyContent: 'space-between', gap: 16 }}>
        <button className="vm-brand" onClick={() => go('top')} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer',
                                                   textAlign: 'left', color: 'inherit', display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src={V_ALPINE.photos.logo || 'favicon.svg'} alt="" style={{ height: 40, width: 'auto', flexShrink: 0 }}/>
          <span>
            <div style={{ font: '600 19px/1 "Fraunces", serif', whiteSpace: 'nowrap' }}>{V_ALPINE.brand.name}</div>
            <div className="vm-muted" style={{ font: '500 12px/1 "Manrope", sans-serif', marginTop: 5, whiteSpace: 'nowrap' }}>
              Réf. {V_ALPINE.brand.ref}
            </div>
          </span>
        </button>

        <nav className="vm-nav" style={{ display: 'flex', gap: 2, whiteSpace: 'nowrap', font: '500 15px/1 "Manrope", sans-serif' }}>
          {navItems.map(item => (
            <a key={item.k} href={'#' + item.id} onClick={(e) => { e.preventDefault(); go(item.id); }}
               aria-current={active === item.id}>
              <StableText k={item.k} lang={lang}/>
            </a>
          ))}
        </nav>

        <div className="vm-header-right" style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 8 }}>
          <button className="vm-icon-btn" aria-label="Langue / Language / Taal" aria-expanded={menu === 'lang'}
                  onClick={() => setMenu(m => m === 'lang' ? null : 'lang')}>{Ico.globe}</button>
          <button className="vm-btn vm-btn-primary vm-btn-green vm-pill" onClick={() => go('reserver')}
                  style={{ padding: '10px 18px', fontSize: 15, transition: 'background-color .2s, color .2s',
                           ...(active === 'reserver' && { background: 'var(--accent)' }) }}>
            <StableText k="nav_book" lang={lang}/></button>
          <button className="vm-icon-btn vm-burger" aria-label="Menu" aria-expanded={menu === 'nav'}
                  onClick={() => setMenu(m => m === 'nav' ? null : 'nav')}>{menu === 'nav' ? Ico.close : Ico.menu}</button>
          {menu === 'lang' && (
            <div className="vm-menu" role="menu">
              {LANGS.map(([L, flag, name]) => (
                <button key={L} className="vm-menu-item" aria-current={lang === L} onClick={() => { setLang(L); setMenu(null); }}>
                  {flag}{name}
                </button>
              ))}
            </div>
          )}
          {menu === 'nav' && (
            <div className="vm-menu" style={{ minWidth: 250 }}>
              {navItems.map(item => (
                <button key={item.k} className="vm-menu-item" aria-current={active === item.id} onClick={() => go(item.id)}
                        style={{ font: '600 17px/1.2 "Fraunces", serif', padding: '14px 20px' }}>{t(item.k)}</button>
              ))}
            </div>
          )}
        </div>
      </div>
    </header>
  );
}

// ─── TITLE + PHOTO GRID ─────────────────────────────────────────────────
function TitleA({ lang, rv }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const b = V_ALPINE.brand;
  const open = useContext(LightboxCtx);
  return (
    <section id="top" className="vm-sec" style={{ paddingTop: 40 }}>
      <div className="vm-hero" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.15fr)', gap: 56, alignItems: 'center' }}>
        <div>
          <h1 className="vm-h1" style={{ fontSize: 'clamp(34px, 4.2vw, 58px)', lineHeight: 1.05 }}>
            {t('hero_title_a')}<br/><span style={{ color: 'var(--accent)' }}>{t('hero_title_b')}</span>
          </h1>
          <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '6px 20px', marginTop: 16,
                        font: '500 15px/1.4 "Manrope", sans-serif' }}>
            {rv.count > 0 && (
              <button className="vm-link" onClick={() => scrollToId('avis')} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <span style={{ color: 'var(--accent)', display: 'flex' }}>{Ico.star}</span>{rv.title}
              </button>
            )}
            <button className="vm-link" onClick={() => scrollToId('localisation')}>{b.town}, {b.region}</button>
          </div>
          <p className="vm-p" style={{ fontSize: 17, lineHeight: 1.65, color: '#4a4233', maxWidth: 520, marginTop: 24 }}>{linkify(t('hero_lede'))}</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginTop: 32 }}>
            <button className="vm-btn vm-btn-dark" onClick={() => scrollToId('reserver')}>{t('hero_check')}</button>
            {V_ALPINE.photos.gallery.length > 0 && (
              <button className="vm-btn vm-btn-outline" onClick={() => open(0)}>{Ico.grid}{t('gal_all')}</button>
            )}
          </div>
        </div>
        <HeroVideoA lang={lang}/>
      </div>
      <PhotoRowA lang={lang}/>
    </section>
  );
}

function HeroVideoA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [playing, setPlaying] = useState(false);
  return (
    <div className="vm-hero-media">
      {playing ? (
        <iframe src={`https://www.youtube.com/embed/${V_ALPINE.brand.video}?autoplay=1&rel=0&modestbranding=1&playsinline=1`}
                title={`${V_ALPINE.brand.name}, Valmorel`}
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen"
                allowFullScreen referrerPolicy="strict-origin-when-cross-origin"
                style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none', background: '#000' }}/>
      ) : (
        <button className="vm-play-tile" onClick={() => setPlaying(true)} aria-label={t('hero_video')} disabled={!V_ALPINE.brand.video}
                style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none', padding: 0, cursor: 'pointer',
                         background: `#3a4a37 url(${V_ALPINE.photos.hero}) center top/cover` /* top: keeps the Gîtes de France logo in view */ }}>
          <span style={{ position: 'absolute', inset: 0,
                         background: 'radial-gradient(ellipse at center, rgba(20,28,20,0.35) 0%, rgba(20,28,20,0.12) 70%)' }}/>
          {V_ALPINE.brand.video && <span style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
                         alignItems: 'center', justifyContent: 'center', gap: 16 }}>
            <span className="vm-play" style={{ width: 80, height: 80, borderRadius: '50%', background: 'var(--accent)', color: 'var(--bg)',
                                               display: 'grid', placeItems: 'center',
                                               boxShadow: '0 12px 32px rgba(0,0,0,0.35), 0 0 0 8px rgba(245,241,234,0.2)' }}>{Ico.play}</span>
            <span style={{ padding: '9px 16px', borderRadius: 999, background: 'rgba(255,252,247,0.92)', color: 'var(--ink)',
                           font: '600 15px/1 "Manrope", sans-serif' }}>{t('hero_video')}</span>
          </span>}
        </button>
      )}
    </div>
  );
}

// Gallery photos under the hero; the photo behind the video is left out so nothing shows twice
// Marks a horizontal scroller with data-l / data-r while more is hidden on that side; CSS fades that edge on phones.
function useEdgeFade(ref, dep) {
  useEffect(() => {
    const s = ref.current; if (!s) return;
    const m = () => { s.toggleAttribute('data-l', s.scrollLeft > 4); s.toggleAttribute('data-r', s.scrollLeft + s.clientWidth < s.scrollWidth - 4); };
    m(); s.addEventListener('scroll', m, { passive: true }); addEventListener('resize', m);
    return () => { s.removeEventListener('scroll', m); removeEventListener('resize', m); };
  }, [dep]);
}

function PhotoRowA({ lang }) {
  const row = V_ALPINE.photos.gallery.map((p, i) => [p, i]).filter(([p]) => p.photo !== V_ALPINE.photos.hero);
  const el = useRef(null), drag = useRef(null);
  const [edge, setEdge] = useState({ left: false, right: false }); // fades show where more photos are hidden
  const measure = () => { const s = el.current; if (s) setEdge({ left: s.scrollLeft > 4, right: s.scrollLeft + s.clientWidth < s.scrollWidth - 4 }); };
  useEffect(() => { measure(); addEventListener('resize', measure); return () => removeEventListener('resize', measure); }, []);
  if (!row.length) return null;
  // Mouse drag scrolls the row; touch scrolls natively. A drag never opens the photo.
  const down = (e) => { if (e.pointerType === 'mouse') drag.current = { x: e.clientX, left: el.current.scrollLeft, moved: false }; };
  const move = (e) => {
    const d = drag.current; if (!d) return;
    if (Math.abs(e.clientX - d.x) > 5) d.moved = true;
    el.current.scrollLeft = d.left - (e.clientX - d.x);
  };
  const up = () => { setTimeout(() => { drag.current = null; }, 0); };
  const fade = (side) => ({ position: 'absolute', top: 0, bottom: 0, [side]: 0, width: 72, pointerEvents: 'none', transition: 'opacity .25s',
    background: `linear-gradient(to ${side === 'right' ? 'left' : 'right'}, var(--bg), transparent)`, opacity: edge[side] ? 1 : 0 });
  return (
    <div className="vm-photo-wrap" style={{ position: 'relative', marginTop: 24 }}>
      <div ref={el} className="vm-photo-row" onScroll={measure} onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerLeave={up}
           onClickCapture={(e) => { if (drag.current?.moved) { e.stopPropagation(); e.preventDefault(); } }}>
        {row.map(([p, i]) => <PhotoA key={i} idx={i} ratio="4/3" label={trA(p.caption, lang)} tone={TONES[i % 3]}/>)}
      </div>
      <div aria-hidden="true" style={fade('left')}/>
      <div aria-hidden="true" style={fade('right')}/>
    </div>
  );
}

// ─── LEFT COLUMN: about the gîte ────────────────────────────────────────
function OverviewA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const b = V_ALPINE.brand, c = V_ALPINE.contact;
  const amen = (key) => trA(V_ALPINE.amenities.find(a => a.key === key), lang);
  const highlights = [
    [IconA.ski, `${b.distToLift} m ${t('stat_lift')}`],
    [IconA.garage, amen('garage')],
    [IconA.terrace, amen('terrace')],
  ].filter(([, text]) => text); // an amenity removed in the CMS drops out here too
  return (
    <section className="vm-sec" id="le-gite">
      <div className="vm-split" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.4fr)' }}>
        <div>
          <h2 className="vm-h2" style={{ marginBottom: 10 }}>{t('intro_title')}</h2>
          <p className="vm-p vm-muted">
            {b.capacity} {t('stat_guests')}, {b.bedrooms} {t('stat_rooms')}, {b.bathrooms} {t('stat_baths')}, {b.surface} m²
          </p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 28 }}>
            <Avatar size={48}/>
            <div>
              <div style={{ font: '600 16px/1.3 "Manrope", sans-serif' }}>{t('own_host')}: {c.name}</div>
              {c.since && <div className="vm-small vm-muted">{t('own_since')} {c.since}</div>}
            </div>
          </div>
        </div>
        <div>
          <p className="vm-p" style={{ fontSize: 17, lineHeight: 1.7 }}>{linkify(t('intro_body'))}</p>
        </div>
      </div>
      <div className="vm-grid-3" style={{ marginTop: 40 }}>
        {highlights.map(([icon, text], i) => (
          <div key={i} className="vm-card" style={{ padding: '20px 24px', display: 'flex', alignItems: 'center', gap: 16 }}>
            <span style={{ width: 28, height: 28, flexShrink: 0, color: 'var(--accent)' }}>{icon}</span>
            <span style={{ font: '600 16px/1.35 "Manrope", sans-serif' }}>{text}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

function FloorsA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [zoom, setZoom] = useState(null);
  const plans = [
    { src: 'images/plan-rdc.jpg', label: t('floor_gf'),
      note: lang === 'fr' ? 'Sur 2 niveaux : salon, cuisine, 3 chambres (1, 2 et 3), 2 terrasses, parking 2 places'
          : lang === 'nl' ? 'Over 2 niveaus: salon, keuken, 3 slaapkamers (1, 2 en 3), 2 terrassen, parking 2 plekken'
          : 'Across 2 levels: living, kitchen, 3 bedrooms (1, 2 and 3), 2 terraces, parking for 2' },
    { src: 'images/plan-etage.jpg', label: t('floor_1'),
      note: lang === 'fr' ? 'Chambre 4 (2 lits 80×200), salle d’eau privée (SDB 4)'
          : lang === 'nl' ? 'Slaapkamer 4 (2 bedden 80×200), privé-badkamer (SDB 4)'
          : 'Bedroom 4 (2 single beds 80×200), private bathroom (SDB 4)' },
  ];
  const floors = [['01', 'floor_1', 'floor_1_desc'], ['00', 'floor_gf', 'floor_gf_desc'], ['-1', 'floor_bs', 'floor_bs_desc'], ['-2', 'floor_base', 'floor_base_desc']];
  return (
    <section className="vm-sec">
      <h2 className="vm-h2">{t('floors_title')}</h2>
      <div className="vm-grid-2">
        {plans.map((p, i) => (
          <button key={i} onClick={() => setZoom(p)} className="vm-card"
                  style={{ padding: 0, overflow: 'hidden', cursor: 'zoom-in', textAlign: 'left', color: 'inherit' }}>
            <div style={{ background: '#fffdf8', padding: 16 }}>
              <img src={p.src} alt={p.label} loading="lazy" decoding="async" className="vm-plan-img"
                   style={{ display: 'block', width: '100%', height: 280, objectFit: 'contain' }}/>
            </div>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ font: '600 16px/1.3 "Manrope", sans-serif' }}>{p.label}</div>
              <div className="vm-small vm-muted" style={{ marginTop: 4 }}>{p.note}</div>
            </div>
          </button>
        ))}
      </div>
      <div style={{ marginTop: 32 }}>
        {floors.map(([n, label, desc], i) => (
          <div key={label} className="vm-floor" style={{ display: 'grid', gridTemplateColumns: '96px minmax(0, 260px) minmax(0, 1fr)', gap: 32,
                                                         alignItems: 'baseline', padding: '22px 0' }}>
            <div style={{ font: '600 44px/1 "Fraunces", serif', color: 'var(--accent)' }}>{n}</div>
            <div style={{ font: '600 20px/1.25 "Fraunces", serif' }}>{t(label)}</div>
            <p className="vm-p" style={{ color: '#4a4233' }}>{linkify(t(desc))}</p>
          </div>
        ))}
      </div>
      {zoom && (
        <div onClick={() => setZoom(null)} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(31,44,30,0.94)',
                                                    display: 'flex', flexDirection: 'column', alignItems: 'center',
                                                    justifyContent: 'center', padding: 24, cursor: 'zoom-out' }}>
          <div style={{ font: '600 20px/1.2 "Fraunces", serif', color: 'var(--bg)', marginBottom: 16 }}>{zoom.label}</div>
          <img src={zoom.src} alt={zoom.label} style={{ maxWidth: '92vw', maxHeight: '78vh', objectFit: 'contain', background: '#fffdf8',
                                                       padding: 20, borderRadius: 12, boxShadow: '0 24px 60px rgba(0,0,0,0.4)' }}/>
          <div className="vm-small" style={{ marginTop: 16, color: '#a8b8a3' }}>
            {lang === 'fr' ? 'Cliquer pour fermer' : lang === 'nl' ? 'Klik om te sluiten' : 'Click to close'}
          </div>
        </div>
      )}
    </section>
  );
}

function AmenitiesA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  return (
    <section className="vm-sec">
      <div className="vm-split">
        <h2 className="vm-h2" style={{ margin: 0 }}>{t('amen_title')}</h2>
        <div className="vm-amen" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: '0 24px' }}>
          {V_ALPINE.amenities.map((a, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '12px 0' }}>
              <span style={{ width: 24, height: 24, flexShrink: 0, color: 'var(--accent)' }}>{IconA[a.key] || IconA.check}</span>
              <span className="vm-p">{trA(a, lang)}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── LIVE DATA: Gîtes de France (ITEA widgets) ─────────────────────────
// The widget endpoint returns its HTML as JSONP (CORS allowed). We parse that HTML
// and render the data in the page's own style instead of the widget's look.
// Language follows Accept-Language; the documented `langue` param is ignored by the server.
const ITEA_URL = (widget) =>
  `https://widget.itea.fr/widget.php?key=tftr8_fc&numGite=${V_ALPINE.brand.ref}&widget=${widget}&callback=cb`;
const ITEA_HOST = { fr: 'widget', en: 'widget-uk', nl: 'widget-nl' }; // booking pages open in this language

const iteaCache = {};
function useItea(widget, lang) {
  const [doc, setDoc] = useState(null); // null = loading, false = failed
  useEffect(() => {
    let alive = true;
    const k = widget + lang;
    iteaCache[k] = iteaCache[k] || fetch(ITEA_URL(widget), { headers: { 'Accept-Language': lang } })
      .then(r => r.text())
      .then(s => new DOMParser().parseFromString(
        JSON.parse(s.slice(s.indexOf('(') + 1, s.lastIndexOf(')'))).html, 'text/html'));
    iteaCache[k].then(d => alive && setDoc(d), () => alive && setDoc(false));
    return () => { alive = false; };
  }, [widget, lang]);
  return doc;
}

const addDays = (iso, n) => { const [y, m, d] = iso.split('-').map(Number); return new Date(Date.UTC(y, m - 1, d + n)).toISOString().slice(0, 10); };
const unshout = (s) => s === s.toUpperCase() ? s.toLowerCase().replace(/(^|[\s'-])\p{L}/gu, c => c.toUpperCase()) : s;
const iteaText = (el, sel) => (el.querySelector(sel)?.textContent || '').replace(/\s+/g, ' ').trim();
const fmtDay = (y, m, d, add, lang) =>
  new Date(y, m - 1, +d + add).toLocaleDateString(LOCALE[lang], { day: 'numeric', month: 'short' });

// Weekly prices per season. Live from Gîtes de France: only free weeks carry a price, grouped per price level
// with the months it applies to. Season names come from V_ALPINE.rates (matched on price), which is also the
// fallback while loading or offline.
function useRates(lang) {
  const doc = useItea('prix', lang);
  const weeks = {}; // Saturday yyyy-mm-dd → weekly price (free weeks only)
  if (doc) doc.querySelectorAll('table[data-duree-tarif="semaine"] td.libre').forEach(td => {
    const [d, m, y] = td.dataset.deb.split('/');
    weeks[`${y}-${m}-${d}`] = parseFloat(td.dataset.prix.replace(',', '.'));
  });
  // Consecutive free weeks at the same price become one period, e.g. "18 déc. – 1 janv. 2028"
  const runs = [];
  Object.keys(weeks).sort().forEach(sat => {
    const last = runs[runs.length - 1];
    if (last && last.price === weeks[sat] && last.to === sat) last.to = addDays(sat, 7);
    else runs.push({ price: weeks[sat], from: sat, to: addDays(sat, 7) });
  });
  const day = (iso, opts) => new Date(iso + 'T12:00:00Z').toLocaleDateString(LOCALE[lang], { timeZone: 'UTC', day: 'numeric', month: 'short', ...opts });
  const prices = [...new Set(runs.map(r => r.price))].sort((a, b) => a - b);
  const rows = prices.length
    ? prices.map(price => ({
        price,
        season: trA(V_ALPINE.rates.find(r => r.price === price)?.season, lang),
        periods: runs.filter(r => r.price === price).map(r => `${day(r.from)} – ${day(r.to, { year: 'numeric' })}`),
      }))
    : V_ALPINE.rates.map(r => ({ season: trA(r.season, lang), periods: [trA(r.months, lang)], price: r.price }));
  return { rows, weeks };
}

const weekOf = (iso) => addDays(iso, -((new Date(iso + 'T00:00:00Z').getUTCDay() + 1) % 7)); // the Saturday that starts iso's week

// Price of a stay, service fees (5%) included, like the weekly prices from Gîtes de France.
// Whole Saturday-to-Saturday weeks: exact, the sum of the weekly prices.
// Shorter stays: Gîtes de France charges a share of the week's rent (measured on their booking page, Oct 2026).
// Seasons from 1300 €/week rent have their own table. 8+ nights: pro rata per night.
// ponytail: measured table, not published by Gîtes de France; re-measure if the owner changes the short-stay rules.
// High season 4 nights is not measured yet (0.75 sits between the measured 3 and 5 nights).
// Service fees: 5% of the rent, at most 90 € (so a 2590 € week is 2500 € rent + 90 €)
const rentOf = (weekly) => weekly > 1890 ? weekly - 90 : weekly / 1.05;
const feeOf = (rent) => Math.min(Math.round(rent * 5) / 100, 90);
const SHORT_STAY = { 1: 0.40, 2: 0.40, 3: 0.55, 4: 0.70, 5: 0.80, 6: 0.90 };
const SHORT_STAY_HIGH = { 1: 0.45, 2: 0.45, 3: 0.60, 4: 0.75, 5: 0.85, 6: 0.90 };
function stayPrice(from, nights, weeks) {
  const known = Object.values(weeks);
  if (!known.length || !nights) return null;
  const weekPrice = (night) => weeks[weekOf(night)] || weeks[Object.keys(weeks).find(w => w.startsWith(night.slice(0, 7)))] || Math.min(...known);
  if (nights % 7 === 0) {
    // Each 7 nights cost the weekly price of the week that holds most of them (its 4th night), for any arrival day:
    // Thu 8 Apr has 2 nights in the high-season week and 5 in the spring week, so Gîtes de France charges spring.
    // Saturday to Saturday is exactly what Gîtes de France publishes; other arrival days are very likely the same.
    // The service fee is charged once per booking (5%, at most 90 €), so it is added to the summed rent, not per week.
    let rent = 0;
    for (let k = 0; k < nights; k += 7) rent += rentOf(weeks[weekOf(addDays(from, k + 3))] || NaN);
    rent = Math.round(rent * 100) / 100;
    if (rent) return { total: Math.round((rent + feeOf(rent)) * 100) / 100, rent, exact: weeks[from] !== undefined };
  }
  const cheapest = (start, n) => { let w = Infinity; for (let i = 0; i < n; i++) w = Math.min(w, weekPrice(addDays(start, i))); return rentOf(w); };
  const short = (rent, n) => Math.round(rent * (rent >= 1300 ? SHORT_STAY_HIGH : SHORT_STAY)[n]);
  const result = (rent) => ({ total: Math.round((rent + feeOf(rent)) * 100) / 100, rent, exact: false });
  // Short stays: a share of the week's rent; the cheaper season wins when a stay spans two (as Gîtes de France does)
  if (nights < 7) return result(short(cheapest(from, nights), nights));
  // Saturday arrival, 8+ nights: whole weeks at the weekly price, the rest as a short stay
  if (weeks[from] !== undefined) {
    const full = Math.floor(nights / 7) * 7, rest = addDays(from, full);
    let rent = 0;
    for (let k = 0; k < full; k += 7) rent += rentOf(weekPrice(addDays(from, k)));
    return result(Math.round((rent + short(cheapest(rest, nights - full), nights - full)) * 100) / 100);
  }
  // Other arrival days, 8+ nights: the cheapest week's rent per night
  return result(Math.round(cheapest(from, nights) / 7 * nights * 100) / 100);
}

// Guest reviews collected by Gîtes de France
function useReviews(lang) {
  const doc = useItea('avis', lang);
  const reviews = doc ? [...doc.querySelectorAll('.div_widget_itea_avis_detailAvisClient')].map(el => {
    const title = iteaText(el, '.p_widget_itea_avis_titreAvis');
    return {
      // No all-caps text on the site: sentence-case shouted titles, title-case shouted names
      title: title === title.toUpperCase() ? title.charAt(0) + title.slice(1).toLowerCase() : title,
      name: unshout(iteaText(el, '.p_widget_itea_avis_pseudoClient')),
      type: iteaText(el, '.p_widget_itea_avis_typeSejourAvis'),
      date: (iteaText(el, '.dateDepotAvis').match(/\d{2}\/\d{2}\/\d{4}/) || [''])[0],
      body: iteaText(el, '.p_widget_itea_avis_descriptionAvis'),
      stars: el.querySelectorAll('.p_widget_itea_avis_noteGlobale .active').length,
      notes: [...el.querySelectorAll('.div_widget_itea_avis_note')]
        .map(n => [iteaText(n, '.sp_widget_itea_avis_libelleQuest'), n.querySelectorAll('.active').length]),
    };
  }) : [];
  const avg = reviews.length ? reviews.reduce((a, r) => a + r.stars, 0) / reviews.length : 0;
  const title = trA(V_ALPINE.i18n.rev_title, lang).replace('{avg}', fmtOne(avg, lang)).replace('{n}', reviews.length);
  return { reviews, avg, title, count: reviews.length };
}

// Availability + the chosen stay, shared by the calendar and the booking card.
// Any stay of free nights can be booked: Saturday → Saturday in a free week is confirmed instantly,
// other dates go to the owner as a request (tested on the Gîtes de France booking page).
function useBooking(lang) {
  const doc = useItea('dispo', lang);
  const [sel, setSel] = useState({ from: null, to: null }); // arrival / departure, yyyy-mm-dd
  const [hover, setHover] = useState(null);

  // Arrival days bookable online ("A" days) → Gîtes de France booking page, keyed by yyyy-mm-dd
  const links = {};
  if (doc) doc.querySelectorAll('a > span.canlendrier_classe_by_lettre_A').forEach(sp => {
    links[sp.dataset.date] = `https://${ITEA_HOST[lang]}.itea.fr${sp.parentNode.getAttribute('href')}`;
  });
  // 18 months, Monday-first weeks
  const months = doc ? [...doc.querySelectorAll('li.calendItea_li[data-mois]')].map(li => ({
    label: iteaText(li, 'caption'),
    heads: [...li.querySelectorAll('thead th')].map(th => th.textContent.trim()),
    days: [...li.querySelectorAll('tbody td > span, tbody td > a > span')].map(sp => ({
      day: +sp.textContent, date: sp.dataset.date, pad: sp.style.display === 'none',
      past: sp.classList.contains('spanCalendJour_avantDatePossible'),
      booked: sp.classList.contains('spanCalendJour_occupe') || sp.classList.contains('spanCalendJour_option'), // option = someone else's pending request
    })),
  })) : [];

  const info = {};
  months.forEach(m => m.days.forEach(d => { if (!d.pad) info[d.date] = d; }));
  const isFree = (iso) => info[iso] && !info[iso].past && !info[iso].booked;
  const nightsFree = (a, b) => { for (let x = a; x < b; x = addDays(x, 1)) if (!isFree(x)) return false; return true; };
  const validEnd = (iso) => sel.from && !sel.to && iso > sel.from && nightsFree(sel.from, iso);
  const pick = (iso) => {
    if (validEnd(iso)) setSel({ from: sel.from, to: iso });
    else if (isFree(iso)) setSel({ from: iso, to: null });
  };
  const nights = sel.to ? Math.round((Date.parse(sel.to) - Date.parse(sel.from)) / 864e5) : 0;
  const instant = nights > 0 && nights % 7 === 0 && !!links[sel.from];
  const resaBase = doc && doc.querySelector('a[href*="etape1"]')?.getAttribute('href').replace(/&jour=.*$/, '');
  const bookUrl = () => {
    const [y, m, d] = sel.from.split('-');
    return `https://${ITEA_HOST[lang]}.itea.fr${resaBase}&jour=${+d}&mois=${+m}&annee=${y}&duree=${nights}`;
  };
  const label = (iso, add = 0) => { const [y, m, d] = iso.split('-'); return fmtDay(y, m, d, add, lang); };
  return {
    doc, links, months, sel, setSel, hover, setHover, isFree, validEnd, pick, nights, instant, bookUrl, label,
    end: sel.to || (hover && validEnd(hover) ? hover : null),
    next: Object.keys(links).sort()[0],
  };
}

// ─── LEFT COLUMN: calendar, rates, why Gîtes de France ─────────────────
function CalendarA({ lang, bk }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [offset, setOffset] = useState(0);
  const per = useMobile() ? 1 : 2; // months in view
  const { months, sel, setSel, setHover, isFree, validEnd, end, pick, doc } = bk;
  const shown = months.slice(offset, offset + per);
  return (
    <div id="kalender" style={{ marginTop: 56 }}>
      <h2 className="vm-h2" style={{ marginBottom: 6 }}>{t('book_how_title')}</h2>
      <p className="vm-small vm-muted" style={{ margin: '0 0 24px', maxWidth: 560 }}>{linkify(t('book_how'))}</p>
      <div style={{ position: 'relative' }} onMouseLeave={() => setHover(null)}>
        {months.length > per && (
          <>
            <button className="vm-round-btn" aria-label={months[offset - 1]?.label} disabled={offset === 0}
                    onClick={() => setOffset(o => o - 1)} style={{ position: 'absolute', left: 0, top: 0 }}>{Ico.left}</button>
            <button className="vm-round-btn" aria-label={months[offset + per]?.label} disabled={offset + per >= months.length}
                    onClick={() => setOffset(o => Math.min(o + 1, months.length - per))}
                    style={{ position: 'absolute', right: 0, top: 0 }}>{Ico.right}</button>
          </>
        )}
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${per}, minmax(0, 1fr))`, gap: 40,
                      minHeight: doc === null ? 320 : undefined }}>
          {shown.map(mo => (
            <div key={mo.label}>
              <div style={{ textAlign: 'center', font: '600 16px/32px "Manrope", sans-serif', marginBottom: 8 }}>{mo.label}</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', rowGap: 2 }}>
                {mo.heads.map((d, i) => (
                  <div key={'h' + i} className="vm-muted" style={{ textAlign: 'center', padding: '6px 0', font: '600 12px/1 "Manrope", sans-serif' }}>{d}</div>
                ))}
                {mo.days.map((d, i) => {
                  if (d.pad) return <div key={i}/>;
                  const col = i % 7; // Monday = 0
                  const isStart = d.date === sel.from;
                  const isEnd = !!end && d.date === end;
                  const preview = !sel.to;                                   // hovering a departure day
                  const inStay = sel.from && end && d.date >= sel.from && d.date <= end;
                  const filled = isStart || isEnd;
                  const clickable = isFree(d.date) || validEnd(d.date);
                  // Band behind the stay: from the middle of the arrival day to the middle of the departure day, rounded at week edges
                  const band = inStay && end > sel.from && {
                    position: 'absolute', top: 2, bottom: 2, left: isStart ? '50%' : 0, right: isEnd ? '50%' : 0,
                    background: preview ? 'rgba(45,62,44,0.07)' : '#e3e9dd',
                    borderTopLeftRadius: col === 0 && !isStart ? 20 : 0, borderBottomLeftRadius: col === 0 && !isStart ? 20 : 0,
                    borderTopRightRadius: col === 6 && !isEnd ? 20 : 0, borderBottomRightRadius: col === 6 && !isEnd ? 20 : 0,
                  };
                  const style = {
                    position: 'relative',
                    background: filled ? 'var(--ink)' : 'transparent',
                    color: filled ? 'var(--bg)' : d.booked ? 'var(--muted)' : 'var(--ink)',
                    fontWeight: filled ? 600 : 500,
                    textDecoration: d.booked ? 'line-through' : 'none',
                    textDecorationColor: 'var(--accent)', textDecorationThickness: 2,
                    opacity: d.past ? 0.3 : 1,
                  };
                  return (
                    <div key={i} style={{ position: 'relative', height: 44, display: 'grid', placeItems: 'center' }}>
                      {band && <span style={band}/>}
                      {clickable
                        ? <button className="vm-day vm-day-free" onClick={() => pick(d.date)} onMouseEnter={() => setHover(d.date)}
                                  aria-pressed={filled} style={style}>{d.day}</button>
                        : <span className="vm-day" style={style}>{d.day}</span>}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="vm-small vm-muted" style={{ display: 'flex', alignItems: 'center', gap: '8px 20px', flexWrap: 'wrap', marginTop: 20 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 14, height: 14, borderRadius: '50%', border: '1px solid var(--ink)' }}/>{t('book_free')}
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ textDecoration: 'line-through', textDecorationColor: 'var(--accent)', textDecorationThickness: 2, fontWeight: 600, color: 'var(--muted)' }}>12</span>{t('rates_booked')}
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 26, height: 14, borderRadius: 7, background: '#e3e9dd', position: 'relative' }}><span style={{ position: 'absolute', left: 0, top: 0, width: 14, height: 14, borderRadius: '50%', background: 'var(--ink)' }}/></span>{t('book_yours')}
        </span>
        {sel.from && (
          <button className="vm-link" onClick={() => setSel({ from: null, to: null })}
                  style={{ marginLeft: 'auto', color: 'var(--ink)' }}>{t('book_clear')}</button>
        )}
      </div>
    </div>
  );
}

function BookingCardA({ lang, bk, price, weeks }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const c = V_ALPINE.contact;
  const { sel, nights, instant, bookUrl, label, links, next } = bk;
  const quote = sel.to ? stayPrice(sel.from, nights, weeks) : null;
  const nightsLabel = `${nights} ${t(nights === 1 ? 'book_night' : 'book_nights')}`;
  const dateBox = (k, iso) => (
    <button onClick={() => scrollToId('kalender')} style={{ flex: 1, minWidth: 0, textAlign: 'left', padding: '10px 14px',
                                                            border: 'none', background: 'transparent', cursor: 'pointer', color: 'inherit' }}>
      <div style={{ font: '700 12px/1.3 "Manrope", sans-serif' }}>{t(k)}</div>
      <div className="vm-small" style={{ color: iso ? 'var(--ink)' : 'var(--muted)', marginTop: 2 }}>{iso ? label(iso) : t('book_add_date')}</div>
    </button>
  );
  return (
    <div className="vm-card" style={{ padding: 24, boxShadow: 'var(--shadow)' }}>
      <div className="vm-small vm-muted">{t(quote ? 'book_stay_price' : 'hero_from')}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, flexWrap: 'wrap' }}>
        <span style={{ font: '600 26px/1.15 "Fraunces", serif' }}>
          {quote ? `${quote.exact ? '' : '≈ '}${fmtEur(quote.total, lang)}` : fmtEur(price, lang)}
        </span>
        <span className="vm-muted">{quote ? `/ ${nightsLabel}` : t('hero_per_week')}</span>
      </div>
      <div className="vm-small vm-muted" style={{ minHeight: 20, margin: '2px 0 16px' }}>{quote && !quote.exact ? t('book_estimate') : ''}</div>
      <div style={{ display: 'flex', border: '1px solid #b9b1a2', borderRadius: 8, marginBottom: 16 }}>
        {dateBox('book_arrival', sel.from)}
        <span style={{ width: 1, background: '#b9b1a2' }}/>
        {dateBox('book_departure', sel.to)}
      </div>
      {sel.to
        ? <a className="vm-btn vm-btn-primary vm-btn-block" href={bookUrl()} target="_blank" rel="noopener">{t('book_go')}</a>
        : <button className="vm-btn vm-btn-primary vm-btn-block" onClick={() => scrollToId('kalender')}>{t('hero_check')}</button>}
      <p className="vm-small vm-muted" style={{ textAlign: 'center', margin: '12px 0 0' }}>
        {sel.to
          ? `${nightsLabel}, ${t(instant ? 'book_instant' : 'book_on_request')}`
          : next && <a href={links[next]} target="_blank" rel="noopener" style={{ color: 'inherit' }}>
              {t('book_next')}: {label(next)} <span style={{ display: 'inline-flex', verticalAlign: 'middle' }}>{Ico.arrow}</span> {label(next, 7)}
            </a>}
      </p>
      {quote && (
        <div className="vm-small" style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '6px 12px', margin: '20px 0 16px', justifyItems: 'end' }}>
          <span className="vm-muted" style={{ justifySelf: 'start' }}>{t('book_rent')} ({nightsLabel})</span><span>{fmtEur(quote.rent, lang)}</span>
          <span className="vm-muted" style={{ justifySelf: 'start' }}>{t('book_fees')}</span><span>{fmtEur(Math.round((quote.total - quote.rent) * 100) / 100, lang)}</span>
          <span style={{ fontWeight: 700, justifySelf: 'start' }}>{t('book_total')}</span><span style={{ fontWeight: 700 }}>{quote.exact ? '' : '≈ '}{fmtEur(quote.total, lang)}</span>
          {!quote.exact && <span className="vm-muted" style={{ gridColumn: '1 / -1', justifySelf: 'start', marginTop: 2 }}>{t('book_exact_next')}</span>}
        </div>
      )}
      <div style={{ textAlign: 'center', marginTop: 8 }}>
        <button className="vm-link vm-small" onClick={() => scrollToId('via-gites-de-france')}>{t('book_why_title')}</button>
      </div>
      <div style={{ marginTop: 24 }}>
        {(c.phone || c.email) && <>
          <div className="vm-small vm-muted">{t('book_help')}</div>
          <div className="vm-small" style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 16px', marginTop: 6, fontWeight: 600 }}>
            {c.phone && <a href={telHref(c.phone)} style={{ color: 'inherit' }}>{c.phone}</a>}
            {c.email && <a href={`mailto:${c.email}`} style={{ color: 'inherit', overflowWrap: 'anywhere' }}>{c.email}</a>}
          </div>
        </>}
        {TS_KEY && (
          <button className="vm-link vm-small" onClick={() => scrollToId('bericht')} style={{ marginTop: 6, fontWeight: 600 }}>{t('form_title')}</button>
        )}
        <div className="vm-small vm-muted" style={{ marginTop: 10 }}>
          {lang === 'fr' ? 'Paiements : carte bancaire, chèques-vacances ANCV, cartes cadeaux.'
            : lang === 'nl' ? 'Betalen: creditcard, ANCV vouchers, cadeaubonnen.'
            : 'Payment: credit card, ANCV vouchers, gift cards.'}
        </div>
      </div>
    </div>
  );
}

function RatesA({ lang, rows, selPrice }) {
  const el = useRef(null);
  useEdgeFade(el, rows.length);
  return (
    <div id="tarifs" ref={el} className="vm-rate-grid vm-edge">
      {rows.map((r, i) => {
        const on = r.price === selPrice; // season of the chosen stay
        return (
          <div key={i} className="vm-card" style={{ padding: '18px 20px', transition: 'box-shadow .2s, border-color .2s',
                                                    borderColor: on ? 'var(--ink)' : undefined, boxShadow: on ? 'inset 0 0 0 1px var(--ink)' : 'none' }}>
            <div style={{ font: '600 22px/1.2 "Fraunces", serif' }}>{fmtEur(r.price, lang)}</div>
            {r.season && <div style={{ font: '600 15px/1.3 "Manrope", sans-serif', marginTop: 4 }}>{r.season}</div>}
            <div className="vm-small vm-muted" style={{ marginTop: 8, lineHeight: 1.6 }}>
              {r.periods.map(p => <div key={p}>{p}</div>)}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function WhyA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const cream = '#fffcf7'; // full cream on terracotta keeps text readable (contrast ≥ 4.5)
  return (
    <section className="vm-sec" id="via-gites-de-france">
      <div className="vm-panel vm-split" style={{ background: 'var(--accent)', color: cream, borderRadius: 24, padding: 48 }}>
        <div>
          <h2 className="vm-h2" style={{ color: cream, marginBottom: 12 }}>{t('book_why_title')}</h2>
          <p className="vm-p" style={{ color: cream }}>{linkify(t('book_why_intro'))}</p>
        </div>
        <div className="vm-grid-2" style={{ gap: 28 }}>
          {V_ALPINE.i18n.book_why.map(({ title, text }, i) => (
            <div key={i} style={{ display: 'flex', gap: 14 }}>
              <span style={{ width: 34, height: 34, borderRadius: '50%', background: cream, color: 'var(--accent)', flexShrink: 0,
                             display: 'grid', placeItems: 'center', font: '700 14px/1 "Manrope", sans-serif' }}>{i + 1}</span>
              <div>
                <div style={{ font: '600 17px/1.3 "Manrope", sans-serif', marginBottom: 4 }}>{trA(title, lang)}</div>
                <div className="vm-small" style={{ color: cream }}>{linkify(trA(text, lang))}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// Prices first, then the calendar; the booking card sits next to them and follows only within this section
function BookingA({ lang, bk, rates, price, weeks }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  return (
    <section className="vm-sec" id="reserver">
      <h2 className="vm-h2" style={{ marginBottom: 6 }}>{t('rates_title')}</h2>
      <p className="vm-small vm-muted" style={{ margin: '0 0 24px' }}>{linkify(t('rates_note'))}</p>
      <div className="vm-book">
        <div style={{ minWidth: 0 }}>
          <RatesA lang={lang} rows={rates} selPrice={bk.sel.from && weeks[weekOf(bk.sel.from)]}/>
          <CalendarA lang={lang} bk={bk}/>
        </div>
        <aside>
          <div className="vm-sticky"><BookingCardA lang={lang} bk={bk} price={price} weeks={weeks}/></div>
        </aside>
      </div>
    </section>
  );
}

// ─── REVIEWS ────────────────────────────────────────────────────────────
function ReviewsA({ lang, rv }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const rail = useRef(null);
  useEdgeFade(rail, rv.reviews.length);
  const [edge, setEdge] = useState({ start: true, end: false });
  const onRailScroll = () => {
    const el = rail.current;
    setEdge({ start: el.scrollLeft < 8, end: el.scrollLeft + el.clientWidth > el.scrollWidth - 8 });
  };
  const slide = (dir) => rail.current.scrollBy({ left: dir * (rail.current.lastElementChild.offsetWidth + 24), behavior: 'smooth' });
  if (!rv.count) return null; // loading, unreachable, or no reviews yet
  // Average score per question across all reviews
  const byLabel = {};
  rv.reviews.forEach(r => r.notes.forEach(([l, v]) => (byLabel[l] = byLabel[l] || []).push(v)));
  const scores = Object.entries(byLabel).map(([l, vs]) => ({ l, v: vs.reduce((a, b) => a + b, 0) / vs.length }));
  return (
    <section className="vm-sec" id="avis">
      <div className="vm-split">
        <div>
          <h2 className="vm-h2" style={{ marginBottom: 12 }}>{rv.title}</h2>
          <p className="vm-small" style={{ display: 'flex', gap: 8, alignItems: 'baseline', margin: '0 0 32px', color: '#4a4233' }}>
            <span aria-hidden="true" style={{ color: 'var(--accent)', display: 'inline-flex' }}>{Ico.check}</span>{linkify(t('rev_verified'))}
          </p>
          <div style={{ display: 'grid', gap: 14 }}>
            {scores.map((s, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <div className="vm-small" style={{ width: 170, flexShrink: 0 }}>{s.l}</div>
                <div style={{ flex: 1, height: 4, borderRadius: 2, background: 'var(--line)', overflow: 'hidden' }}>
                  <div style={{ width: `${(s.v / 5) * 100}%`, height: '100%', borderRadius: 2, background: 'var(--accent)' }}/>
                </div>
                <div style={{ width: 28, textAlign: 'right', font: '600 14px/1 "Manrope", sans-serif' }}>{fmtOne(s.v, lang)}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ minWidth: 0 }}>
          {/* Horizontal rail: two cards in view, swipe or use the arrows; stays compact at any number of reviews */}
          <div ref={rail} onScroll={onRailScroll} className="vm-rail vm-edge" style={{
            display: 'grid', gridAutoFlow: 'column', gridAutoColumns: 'calc((100% - 24px) / 2)', gap: 24,
            overflowX: 'auto', scrollSnapType: 'x mandatory', scrollbarWidth: 'none' }}>
            {rv.reviews.map(r => <ReviewCardA key={r.name + r.date} r={r} lang={lang}/>)}
          </div>
          {rv.count > 1 && (
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 20 }}>
              <button className="vm-round-btn" style={{ width: 40, height: 40 }} aria-label={t('rev_prev')}
                      disabled={edge.start} onClick={() => slide(-1)}>{Ico.left}</button>
              <button className="vm-round-btn" style={{ width: 40, height: 40 }} aria-label={t('rev_next')}
                      disabled={edge.end} onClick={() => slide(1)}>{Ico.right}</button>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function ReviewCardA({ r, lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [original, setOriginal] = useState(false);
  // Translations are added by the owners in Pages CMS (content/reviews.json), matched on name + date
  const tr = V_ALPINE.reviews.find(x => x.name === r.name && x.date === r.date);
  const hasTr = !!tr?.body?.[lang];
  const showTr = hasTr && !original;
  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 16, padding: 28,
                  scrollSnapAlign: 'start', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <span role="img" aria-label={`${r.stars}/5`} style={{ color: 'var(--accent)', display: 'flex', gap: 2 }}>
          {[1, 2, 3, 4, 5].map(n => <span key={n} style={{ display: 'flex', opacity: n <= r.stars ? 1 : 0.3 }}>{Ico.star}</span>)}
        </span>
        <span className="vm-small vm-muted">{r.date}</span>
      </div>
      <h3 style={{ font: '600 19px/1.25 "Fraunces", serif', margin: '0 0 12px' }}>« {showTr ? tr.title[lang] || r.title : r.title} »</h3>
      <p className="vm-p" style={{ fontSize: 15, lineHeight: 1.65, color: '#4a4233', flex: 1 }}>{showTr ? tr.body[lang] : r.body}</p>
      <div style={{ marginTop: 20, display: 'flex', justifyContent: 'space-between',
                    alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span aria-hidden="true" style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--soft)', flexShrink: 0,
                                            display: 'grid', placeItems: 'center', font: '600 15px/1 "Fraunces", serif' }}>{r.name.charAt(0)}</span>
          <div>
            <div style={{ font: '600 14px/1.3 "Manrope", sans-serif' }}>{r.name}</div>
            <div className="vm-small vm-muted" style={{ fontSize: 13 }}>{r.type}</div>
          </div>
        </div>
        {hasTr && (
          <div className="vm-small vm-muted" style={{ fontSize: 13 }}>
            {showTr && <span style={{ marginRight: 8 }}>{t('rev_translated')}</span>}
            <button className="vm-link" style={{ color: 'var(--accent)' }} onClick={() => setOriginal(o => !o)}>
              {showTr ? t('rev_show_original') : t('rev_show_translation')}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// "Route openen" button with a menu of map apps; closes on outside click or Esc
function RouteMenu({ apps, lang, left }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const onDown = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDown); document.removeEventListener('keydown', onKey); };
  }, [open]);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="vm-btn vm-btn-outline vm-btn-sm" aria-expanded={open} onClick={() => setOpen(o => !o)}>
        {Ico.route}
        {lang === 'fr' ? 'Itinéraire' : lang === 'nl' ? 'Route openen' : 'Get directions'}
        <span style={{ display: 'flex', transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}>{Ico.down}</span>
      </button>
      {open && (
        <div role="menu" className="vm-menu vm-menu-start" style={{ minWidth: 260, ...(left && { left: 0, right: 'auto' }) }}>
          {apps.map(app => (
            <a key={app.key} href={app.url} target="_blank" rel="noopener noreferrer" className="vm-menu-item"
               onClick={() => setOpen(false)} style={{ justifyContent: 'space-between' }}>
              <span>
                <span style={{ display: 'block', fontWeight: 600 }}>{app.label}</span>
                <span className="vm-small vm-muted">{app.sub}</span>
              </span>
              <span style={{ color: 'var(--accent)', display: 'flex' }}>{Ico.out}</span>
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── LOCATION ───────────────────────────────────────────────────────────
function LocationA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const b = V_ALPINE.brand;
  const fmt = (m) => m >= 1000 ? `${(m / 1000).toFixed(1).replace('.0', '')} km` : `${m} m`;
  const onSite = lang === 'fr' ? 'sur place' : lang === 'nl' ? 'ter plaatse' : 'on site';

  const [place, setPlace] = useState(null); // index of the nearby place shown on the map
  const sel = place != null ? V_ALPINE.places[place] : null;
  const target = sel && { lat: sel.lat, lng: sel.lng, name: trA(sel.name, lang) };
  const lat = b.lat, lng = b.lng; // the directions menu always leads to the gîte
  const mapApps = [
    { key: 'osm', label: 'OpenStreetMap',
      sub: lang === 'fr' ? 'Dans le navigateur' : lang === 'nl' ? 'In de browser' : 'In your browser',
      url: `https://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=16/${lat}/${lng}` },
    { key: 'google', label: 'Google Maps',
      sub: lang === 'fr' ? 'Itinéraire, tous appareils' : lang === 'nl' ? 'Route, alle apparaten' : 'Directions, any device',
      url: `https://www.google.com/maps/dir/?api=1&destination=${lat}%2C${lng}` },
    { key: 'apple', label: 'Apple Plans', sub: 'iPhone, iPad, Mac',
      url: `https://maps.apple.com/?daddr=${lat},${lng}&q=${encodeURIComponent(`${b.name}, ${b.town}`)}` },
    { key: 'waze', label: 'Waze',
      sub: lang === 'fr' ? 'Navigation auto' : lang === 'nl' ? 'Auto-navigatie' : 'Driving navigation',
      url: `https://www.waze.com/ul?ll=${lat}%2C${lng}&navigate=yes` },
  ];

  const mapEl = useRef(null);
  const mapInst = useRef(null);
  useEffect(() => {
    if (!mapEl.current || mapInst.current || typeof L === 'undefined') return;
    const map = L.map(mapEl.current, { zoomControl: false, scrollWheelZoom: false, dragging: !L.Browser.mobile }).setView([b.lat, b.lng], 15);
    L.control.zoom({ position: 'bottomright' }).addTo(map);
    mapInst.current = map;
    // OpenStreetMap tiles: no API key needed; attribution is mandatory
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    }).addTo(map);
    const houseIcon = L.divIcon({
      className: 'vm-house-marker',
      html: `<div style="position:relative;transform:translate(-11px,-11px)">
        <div style="width:22px;height:22px;border-radius:50%;background:#c44d2e;border:3px solid #fffcf7;box-shadow:0 0 0 8px rgba(196,77,46,0.2),0 2px 6px rgba(0,0,0,0.2)"></div>
        <div style="position:absolute;left:30px;top:-1px;font:600 13px/1 Manrope,sans-serif;color:#2d3e2c;background:#fffcf7;padding:7px 12px;border-radius:999px;white-space:nowrap;box-shadow:0 2px 10px rgba(45,62,44,0.2)">${esc(b.name)}</div>
      </div>`,
      iconSize: [0, 0], iconAnchor: [0, 0],
    });
    L.marker([b.lat, b.lng], { icon: houseIcon, keyboard: false }).addTo(map);
    return () => { map.remove(); mapInst.current = null; };
  }, []);

  // The chosen nearby place: a green marker, framed together with the gîte
  useEffect(() => {
    const map = mapInst.current;
    if (!map || !sel) return;
    const label = document.createElement('div');
    label.textContent = target.name; // text, not HTML: the name comes from the CMS
    label.style.cssText = 'position:absolute;left:28px;top:-2px;font:600 13px/1 Manrope,sans-serif;color:#fffcf7;background:#2d3e2c;padding:7px 12px;border-radius:999px;white-space:nowrap;box-shadow:0 2px 10px rgba(45,62,44,0.25)';
    const html = document.createElement('div');
    html.style.cssText = 'position:relative;transform:translate(-9px,-9px)';
    html.innerHTML = '<div style="width:18px;height:18px;border-radius:50%;background:#2d3e2c;border:3px solid #fffcf7;box-shadow:0 2px 6px rgba(0,0,0,0.25)"></div>';
    html.appendChild(label);
    const marker = L.marker([target.lat, target.lng], { icon: L.divIcon({ className: '', html, iconSize: [0, 0] }), keyboard: false }).addTo(map);
    map.flyToBounds([[b.lat, b.lng], [target.lat, target.lng]], { padding: [80, 80], maxZoom: 16, duration: 0.8 });
    return () => marker.remove();
  }, [place, lang]);

  const show = (i) => {
    setPlace(i);
    // Phones only: there the map is out of view above the list. On wider screens the page stays put.
    if (matchMedia('(max-width: 760px)').matches) mapEl.current.parentNode.scrollIntoView({ behavior: 'smooth', block: 'center' });
  };

  return (
    <section className="vm-sec" id="localisation">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap', marginBottom: 24 }}>
        <div>
          <h2 className="vm-h2" style={{ marginBottom: 6 }}>{t('loc_title')}</h2>
          <p className="vm-p vm-muted">{b.name}, {b.postalCode} {b.town}, {b.region}, {b.country}</p>
        </div>
        <RouteMenu apps={mapApps} lang={lang}/>
      </div>
      <div className="vm-map" style={{ position: 'relative', height: 480, borderRadius: 12, overflow: 'hidden', isolation: 'isolate', background: 'var(--soft)' }}>
        <div ref={mapEl} style={{ position: 'absolute', inset: 0 }}/>
        {sel && (
          <button className="vm-btn vm-btn-sm vm-pill" onClick={() => { setPlace(null); mapInst.current.flyTo([b.lat, b.lng], 15, { duration: 0.8 }); }}
                  style={{ position: 'absolute', top: 12, left: 12, zIndex: 1000, background: 'var(--surface)', color: 'var(--ink)', boxShadow: 'var(--shadow)' }}>
            {target.name} {Ico.close}
          </button>
        )}
      </div>
      {sel && (() => {
        const from = `${b.lat},${b.lng}`, to = `${target.lat},${target.lng}`;
        const routes = [
          { key: 'google', label: 'Google Maps', sub: mapApps.find(a => a.key === 'google').sub,
            url: `https://www.google.com/maps/dir/?api=1&origin=${from}&destination=${to}` },
          { key: 'apple', label: 'Apple Plans', sub: 'iPhone, iPad, Mac', url: `https://maps.apple.com/?saddr=${from}&daddr=${to}` },
          { key: 'osm', label: 'OpenStreetMap', sub: mapApps.find(a => a.key === 'osm').sub,
            url: `https://www.openstreetmap.org/directions?route=${b.lat}%2C${b.lng}%3B${target.lat}%2C${target.lng}` },
        ];
        const to_ = <span style={{ color: 'var(--accent)', fontWeight: 600 }}>{target.name}</span>;
        return (
          <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px 12px', marginTop: 14 }}>
            <span className="vm-small vm-muted">
              {lang === 'fr' ? <>Itinéraire de {b.name} à {to_} :</> : lang === 'nl' ? <>Route van {b.name} naar {to_}:</> : <>Directions from {b.name} to {to_}:</>}
            </span>
            <RouteMenu apps={routes} lang={lang} left/>
          </div>
        );
      })()}
      <div style={{ marginTop: 40 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}>
          <h3 className="vm-h3">
            {lang === 'fr' ? 'Loisirs & commodités' : lang === 'nl' ? 'Voorzieningen in de buurt' : 'Leisure & amenities'}
          </h3>
        </div>
        <div className="vm-dist" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', columnGap: 40 }}>
          {V_ALPINE.places.map((d, i) => {
            const inner = <>
              <span style={{ minWidth: 0 }}>
                <span className="vm-place-name" style={{ font: '400 15px/1.3 "Manrope", sans-serif' }}>{trA(d.name, lang)}</span>
                {trA(d.description, lang) && <span className="vm-small vm-muted" style={{ display: 'block', marginTop: 2 }}>{trA(d.description, lang)}</span>}
              </span>
              <span style={{ font: '600 15px/1.3 "Manrope", sans-serif', whiteSpace: 'nowrap' }}>{d.distance == null ? '' : d.distance === 0 ? onSite : fmt(d.distance)}</span>
            </>;
            const row = { display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, padding: '10px 0', font: 'inherit' };
            return d.lat == null
              ? <div key={i} style={row}>{inner}</div>
              : <button key={i} className="vm-place" aria-pressed={place === i} onClick={() => show(i)} style={row}>{inner}</button>;
          })}
        </div>
      </div>
    </section>
  );
}

// ─── SKI AREA ───────────────────────────────────────────────────────────
function SkiAreaA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const stats = V_ALPINE.skiStats.map(s => ({ n: s.number, l: s.label })); // edited in the CMS
  return (
    <section className="vm-sec" id="le-domaine">
      <div className="vm-ski" style={{ background: 'var(--ink)', color: 'var(--bg)', borderRadius: 24, padding: 48, display: 'grid',
                                       gridTemplateColumns: 'minmax(0, 1.2fr) minmax(0, 1fr)', gap: 48, alignItems: 'center' }}>
        <div>
          <h2 className="vm-h2" style={{ color: 'var(--bg)' }}>{t('ski_title')}</h2>
          <p className="vm-p" style={{ color: '#c5d1bf' }}>{linkify(t('ski_body'))}</p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12, marginTop: 32 }}>
            {stats.map((s, i) => (
              <div key={i} style={{ background: 'rgba(245,241,234,0.08)', borderRadius: 12, padding: '14px 16px' }}>
                <div style={{ font: '600 24px/1.1 "Fraunces", serif', color: '#d4a574', whiteSpace: 'nowrap' }}>{s.n}</div>
                <div className="vm-small" style={{ color: '#a8b8a3', marginTop: 4 }}>{trA(s.l, lang)}</div>
              </div>
            ))}
          </div>
        </div>
        <PhotoA src={V_ALPINE.photos.ski} ratio="4/5" radius={16} label="Grand Domaine" tone="forest"/>
      </div>
    </section>
  );
}

// ─── THINGS TO DO ───────────────────────────────────────────────────────
function ThingsA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [season, setSeason] = useState('winter');
  const name = { winter: { fr: 'Hiver', en: 'Winter', nl: 'Winter' }, summer: { fr: 'Été', en: 'Summer', nl: 'Zomer' } };
  return (
    <section className="vm-sec">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap', marginBottom: 24 }}>
        <h2 className="vm-h2" style={{ margin: 0 }}>{t('todo_title')}</h2>
        <div role="tablist" style={{ display: 'inline-flex', background: 'var(--soft)', borderRadius: 999, padding: 4 }}>
          {['winter', 'summer'].map(s => (
            <button key={s} role="tab" aria-selected={season === s} onClick={() => setSeason(s)} style={{
              border: 'none', borderRadius: 999, padding: '9px 20px', cursor: 'pointer', color: 'var(--ink)',
              background: season === s ? 'var(--surface)' : 'transparent', boxShadow: season === s ? 'var(--shadow)' : 'none',
              font: '600 14px/1 "Manrope", sans-serif', transition: 'background-color .2s, box-shadow .2s' }}>{trA(name[s], lang)}</button>
          ))}
        </div>
      </div>
      <div className="vm-todo" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16 }}>
        {V_ALPINE.todo[season].map((item, i) => (
          <div key={i} className="vm-card" style={{ padding: 20 }}>
            <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--soft)', color: 'var(--accent)', marginBottom: 14,
                          display: 'grid', placeItems: 'center', font: '700 14px/1 "Manrope", sans-serif' }}>{i + 1}</div>
            <div style={{ font: '600 16px/1.35 "Manrope", sans-serif' }}>{trA(item, lang)}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─── HOST ───────────────────────────────────────────────────────────────
function HostA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const c = V_ALPINE.contact;
  const row = (label, value, copy) => (
    <div style={{ padding: '10px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
      <div style={{ minWidth: 0 }}>
        <div className="vm-small vm-muted">{label}</div>
        <div style={{ font: '600 16px/1.35 "Manrope", sans-serif', overflowWrap: 'anywhere' }}>{value}</div>
      </div>
      {copy && <CopyBtn text={value} lang={lang}/>}
    </div>
  );
  return (
    <section className="vm-sec" id="hote">
      <div className="vm-host" style={{ display: 'grid', gridTemplateColumns: V_ALPINE.photos.owner ? 'minmax(0, 280px) minmax(0, 1fr)' : 'minmax(0, 720px)', gap: 56, alignItems: 'center' }}>
        {/* Photo of the host, kept small ("Foto eigenaar" in the CMS); without one the text stands alone */}
        {V_ALPINE.photos.owner && <div style={{ maxWidth: 280 }}><PhotoA src={V_ALPINE.photos.owner} ratio="4/5" radius={24} label={c.name} tone="cream"/></div>}
        <div>
          <h2 className="vm-h2" style={{ fontSize: 'clamp(26px, 3vw, 34px)', marginBottom: 20 }}>{t('own_title')}</h2>
          <p className="vm-p" style={{ fontSize: 17, lineHeight: 1.7, marginBottom: 28 }}>{linkify(t('own_body'))}</p>
          <div className="vm-card" style={{ padding: '10px 24px', marginBottom: 24 }}>
            {row(t('own_host'), c.name)}
            {c.since && row(t('own_since'), c.since)}
            {c.languages && row(t('own_languages'), c.languages)}
            {c.phone && row(t('own_phone'), c.phone, true)}
            {c.email && row(t('own_email'), c.email, true)}
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
            {c.phone && <a className="vm-btn vm-btn-dark" href={telHref(c.phone)}>{t('own_call')}</a>}
            {c.email && <a className="vm-btn vm-btn-outline" href={`mailto:${c.email}`}>{t('own_mail')}</a>}
          </div>
        </div>
      </div>
      {TS_KEY && <ContactFormA lang={lang}/>}
    </section>
  );
}

// Copies a phone number or email address; shows "Copied" for a moment
// Contact form → /api/contact (functions/api/contact.js → worker/contact.js), which mails the owners.
// Cloudflare Turnstile keeps spam out; it is usually invisible and only asks for a click when in doubt.
// The real key only works on the site's own domains; localhost uses Cloudflare's always-pass test key for previewing.
const TS_KEY = location.hostname === 'localhost' ? '1x00000000000000000000AA' : V_ALPINE.brand.turnstileKey;
let turnstileLoad;
const loadTurnstile = () => turnstileLoad ||= new Promise((resolve, reject) => {
  const s = document.createElement('script');
  s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
  s.async = true; s.onload = resolve; s.onerror = reject;
  document.head.appendChild(s);
});

function ContactFormA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [state, setState] = useState('idle'); // idle | sending | flying | sent | error
  const { logo_form: logo, contact_photo: side } = V_ALPINE.photos;
  const inner = useRef(null), [height, setHeight] = useState(300); // the card keeps the form's height while animating
  const [fly, setFly] = useState(600); // how far right the paper plane flies: out of the card, over the photo
  const box = useRef(null), widget = useRef(null);
  useEffect(() => {
    let alive = true;
    loadTurnstile().then(() => {
      if (alive) widget.current = window.turnstile.render(box.current, {
        sitekey: TS_KEY, language: lang, appearance: 'interaction-only', theme: 'light', size: 'flexible' }); // shows a checkbox only when Cloudflare is unsure
    }).catch(() => {}); // without Turnstile the server refuses the message and the error line shows
    return () => { alive = false; if (widget.current != null) window.turnstile.remove(widget.current); widget.current = null; };
  }, [lang]);

  const send = async (e) => {
    e.preventDefault();
    const f = new FormData(e.currentTarget);
    setState('sending');
    try {
      // ponytail: localhost has no mail backend, so it pretends to send to preview the animation
      if (location.hostname === 'localhost') await new Promise(r => setTimeout(r, 600));
      else {
        const r = await fetch('/api/contact', { method: 'POST', headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ name: f.get('name'), email: f.get('email'), message: f.get('message'), lang,
                                 token: widget.current != null ? window.turnstile.getResponse(widget.current) : '' }) });
        if (!r.ok) throw new Error(r.status);
      }
      // The form fades out, the letter flies off, then the confirmation appears
      const calm = matchMedia('(prefers-reduced-motion: reduce)').matches;
      setHeight(Math.max(300, inner.current.offsetHeight - 64));
      setFly(inner.current.parentElement.offsetWidth - inner.current.offsetWidth / 2 + 140);
      setState('leaving');
      setTimeout(() => setState('flying'), calm ? 0 : 400);
      setTimeout(() => setState('sent'), calm ? 300 : 3600);
    } catch {
      setState('error');
      if (widget.current != null) window.turnstile.reset(widget.current);
    }
  };

  return (
    <div id="bericht" className="vm-card vm-contact" style={{ marginTop: 56, scrollMarginTop: 96, overflow: 'hidden' }}>
      <div ref={inner} style={{ padding: 32 }}>
      {state === 'flying' ? (
        <div className="vm-fade-in" style={{ height, display: 'grid', placeItems: 'center' }}>
          {/* The note slides into the envelope, the flap folds shut, the envelope folds into a paper plane that flies off */}
          <svg className="vm-env" style={{ '--fx': `${fly}px` }} width="176" height="154" viewBox="0 0 160 140" stroke="var(--accent)" strokeWidth="2.5" strokeLinejoin="round" aria-hidden="true">
            <g className="vm-env-body">
            <rect x="20" y="60" width="120" height="76" rx="6" fill="#f3ebdd"/>
            <polygon className="vm-env-open" points="20,60 80,22 140,60" fill="#f3ebdd"/>
            <g className="vm-env-note">
              <rect x="36" y="0" width="88" height="68" rx="4" fill="#fffdf8"/>
              <path d="M48 16h64M48 28h64M48 40h44" stroke="#2d3e2c" strokeWidth="2" strokeLinecap="round" opacity=".45"/>
            </g>
            <polygon points="20,60 80,100 140,60 140,136 20,136" fill="#fffcf7"/>
            <polygon className="vm-env-shut" points="20,60 80,102 140,60" fill="#fffcf7"/>
            </g>
            <g className="vm-plane">
              <polygon points="22,98 140,62 62,106" fill="#fffcf7"/>
              <polygon points="62,106 140,62 76,126" fill="#f3ebdd"/>
              <polygon points="62,106 76,126 70,108" fill="#e9dcc6"/>
            </g>
          </svg>
        </div>
      ) : state === 'sent' ? (
        <div role="status" className="vm-rise" style={{ textAlign: 'center', minHeight: height, display: 'grid', alignContent: 'center' }}>
          {logo && <img src={logo} alt="" style={{ display: 'block', height: 120, width: 'auto', margin: '24px auto 0' }}/>}
          <h3 style={{ font: '600 24px/1.2 "Fraunces", serif', margin: '20px 0 8px' }}>{t('form_sent_title')}</h3>
          <p className="vm-p" style={{ margin: '0 auto', maxWidth: 440 }}>{t('form_sent')}</p>
        </div>
      ) : (<div style={{ transition: 'opacity .4s ease', opacity: state === 'leaving' ? 0 : 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
          <div>
            <h3 style={{ font: '600 21px/1.2 "Fraunces", serif', margin: '0 0 6px' }}>{t('form_title')}</h3>
            <p className="vm-small vm-muted" style={{ margin: 0 }}>{linkify(t('form_intro'))}</p>
          </div>
          {logo && <img src={logo} alt="" style={{ height: 64, width: 'auto', flexShrink: 0 }}/>}
        </div>
        <form onSubmit={send} style={{ display: 'grid', gap: 12, marginTop: 18 }}>
          <div className="vm-form-2">
            <label className="vm-field">{t('form_name')}<input className="vm-input" name="name" required maxLength={100} autoComplete="name"/></label>
            <label className="vm-field">{t('form_email')}<input className="vm-input" name="email" type="email" required maxLength={200} autoComplete="email"/></label>
          </div>
          <label className="vm-field">{t('form_message')}<textarea className="vm-input" name="message" required maxLength={5000} rows={5} style={{ resize: 'vertical', maxHeight: 360 }}
            onInput={e => { const el = e.currentTarget; el.style.height = 'auto'; el.style.height = el.scrollHeight + 2 + 'px'; }}/></label>
          <div ref={box}/>
          {state === 'error' && <p role="alert" className="vm-small" style={{ color: 'var(--accent)', margin: 0 }}>{t('form_error')}</p>}
          <div>
            <button className="vm-btn vm-btn-primary vm-pill" disabled={state === 'sending' || state === 'leaving'}>{t(state !== 'idle' && state !== 'error' ? 'form_sending' : 'form_send')}</button>
          </div>
          <p className="vm-small vm-muted" style={{ margin: '4px 0 0' }}>{linkify(t('form_protected'))}</p>
        </form>
      </div>)}
      </div>
      {side && <div className="vm-contact-photo" style={{ background: `url(${side}) center/cover` }}/>}
    </div>
  );
}

function CopyBtn({ text, lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [done, setDone] = useState(false);
  const copy = () => navigator.clipboard.writeText(text).then(() => { setDone(true); setTimeout(() => setDone(false), 1600); });
  return (
    <button onClick={copy} aria-label={`${t('copy')}: ${text}`} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 999, flexShrink: 0, cursor: 'pointer',
      border: '1px solid var(--line)', background: done ? 'var(--soft)' : 'transparent', color: 'var(--ink)',
      font: '600 13px/1 "Manrope", sans-serif', transition: 'background-color .2s' }}>
      {done ? Ico.check : Ico.copy}{t(done ? 'copied' : 'copy')}
    </button>
  );
}

// ─── FAQ ────────────────────────────────────────────────────────────────
function FaqA({ lang }) {
  const t = (k) => trA(V_ALPINE.i18n[k], lang);
  const [open, setOpen] = useState(0);
  return (
    <section className="vm-sec" id="faq">
      <div className="vm-split">
        <h2 className="vm-h2" style={{ margin: 0 }}>{t('faq_title')}</h2>
        <div>
          {V_ALPINE.faq.map((f, i) => {
            const isOpen = open === i;
            return (
              <div key={i} style={{ background: 'var(--surface)', borderRadius: 12, padding: '0 20px', marginBottom: 8 }}>
                <button onClick={() => setOpen(isOpen ? -1 : i)} aria-expanded={isOpen} style={{
                  width: '100%', padding: '18px 0', background: 'transparent', border: 'none', cursor: 'pointer',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, textAlign: 'left',
                  font: '600 17px/1.4 "Manrope", sans-serif', color: 'var(--ink)' }}>
                  <span>{trA(f.q, lang)}</span>
                  <span style={{ display: 'flex', flexShrink: 0, transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}>{Ico.down}</span>
                </button>
                {isOpen && <p className="vm-p vm-muted" style={{ paddingBottom: 20, maxWidth: 720 }}>{linkify(trA(f.a, lang))}</p>}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ─── FOOTER ─────────────────────────────────────────────────────────────
function FooterA({ lang }) {
  const c = V_ALPINE.contact;
  const head = { font: '600 14px/1.3 "Manrope", sans-serif', color: '#d4a574', marginBottom: 12 };
  return (
    <footer style={{ background: '#1f2c1e', color: '#a8b8a3', marginTop: 48, padding: '48px 0 28px' }}>
      <div className="vm-wrap">
        <div className="vm-footer-grid" style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: '28px 48px', paddingBottom: 16 }}>
          <div>
            <div style={{ font: '600 21px/1.1 "Fraunces", serif', color: 'var(--bg)' }}>{V_ALPINE.brand.name}</div>
            <div className="vm-small" style={{ marginTop: 10 }}>{linkify(trA(V_ALPINE.i18n.footer_location, lang))}</div>
          </div>
          {(c.phone || c.email) && (
            <div>
              <div style={head}>Contact</div>
              <div className="vm-small" style={{ lineHeight: 1.8, overflowWrap: 'anywhere' }}>
                {c.email && <><a href={`mailto:${c.email}`} style={{ color: 'inherit' }}>{c.email}</a><br/></>}
                {c.phone && <a href={telHref(c.phone)} style={{ color: 'inherit' }}>{c.phone}</a>}
              </div>
            </div>
          )}
        </div>
        <div className="vm-small" style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginTop: 20, color: '#6b7d68' }}>
          <span>© 2026 {V_ALPINE.brand.name}, réf. {V_ALPINE.brand.ref}</span>
          <span>45.45°N, 6.41°E, 1 350 m</span>
        </div>
      </div>
    </footer>
  );
}

// ─── LIGHTBOX ───────────────────────────────────────────────────────────
function LightboxA({ index, lang, onClose, onPrev, onNext, onJump }) {
  const strip = useRef(null);
  const touch = useRef(null);
  useEffect(() => { strip.current?.children[index]?.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' }); }, [index]);
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowRight') onNext();
      else if (e.key === 'ArrowLeft') onPrev();
    };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [onClose, onPrev, onNext]);

  const photos = V_ALPINE.photos.gallery;
  const img = photos[index];
  if (!img) return null;
  const label = trA(img.caption, lang);
  const tone = TONE[TONES[index % 3]];
  const roundBtn = { width: 48, height: 48, borderRadius: '50%', border: 'none', background: 'rgba(255,252,247,0.92)',
                     color: 'var(--ink)', cursor: 'pointer', display: 'grid', placeItems: 'center', boxShadow: 'var(--shadow)' };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 1000, background: '#141912', display: 'flex',
                  flexDirection: 'column', animation: 'lbFadeIn .22s ease' }}>
      <style>{`@keyframes lbFadeIn { from {opacity:0} to {opacity:1} }`}</style>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 20px', color: 'var(--bg)', flexShrink: 0, gap: 16 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', minWidth: 0 }}>
          <span style={{ padding: '6px 12px', borderRadius: 999, background: 'rgba(245,241,234,0.12)', font: '600 13px/1 "Manrope", sans-serif', whiteSpace: 'nowrap' }}>
            {index + 1} / {photos.length}
          </span>
          <span style={{ font: '600 17px/1.2 "Fraunces", serif', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
        </div>
        <button onClick={onClose} aria-label="Close" style={roundBtn}>{Ico.close}</button>
      </div>
      <div className="vm-lb-stage" style={{ flex: 1, position: 'relative', display: 'flex', alignItems: 'center',
                                            justifyContent: 'center', padding: '4px 88px 16px', minHeight: 0 }}
           onTouchStart={(e) => { touch.current = e.touches[0].clientX; }}
           onTouchEnd={(e) => { const dx = e.changedTouches[0].clientX - touch.current; if (Math.abs(dx) > 50) (dx < 0 ? onNext : onPrev)(); }}>
        <button onClick={onPrev} aria-label="Previous" style={{ ...roundBtn, position: 'absolute', left: 20, top: '50%', transform: 'translateY(-50%)', zIndex: 5 }}>{Ico.left}</button>
        <div style={{ width: '100%', height: '100%', minHeight: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      containerType: 'size' }}>
          {img.photo ? (
            <img key={img.photo} src={img.photo} alt={label}
                 onLoad={(e) => e.currentTarget.style.setProperty('--r', e.currentTarget.naturalWidth / e.currentTarget.naturalHeight)}
                 style={{ width: 'min(100cqw, calc(100cqh * var(--r, 1.5)))', aspectRatio: 'var(--r, 1.5)', height: 'auto', display: 'block',
                          objectFit: 'contain', borderRadius: 12, boxShadow: '0 30px 80px rgba(0,0,0,0.45)' }}/>
          ) : (
            <div style={{ height: '100%', aspectRatio: '3/2', maxWidth: '100%', borderRadius: 12, position: 'relative',
                          background: tone.bg, backgroundImage: stripes(tone) }}>
              <div style={{ position: 'absolute', bottom: 20, left: 24, font: '600 13px/1.2 "Manrope", sans-serif', color: tone.text }}>{label}</div>
            </div>
          )}
        </div>
        <button onClick={onNext} aria-label="Next" style={{ ...roundBtn, position: 'absolute', right: 20, top: '50%', transform: 'translateY(-50%)', zIndex: 5 }}>{Ico.right}</button>
      </div>
      <div ref={strip} className="vm-lb-strip" style={{ flexShrink: 0, display: 'flex', gap: 8, overflowX: 'auto', overscrollBehaviorX: 'contain',
                    padding: '8px 20px max(16px, env(safe-area-inset-bottom))', scrollbarWidth: 'none' }}>
        {photos.map((g, i) => {
          const gt = TONE[TONES[i % 3]];
          const active = i === index;
          return (
            <button key={i} onClick={() => onJump(i)} aria-label={trA(g.caption, lang)} style={{
              width: 72, height: 50, flexShrink: 0, padding: 0, cursor: 'pointer', borderRadius: 8,
              backgroundColor: gt.bg, backgroundImage: g.photo ? `url(${g.photo})` : stripes(gt, 8),
              backgroundSize: 'cover', backgroundPosition: 'center',
              border: active ? '2px solid var(--bg)' : '2px solid transparent', opacity: active ? 1 : 0.55,
              transition: 'opacity .18s, border-color .18s' }}/>
          );
        })}
      </div>
    </div>
  );
}

// ─── PAGE ───────────────────────────────────────────────────────────────
// Start language: the visitor's earlier choice, else the browser's language (Dutch, French), else English
const startLang = () => {
  try { const saved = localStorage.getItem('lang'); if (['fr', 'en', 'nl'].includes(saved)) return saved; } catch {}
  const pref = (navigator.languages?.[0] || navigator.language || '').slice(0, 2).toLowerCase();
  return pref === 'nl' || pref === 'fr' ? pref : 'en';
};

function VariantAlpine() {
  const [lang, setLangState] = useState(startLang);
  const setLang = useCallback((l) => { setLangState(l); try { localStorage.setItem('lang', l); } catch {} }, []);
  useEffect(() => { document.documentElement.lang = lang; }, [lang]);
  const [lightboxIdx, setLightboxIdx] = useState(null);
  const n = V_ALPINE.photos.gallery.length;
  const open = useCallback((i) => setLightboxIdx(i), []);
  const close = useCallback(() => setLightboxIdx(null), []);
  const goNext = useCallback(() => setLightboxIdx(i => (i + 1) % n), [n]);
  const goPrev = useCallback(() => setLightboxIdx(i => (i - 1 + n) % n), [n]);
  const bk = useBooking(lang);
  const rv = useReviews(lang);
  const { rows: rates, weeks } = useRates(lang);
  const price = Math.min(...rates.map(r => r.price));
  return (
    <LightboxCtx.Provider value={open}>
      <TopBarA lang={lang} setLang={setLang}/>
      <main className="vm-wrap">
        <TitleA lang={lang} rv={rv}/>
        <OverviewA lang={lang}/>
        <FloorsA lang={lang}/>
        <AmenitiesA lang={lang}/>
        <BookingA lang={lang} bk={bk} rates={rates} price={price} weeks={weeks}/>
        <WhyA lang={lang}/>
        <ReviewsA lang={lang} rv={rv}/>
        <LocationA lang={lang}/>
        <SkiAreaA lang={lang}/>
        <ThingsA lang={lang}/>
        <FaqA lang={lang}/>
        <HostA lang={lang}/>
      </main>
      <FooterA lang={lang}/>
      {lightboxIdx !== null && (
        <LightboxA index={lightboxIdx} lang={lang} onClose={close} onPrev={goPrev} onNext={goNext} onJump={setLightboxIdx}/>
      )}
    </LightboxCtx.Provider>
  );
}

window.VariantAlpine = VariantAlpine;
