/* Sea La Vie — shared chrome: nav, footer, hero, marquee, logo, modals */
const { useState: useS, useEffect: useE, useMemo: useM } = React;

/* ────── Brand Logo (SVG) ────── */
function BrandLogo({ compact, tiny, onDark }) {
  const navy = onDark ? "#f6f1e7" : "#0e2a4e";
  const sky = "#7ba3d1";
  const skyDeep = onDark ? "#9fc0e0" : "#4f7eb2";
  const width = tiny ? 130 : compact ? 200 : 280;
  return (
    <svg className={`brand-logo ${compact?"compact":""} ${tiny?"tiny":""}`} viewBox="0 0 280 100" width={width} xmlns="http://www.w3.org/2000/svg">
      <g fontFamily="Cormorant Garamond, Georgia, serif" fontSize="40" fontWeight="500" letterSpacing="3">
        <text x="42" y="52" fill={navy}>SEA</text>
        <text x="120" y="52" fill={sky}>LA</text>
        <text x="180" y="52" fill={navy}>VIE</text>
      </g>
      {/* wave under LA */}
      <path d="M 116 64 Q 130 56 144 64 T 168 64" fill="none" stroke={skyDeep} strokeWidth="2.4" strokeLinecap="round" />
      <path d="M 114 70 Q 130 62 146 70 T 170 70" fill="none" stroke={sky} strokeWidth="1.8" strokeLinecap="round" opacity="0.75" />
      {/* LUXURY RESIDENCES DIANI subtitle */}
      <line x1="50" y1="84" x2="84" y2="84" stroke={sky} strokeWidth="1" />
      <text x="140" y="88" textAnchor="middle"
            fontFamily="Jost, Helvetica Neue, sans-serif"
            fontSize="9"
            letterSpacing="3.5"
            fill={navy}>
        LUXURY RESIDENCES DIANI
      </text>
      <line x1="196" y1="84" x2="230" y2="84" stroke={sky} strokeWidth="1" />
    </svg>
  );
}

/* ────── Utility Bar ────── */
function UtilityBar({ onSearch, onLogin }) {
  const [currency, setCurrency] = useCurrency();
  const [session, setSess] = useS(() => { try { return JSON.parse(localStorage.getItem("slv_session_v1") || "null"); } catch(e) { return null; } });
  useE(() => {
    function onSess(e) { setSess(e.detail); }
    window.addEventListener("slv:session", onSess);
    return () => window.removeEventListener("slv:session", onSess);
  }, []);
  const firstName = session && session.name ? session.name.split(" ")[0] : null;
  return (
    <div className="utility-bar">
      <div className="group">
        <a href="contact.html">Diani, Kenya</a>
        <span className="utility-divider"></span>
        <div className="currency-switch">
          {Object.keys(CURRENCIES).map(c => (
            <button key={c} className={currency === c ? "active" : ""} onClick={() => setCurrency(c)}>{c}</button>
          ))}
        </div>
      </div>
      <div className="group">
        <a href={`tel:${CONTACT.phoneRaw}`}>{CONTACT.phone}</a>
        <span className="utility-divider"></span>
        <a href="contact.html">Travel Advisors</a>
        <span className="utility-divider"></span>
        <button onClick={onSearch}>⌕ &nbsp; Search</button>
        <span className="utility-divider"></span>
        {session
          ? <a href="account.html" style={{color: "var(--sky)"}}>{firstName} · My Stay</a>
          : <button onClick={onLogin}>Sign in</button>}
      </div>
    </div>
  );
}

/* ────── Main Nav (with mobile drawer) ────── */
function MainNav({ current, onSearch, onLogin }) {
  const [open, setOpen] = useS(false);
  const links = [
    { l: "Residences",   h: "residences.html" },
    { l: "Availability", h: "availability.html" },
    { l: "Experiences",  h: "experiences.html" }
  ];
  const right = [
    { l: "Cuisine",  h: "cuisine.html" },
    { l: "Wellness", h: "wellness.html" },
    { l: "Journal",  h: "journal.html" }
  ];

  useE(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  return (
    <>
      <nav className="main-nav">
        <div className="nav-left">
          {links.map(l => (
            <a key={l.l} href={l.h} className={current === l.l ? "active" : ""}>{l.l}</a>
          ))}
        </div>
        <a href="index.html" style={{textDecoration: "none"}}>
          <BrandLogo compact />
        </a>
        <div className="nav-right">
          {right.map(l => (
            <a key={l.l} href={l.h} className={current === l.l ? "active" : ""}>{l.l}</a>
          ))}
          <a href="availability.html" style={{color: "var(--sky-deep)"}}>Reserve</a>
        </div>
        <button className={`mobile-toggle ${open ? "open" : ""}`} onClick={() => setOpen(!open)} aria-label="Menu">
          <span></span><span></span><span></span>
        </button>
      </nav>

      <div className={`mobile-drawer-backdrop ${open ? "open" : ""}`} onClick={() => setOpen(false)}></div>
      <div className={`mobile-drawer ${open ? "open" : ""}`}>
        <ul>
          <li><a href="index.html" className={current === "Home" ? "active" : ""}>Home</a></li>
          <li><a href="residences.html" className={current === "Residences" ? "active" : ""}>Residences</a></li>
          <li><a href="availability.html" className={current === "Availability" ? "active" : ""}>Availability</a></li>
          <li><a href="experiences.html" className={current === "Experiences" ? "active" : ""}>Experiences</a></li>
          <li><a href="wellness.html" className={current === "Wellness" ? "active" : ""}>Wellness</a></li>
          <li><a href="cuisine.html" className={current === "Cuisine" ? "active" : ""}>Cuisine</a></li>
          <li><a href="journal.html" className={current === "Journal" ? "active" : ""}>Journal</a></li>
          <li><a href="story.html" className={current === "Story" ? "active" : ""}>Our Story</a></li>
          <li><a href="contact.html" className={current === "Contact" ? "active" : ""}>Contact</a></li>
        </ul>
        <div className="util">
          <a href={`tel:${CONTACT.phoneRaw}`}>{CONTACT.phone}</a>
          <a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a>
          <MobileCurrency />
          <a href="#" onClick={(e) => { e.preventDefault(); setOpen(false); onSearch && onSearch(); }}>⌕ Search</a>
          <a href="#" onClick={(e) => { e.preventDefault(); setOpen(false); onLogin && onLogin(); }}>Sign in</a>
        </div>
      </div>
    </>
  );
}

function MobileCurrency() {
  const [currency, setCurrency] = useS(getStoredCurrency());
  function pick(c) { setCurrency(c); setStoredCurrency(c); }
  return (
    <div className="mobile-currency">
      <span className="lbl">Currency</span>
      <div className="currency-switch">
        {Object.keys(CURRENCIES).map(c => (
          <button key={c} className={currency === c ? "active" : ""} onClick={() => pick(c)}>{c}</button>
        ))}
      </div>
    </div>
  );
}

/* ────── Hero ────── */
function Hero() {
  return (
    <section className="hero">
      <div className="hero-image" style={{backgroundImage: `url(${PHOTO.villasAerial})`}}></div>
      <div className="hero-content">
        <div className="ornament"><span></span><span className="dot"></span><span></span></div>
        <div className="eyebrow">Opening November 2026 · Diani Beach, Kenya</div>
        <h1>The Indian Ocean,<br/><em>privately yours.</em></h1>
        <p className="lede">Four exclusive residences set within indigenous coastal forest, one hundred metres from the warm shallows of Diani Beach. A refined coastal escape designed around privacy, space, and a slower rhythm of living.</p>
        <div style={{marginTop: 36, display:"flex", gap: 24}}>
          <a href="availability.html" className="btn-solid" style={{background: "var(--ivory)", color: "var(--ink)"}}>Reserve a residence</a>
          <a href="story.html" className="btn-line" style={{color: "var(--ivory)", borderBottomColor: "var(--ivory)"}}>Our story <span className="arrow"></span></a>
        </div>
      </div>
      <div className="hero-scroll"><div>Scroll</div><div className="line"></div></div>
    </section>
  );
}

/* ────── Location Map (shared) ────── */
function LocationMapSection({ compact, dark }) {
  return (
    <section className="location-section" style={{background: dark ? "var(--ink)" : "var(--ivory-deep)"}}>
      <div className="location-inner">
        <div className="location-copy" style={{color: dark ? "var(--ivory)" : "var(--ink)"}}>
          <OrnamentRow />
          <div className="eyebrow" style={{color: dark ? "var(--sky-pale)" : undefined}}>Location</div>
          <h2 style={{color: dark ? "var(--ivory)" : "var(--ink)"}}>
            On the south coast,<br/><em style={{color: dark ? "var(--sky)" : "var(--sky-deep)"}}>seven minutes from the runway.</em>
          </h2>
          <p style={{color: dark ? "rgba(246,241,231,0.85)" : "var(--ink-soft)"}}>
            Sea La Vie sits on Galu Beach, the southern stretch of Diani — a quiet, broad arc of white sand at the lower end of Kenya's south coast. Ukunda Airstrip (UKA) is a seven-minute drive away; Moi International, Mombasa (MBA), is forty-five.
          </p>
          <div className="location-facts">
            <div><div className="lbl">Ukunda (UKA)</div><div className="val">7 min by car</div></div>
            <div><div className="lbl">Mombasa (MBA)</div><div className="val">45 min by car</div></div>
            <div><div className="lbl">Diani village</div><div className="val">5 min by car</div></div>
            <div><div className="lbl">The ocean</div><div className="val">100 metres</div></div>
          </div>
          <div style={{display:"flex", gap: 18, marginTop: 28, flexWrap:"wrap"}}>
            <a href={`https://www.google.com/maps?q=${CONTACT.geo.lat},${CONTACT.geo.lng}`} target="_blank" rel="noopener" className="btn-line" style={{color: dark ? "var(--ivory)" : "var(--ink)", borderBottomColor: dark ? "var(--ivory)" : "var(--ink)"}}>Open in Google Maps <span className="arrow"></span></a>
            <a href={`https://www.google.com/maps/dir/?api=1&destination=${CONTACT.geo.lat},${CONTACT.geo.lng}`} target="_blank" rel="noopener" className="btn-line" style={{color: dark ? "var(--ivory)" : "var(--ink)", borderBottomColor: dark ? "var(--ivory)" : "var(--ink)"}}>Get directions <span className="arrow"></span></a>
          </div>
        </div>
        <div className="location-map">
          <iframe
            title="Sea La Vie location"
            src={`https://maps.google.com/maps?q=${CONTACT.geo.lat},${CONTACT.geo.lng}&z=13&output=embed`}
            style={{border: 0, width: "100%", height: "100%"}}
            loading="lazy"
            referrerPolicy="no-referrer-when-downgrade"
            allowFullScreen
          ></iframe>
        </div>
      </div>
    </section>
  );
}

/* ────── Page Head (for interior pages) ────── */
function PageHead({ eyebrow, title, titleEm, blurb, img, crumb }) {
  return (
    <section className="page-head">
      <div className="bg" style={{backgroundImage: `url(${img || PHOTO.villaTerrace})`}}></div>
      <div className="inner">
        <OrnamentRow />
        <div className="eyebrow">{eyebrow}</div>
        <h1>{title} {titleEm && <em>{titleEm}</em>}</h1>
        {blurb && <p>{blurb}</p>}
        {crumb && (
          <div className="crumbs">
            <a href="index.html">Home</a><span className="sep">·</span><span>{crumb}</span>
          </div>
        )}
      </div>
    </section>
  );
}

/* ────── Marquee ────── */
function Marquee() {
  const items = [
    "Opening November 2026",
    "Hidden within indigenous coastal forest",
    "One hundred metres from the Indian Ocean",
    "Four exclusive residences",
    "One staff member for every two guests",
    "Diani Beach · Kwale County · Kenya"
  ];
  const repeated = [...items, ...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        <span>
          {repeated.map((it, i) => (
            <React.Fragment key={i}>{it}<span className="sep">◆</span></React.Fragment>
          ))}
        </span>
      </div>
    </div>
  );
}

/* ────── Footer ────── */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="brand-block">
          <BrandLogo onDark />
          <p style={{marginTop: 24}}>Four exclusive residences a hundred metres from the warm shallows of Diani Beach, set within indigenous coastal forest. Doors open November 2026.</p>
          <p style={{marginTop: 18, fontSize: 12, letterSpacing: "0.06em"}}>
            {CONTACT.address.map((l, i) => <React.Fragment key={i}>{l}<br/></React.Fragment>)}
          </p>
        </div>
        <div>
          <h5>Visit</h5>
          <ul>
            <li><a href="residences.html">The Residences</a></li>
            <li><a href="availability.html">Availability</a></li>
            <li><a href="experiences.html">Experiences</a></li>
            <li><a href="cuisine.html">Cuisine</a></li>
            <li><a href="wellness.html">Wellness</a></li>
            <li><a href="contact.html">Whole-Estate Hire</a></li>
          </ul>
        </div>
        <div>
          <h5>About</h5>
          <ul>
            <li><a href="story.html">Our Story</a></li>
            <li><a href="story.html#coastline">The Coastline</a></li>
            <li><a href="factsheet.html">Factsheet (PDF)</a></li>
            <li><a href="journal.html">Journal</a></li>
            <li><a href="contact.html">Press</a></li>
            <li><a href="contact.html">Careers</a></li>
          </ul>
        </div>
        <div>
          <h5>Reach Us</h5>
          <ul>
            <li><a href={`tel:${CONTACT.phoneRaw}`}>{CONTACT.phone}</a></li>
            <li><a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a></li>
            <li><a href="contact.html">Guest Register</a></li>
            <li><a href="contact.html">Travel Advisors</a></li>
            <li><a href="contact.html#getting-here">Getting Here</a></li>
          </ul>
        </div>
        <div className="footer-news">
          <h5>The Letter</h5>
          <p>A quarterly note from the founders on the coast, the season, and the small movements of the estate.</p>
          <NewsletterForm />
          <p style={{marginTop: 30, fontSize: 11, letterSpacing: "0.04em"}}>Member of the Kenya Coast Tourist Association. Built to LEED-equivalent standard, 2026.</p>
        </div>
      </div>
      <div className="footer-bottom">
        <div>© 2026 Sea La Vie Residences. All rights reserved.</div>
        <div className="links">
          <a href="privacy.html">Privacy</a>
          <a href="terms.html">Terms</a>
          <a href="cookies.html">Cookies</a>
          <a href="accessibility.html">Accessibility</a>
        </div>
      </div>
    </footer>
  );
}

function NewsletterForm() {
  const [email, setEmail] = useS("");
  const [done, setDone] = useS(false);
  async function submit(e) {
    e.preventDefault();
    if (!email.trim()) return;
    try {
      await apiEnquiry({ name: "Newsletter", email: email.trim(), subject: "The Letter — subscribe", message: "Please add me to The Letter." });
    } catch(e) {}
    setDone(true);
  }
  return (
    <form className="news-input" onSubmit={submit}>
      {done ? (
        <div style={{color: "var(--sky-pale)", fontStyle: "italic", fontFamily: "var(--serif)", fontSize: 15}}>Thank you — see you on the coast.</div>
      ) : (
        <>
          <input placeholder="your email" type="email" value={email} onChange={e => setEmail(e.target.value)} />
          <button type="submit">Subscribe</button>
        </>
      )}
    </form>
  );
}

/* ────── Login Modal ────── */
function LoginModal({ onClose, onSwitchToSignup, isSignup, onSwitchToLogin }) {
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-aside" style={{backgroundImage: `url(${PHOTO.villaTerrace})`}}>
          <div>
            <div className="eyebrow" style={{color: "var(--sky-pale)"}}>The Guest Register</div>
            <h3>{isSignup ? "Begin your" : "Welcome"} <em>{isSignup ? "register" : "back"}</em></h3>
            <p>{isSignup
              ? "Open a Guest Register to receive priority access to the opening season, private rates, and a dedicated travel curator."
              : "Sign in to view held reservations, your travel curator's recommendations, and the inner pages of the journal."}</p>
          </div>
          <div className="quote">
            "Karibu, rafiki — welcome home."
            <div style={{fontFamily:"var(--sans)", fontStyle:"normal", fontSize: 10, letterSpacing: "0.24em", textTransform:"uppercase", color:"var(--sky)", marginTop: 14}}>— Sea La Vie</div>
          </div>
        </div>
        <div className="modal-body">
          <button className="modal-close" onClick={onClose}>×</button>
          <div className="eyebrow">{isSignup ? "Create an account" : "Sign in"}</div>
          <h2>{isSignup ? "Open the" : "Enter your"} <em>register</em></h2>
          <p>{isSignup ? "Two minutes. No commitment." : "We'll remember where you left off."}</p>

          <LoginForm isSignup={isSignup} onClose={onClose} />

          <div className="divider">or</div>
          <div className="alt-create">
            {isSignup
              ? <>Already registered? <a href="#" onClick={e => {e.preventDefault(); onSwitchToLogin();}}>Sign in</a></>
              : <>Not yet a guest? <a href="#" onClick={e => {e.preventDefault(); onSwitchToSignup();}}>Open a register</a></>
            }
          </div>
        </div>
      </div>
    </div>
  );
}

function LoginForm({ isSignup, onClose }) {
  const [form, setForm] = useS({ name: "", email: "", password: "" });
  const [busy, setBusy] = useS(false);
  const [err, setErr] = useS("");
  function up(k, v) { setForm(prev => ({ ...prev, [k]: v })); }
  async function submit(e) {
    e.preventDefault();
    setErr("");
    if (!form.email || !form.password || (isSignup && !form.name)) {
      setErr("Please fill every field."); return;
    }
    setBusy(true);
    const r = isSignup
      ? await acctRegister({ name: form.name, email: form.email, password: form.password })
      : await acctLogin({ email: form.email, password: form.password });
    setBusy(false);
    if (!r.ok) { setErr(r.error || "Something went wrong."); return; }
    // Success → go to the portal
    window.location.href = "account.html";
  }
  return (
    <form onSubmit={submit}>
      {isSignup && (
        <div className="field-group">
          <label>Full Name</label>
          <input type="text" placeholder="As it appears on your passport" value={form.name} onChange={e => up("name", e.target.value)} />
        </div>
      )}
      <div className="field-group">
        <label>Email Address</label>
        <input type="email" placeholder="you@example.com" value={form.email} onChange={e => up("email", e.target.value)} />
      </div>
      <div className="field-group">
        <label>Password</label>
        <input type="password" placeholder="At least eight characters" value={form.password} onChange={e => up("password", e.target.value)} />
      </div>
      {!isSignup && (
        <div className="row">
          <label style={{display:"flex", alignItems:"center", gap: 8, color: "var(--ink-soft)"}}>
            <input type="checkbox" defaultChecked /> Remember me
          </label>
          <a href={`mailto:${CONTACT.email}?subject=Password%20reset`}>Forgotten?</a>
        </div>
      )}
      {err && <div className="err-msg">{err}</div>}
      <button className="submit" type="submit" disabled={busy}>
        {busy ? "One moment…" : (isSignup ? "Open Register" : "Sign in")}
      </button>
      <p style={{marginTop: 14, fontSize: 11, color: "var(--ink-mute)", textAlign: "center"}}>
        Try the demo · <code style={{fontFamily: "JetBrains Mono, monospace"}}>demo@sealaviediani.com</code> / <code style={{fontFamily: "JetBrains Mono, monospace"}}>demo</code>
      </p>
    </form>
  );
}

/* ────── Search Overlay ────── */
function SearchOverlay({ onClose }) {
  const [q, setQ] = useS("");
  const suggestions = {
    "Residences":  [["Kasi Villa","residences.html#kasi"],["Bahari Villa","residences.html#bahari"],["Pwani Villa","residences.html#pwani"],["Samaki Villa","residences.html#samaki"]],
    "Experiences": [["Kite Atelier","experiences.html"],["Jet Ski","experiences.html"],["Tandem Skydive","experiences.html"],["Parasail","experiences.html"],["Sundowner Dhow","experiences.html"],["Wasini Channel","experiences.html"],["Shimba Hills Safari","experiences.html"],["Colobus Conservation","wellness.html"]],
    "Cuisine":     [["Ali Barbour's Cave","cuisine.html"],["Nomad Beach Bar","cuisine.html"],["The Salty Squid","cuisine.html"],["Leonardo's","cuisine.html"],["Sails Beach Bar","cuisine.html"],["Ozi's Bistro","cuisine.html"],["Shan-e-Punjab","cuisine.html"],["Kokkos Beach Bar","cuisine.html"],["Bonfire Table","cuisine.html"]],
    "Journal":     [["A guide to Kaskazi season","journal.html"],["The dhows of Shimoni","journal.html"],["Twelve plates to know","journal.html"]],
    "Information": [["Opening November 2026","story.html"],["Getting here","contact.html#getting-here"],["Whole-estate buyouts","contact.html"],["The Guest Register","contact.html"]]
  };
  const filtered = Object.fromEntries(
    Object.entries(suggestions).map(([cat, items]) => [cat, items.filter(([t]) => t.toLowerCase().includes(q.toLowerCase()))])
  );
  return (
    <div className="search-overlay">
      <div className="close-row">
        <div className="eyebrow">Search Sea La Vie</div>
        <button className="closebtn" onClick={onClose}>×</button>
      </div>
      <div className="input-wrap">
        <span className="script-mono">⌕</span>
        <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Try 'kite atelier' or 'November availability'" />
      </div>
      <div className="results">
        {Object.entries(filtered).map(([cat, items]) => items.length > 0 && (
          <div className="group" key={cat}>
            <h5>{cat}</h5>
            <ul>
              {items.map(([t, h]) => (
                <li key={t} onClick={() => { window.location.href = h; }}>
                  {t}<span className="tag">View</span>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ────── Provenance (story snippet for home page) ────── */
function ProvenanceSection() {
  return (
    <section className="provenance" id="story">
      <div className="provenance-image" style={{backgroundImage: `url(${PHOTO.villaTerrace})`}}></div>
      <div className="provenance-copy">
        <OrnamentRow />
        <div className="eyebrow">Our Story</div>
        <h2>Set moments from <em>the Indian Ocean.</em></h2>
        <p>Sea La Vie was created as a quiet coastal retreat designed around privacy, space, and a slower rhythm of living. Hidden within Diani's lush coastline, the residences bring together contemporary coastal design with the textures, materials, and craftsmanship of the Swahili coast — lime-washed walls, hand-carved details, natural timber, soft linen.</p>
        <p>Every element has been intentionally considered to create an experience that feels calm, discreet, and deeply connected to place. More than a place to stay, Sea La Vie is designed to feel private, effortless, and removed from the pace of everyday life.</p>
        <div className="facts">
          <div><div className="label">Opening</div><div className="value">November 2026</div></div>
          <div><div className="label">From the airport</div><div className="value">7 minutes</div></div>
          <div><div className="label">From the ocean</div><div className="value">100 metres</div></div>
          <div><div className="label">Residences</div><div className="value">Four</div></div>
        </div>
        <a href="story.html" className="btn-line" style={{marginTop: 36}}>Read our full story <span className="arrow"></span></a>
      </div>
    </section>
  );
}

/* ────── Re-usable Grids ────── */
function ResidencesGrid() {
  const [currency] = useCurrency();
  return (
    <div className="villa-grid">
      {VILLAS.map(v => (
        <a key={v.id} href={`residences.html#${v.id}`} className="villa-card" style={{textDecoration: "none", color: "inherit"}}>
          <div className="villa-image" style={{backgroundImage: `url(${v.image})`}}>
            <div className="badge">{v.badge}</div>
          </div>
          <div className="villa-meta">
            <h3>{v.name[0]} <em>{v.name[1]}</em></h3>
            <div className="villa-rate"><strong>from {formatPrice(v.priceUSD, currency)}</strong>{v.period}</div>
          </div>
          <p>{v.desc}</p>
          <div className="villa-attrs">
            <span><strong>{v.bedrooms}</strong>Bedrooms</span>
            <span><strong>{v.baths}</strong>Baths</span>
            <span><strong>{v.sqft}</strong>Sq Ft</span>
            <span><strong>{v.sleeps}</strong>Sleeps</span>
          </div>
        </a>
      ))}
    </div>
  );
}

function ExperiencesGrid({ kind }) {
  const list = EXPERIENCES[kind] || [];
  return (
    <div className="exp-grid">
      {list.map((e, i) => (
        <div className="exp-card" key={i}>
          <div className="exp-image" style={{backgroundImage: `url(${e.ph})`}}>
            <div className="pcat">{e.cat}</div>
            {e.provider && <div className="provider">{e.provider}</div>}
          </div>
          <div className="exp-body">
            <h4>{e.title[0]} <em>{e.title[1]}</em></h4>
            <div className="exp-meta">{e.meta.map((m, j) => <span key={j}>{m}</span>)}</div>
            <p>{e.desc}</p>
            <div className="exp-foot">
              <div className="exp-price"><span className="from">From</span>{e.from}</div>
              <a href={`mailto:${CONTACT.email}?subject=${encodeURIComponent("Booking — " + e.title.join(" "))}&body=${encodeURIComponent("I'd like to book the " + e.title.join(" ") + " experience. Please send availability and details.")}`} className="exp-book">Book Now</a>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function CuisineGrid() {
  return (
    <div className="exp-grid">
      {CUISINE.map((c, i) => (
        <div className="exp-card" key={i}>
          <div className="exp-image" style={{backgroundImage: `url(${c.ph})`}}>
            <div className="pcat">{c.cat}</div>
            {c.provider && <div className="provider">{c.provider}</div>}
          </div>
          <div className="exp-body">
            <h4>{c.title[0]} <em>{c.title[1]}</em></h4>
            <div className="exp-meta">{c.meta.map((m, j) => <span key={j}>{m}</span>)}</div>
            <p>{c.desc}</p>
            <div className="exp-foot">
              <div className="exp-price">
                {c.from.startsWith("$")
                  ? <><span className="from">From</span>{c.from}</>
                  : <span style={{fontSize: 12, letterSpacing: "0.18em", textTransform:"uppercase", color: "var(--ink-mute)"}}>{c.from}</span>}
              </div>
              <a href={`mailto:${CONTACT.email}?subject=${encodeURIComponent("Reservation — " + c.title.join(" "))}&body=${encodeURIComponent("I'd like to make a reservation at " + c.title.join(" ") + ". Please send the next available evenings.")}`} className="exp-book">Reserve</a>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ────── Availability Strip (live data, used on home + availability pages) ────── */
function AvailabilityStrip() {
  const [year, setYear] = useS(2026);
  const [month, setMonth] = useS(10);
  const [currency] = useCurrency();
  const avail = useAvailability();
  const dim = daysInMonth(year, month);

  function shift(delta) {
    let m = month + delta, y = year;
    while (m < 0) { m += 12; y -= 1; }
    while (m > 11) { m -= 12; y += 1; }
    setMonth(m); setYear(y);
  }

  function cellClass(villaId, day) {
    const key = dateKey(year, month, day);
    if (avail.isBooked(villaId, key)) return "ac booked";
    return "ac avail";
  }

  return (
    <section className="section" id="availability" style={{paddingTop: 30, paddingBottom: 120}}>
      <div className="section-header">
        <OrnamentRow />
        <div className="eyebrow">Live Availability</div>
        <h2>See the season <em>at a glance.</em></h2>
        <p>A live view of every residence across the calendar. Reserved cells are unavailable; tap any open cell to begin building your stay.</p>
      </div>

      <div className="avail-strip">
        <div className="avail-head">
          <h3>Residence <em>availability</em></h3>
          <div className="avail-controls">
            <button onClick={() => shift(-1)}>‹</button>
            <div className="month-label">{MONTHS[month]} {year}</div>
            <button onClick={() => shift(1)}>›</button>
          </div>
        </div>

        <div className="avail-table">
          <div className="avail-villa-label head"><div className="n">Residence</div></div>
          <div className="avail-cells head" style={{gridTemplateColumns: `repeat(${dim}, 1fr)`}}>
            {Array.from({length: dim}, (_, i) => {
              const d = i + 1;
              const date = new Date(year, month, d);
              const dow = date.getDay();
              return <div key={d} className={`ac ${dow === 0 || dow === 6 ? "weekend" : ""}`}>{d}</div>;
            })}
          </div>

          {VILLAS.map(v => (
            <React.Fragment key={v.id}>
              <div className="avail-villa-label">
                <div className="n">{v.name.join(" ")}</div>
                <div className="r">from {formatPrice(v.priceUSD, currency)}</div>
              </div>
              <div className="avail-cells" style={{gridTemplateColumns: `repeat(${dim}, 1fr)`}}>
                {Array.from({length: dim}, (_, i) => <div key={i} className={cellClass(v.id, i + 1)}></div>)}
              </div>
            </React.Fragment>
          ))}
        </div>

        <div className="avail-legend">
          <span><span className="swatch avail"></span>Available</span>
          <span><span className="swatch booked"></span>Reserved</span>
          <span style={{marginLeft: "auto", fontFamily: "var(--serif)", textTransform:"none", letterSpacing: 0, fontSize: 13, fontStyle: "italic", color: "var(--ink-soft)"}}>
            Whole-estate buyouts available for parties of sixteen or more.
          </span>
        </div>
      </div>
    </section>
  );
}

/* ────── Page Layout (wraps each page with header/footer + modal state) ────── */
function PageLayout({ current, children, withMarquee }) {
  const [showSearch, setShowSearch] = useS(false);

  return (
    <>
      <div className="banner-strip"></div>
      <UtilityBar
        onSearch={() => setShowSearch(true)}
        onLogin={() => { window.location.href = "account.html"; }}
      />
      <MainNav
        current={current}
        onSearch={() => setShowSearch(true)}
        onLogin={() => { window.location.href = "account.html"; }}
      />
      {children}
      {withMarquee && <Marquee />}
      <Footer />

      {showSearch && <SearchOverlay onClose={() => setShowSearch(false)} />}
    </>
  );
}

Object.assign(window, {
  BrandLogo, UtilityBar, MainNav, Hero, PageHead, Marquee, Footer, NewsletterForm,
  LoginModal, LoginForm, SearchOverlay, ProvenanceSection,
  ResidencesGrid, ExperiencesGrid, CuisineGrid, AvailabilityStrip,
  PageLayout, LocationMapSection, MobileCurrency
});
