// Shared: Nav, Footer, Icons — uses real image URLs
const { useState, useEffect, useRef } = React;

// Images served from Cloudflare R2 via /media/. Named IMAGES slots were refreshed
// on 2026-04-23 from the 2026 Airbnb photo tour (188 photos, room-categorized via
// Airbnb's roomTourLayoutInfos). Selections chosen by visual review of staged files.
// Prior 2026-04-19 picks + the original Wix set are both preserved in R2 — see
// airbnb-uploaded.json (v1) and airbnb-uploaded-v2.json (current) for provenance.
const IMAGES = {
  logo:     '/media/logo.png',
  hero:     '/media/gallery/airbnb/2461731ce60f.jpg', // Living room opening to ocean patio at golden hour
  elCielo1: '/media/gallery/airbnb/5631c3fc5700.jpg', // El Cielo master bedroom with deck + ocean view (hero)
  elCielo2: '/media/gallery/airbnb/b797e303cfd3.jpg', // El Cielo interior with coffee bar + open slider to ocean
  elCielo3: '/media/gallery/airbnb/d061382afc05.jpg', // El Cielo top deck with wicker chairs looking into master
  elSol1:   '/media/gallery/airbnb/0e8aef8beeed.jpg', // El Sol bedroom — twin + queen with sunset photo art
  elSol2:   '/media/gallery/airbnb/474aaef30f09.jpg', // Renovated master bath — large walk-in shower, dual heads
  elSol3:   '/media/gallery/airbnb/81093da25c34.jpg', // Indoor pineapple fountain in the courtyard
  nubes1:   '/media/gallery/airbnb/b47dff2dee09.jpg', // Nubes bedroom with king bed + sunburst art (hero)
  nubes2:   '/media/gallery/airbnb/d36c4654910c.jpg', // Nubes alternate — pair of queens + wave art
  nubes3:   '/media/gallery/airbnb/e478bf918b2e.jpg', // Entry to "Clouds · Nubes" from staircase
  mar1:     '/media/gallery/airbnb/951df46631c4.jpg', // el Mar — twin beds with marine photo art (kids room)
  living1:  '/media/gallery/airbnb/7a2b91a2f3c2.jpg', // Living room wide through to private pool + ocean
  living2:  '/media/gallery/airbnb/dfc69a2e435b.jpg', // Formal dining room — seats 12 with ocean view
  living3:  '/media/gallery/airbnb/84112fd766fc.jpg', // Reverse angle — from outdoor patio back into living
  porch1:   '/media/gallery/airbnb/0e61fb8ac714.jpg', // Covered oceanfront patio with palapa roof (signature)
  porch2:   '/media/gallery/airbnb/213421aabebb.jpg', // Secondary covered deck with blue cushions + ocean
  rooms:    '/media/gallery/airbnb/229e7b63486f.jpg', // Pristine beach + ocean view from above the villa
  // Staff portraits mirrored from the guidebook (hostmoat.com/guide/80a7799e) to R2 on 2026-04-20
  // via scripts/migrate-guidebook-staff-to-r2.sh. Updated when Wayne/Karen update the guidebook.
  staffTeam:    '/media/gallery/staff/team.jpg',
  staffHillary: '/media/gallery/staff/hillary.jpg',
  staffEnrique: '/media/gallery/staff/enrique.jpg',
  staffGabriel: '/media/gallery/staff/gabriel.jpg',
  staffAna:     '/media/gallery/staff/ana.jpg',
};

const Icon = ({ name, size = 18, stroke = 1.5, filled = false }) => {
  const paths = {
    close: <><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></>,
    chevronRight: <polyline points="9 18 15 12 9 6"/>,
    chevronLeft: <polyline points="15 18 9 12 15 6"/>,
    bed: <><path d="M2 10v10"/><path d="M22 10v10"/><path d="M2 14h20"/><path d="M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4"/></>,
    users: <><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>,
    bath: <><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/><path d="M3 10h18v5a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3v-5z"/></>,
    mapPin: <><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></>,
    phone: <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>,
    mail: <><rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="22 6 12 13 2 6"/></>,
    calendar: <><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></>,
    image: <><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></>,
    utensils: <><path d="M3 2v7c0 1.1.9 2 2 2h0a2 2 0 0 0 2-2V2"/><path d="M5 11v11"/><path d="M19 22V2a4 4 0 0 0-4 4v7h4"/></>,
    edit: <><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82 2 2 0 1 1-2.83 2.83 1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33 2 2 0 1 1-2.83-2.83 1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82 2 2 0 1 1 2.83-2.83 1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33 2 2 0 1 1 2.83 2.83 1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></>,
    logout: <><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></>,
    plus: <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    trash: <><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></>,
    upload: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></>,
    eye: <><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></>,
    star: <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>,
    file: <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></>,
    instagram: <><rect x="2" y="2" width="20" height="20" rx="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/></>,
    facebook: <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/>,
    bold: <><path d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/></>,
    italic: <><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></>,
    link: <><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></>,
  };
  // `filled` swaps the SVG fill to currentColor (used by stars so they actually look like stars).
  const svgFill = filled ? 'currentColor' : 'none';
  return <svg width={size} height={size} viewBox="0 0 24 24" fill={svgFill} stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={{flexShrink: 0, display: 'inline-block', verticalAlign: 'middle'}}>{paths[name]}</svg>;
};

const Nav = ({ current, navigate, navigateTarget }) => {
  const [mobileOpen, setMobileOpen] = useState(false);
  // Nav goes transparent when the current page has a cinematic hero (home only)
  // AND the user hasn't scrolled past the first viewport.
  const hasCinematicHero = current === 'home';
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    if (hasCinematicHero) document.body.classList.add('has-cinematic-hero');
    else document.body.classList.remove('has-cinematic-hero');
    const onScroll = () => setScrolled(window.scrollY > 80);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [hasCinematicHero]);
  const transparent = hasCinematicHero && !scrolled && !mobileOpen;

  const content = window.useContent ? window.useContent() : null;
  const settings = content?.settings || {};
  const bookProps = bookCtaProps(settings);
  const navItems = (content?.nav && content.nav.length)
    ? content.nav
    : [
        { id: 'nav_home',    label: 'Welcome',  type: 'internal', target: 'home' },
        { id: 'nav_rooms',   label: 'Rooms',    type: 'internal', target: 'rooms' },
        { id: 'nav_gallery', label: 'Gallery',  type: 'internal', target: 'gallery' },
        { id: 'nav_menu',    label: 'Menu',     type: 'internal', target: 'menu' },
        { id: 'nav_exp',     label: 'Staff',    type: 'internal', target: 'staff' },
        { id: 'nav_contact', label: 'Contact',  type: 'internal', target: 'contact' },
      ];
  const clickItem = (it) => {
    if (it.type === 'external') {
      if (it.new_tab) window.open(it.target, '_blank', 'noopener');
      else window.location.href = it.target;
    } else {
      navigate(it.target);
    }
  };
  return (
    <>
      <nav className={`nav ${transparent ? 'nav-transparent' : ''}`}>
        <div className="container-wide nav-inner">
          <a onClick={() => navigate('home')} className="nav-logo-wrap" style={{cursor: 'pointer'}}>
            <img src={IMAGES.logo} alt={settings.site_name || 'Villa Karaway'} className="nav-logo"/>
          </a>
          <div className="nav-links">
            {navItems.map(l => (
              <a key={l.id} className={`nav-link ${current === l.target ? 'active' : ''}`} onClick={() => clickItem(l)} style={{cursor: 'pointer'}}>
                {l.label}
              </a>
            ))}
            <a className="nav-cta" {...bookProps}>Book Stay</a>
          </div>
          <button className="nav-mobile-toggle" onClick={() => setMobileOpen(true)} aria-label="Menu"><span></span><span></span><span></span></button>
        </div>
      </nav>
      <div className={`mobile-menu ${mobileOpen ? 'open' : ''}`}>
        <button className="mobile-menu-close" onClick={() => setMobileOpen(false)}><Icon name="close" size={28}/></button>
        {navItems.map(l => (
          <a key={l.id} onClick={() => { clickItem(l); setMobileOpen(false); }} style={{cursor: 'pointer'}}>
            {l.label}
          </a>
        ))}
        <a {...bookProps} style={{color: 'var(--terracotta)', marginTop: 16}}>Book Your Stay →</a>
      </div>
    </>
  );
};

const Footer = ({ navigate }) => {
  const content = window.useContent ? window.useContent() : null;
  const s = content?.settings || {};
  const year = new Date().getFullYear();
  return (
    <footer className="footer">
      <div className="container-wide">
        <div className="footer-grid">
          <div>
            <img src={IMAGES.logo} alt={s.site_name || 'Villa Karaway'} style={{width: 160, marginBottom: 24, filter: 'brightness(0) invert(1)', opacity: 0.95}}/>
            <p style={{fontSize: 14, lineHeight: 1.7, maxWidth: 320, color: 'rgba(250,246,239,0.7)'}}>{s.meta_description || 'A private beachfront villa in Puerto Vallarta.'}</p>
            <div style={{display: 'flex', gap: 14, marginTop: 28}}>
              {s.instagram_url && <a href={s.instagram_url} target="_blank" rel="noreferrer" aria-label="Instagram"><Icon name="instagram" size={18}/></a>}
              {s.facebook_url && <a href={s.facebook_url} target="_blank" rel="noreferrer" aria-label="Facebook"><Icon name="facebook" size={18}/></a>}
            </div>
          </div>
          <div>
            <h4>Visit</h4>
            <a onClick={() => navigate('rooms')} style={{cursor: 'pointer'}}>The Rooms</a>
            <a onClick={() => navigate('gallery')} style={{cursor: 'pointer'}}>Gallery</a>
            <a onClick={() => navigate('video')} style={{cursor: 'pointer'}}>Video Tour</a>
            <a onClick={() => navigate('webcam')} style={{cursor: 'pointer'}}>Live Webcam</a>
            <a onClick={() => navigate('menu')} style={{cursor: 'pointer'}}>House Menu</a>
            <a onClick={() => navigate('staff')} style={{cursor: 'pointer'}}>The Staff</a>
          </div>
          <div>
            <h4>Guests</h4>
            {s.pre_arrival_url && <a href={s.pre_arrival_url} target="_blank" rel="noreferrer">Pre-Arrival Form</a>}
            <a onClick={() => navigate('guest')} style={{cursor: 'pointer'}}>Guest Info</a>
            <a onClick={() => navigate('activities')} style={{cursor: 'pointer'}}>PV Activities</a>
            <a onClick={() => navigate('reviews')} style={{cursor: 'pointer'}}>Reviews</a>
            <a onClick={() => navigate('contact')} style={{cursor: 'pointer'}}>Contact</a>
          </div>
          <div>
            <h4>Contact</h4>
            <p style={{fontSize: 14, color: 'rgba(250,246,239,0.7)', marginBottom: 14}}>
              {s.address_line1 || 'Carretera a Barra de Navidad Km. 7.5'}<br/>
              {s.address_line2 || 'Playa Punta Negra, Puerto Vallarta'}<br/>
              {s.address_line3 || 'Jalisco, Mexico'}
            </p>
            {s.phone && <p style={{fontSize: 14, color: 'rgba(250,246,239,0.9)'}}>{s.phone}</p>}
          </div>
        </div>
        <div className="footer-bottom">
          <div>© {year} {s.site_name || 'Karaway Properties'} · All rights reserved</div>
          <div>Bookings powered by <a href="https://www.hostmoat.com" target="_blank" rel="noreferrer" style={{color: 'inherit', textDecoration: 'underline', textUnderlineOffset: 3}}>HostMoat</a></div>
        </div>
      </div>
    </footer>
  );
};

// Mobile-only sticky bottom bar with three quick actions. Hidden on desktop via CSS.
// Kept outside AdminPanel — admin doesn't need a booking button.
const MobileCTA = ({ navigate }) => {
  const content = window.useContent ? window.useContent() : null;
  const s = content?.settings || {};
  const bookProps = bookCtaProps(s);
  return (
    <div className="mobile-cta-bar" role="navigation" aria-label="Quick actions">
      <a className="primary" {...bookProps} aria-label="Book your stay">Book</a>
      <button onClick={() => navigate('availability')} aria-label="Check availability">Dates</button>
    </div>
  );
};

// `as` lets the page-top SectionHead render an <h1> instead of <h2> so each route has exactly
// one H1 (every other usage on the page stays h2). Without this, only the home page had an h1
// and crawlers couldn't see a primary heading on /rooms, /gallery, /reviews, etc.
const SectionHead = ({ eyebrow, title, intro, align = 'left', as = 'h2' }) => {
  const Heading = as;
  return (
    <div style={{maxWidth: 720, margin: align === 'center' ? '0 auto 64px' : '0 0 64px', textAlign: align}}>
      {eyebrow && <div className="eyebrow" style={{marginBottom: 20}}>{eyebrow}</div>}
      <Heading className="display" style={{fontSize: 'clamp(36px, 5vw, 64px)', marginBottom: 24, fontWeight: 300, letterSpacing: '-0.02em'}}>{title}</Heading>
      {intro && <p className="lead">{intro}</p>}
    </div>
  );
};

// "Book your stay" CTA props. If a HostMoat booking URL is configured, link
// externally in a new tab. Otherwise route the click to the in-site contact form
// instead of leaving a dead "#" anchor or dumping visitors at hostmoat.com root.
const bookCtaProps = (settings) => {
  const url = settings && settings.hostmoat_booking_url;
  if (url) return { href: url, target: '_blank', rel: 'noreferrer' };
  return {
    href: '/contact',
    onClick: (e) => {
      if (window.__karaway_navigate) { e.preventDefault(); window.__karaway_navigate('contact'); }
    },
  };
};

Object.assign(window, { Icon, Nav, Footer, SectionHead, MobileCTA, IMAGES, bookCtaProps });
