// Public pages — content driven by /api/content, narrative copy kept inline
const { useState: useStateP, useEffect: useEffectP } = React;

// Hook to read site content from the App-level context
const useSite = () => (window.useContent ? window.useContent() : null) || { settings: {}, reviews: [], menu_cards: [], gallery: [], pages: [], widgets: [] };

// Resolve a photo reference. Accepts:
//   - a full URL → returned as-is
//   - an R2 key → prefixed with /media/
//   - an IMAGES.<key> id → returned from the Wix-hotlinked fallback map
const resolvePhoto = (v, fallback = '') => {
  if (!v) return fallback;
  if (typeof v !== 'string') return fallback;
  if (v.startsWith('http://') || v.startsWith('https://') || v.startsWith('/')) return v;
  if (IMAGES[v]) return IMAGES[v];
  return '/media/' + v;
};

const HomePage = ({ navigate }) => {
  const { settings, reviews } = useSite();
  const bookUrl = settings.hostmoat_booking_url || '#';
  const featured = reviews.find(r => r.featured) || reviews[0];
  return (
  <>
    <section className="hero-cinematic">
      <div className="hero-bg">
        <video
          autoPlay muted loop playsInline
          preload="auto"
          poster={IMAGES.hero}
          aria-hidden="true"
          className="hero-video"
        >
          {/* Mobile gets 480p, tablet 720p, desktop 1080p. Browser picks the first it can use. */}
          <source src="/media/gallery/hero-480p.mp4" type="video/mp4" media="(max-width: 640px)"/>
          <source src="/media/gallery/hero-720p.mp4" type="video/mp4" media="(max-width: 1280px)"/>
          <source src="/media/gallery/hero.mp4"      type="video/mp4"/>
        </video>
      </div>
      <div className="hero-inner">
        <div className="hero-eyebrow">Puerto Vallarta · Since 1999</div>
        <h1 className="hero-title">Arrive and revive.</h1>
        <p className="hero-lead">A private beachfront villa on Playa Punta Negra. Four en-suite bedrooms, private infinity pool, chef and maid included. Family-owned and operated.</p>
        <div className="hero-ctas">
          <a className="btn btn-primary" href={bookUrl} target="_blank" rel="noreferrer">Book Your Stay</a>
          <button className="btn-ghost-light" onClick={() => navigate('rooms')}>Tour the villa</button>
        </div>
        <div className="hero-stats">
          <div><div className="stat-num">4.9</div><div className="stat-label">Google reviews</div></div>
          <div><div className="stat-num">4</div><div className="stat-label">Boutique suites</div></div>
          <div><div className="stat-num">27</div><div className="stat-label">Years hosting</div></div>
        </div>
      </div>
      <div className="hero-scroll-indicator">Scroll</div>
    </section>
    <section className="section-pullquote">
      <div className="container">
        <div className="pullquote-grid">
          <div className="pullquote-img"><img src={IMAGES.elSol3} alt="Courtyard fountain"/></div>
          <div className="pullquote-text">
            <div className="eyebrow" style={{marginBottom: 28, color: 'var(--terracotta)'}}>The Villa</div>
            <p className="display" style={{fontSize: 'clamp(28px, 3vw, 44px)', lineHeight: 1.25, fontWeight: 300, letterSpacing: '-0.015em'}}>The water comes all the way to the backyard.</p>
            <p className="body" style={{fontSize: 17, marginTop: 24, maxWidth: 520}}>Each boutique bedroom is en suite. An architectural wonder built around a central courtyard fountain, where the sound of the sea permeates every wall.</p>
          </div>
        </div>
      </div>
    </section>
    <section className="section section-warm">
      <div className="container">
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 60, flexWrap: 'wrap', gap: 24}}>
          <div>
            <div className="eyebrow" style={{marginBottom: 16}}>Accommodations</div>
            <h2 className="display" style={{fontSize: 'clamp(36px, 4.5vw, 56px)'}}>Four suites, four moods.</h2>
          </div>
          <button className="btn btn-ghost" onClick={() => navigate('rooms')}>View all rooms</button>
        </div>
        <div className="grid-4 suite-grid">
          {[
            { name: 'el Cielo',  sub: 'Master Suite',   img: IMAGES.elCielo1 },
            { name: 'el Sol',    sub: 'Courtyard · 2 Queens', img: IMAGES.elSol1 },
            { name: 'las Nubes', sub: 'King + Queen',   img: IMAGES.nubes1 },
            { name: 'el Mar',    sub: 'Garden · 2 Twin', img: IMAGES.mar1 },
          ].map(r => (
            <div key={r.name} className="suite-card" onClick={() => navigate('rooms')}>
              <div className="suite-photo"><img src={r.img} alt={r.name} loading="lazy"/></div>
              <div className="suite-meta">
                <div className="eyebrow">{r.sub}</div>
                <h3 className="serif">{r.name}</h3>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
    <section className="section">
      <div className="container">
        <div className="grid-2" style={{alignItems: 'center', gap: 80}}>
          <div className="photo" style={{aspectRatio: '4/5'}}><img src={IMAGES.porch1} alt="Front porch"/></div>
          <div>
            <div className="eyebrow" style={{marginBottom: 20}}>The Experience</div>
            <h2 className="display" style={{fontSize: 'clamp(36px, 4vw, 52px)', marginBottom: 28}}>Staff who make you feel like family.</h2>
            <p className="body" style={{marginBottom: 20, fontSize: 17}}>Enrique, Gabo, Anna — with Elba and Gloria on rotation — have been the heart of Villa Karaway for years. Five-star cooking on request, fresh-pressed juice at sunrise, margaritas on the front porch at sunset.</p>
            <p className="body" style={{marginBottom: 32, fontSize: 16}}>You'll not feel like a guest, but an owner of the house.</p>
            <button className="btn btn-outline" onClick={() => navigate('experience')}>Meet the staff</button>
          </div>
        </div>
      </div>
    </section>
    <section className="section section-dark">
      <div className="container-narrow text-center">
        <div className="eyebrow" style={{marginBottom: 32, color: 'rgba(250,246,239,0.6)'}}>From our guests</div>
        <p className="display" style={{fontSize: 'clamp(26px, 3vw, 38px)', fontStyle: 'italic', fontWeight: 300, lineHeight: 1.4, color: 'var(--bg)', marginBottom: 40}}>"{featured?.text || 'A private beachfront villa, cared for by a full staff — the kind of place you arrive at and instantly slow down.'}"</p>
        <div className="eyebrow" style={{color: 'var(--sand)'}}>— {featured?.author || 'Guest review'}</div>
        <div style={{marginTop: 48}}><button className="btn btn-light" onClick={() => navigate('reviews')}>Read all reviews</button></div>
      </div>
    </section>
    <section className="section">
      <div className="container">
        <div className="grid-2" style={{alignItems: 'center', gap: 80}}>
          <div>
            <div className="eyebrow" style={{marginBottom: 20}}>Location</div>
            <h2 className="display" style={{fontSize: 'clamp(36px, 4vw, 52px)', marginBottom: 28}}>Playa Punta Negra, Puerto Vallarta.</h2>
            <p className="body" style={{marginBottom: 24, fontSize: 16}}>Seven-and-a-half kilometers south of downtown on the old road to Barra de Navidad — far enough to feel private, close enough to be in town in fifteen minutes.</p>
            <div className="stack" style={{marginTop: 32, paddingTop: 32, borderTop: '1px solid var(--line-soft)'}}>
              <div style={{display: 'flex', gap: 16}}><Icon name="mapPin" size={20}/><div><div style={{fontWeight: 500, marginBottom: 4}}>Address</div><div className="body" style={{fontSize: 14}}>Carretera a Barra de Navidad Km. 7.5, Playa Punta Negra, Puerto Vallarta</div></div></div>
              <div style={{display: 'flex', gap: 16}}><Icon name="phone" size={20}/><div><div style={{fontWeight: 500, marginBottom: 4}}>Book by phone</div><div className="body" style={{fontSize: 14}}>720-422-2216</div></div></div>
            </div>
          </div>
          <div className="photo" style={{aspectRatio: '1/1'}}><img src={IMAGES.rooms} alt="Villa"/></div>
        </div>
      </div>
    </section>
  </>
  );
};

const RoomsPage = ({ navigate }) => {
  const { settings } = useSite();
  const bookUrl = settings.hostmoat_booking_url || '#';

  // The four boutique bedroom suites. Named "sea to heaven" (del mar, nubes, sol, cielo).
  // Every bedroom: en-suite bath, individual temperature control, TV, Nest Hub.
  const suites = [
    { name: 'el Cielo', sub: 'Heaven — Master Suite', desc: "The main master bedroom: king bed + a futon/couch for an extra sleeper, and a large private porch to take in the ocean, wildlife, and some of the best sunsets in the bay. The suite was made to be lived in, not just slept in.", bed: 'King + Futon', guests: '3', bath: 'En suite · Large shower', img: IMAGES.elCielo1 },
    { name: 'el Sol', sub: 'The Sun — Courtyard Suite', desc: "Two queen beds next door to the master. Overlooks the fountain courtyard, so the sound of water and the ocean carries straight through. Private en-suite bath.", bed: '2 Queen', guests: '4', bath: 'En suite · Private', img: IMAGES.elSol1 },
    { name: 'las Nubes', sub: 'The Clouds — Courtyard Suite', desc: "One of the largest bedrooms at the villa: a king and a queen bed together, and an oversized bathroom with a huge shower. Looks onto the courtyard fountain.", bed: 'King + Queen', guests: '4', bath: 'En suite · Large shower', img: IMAGES.nubes1 },
    { name: 'el Mar', sub: 'The Sea — Garden / Ground Floor', desc: "A downstairs bedroom — super quiet, and ideal for guests who’d rather avoid stairs. Two twin beds that can be combined into a king on request. Private en-suite bath (recently renovated).", bed: '2 Twin (or King)', guests: '2', bath: 'En suite · Ground floor', img: IMAGES.mar1 },
  ];

  // Shared spaces: pool, decks, dining, courtyard, kitchen, beach.
  // Image refs point at specific R2 keys from the Airbnb set (not in IMAGES map).
  const spaces = [
    { name: 'Private Infinity Pool', sub: 'Beachfront', desc: "Your own private soaking pool opens straight onto the sand, with uninterrupted bay views. Sunrise coffee, afternoon laps, sunset margaritas, late-night swims under the stars — most of your stay will happen here.", img: '/media/gallery/airbnb/fc5644735baa.jpg' },
    { name: "Upstairs Deck", sub: "Off el Cielo · Master Porch", desc: "A private porch connected to the master suite with uninterrupted views of the Pacific, the bay, and the sunset. Ideal spot for yoga at sunrise or a quiet drink after dinner.", img: '/media/gallery/airbnb/527d6ad9b3df.jpg' },
    { name: "Living Room", sub: "Indoor–Outdoor Flow", desc: "Soaring ceilings, natural light, and a direct opening onto the patio. Sofas face the waves, the breeze moves through, and the sound of the surf is constant.", img: '/media/gallery/airbnb/5a4745400ff0.jpg' },
    { name: "Dining Room", sub: "Table for Twelve", desc: "The large dining table seats up to 12 — sized for sunset dinners, shared breakfasts, and the kind of long evenings that pile up into memories. Indoor dining plus an outdoor table with the best view in the house.", img: '/media/gallery/airbnb/5eb2dd7a9dfb.jpg' },
    { name: "Kitchen", sub: "Staff-Run, Guest-Open", desc: "Top-of-the-line appliances, kept immaculate by the staff. Your chef prepares meals customized for your group — pre-paid meal plan optional (ask for details), or pay separately for groceries and drinks.", img: '/media/gallery/airbnb/4a79fa9827f6.jpg' },
    { name: "Central Courtyard", sub: "The Villa’s Heart", desc: "An architectural wonder built around a central fountain. Every bedroom opens onto the courtyard, so the sound of running water and the Pacific carries through every wall.", img: '/media/gallery/airbnb/e6d3dd86d560.jpg' },
    { name: "Beach & Water Toys", sub: "Playa Punta Negra", desc: "Steps off the back patio onto Playa Punta Negra. Lifeguard-patrolled, quiet, uncrowded. Paddleboards, kayaks, boogie boards, and pool toys are all included with your stay.", img: '/media/gallery/airbnb/0847a743a21f.jpg' },
  ];

  const card = (r, i) => (
    <div key={r.name} className={`room-card ${i % 2 === 1 ? 'reverse' : ''}`}>
      <div className="room-card-img"><img src={r.img} alt={r.name} loading="lazy" style={{width: '100%', height: '100%', objectFit: 'cover'}}/></div>
      <div className="room-card-content">
        <div className="eyebrow">{r.sub}</div>
        <h3>{r.name}</h3>
        <p className="body" style={{fontSize: 16}}>{r.desc}</p>
        {r.bed && <div className="room-card-meta">
          <span><Icon name="bed" size={16}/> {r.bed}</span>
          <span><Icon name="users" size={16}/> {r.guests}</span>
          <span><Icon name="bath" size={16}/> {r.bath}</span>
        </div>}
      </div>
    </div>
  );

  return (
    <>
      <section style={{padding: '120px 0 40px'}}>
        <div className="container">
          <SectionHead
            eyebrow="Tour the Villa"
            title="4 bedrooms, one private villa."
            intro="Villa Karaway is an open-air, 3-story, 4,000+ sq ft oceanfront villa in Puerto Vallarta’s South Zone. Four en-suite bedrooms — named sea-to-heaven — wrap around a central courtyard fountain, so the sound of water and the Pacific carries through every room. Private infinity soaking pool. Chef and maid included. Up to 12 guests."
          />
          <div className="villa-facts">
            {[
              ['Bedrooms',  '4 · all en-suite'],
              ['Bathrooms', '5'],
              ['Sleeps',    'Up to 12'],
              ['Size',      '4,000+ sq ft'],
              ['Stories',   '3'],
              ['Pool',      'Private infinity'],
              ['Staff',     'Chef · Maid · Manager'],
              ['Wi-Fi',     'Fiber optic, every room'],
            ].map(([k, v]) => (
              <div key={k} className="villa-fact">
                <div className="eyebrow">{k}</div>
                <div className="villa-fact-val">{v}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <div className="container">{suites.map(card)}</div>

      <section style={{padding: '80px 0 32px'}}>
        <div className="container">
          <SectionHead eyebrow="Shared Spaces" title="The rest of the villa." intro="The common areas are where the villa opens up — the private pool, the upstairs deck, the dining room and kitchen, the courtyard, and the beach just past the back patio."/>
        </div>
      </section>

      <div className="container">{spaces.map(card)}</div>

      <section className="section text-center">
        <div className="container-narrow">
          <div className="eyebrow" style={{marginBottom: 20}}>Ready to book?</div>
          <h2 className="display" style={{fontSize: 'clamp(32px, 4vw, 48px)', marginBottom: 32}}>The villa is waiting.</h2>
          <div style={{display: 'flex', gap: 20, justifyContent: 'center', flexWrap: 'wrap'}}>
            <a className="btn btn-primary" href={bookUrl} target="_blank" rel="noreferrer">Book Your Stay</a>
            <button className="btn btn-outline" onClick={() => navigate('availability')}>See availability</button>
          </div>
        </div>
      </section>
    </>
  );
};

const GalleryPage = () => {
  const items = [
    { src: IMAGES.hero, label: 'Beachfront at dusk', class: 'wide' },
    { src: IMAGES.elCielo1, label: 'el Cielo' },
    { src: IMAGES.porch1, label: 'Front porch' },
    { src: IMAGES.elSol1, label: 'el Sol' },
    { src: IMAGES.elSol2, label: 'el Sol bath' },
    { src: IMAGES.nubes1, label: 'las Nubes' },
    { src: IMAGES.elCielo2, label: 'el Cielo sitting' },
    { src: IMAGES.living1, label: 'Living room', class: 'wide' },
    { src: IMAGES.elCielo3, label: 'el Cielo veranda' },
    { src: IMAGES.elSol3, label: 'el Sol detail' },
    { src: IMAGES.nubes2, label: 'las Nubes bath' },
    { src: IMAGES.nubes3, label: 'las Nubes closet' },
    { src: IMAGES.living2, label: 'Dining area' },
    { src: IMAGES.living3, label: 'Common area' },
    { src: IMAGES.porch2, label: 'Porch view' },
    { src: IMAGES.mar1, label: 'el Mar' },
    { src: IMAGES.rooms, label: 'Courtyard', class: 'wide' },
  ];
  return (
    <>
      <section style={{padding: '120px 0 60px'}}>
        <div className="container">
          <SectionHead eyebrow="The Villa in Pictures" title="Gallery." intro="Every corner of Villa Karaway is framed by either ocean, courtyard, or garden."/>
        </div>
      </section>
      <div className="container" style={{paddingBottom: 120}}>
        <div className="gallery-grid">
          {items.map((it, i) => (
            <div key={i} className={`gallery-item ${it.class || ''}`}>
              <div className="photo" style={{height: '100%'}}><img src={it.src} alt={it.label}/></div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

const MenuPage = () => {
  const { menu_cards, settings } = useSite();
  const hillary = settings.hillary_email || 'hillary@karaway.com';
  return (
  <>
    <section style={{padding: '120px 0 60px'}}>
      <div className="container">
        <SectionHead eyebrow="Cooked by Chef Gabo" title="The Villa Menu." intro="Your stay is made more memorable by the fresh cuisine Gabo prepares on-site. Select from the menu in advance and he'll meet almost any dietary need — vegetarian, gluten-free, low-calorie. Off-menu requests welcome, and appetizers can become entrées (or vice versa)."/>
      </div>
    </section>
    <div className="container" style={{paddingBottom: 80}}>
      <div className="grid-3">
        {menu_cards.map(m => (
          <a key={m.id} href={m.url} target="_blank" rel="noreferrer" className="card" style={{padding: 40, textDecoration: 'none', display: 'flex', flexDirection: 'column', gap: 16}}>
            <Icon name="file" size={28}/>
            <h3 className="serif" style={{fontSize: 28, fontWeight: 400, letterSpacing: '-0.01em'}}>{m.label}</h3>
            <div style={{flex: 1}}></div>
            <div style={{fontFamily: 'var(--sans)', fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--terracotta)', fontWeight: 500, marginTop: 8}}>View PDF →</div>
          </a>
        ))}
      </div>
    </div>
    <section className="section section-warm">
      <div className="container">
        <div className="grid-2" style={{alignItems: 'center', gap: 80}}>
          <div className="photo" style={{aspectRatio: '4/5'}}><img src={IMAGES.living2} alt="Dining room"/></div>
          <div>
            <div className="eyebrow" style={{marginBottom: 20}}>Pre-paid Food & Drink (optional)</div>
            <h2 className="display" style={{fontSize: 'clamp(32px, 3.8vw, 46px)', marginBottom: 24}}>Take the guesswork out of the grocery tab.</h2>
            <p className="body" style={{fontSize: 17, marginBottom: 20}}>If your group would like the pre-paid food & drink option, mention it on the arrival form or email Hillary directly. Current pricing is shown in the arrival form (it does shift over time with ingredient costs).</p>
            <p className="body" style={{fontSize: 17, marginBottom: 32}}>The whole group must opt in for all dates you've booked. If you choose it, we'll send a separate invoice.</p>
            <a className="btn btn-primary" href={`mailto:${hillary}`}>Email Hillary</a>
          </div>
        </div>
      </div>
    </section>
    <section className="section">
      <div className="container-narrow text-center">
        <div className="eyebrow" style={{marginBottom: 24}}>A taste of what we cook</div>
        <p className="display" style={{fontSize: 'clamp(24px, 2.6vw, 34px)', lineHeight: 1.4, marginBottom: 40}}>Fresh-pressed juice at sunrise. Whole grilled fish. Margaritas on the porch. Gabo's Piña Fresh and Strawberry juices (mix with vodka or tequila, or don't). Whatever you're craving, Gabo can make it.</p>
        <p className="body" style={{fontSize: 16}}>Tell Gabo what you love — he'll cook it.</p>
      </div>
    </section>
  </>
  );
};

const ExperiencePage = () => {
  const { settings } = useSite();
  const preArrival = settings.pre_arrival_url || settings.hostmoat_booking_url || '#';
  // Staff roster per the live karaway.com: Enrique (manager), Gabo (cook), Anna (housekeeping).
  // Elba (cook on other rotations) and Gloria are mentioned in reviews + guest-info — the live site's
  // /the-staff page only formally introduces these three, so we match that for parity.
  const staff = [
    { name: 'Enrique', role: 'Villa Manager', bio: "Enrique — Kike to the guests who keep coming back — runs the house. He lives nearby, speaks perfect English, and can arrange anything you need: airport pickup, a boat to Yelapa, fresh flowers in your room before you arrive.", img: IMAGES.porch2 },
    { name: 'Gabo',    role: 'Chef',          bio: "Gabo cooks for the villa and speaks English. He has a huge repertoire of dishes and happily tailors meals to whatever you and your group love — gluten-free, vegetarian, low-calorie, off-menu. You will not be disappointed.",              img: IMAGES.living2 },
    { name: 'Anna',    role: 'Housekeeping',  bio: "Anna keeps the villa immaculate — every bedroom, fresh towels, clean linens. She arrives around 9 AM and usually finishes by late afternoon. Dependable, trustworthy, and quietly everywhere at once.",                                 img: IMAGES.porch1 },
  ];
  return (
    <>
      <section style={{padding: '120px 0 80px'}}>
        <div className="container"><SectionHead eyebrow="The Experience" title="The staff who make Karaway home." intro="Enrique, Gabo, and Anna — along with Elba and Gloria on rotation — are the reason guests return year after year. They work Monday through Saturday; if you arrive on a Sunday, you'll still find them at the villa getting everything ready for you."/></div>
      </section>
      <div className="container" style={{paddingBottom: 80}}>
        <div className="grid-3">
          {staff.map(s => (
            <div key={s.name}>
              <div className="photo" style={{aspectRatio: '1/1'}}><img src={s.img} alt={s.name}/></div>
              <div style={{paddingTop: 20}}>
                <div className="eyebrow" style={{marginBottom: 6}}>{s.role}</div>
                <h3 className="serif" style={{fontSize: 26, fontWeight: 400, marginBottom: 8}}>{s.name}</h3>
                <p className="body" style={{fontSize: 14}}>{s.bio}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
      <section className="section section-warm">
        <div className="container">
          <div className="grid-2" style={{alignItems: 'center', gap: 80}}>
            <div>
              <div className="eyebrow" style={{marginBottom: 20}}>Before you arrive</div>
              <h2 className="display" style={{fontSize: 'clamp(32px, 4vw, 48px)', marginBottom: 28}}>Fill out the arrival form.</h2>
              <p className="body" style={{fontSize: 16, marginBottom: 20}}>The arrival form is the one piece of paperwork we ask every guest group to complete 7–10 days before checking in. It has everything we need to know to prep the villa — flights, dietary preferences, pre-paid food & drink options, grocery requests — and everything you need to know about the stay.</p>
              <p className="body" style={{fontSize: 16, marginBottom: 32}}>One person fills it out for the whole group; you can redo it anytime, and we'll always work from the most recent version.</p>
              <a className="btn btn-primary" href={preArrival} target="_blank" rel="noreferrer">Open Arrival Form</a>
            </div>
            <div className="photo" style={{aspectRatio: '4/3'}}><img src={IMAGES.living1} alt="Living area"/></div>
          </div>
        </div>
      </section>
    </>
  );
};

const ReviewsPage = () => {
  const { reviews } = useSite();
  const avg = reviews.length ? (reviews.reduce((a, r) => a + (r.rating || 0), 0) / reviews.length) : 0;
  return (
    <>
      <section style={{padding: '120px 0 60px'}}>
        <div className="container">
          <SectionHead eyebrow="Guest Comments" title="From our guests." intro="A decade and a half of families, friends, honeymooners, and yogis."/>
          <div style={{display: 'flex', gap: 40, alignItems: 'center', paddingTop: 32, borderTop: '1px solid var(--line-soft)'}}>
            <div>
              <div style={{fontFamily: 'var(--serif)', fontSize: 56, fontWeight: 300, lineHeight: 1}}>{avg ? avg.toFixed(1) : '—'}</div>
              <div style={{display: 'flex', gap: 2, marginTop: 8, color: 'var(--terracotta)'}}>{[1,2,3,4,5].map(i => <Icon key={i} name="star" size={14}/>)}</div>
            </div>
            <div>
              <div className="eyebrow" style={{marginBottom: 6}}>Average rating</div>
              <div className="body" style={{fontSize: 14}}>Based on {reviews.length} review{reviews.length !== 1 ? 's' : ''} across Google, Airbnb, and guest books since 1999.</div>
            </div>
          </div>
        </div>
      </section>
      <div className="container" style={{paddingBottom: 120}}>
        <div style={{columns: '2 360px', columnGap: 32}}>
          {reviews.length === 0 ? (
            <p style={{color: 'var(--muted)', fontSize: 15}}>No reviews yet.</p>
          ) : reviews.map((r) => (
            <div key={r.id} className="card" style={{padding: 32, marginBottom: 32, breakInside: 'avoid'}}>
              <div style={{display: 'flex', gap: 2, color: 'var(--terracotta)', marginBottom: 16}}>{Array.from({length: r.rating}).map((_, j) => <Icon key={j} name="star" size={12}/>)}</div>
              <p style={{fontFamily: 'var(--serif)', fontSize: 19, fontWeight: 300, lineHeight: 1.5, fontStyle: 'italic', marginBottom: 24}}>"{r.text}"</p>
              <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 16, borderTop: '1px solid var(--line-soft)'}}>
                <div style={{fontWeight: 500, fontSize: 14}}>{r.author}</div>
                <div className="eyebrow">{r.source || '—'}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

const ContactPage = () => {
  const { settings } = useSite();
  const bookUrl = settings.hostmoat_booking_url || '#';
  const [form, setForm] = useStateP({ name: '', email: '', subject: 'General question', message: '', website: '' });
  const [state, setState] = useStateP({ sending: false, sent: false, error: null });

  const submit = async (e) => {
    e.preventDefault();
    setState({ sending: true, sent: false, error: null });
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!r.ok) throw new Error(await r.text());
      setState({ sending: false, sent: true, error: null });
      setForm({ name: '', email: '', subject: 'General question', message: '', website: '' });
    } catch (e) {
      setState({ sending: false, sent: false, error: String(e) });
    }
  };

  return (
  <>
    <section style={{padding: '120px 0 60px'}}>
      <div className="container"><SectionHead eyebrow="Contact" title="Get in touch." intro="For bookings, use the button below — our reservation system is handled by HostMoat. For any other questions, reach us directly."/></div>
    </section>
    <div className="container" style={{paddingBottom: 120}}>
      <div className="grid-2" style={{alignItems: 'flex-start', gap: 64}}>
        <form onSubmit={submit}>
          <h3 className="serif" style={{fontSize: 32, fontWeight: 400, marginBottom: 20}}>Send a message</h3>
          <div className="form-row"><label className="label">Your name</label><input className="input" placeholder="Full name" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required/></div>
          <div className="form-row"><label className="label">Email</label><input className="input" type="email" placeholder="you@example.com" value={form.email} onChange={e => setForm({...form, email: e.target.value})} required/></div>
          <div className="form-row"><label className="label">Subject</label>
            <select className="select" value={form.subject} onChange={e => setForm({...form, subject: e.target.value})}>
              <option>General question</option><option>Custom stay</option><option>Press / media</option><option>Other</option>
            </select>
          </div>
          <div className="form-row"><label className="label">Message</label><textarea className="textarea" rows={6} placeholder="How can we help?" value={form.message} onChange={e => setForm({...form, message: e.target.value})} required/></div>
          {/* honeypot, hidden */}
          <input type="text" name="website" value={form.website} onChange={e => setForm({...form, website: e.target.value})} tabIndex={-1} autoComplete="off" style={{position: 'absolute', left: '-9999px', opacity: 0}}/>
          <button type="submit" className="btn btn-primary" disabled={state.sending}>{state.sending ? 'Sending…' : (state.sent ? 'Sent ✓' : 'Send Message')}</button>
          {state.error && <p className="small" style={{color: '#a0403a', marginTop: 16}}>{state.error}</p>}
          {state.sent && <p className="small" style={{color: 'var(--sage)', marginTop: 16}}>Thanks — we'll get back to you soon.</p>}
          <p className="small" style={{color: 'var(--muted)', marginTop: 16}}>For bookings, please use the HostMoat system →</p>
        </form>
        <div className="card" style={{padding: 40, background: 'var(--bg-warm)', border: 'none'}}>
          <div className="stack-lg">
            <div>
              <div className="eyebrow" style={{marginBottom: 16}}>Book your stay</div>
              <a className="btn btn-primary" href={bookUrl} target="_blank" rel="noreferrer" style={{width: '100%', justifyContent: 'center'}}>Open Booking System</a>
            </div>
            {settings.phone && <div><div className="eyebrow" style={{marginBottom: 12}}>Call us</div><div className="serif" style={{fontSize: 28, fontWeight: 400}}>{settings.phone}</div></div>}
            {settings.email && <div><div className="eyebrow" style={{marginBottom: 12}}>Email</div><div style={{fontSize: 17}}>{settings.email}</div></div>}
            <div><div className="eyebrow" style={{marginBottom: 12}}>Address</div><div className="body" style={{fontSize: 15}}>{settings.address_line1 || 'Carretera a Barra de Navidad Km. 7.5'}<br/>{settings.address_line2 || 'Playa Punta Negra, Puerto Vallarta'}<br/>{settings.address_line3 || 'Jalisco, Mexico'}</div></div>
            <div><div className="eyebrow" style={{marginBottom: 12}}>Follow</div>
              <div style={{display: 'flex', gap: 14}}>
                {settings.instagram_url && <a href={settings.instagram_url} target="_blank" rel="noreferrer"><Icon name="instagram" size={22}/></a>}
                {settings.facebook_url && <a href={settings.facebook_url} target="_blank" rel="noreferrer"><Icon name="facebook" size={22}/></a>}
                {settings.airbnb_url && <a href={settings.airbnb_url} target="_blank" rel="noreferrer" style={{fontSize: 13, fontWeight: 500}}>Airbnb</a>}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </>
  );
};

// ============ NEW PAGES ============

// Real Villa Karaway YouTube IDs, ripped from karaway.com /video and /video-vk on 2026-04-19.
const VideoPage = () => {
  const [active, setActive] = useStateP('tg__9dnY6G0');
  const videos = [
    { id: 'tg__9dnY6G0', title: 'Welcome to Villa Karaway',        desc: 'See what Villa Karaway is all about.' },
    { id: 'jeoH1u0E-qA', title: 'Yoga Retreat 2014',                desc: 'Meditation, adventure, new friendships, and yoga.' },
    { id: 'AZHcWzDsChc', title: 'Villa Karaway by Air',             desc: 'The villa and the surrounding coast from above.' },
    { id: '1ln7Qhw7LdY', title: 'Kayak Time',                       desc: 'There’s a kayak at the villa — great way to explore the cove.' },
    { id: 'ngbpPZ2RX7I', title: 'How To Vacation',                  desc: 'A walkthrough of what the villa has to offer.' },
    { id: '1UXfwAMeL1I', title: 'Escape',                           desc: 'No worries here.' },
    { id: 'X6DJmWBei_s', title: 'Want a Better View?',              desc: 'A flight around the grounds and inside the villa.' },
  ];
  return (
  <>
    <section style={{padding: '120px 0 60px'}}>
      <div className="container"><SectionHead eyebrow="Video Tour" title="See the villa in motion." intro="The main Villa Karaway tour, plus a handful of films guests and friends have made of the place over the years."/></div>
    </section>
    <div className="container" style={{paddingBottom: 120}}>
      <div style={{position: 'relative', aspectRatio: '16/9', background: 'var(--ocean)', marginBottom: 40, overflow: 'hidden'}}>
        <iframe
          key={active}
          src={`https://www.youtube.com/embed/${active}?autoplay=0&rel=0&modestbranding=1`}
          title={videos.find(v => v.id === active)?.title || 'Villa Karaway'}
          style={{width: '100%', height: '100%', border: 'none'}}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
        />
      </div>
      <div className="grid-3">
        {videos.map(v => (
          <button key={v.id} onClick={() => { setActive(v.id); window.scrollTo({top: 0, behavior: 'smooth'}); }} style={{cursor: 'pointer', textAlign: 'left', background: 'transparent', border: 'none', padding: 0, opacity: active === v.id ? 1 : 0.85}}>
            <div style={{position: 'relative', aspectRatio: '16/10', overflow: 'hidden', border: active === v.id ? '2px solid var(--terracotta)' : '2px solid transparent'}}>
              <img src={`https://i.ytimg.com/vi/${v.id}/hqdefault.jpg`} alt={v.title} style={{width: '100%', height: '100%', objectFit: 'cover'}} loading="lazy"/>
            </div>
            <div style={{padding: '16px 4px'}}>
              <h3 className="serif" style={{fontSize: 22, fontWeight: 400, marginBottom: 6}}>{v.title}</h3>
              <p className="body" style={{fontSize: 13, color: 'var(--muted)'}}>{v.desc}</p>
            </div>
          </button>
        ))}
      </div>
    </div>
  </>
  );
};

const WebcamPage = () => {
  const { settings } = useSite();
  const webcamUrl = settings.webcam_url || '';
  const webcamType = settings.webcam_type || 'iframe'; // iframe | youtube | mp4 | still
  const locationName = settings.webcam_location_name || 'Punta Negra · Jalisco';
  const weatherLoc = settings.weather_location || 'Puerto Vallarta';
  const [now, setNow] = useStateP(() => new Date());
  const [weather, setWeather] = useStateP(null);

  useEffectP(() => {
    const t = setInterval(() => setNow(new Date()), 60000);
    return () => clearInterval(t);
  }, []);

  // Pull current conditions from wttr.in (free, no key needed)
  useEffectP(() => {
    let cancel = false;
    fetch(`https://wttr.in/${encodeURIComponent(weatherLoc)}?format=j1`, { cache: 'no-store' })
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (cancel || !data?.current_condition?.[0]) return;
        const c = data.current_condition[0];
        setWeather({
          tempF: c.temp_F,
          desc: c.weatherDesc?.[0]?.value || '',
          windMph: c.windspeedMiles,
          windDir: c.winddir16Point,
          humidity: c.humidity,
        });
      })
      .catch(() => {});
    return () => { cancel = true; };
  }, [weatherLoc]);

  const renderCam = () => {
    if (!webcamUrl) {
      return (
        <div style={{width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(250,246,239,0.7)', fontFamily: "'EB Garamond', Georgia, serif", fontSize: 24, fontWeight: 300, textAlign: 'center', padding: 40}}>
          Webcam coming soon.<br/>
          <span style={{fontSize: 13, fontFamily: 'var(--sans)', color: 'rgba(250,246,239,0.5)', letterSpacing: '0.08em', marginTop: 12, display: 'block'}}>Admin → Settings → Webcam URL</span>
        </div>
      );
    }
    if (webcamType === 'youtube') {
      // Accept full URL, video ID, or livestream URL
      const m = webcamUrl.match(/(?:v=|youtu\.be\/|embed\/)([A-Za-z0-9_-]{11})/);
      const id = m ? m[1] : webcamUrl;
      return <iframe src={`https://www.youtube.com/embed/${id}?autoplay=1&mute=1&controls=0&rel=0`} style={{width: '100%', height: '100%', border: 'none'}} allow="autoplay; encrypted-media" allowFullScreen/>;
    }
    if (webcamType === 'mp4') {
      return <video src={webcamUrl} autoPlay muted loop playsInline style={{width: '100%', height: '100%', objectFit: 'cover'}}/>;
    }
    if (webcamType === 'still') {
      // Cache-bust every 30s
      return <img src={webcamUrl + (webcamUrl.includes('?') ? '&' : '?') + '_=' + Math.floor(now.getTime() / 30000)} style={{width: '100%', height: '100%', objectFit: 'cover'}} alt={locationName}/>;
    }
    // iframe fallback
    return <iframe src={webcamUrl} style={{width: '100%', height: '100%', border: 'none'}} allow="fullscreen; autoplay" sandbox="allow-scripts allow-same-origin"/>;
  };

  return (
  <>
    <section style={{padding: '120px 0 60px'}}>
      <div className="container"><SectionHead eyebrow={`Live from ${locationName}`} title="The Karaway webcam." intro="A live view of Bahía de Banderas from Villa Karaway in Puerto Vallarta. The image refreshes approximately every 10 minutes."/></div>
    </section>
    <div className="container" style={{paddingBottom: 60}}>
      <div style={{position: 'relative', aspectRatio: '16/9', overflow: 'hidden', background: 'var(--ocean)'}}>
        {renderCam()}
        {webcamUrl && (
          <div style={{position: 'absolute', top: 20, left: 20, display: 'flex', alignItems: 'center', gap: 10, background: 'rgba(15,35,38,0.85)', color: 'var(--bg)', padding: '8px 14px', fontSize: 12, fontFamily: 'var(--sans)', letterSpacing: '0.16em', textTransform: 'uppercase'}}>
            <span style={{width: 8, height: 8, borderRadius: '50%', background: '#ff4444', boxShadow: '0 0 8px #ff4444'}}/> Live
          </div>
        )}
        <div style={{position: 'absolute', bottom: 20, left: 20, color: 'var(--bg)', fontFamily: 'var(--mono)', fontSize: 13, textShadow: '0 1px 3px rgba(0,0,0,0.6)'}}>
          <div style={{fontSize: 11, opacity: 0.8, letterSpacing: '0.1em'}}>{locationName.toUpperCase()}</div>
          <div style={{fontSize: 18, marginTop: 4}}>{now.toLocaleTimeString('en-US', {hour: 'numeric', minute: '2-digit'})} local</div>
        </div>
      </div>
      <div className="grid-4" style={{marginTop: 48, gap: 24}}>
        {[
          { label: 'Temperature', value: weather ? `${weather.tempF}°F` : '—' },
          { label: 'Conditions',  value: weather ? weather.desc : '—' },
          { label: 'Wind',        value: weather ? `${weather.windMph} mph ${weather.windDir}` : '—' },
          { label: 'Humidity',    value: weather ? `${weather.humidity}%` : '—' },
        ].map(c => (
          <div key={c.label} style={{paddingTop: 24, borderTop: '1px solid var(--line)'}}>
            <div className="eyebrow" style={{marginBottom: 8}}>{c.label}</div>
            <div style={{fontFamily: 'var(--serif)', fontSize: 32, fontWeight: 300, letterSpacing: '-0.01em'}}>{c.value}</div>
          </div>
        ))}
      </div>
      <p className="small" style={{color: 'var(--muted)', marginTop: 24}}>Weather via wttr.in · {weatherLoc}. The camera feed is provided for entertainment only — experimental, may be delayed, intermittently unavailable, or inaccurate. Do not rely on it for weather, ocean conditions, or safety decisions.</p>
    </div>
  </>
  );
};

const GuestInfoPage = ({ navigate }) => {
  const { settings } = useSite();
  const preArrival = settings.pre_arrival_url || settings.hostmoat_booking_url || '#';
  return (
  <>
    <section style={{padding: '120px 0 60px'}}>
      <div className="container"><SectionHead eyebrow="Before You Arrive" title="Guest information." intro="Everything you need to know to make your stay at Villa Karaway effortless. Fill out the pre-arrival form at least 7 days before check-in so we can have everything ready."/></div>
    </section>
    <div className="container" style={{paddingBottom: 80}}>
      <div className="grid-3">
        {[
          { title: 'Pre-Arrival Form', desc: 'Flight details, dietary preferences, grocery requests, and any special arrangements.', href: preArrival, cta: 'Open Form →' },
          { title: 'Villa Q&A', desc: 'The full guest handbook: Wi-Fi, beach access, appliances, quiet hours, and more.', href: 'https://docs.google.com/document/d/10slhcVgZSTZ56xkx6ZjNSsvv_CXxmeLDz9PxGsiX1LY/edit?usp=sharing', cta: 'Open Q&A →' },
          { title: 'Activities in PV', desc: 'Hiking, snorkeling, whale watching, restaurants, and beach clubs.', href: '#', cta: 'Browse Activities →', internal: 'activities' },
        ].map(c => (
          c.internal ? (
            <button key={c.title} onClick={() => navigate(c.internal)} className="card" style={{padding: 40, textAlign: 'left', cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 16}}>
              <Icon name="mapPin" size={28}/>
              <h3 className="serif" style={{fontSize: 28, fontWeight: 400}}>{c.title}</h3>
              <p className="body" style={{fontSize: 16, flex: 1}}>{c.desc}</p>
              <div style={{fontFamily: 'var(--sans)', fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--terracotta)', fontWeight: 500}}>{c.cta}</div>
            </button>
          ) : (
            <a key={c.title} href={c.href} target="_blank" rel="noreferrer" className="card" style={{padding: 40, display: 'flex', flexDirection: 'column', gap: 16}}>
              <Icon name={c.title.includes('Form') ? 'calendar' : 'file'} size={28}/>
              <h3 className="serif" style={{fontSize: 28, fontWeight: 400}}>{c.title}</h3>
              <p className="body" style={{fontSize: 16, flex: 1}}>{c.desc}</p>
              <div style={{fontFamily: 'var(--sans)', fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--terracotta)', fontWeight: 500}}>{c.cta}</div>
            </a>
          )
        ))}
      </div>
    </div>
    <section className="section section-warm">
      <div className="container">
        <SectionHead eyebrow="The Essentials" title="Practical details."/>
        <div className="grid-2" style={{gap: 60}}>
          <div className="stack-lg">
            {[
              ['Check-in', '4:00 PM — Kike will meet you at the door with cold towels and agua fresca.'],
              ['Check-out', '11:00 AM — late check-out available on request.'],
              ['Airport transfer', 'Private transfer from PVR to the villa (~35 min) arranged via Kike.'],
              ['Wi-Fi', 'Fiber throughout the villa and front porch. Password provided on arrival.'],
            ].map(([k, v]) => (
              <div key={k}>
                <div className="eyebrow" style={{marginBottom: 8}}>{k}</div>
                <div className="body" style={{fontSize: 17}}>{v}</div>
              </div>
            ))}
          </div>
          <div className="stack-lg">
            {[
              ['Beach access', 'Private steps from the back patio directly onto Playa Punta Negra.'],
              ['Groceries', 'Stock the villa before arrival — email Hillary at hillary@karaway.com.'],
              ['Payment', 'Bookings handled by HostMoat. Staff gratuities welcome at departure.'],
              ['Languages', 'All staff speak English and Spanish. Kike also speaks French.'],
            ].map(([k, v]) => (
              <div key={k}>
                <div className="eyebrow" style={{marginBottom: 8}}>{k}</div>
                <div className="body" style={{fontSize: 17}}>{v}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  </>
  );
};

const ActivitiesPage = () => {
  // The live karaway.com activity list, expanded with brief context — all of these are real options
  // Kike (Enrique) can help plan. Whale-watching window is mid-October through mid-March.
  const activities = [
    { title: 'Zip-lining',        cat: 'Jungle Canopy',           desc: 'See the Sierra Madre from above. Several outfitters run half-day tours from PV.', img: IMAGES.porch1 },
    { title: 'Horseback Riding',  cat: 'Coast & Jungle',          desc: 'Trail rides along the beach and up into the jungle. Morning and sunset sessions.', img: IMAGES.rooms },
    { title: 'Whale Watching',    cat: 'Mid-Oct – Mid-March',     desc: 'Humpback whales migrate past Bahía de Banderas each winter to calve. Morning charters leave from Marina Vallarta.', img: IMAGES.porch2 },
    { title: 'Hiking',            cat: 'Sierra Madre',            desc: 'Trails in Vallarta Botanical Gardens, Yelapa waterfalls, and El Cuale up the river.', img: IMAGES.hero },
    { title: 'Sport Fishing',     cat: 'Half / Full Day',         desc: 'Marlin, dorado, sailfish. Private charters from Marina Vallarta or Boca de Tomatlán.', img: IMAGES.elSol2 },
    { title: 'Snorkeling & Diving', cat: 'Marietas / Los Arcos', desc: 'Los Arcos National Marine Park for easy snorkel; the Marietas Islands for a UNESCO day out.', img: IMAGES.elCielo3 },
    { title: 'Yoga at the Villa', cat: 'On Request',              desc: 'Private instructor on the front porch at sunrise. Villa Karaway has hosted full yoga retreats.', img: IMAGES.living1 },
    { title: 'Kayak the Cove',    cat: 'Included with Stay',      desc: 'A kayak lives at the villa — head out for a quiet morning paddle along the coast.', img: IMAGES.elSol1 },
    { title: 'Vallarta Zoo',      cat: 'Mismaloya',               desc: 'Small, hands-on zoo 20 min south of the villa. Good for families with kids.', img: IMAGES.elCielo1 },
    { title: 'Downtown Vallarta', cat: '15 Min North',            desc: 'El Malecón, Los Muertos beach, the old town cathedral, galleries, taquerías, and nightlife.', img: IMAGES.mar1 },
    { title: 'Shopping & Nightclubs', cat: 'Old Town',            desc: 'Artisan markets by day, rooftop bars and beach clubs by night. Most are 15 min away.', img: IMAGES.nubes1 },
  ];
  return (
    <>
      <section style={{padding: '120px 0 60px'}}>
        <div className="container"><SectionHead eyebrow="Find Adventure" title="Puerto Vallarta awaits." intro="Zip-lines above the canopy, horseback miles through the jungle, whales in the bay from mid-October through mid-March. While you're at the villa, the staff will help you plan and schedule anything you want to do."/></div>
      </section>
      <div className="container" style={{paddingBottom: 120}}>
        <div className="grid-3">
          {activities.map(a => (
            <div key={a.title} className="card">
              <div className="photo" style={{aspectRatio: '4/3'}}><img src={a.img} alt={a.title}/></div>
              <div style={{padding: 28}}>
                <div className="eyebrow" style={{marginBottom: 10}}>{a.cat}</div>
                <h3 className="serif" style={{fontSize: 26, fontWeight: 400, marginBottom: 10, letterSpacing: '-0.01em'}}>{a.title}</h3>
                <p className="body" style={{fontSize: 15}}>{a.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

// Generic page renderer for admin-created pages that don't have hand-coded components.
// Renders hero + sanitized body_html + optional widgets bound to this page.
const GenericPage = ({ pageId }) => {
  const { pages, widgets } = useSite();
  const page = pages.find(p => p.id === pageId || p.slug === '/' + pageId || p.slug === pageId);
  const pageWidgets = widgets.filter(w => w.placement === pageId + ' page' || w.placement === 'custom page');

  if (!page) {
    return (
      <section style={{padding: '160px 0', textAlign: 'center'}}>
        <div className="container">
          <SectionHead eyebrow="Page not found" title={pageId}/>
          <p className="body">This page doesn't exist yet.</p>
        </div>
      </section>
    );
  }

  return (
    <>
      <section style={{padding: '120px 0 60px'}}>
        <div className="container">
          <SectionHead eyebrow={page.title} title={page.hero_headline || page.title}/>
        </div>
      </section>
      {page.hero_image && (
        <div className="container" style={{marginBottom: 60}}>
          <div className="photo" style={{aspectRatio: '16/9'}}>
            <img src={resolvePhoto(page.hero_image)} alt={page.title}/>
          </div>
        </div>
      )}
      {page.body_html && (
        <div className="container-narrow" style={{paddingBottom: 80}}>
          <div className="body-serif prose" dangerouslySetInnerHTML={{__html: page.body_html}}/>
        </div>
      )}
      {pageWidgets.length > 0 && (
        <div className="container" style={{paddingBottom: 120}}>
          {pageWidgets.map(w => (
            <div key={w.id} style={{marginBottom: 32}}>
              <iframe
                src={w.kind === 'iframe' ? w.src : undefined}
                srcDoc={w.kind === 'html' ? w.src : undefined}
                style={{width: w.width || '100%', height: (w.height || 400) + 'px', border: 'none', maxWidth: '100%'}}
                sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
              />
            </div>
          ))}
        </div>
      )}
    </>
  );
};

// Availability page — embeds HostMoat's calendar-embed edge function.
// IMPORTANT: calendar-embed returns `Content-Type: text/plain` to browsers, so a direct
// <iframe src=...> would render the HTML as raw text. Workaround: fetch as text
// client-side, then set as `srcDoc`. This mirrors what HostMoat's own booking-site does.
const AvailabilityPage = () => {
  const { settings } = useSite();
  const propId = settings.hostmoat_property_id;
  const bookUrl = settings.hostmoat_booking_url || '#';
  const [html, setHtml] = useStateP(null);
  const [err, setErr] = useStateP(null);

  useEffectP(() => {
    if (!propId) return;
    const url = `https://tofekzsdwdpyevrdluhb.supabase.co/functions/v1/calendar-embed?property_id=${encodeURIComponent(propId)}&months=6&show_prices=1`;
    fetch(url, { credentials: 'omit' })
      .then(r => r.ok ? r.text() : Promise.reject(new Error(`HTTP ${r.status}`)))
      .then(setHtml)
      .catch(e => setErr(String(e)));
  }, [propId]);

  return (
    <>
      <section style={{padding: '120px 0 40px'}}>
        <div className="container">
          <SectionHead eyebrow="Check the calendar" title="Availability." intro="Pick your dates. Rates and open nights come straight from our HostMoat booking calendar — you’ll see exactly what we see."/>
        </div>
      </section>
      <div className="container" style={{paddingBottom: 40}}>
        {!propId ? (
          <p className="body" style={{color: 'var(--muted)'}}>Calendar will appear here once the HostMoat property is linked in Admin → Settings.</p>
        ) : err ? (
          <p className="body" style={{color: '#a0403a'}}>Couldn’t load the calendar: {err}. <a href={bookUrl} target="_blank" rel="noreferrer" style={{color: 'var(--terracotta)'}}>Open the booking site instead →</a></p>
        ) : html ? (
          <iframe
            srcDoc={html}
            title="Villa Karaway Availability"
            style={{width: '100%', height: 720, border: '1px solid var(--line)', background: 'var(--white)'}}
            sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
          />
        ) : (
          <div style={{width: '100%', height: 720, border: '1px solid var(--line)', background: 'var(--bg-warm)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 14, letterSpacing: '0.08em'}}>Loading calendar…</div>
        )}
      </div>
      <section className="section section-warm">
        <div className="container-narrow text-center">
          <div className="eyebrow" style={{marginBottom: 20}}>Ready to book?</div>
          <h2 className="display" style={{fontSize: 'clamp(32px, 4vw, 48px)', marginBottom: 28}}>Head to the direct booking site.</h2>
          <p className="body" style={{fontSize: 16, marginBottom: 32}}>Every confirmed booking is managed through HostMoat — you’ll get the reservation, payment, and pre-arrival form all in one place.</p>
          <a className="btn btn-primary" href={bookUrl} target="_blank" rel="noreferrer">Open Booking Site</a>
        </div>
      </section>
    </>
  );
};

Object.assign(window, { HomePage, RoomsPage, GalleryPage, MenuPage, ExperiencePage, ReviewsPage, ContactPage, VideoPage, WebcamPage, GuestInfoPage, ActivitiesPage, AvailabilityPage, GenericPage });
