/* Shared scaffold for Nirvana sub-pages: Nav, Footer, palette, hooks. */
const { useState, useEffect, useRef } = React;

const PALETTES = {
  'teal-stone': {
    teal: '#1B7F97', tealDark: '#0E5B6E', tealLight: '#2BA4BF', tealHighlight: '#7FC6D4',
    sand: '#c4a882', stone: '#8a7563', warmWhite: '#f8f5f0', warmDark: '#2a2420',
    mid: '#6b5d52', dark: '#0E5B6E'
  },
  'ocean-blue': {
    teal: '#2060b0', tealDark: '#164888', tealLight: '#5090d8', tealHighlight: '#90c0f0',
    sand: '#90b4d8', stone: '#5878a0', warmWhite: '#f0f4f8', warmDark: '#18232e',
    mid: '#486075', dark: '#12202e'
  },
  'sage-sand': {
    teal: '#527a60', tealDark: '#3a5844', tealLight: '#82b090', tealHighlight: '#a8c6b0',
    sand: '#d0b090', stone: '#907060', warmWhite: '#f6f2ec', warmDark: '#261e14',
    mid: '#60503c', dark: '#1a2418'
  },
  'moody-dark': {
    teal: '#1B7F97', tealDark: '#0E5B6E', tealLight: '#2BA4BF', tealHighlight: '#7FC6D4',
    sand: '#c4a882', stone: '#8a7563', warmWhite: '#1c1814', warmDark: '#f0ece6',
    mid: '#b0a090', dark: '#0e1418'
  }
};

const SERVICES_SUB = [
['Custom Concrete Pools', 'custom-concrete-pools.html'],
['Bodies Corporate & Commercial', 'body-corporate.html'],
['Spas & Water Features', 'spas-water-features.html']];

const PORTFOLIO_SUB = [
['Newport Waterfront', 'newport.html'],
['Kangaroo Point', 'kangaroo-point.html'],
['Windsor Mosaic', 'windsor.html']];

const NAV_ITEMS = [
['About', 'index.html#about'],
['Process', 'index.html#process'],
['Portfolio', 'index.html#pools', PORTFOLIO_SUB],
['Services', 'services.html', SERVICES_SUB],
['Testimonials', 'testimonials.html'],
['FAQ', 'faq.html'],
['Contact', 'index.html#contact']];


function getTweaks() {
  try {
    const s = localStorage.getItem('nirvana-tweaks');
    return s ? JSON.parse(s) : {};
  } catch {return {};}
}

function useReveal(opts = {}) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (!ref.current || shown) return;
    const io = new IntersectionObserver((entries) => entries.forEach((e) => {
      if (e.isIntersecting) {setShown(true);io.disconnect();}
    }), { threshold: opts.threshold ?? 0.18, rootMargin: '0px 0px -8% 0px' });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [shown]);
  return [ref, shown];
}

const Reveal = ({ as: Tag = 'div', kind = 'reveal', delay = 0, children, style, ...rest }) => {
  const [ref, shown] = useReveal();
  return (
    <Tag ref={ref} className={`${kind} ${shown ? 'in' : ''}`} style={{ transitionDelay: `${delay}ms`, ...style }} {...rest}>
      {children}
    </Tag>);

};

const NavDropdown = ({ label, href, sub, colors, isDark }) => {
  const [open, setOpen] = useState(false);
  const closeT = useRef(null);
  const handleEnter = () => { if (closeT.current) clearTimeout(closeT.current); setOpen(true); };
  const handleLeave = () => { closeT.current = setTimeout(() => setOpen(false), 140); };
  const panelBg = isDark ? 'rgba(28,24,20,0.98)' : 'rgba(250,247,244,0.98)';
  return (
    <div style={{ position: 'relative' }} onMouseEnter={handleEnter} onMouseLeave={handleLeave}>
      <a href={href} style={{ textDecoration: 'none', color: open ? colors.teal : colors.warmDark, fontSize: 11, letterSpacing: '0.13em', textTransform: 'uppercase', fontWeight: 500, transition: 'color 0.3s', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 6 }}>
        {label}
        <svg width="8" height="6" viewBox="0 0 8 6" fill="none" style={{ transition: 'transform 0.25s', transform: open ? 'rotate(180deg)' : 'rotate(0)' }}>
          <path d="M1 1l3 3 3-3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
        </svg>
      </a>
      <div style={{
        position: 'absolute', top: 'calc(100% + 14px)', left: '50%', transform: `translateX(-50%) translateY(${open ? '0' : '-6px'})`,
        minWidth: 260, background: panelBg, backdropFilter: 'blur(14px)',
        border: `1px solid ${isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'}`,
        borderRadius: 14, padding: '14px 0', boxShadow: '0 24px 60px rgba(0,0,0,0.18)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 0.22s, transform 0.22s' }}>
        <div aria-hidden style={{ position: 'absolute', top: -6, left: '50%', transform: 'translateX(-50%) rotate(45deg)', width: 12, height: 12, background: panelBg, borderTop: `1px solid ${isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'}`, borderLeft: `1px solid ${isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'}` }} />
        {sub.map(([sl, sh]) =>
          <a key={sl} href={sh} style={{ display: 'block', padding: '11px 24px', textDecoration: 'none', color: colors.warmDark, fontSize: 12.5, letterSpacing: '0.04em', fontWeight: 400, transition: 'all 0.2s', whiteSpace: 'nowrap', fontFamily: "'Inter', sans-serif" }}
            onMouseEnter={(e) => { e.currentTarget.style.color = colors.teal; e.currentTarget.style.paddingLeft = '30px'; }}
            onMouseLeave={(e) => { e.currentTarget.style.color = colors.warmDark; e.currentTarget.style.paddingLeft = '24px'; }}>
            {sl}
          </a>
        )}
      </div>
    </div>);
};

const useIsMobile = (bp = 880) => {
  const [m, setM] = useState(typeof window !== 'undefined' ? window.innerWidth < bp : false);
  useEffect(() => {
    const h = () => setM(window.innerWidth < bp);
    h();
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, [bp]);
  return m;
};

const MobileMenu = ({ open, onClose, colors, isDark }) => {
  useEffect(() => {
    if (open) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  const panelBg = isDark ? '#1c1814' : '#faf7f4';
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(0,0,0,0.5)', opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'opacity 0.35s ease' }} />
      <aside style={{ position: 'fixed', top: 0, left: 0, bottom: 0, zIndex: 301, width: 'min(86vw, 360px)', background: panelBg, transform: open ? 'translateX(0)' : 'translateX(-105%)', transition: 'transform 0.4s cubic-bezier(0.22,0.61,0.36,1)', display: 'flex', flexDirection: 'column', padding: '24px 24px 40px', overflowY: 'auto', boxShadow: open ? '0 24px 60px rgba(0,0,0,0.3)' : 'none' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 32 }}>
          <img src="uploads/Logo-Textured - no background.png" alt="Nirvana" style={{ height: 34, filter: isDark ? 'brightness(0) invert(1)' : 'none' }} />
          <button onClick={onClose} aria-label="Close menu" style={{ width: 40, height: 40, border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke={colors.warmDark} strokeWidth="1.6" strokeLinecap="round"><path d="M4 4l12 12M16 4L4 16" /></svg>
          </button>
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column' }}>
          {NAV_ITEMS.map(([l, href, sub]) => (
            <div key={l} style={{ borderBottom: `1px solid ${isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'}` }}>
              <a href={href} onClick={onClose} style={{ display: 'block', padding: '18px 4px', color: colors.warmDark, textDecoration: 'none', fontSize: 14, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 500 }}>{l}</a>
              {sub && (
                <div style={{ paddingBottom: 14, paddingLeft: 8, display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {sub.map(([sl, sh]) => (
                    <a key={sl} href={sh} onClick={onClose} style={{ color: colors.mid, textDecoration: 'none', fontSize: 13, fontFamily: "'Cormorant Garamond',serif", fontStyle: 'italic' }}>— {sl}</a>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>
        <a href="index.html#contact" onClick={onClose} style={{ marginTop: 28, padding: '14px 24px', border: `1.5px solid ${colors.teal}`, borderRadius: 999, color: colors.teal, textDecoration: 'none', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 600, textAlign: 'center' }}>
          Begin your Nirvana Journey
        </a>
      </aside>
    </>
  );
};

const Nav = ({ colors }) => {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const isMobile = useIsMobile(880);
  useEffect(() => {
    const h = () => setScrolled(window.scrollY > 40);
    h();
    window.addEventListener('scroll', h, { passive: true });
    return () => window.removeEventListener('scroll', h);
  }, []);
  const isDark = colors.warmWhite === '#1c1814';
  const navBg = scrolled
    ? (isDark ? 'rgba(28,24,20,0.7)' : 'rgba(250,247,244,0.7)')
    : 'transparent';
  const navBorder = scrolled
    ? (isDark ? '1px solid rgba(255,255,255,0.06)' : '1px solid rgba(0,0,0,0.06)')
    : '1px solid transparent';

  return (
    <>
      <nav style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 200, background: navBg, backdropFilter: scrolled ? 'blur(16px) saturate(140%)' : 'none', WebkitBackdropFilter: scrolled ? 'blur(16px) saturate(140%)' : 'none', borderBottom: navBorder, padding: '0 clamp(16px,4vw,56px)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 64, transition: 'background 0.3s ease, backdrop-filter 0.3s ease, border-color 0.3s ease' }}>
        {isMobile ? (
          <>
            <button onClick={() => setMenuOpen(true)} aria-label="Open menu" style={{ width: 40, height: 40, border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
              <svg width="22" height="16" viewBox="0 0 22 16" fill="none" stroke={colors.warmDark} strokeWidth="1.6" strokeLinecap="round">
                <path d="M1 2h20M1 8h20M1 14h14" />
              </svg>
            </button>
            <a href="index.html" style={{ display: 'flex', alignItems: 'center' }}>
              <img src="uploads/Logo-Textured - no background.png" alt="Nirvana" style={{ height: 32, filter: isDark ? 'brightness(0) invert(1)' : 'none' }} />
            </a>
            <div style={{ width: 40 }} />
          </>
        ) : (
          <>
            <a href="index.html" style={{ display: 'flex', alignItems: 'center' }}>
              <img src="uploads/Logo-Textured - no background.png" alt="Nirvana" style={{ height: 38, filter: isDark ? 'brightness(0) invert(1)' : 'none' }} />
            </a>
            <div style={{ display: 'flex', gap: 22, alignItems: 'center', flexWrap: 'wrap' }}>
              {NAV_ITEMS.map(([l, href, sub]) => sub ?
              <NavDropdown key={l} label={l} href={href} sub={sub} colors={colors} isDark={isDark} /> :
              <a key={l} href={href} style={{ textDecoration: 'none', color: colors.warmDark, fontSize: 11, letterSpacing: '0.13em', textTransform: 'uppercase', fontWeight: 500, transition: 'color 0.3s', whiteSpace: 'nowrap' }}
              onMouseEnter={(e) => e.currentTarget.style.color = colors.teal}
              onMouseLeave={(e) => e.currentTarget.style.color = colors.warmDark}>
                  {l}
                </a>
              )}
              <a href="index.html#contact" style={{ padding: '7px 18px', border: `1px solid ${colors.teal}`, borderRadius: 999, color: colors.teal, textDecoration: 'none', fontSize: 11, letterSpacing: '0.08em', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 6 }}
              onMouseEnter={(e) => {e.currentTarget.style.background = colors.teal;e.currentTarget.style.color = 'white';}}
              onMouseLeave={(e) => {e.currentTarget.style.background = 'transparent';e.currentTarget.style.color = colors.teal;}}>
                Begin your <em style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 14, fontStyle: 'italic', fontWeight: 400, letterSpacing: '0.04em' }}>Nirvana Journey</em>
              </a>
            </div>
          </>
        )}
      </nav>
      <MobileMenu open={menuOpen} onClose={() => setMenuOpen(false)} colors={colors} isDark={isDark} />
    </>);

};

const Footer = ({ colors }) =>
<footer style={{ background: colors.dark, padding: '48px clamp(24px,6vw,80px)', borderTop: '1px solid rgba(255,255,255,0.05)' }}>
    <div style={{ maxWidth: 1200, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 24 }}>
      <img src="uploads/Logo-Textured - no background.png" alt="Nirvana Pools & Spas" style={{ height: 38, filter: 'brightness(0) invert(1)' }} />
      <p style={{ color: '#ffffff', fontSize: 12, letterSpacing: '0.05em' }}>© 2026 Nirvana Pools And Spas · QBCC No. 15309885 · All rights reserved</p>
      <div style={{ display: 'flex', gap: 20 }}>
        {['Instagram', 'Facebook', 'LinkedIn'].map((l) =>
      <a key={l} href="#" style={{ color: 'rgba(255,255,255,0.35)', fontSize: 11, textDecoration: 'none', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{l}</a>
      )}
      </div>
    </div>
  </footer>;


const PageHero = ({ colors, eyebrow, title, subtitle }) =>
<section style={{ padding: 'clamp(140px,16vw,200px) clamp(24px,6vw,80px) clamp(60px,8vw,90px)', background: colors.warmWhite, position: 'relative', overflow: 'hidden' }}>
    <div aria-hidden style={{ position: 'absolute', top: '20%', right: '-6%', fontFamily: "'Cormorant Garamond',serif", fontStyle: 'italic', fontSize: 'clamp(180px,28vw,420px)', color: colors.teal, opacity: 0.05, pointerEvents: 'none', lineHeight: 1, fontWeight: 300 }}>Nirvana</div>
    <div style={{ maxWidth: 1100, margin: '0 auto', position: 'relative' }}>
      {eyebrow && <Reveal as="p" style={{ fontSize: 11, letterSpacing: '0.28em', textTransform: 'uppercase', color: colors.teal, marginBottom: 18, fontWeight: 600 }}>{eyebrow}</Reveal>}
      <Reveal as="h1" delay={120} style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 'clamp(56px,9vw,128px)', fontWeight: 300, color: colors.warmDark, lineHeight: 1.02, letterSpacing: '-0.02em', fontStyle: 'italic', marginBottom: subtitle ? 28 : 0 }}>{title}</Reveal>
      {subtitle && <Reveal as="p" delay={240} style={{ fontSize: 19, color: colors.mid, maxWidth: 640, lineHeight: 1.7, fontWeight: 300 }}>{subtitle}</Reveal>}
      <Reveal style={{ width: 56, height: 2, background: colors.teal, marginTop: 36, borderRadius: 2 }} />
    </div>
  </section>;


const SubpageRoot = ({ children }) => {
  const tweaks = getTweaks();
  const palette = tweaks.palette || 'teal-stone';
  const colors = PALETTES[palette];
  const fontStyle = tweaks.fontStyle;
  const headingFont = fontStyle === 'modern' ? "'Inter', sans-serif" : fontStyle === 'classic' ? "'Georgia', serif" : "'Cormorant Garamond', serif";
  return (
    <>
      <style>{`
        h1, h2, h3, h4, h5 { font-family: ${headingFont}; }
        body { background: ${colors.warmWhite}; color: ${colors.warmDark}; }
        @media (max-width: 880px) {
          [data-responsive-grid="2"], [data-responsive-grid="3"],
          main [style*="repeat(2,"],
          main [style*="repeat(3,"],
          main [style*="repeat(4,"],
          main [style*="auto-fit"],
          main [style*="auto-fill"] {
            grid-template-columns: 1fr !important;
          }
          main [style*="1fr 1fr"],
          main [style*="1fr 1.3fr"], main [style*="1.3fr 1fr"],
          main [style*="1fr 1.2fr"], main [style*="1.2fr 1fr"],
          main [style*="1fr 1.4fr"], main [style*="1.4fr 1fr"] {
            grid-template-columns: 1fr !important;
          }
          main section { padding-left: 20px !important; padding-right: 20px !important; }
          footer > div { flex-direction: column !important; align-items: center; gap: 16px; text-align: center; }
        }
        @media (max-width: 600px) {
          h1, h2 { letter-spacing: -0.01em !important; }
        }
      `}</style>
      <Nav colors={colors} />
      <main style={{ minHeight: '100vh' }}>{children(colors)}</main>
      <Footer colors={colors} />
    </>);

};

window.NirvanaShared = { PALETTES, Nav, Footer, Reveal, PageHero, SubpageRoot, useReveal, getTweaks };