// Shared layout: Logo, Nav, Footer, Reveal, helpers
const { useEffect, useState, useRef, useMemo, useCallback } = React;

// Hash-based router
function useHashRoute() {
  const parse = () => {
    const h = window.location.hash.replace(/^#\/?/, '') || 'home';
    const [path, query] = h.split('?');
    return { path: path || 'home', query: query || '' };
  };
  const [route, setRoute] = useState(parse());
  useEffect(() => {
    const handler = () => { setRoute(parse()); window.scrollTo({ top: 0, behavior: 'instant' }); };
    window.addEventListener('hashchange', handler);
    return () => window.removeEventListener('hashchange', handler);
  }, []);
  return route;
}

function navigate(path) {
  window.location.hash = '/' + path;
}

// Logo mark — replicated abstract square (4 panel grid in diamond)
function LogoMark({ size = 38, dark = false }) {
  const ink = dark ? '#F5F1EA' : '#2B1F18';
  const sky = '#4A90C7';
  const tan = '#C9A97A';
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" style={{ display: 'block' }}>
      <g transform="rotate(45 32 32)">
        <rect x="10" y="10" width="44" height="44" rx="3" fill="none" stroke={ink} strokeWidth="2.5"/>
        <rect x="13" y="13" width="18" height="18" fill={tan} opacity="0.9"/>
        <rect x="33" y="13" width="18" height="9" fill={tan} opacity="0.7"/>
        <rect x="33" y="24" width="18" height="7" fill={tan} opacity="0.55"/>
        <rect x="13" y="33" width="9" height="18" fill={tan} opacity="0.6"/>
        <rect x="24" y="33" width="7" height="18" fill={tan} opacity="0.75"/>
        <rect x="33" y="33" width="18" height="18" fill={tan} opacity="0.5"/>
        <line x1="13" y1="22" x2="31" y2="22" stroke={ink} strokeWidth="1"/>
        <line x1="22" y1="33" x2="22" y2="51" stroke={ink} strokeWidth="1"/>
      </g>
    </svg>
  );
}

function Wordmark({ dark = false }) {
  const ink = dark ? '#F5F1EA' : '#2B1F18';
  return (
    <span className="wordmark" style={{ color: ink, fontFamily: 'Inter', fontWeight: 600, letterSpacing: '0.02em', fontSize: 18, textTransform: 'uppercase' }}>
      SKY <span style={{ fontFamily: 'Fraunces', fontStyle: 'italic', fontWeight: 400, color: '#4A90C7', textTransform: 'lowercase', letterSpacing: '-0.01em', fontSize: 22 }}>flooring</span>
    </span>
  );
}

function Nav({ current }) {
  const [scrolled, setScrolled] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setDrawerOpen(false); }, [current]);

  const links = [
    { id: 'home', label: 'Home' },
    { id: 'services', label: 'Services' },
    { id: 'gallery', label: 'Gallery' },
    { id: 'about', label: 'About' },
    { id: 'contact', label: 'Contact' },
  ];

  return (
    <>
      <nav className={'nav' + (scrolled ? ' scrolled' : '')}>
        <div className="container nav-inner">
          <a href="#/home" className="nav-logo" onClick={(e) => { e.preventDefault(); navigate('home'); }}>
            <LogoMark size={36} />
            <Wordmark />
          </a>
          <div className="nav-links">
            {links.map(l => (
              <a key={l.id} href={'#/' + l.id} className={current === l.id ? 'active' : ''}
                 onClick={(e) => { e.preventDefault(); navigate(l.id); }}>{l.label}</a>
            ))}
          </div>
          <div className="nav-right">
            <a href="tel:+12269887694" className="nav-phone">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><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.72c.13 1.05.37 2.07.72 3.06a2 2 0 0 1-.45 2.11L8.09 10.21a16 16 0 0 0 6 6l1.32-1.32a2 2 0 0 1 2.11-.45c1 .35 2 .59 3.06.72A2 2 0 0 1 22 16.92z"/></svg>
              (226) 988-7694
            </a>
            <a className="btn btn-sky" href="tel:+12269887694">Call for a Quote</a>
            <button className="nav-mobile-toggle" onClick={() => setDrawerOpen(o => !o)} aria-label="Menu">
              {drawerOpen ? (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
              ) : (
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
              )}
            </button>
          </div>
        </div>
      </nav>
      <div className={'nav-drawer' + (drawerOpen ? ' open' : '')}>
        {links.map(l => (
          <a key={l.id} href={'#/' + l.id} className={current === l.id ? 'active' : ''}
             onClick={(e) => { e.preventDefault(); navigate(l.id); }}>{l.label}</a>
        ))}
        <div className="drawer-foot">
          <a className="btn btn-sky" href="tel:+12269887694">Call for a Free Quote</a>
          <a className="btn btn-ghost" href="tel:+12269887694">(226) 988-7694</a>
        </div>
      </div>
      <a className="mobile-cta" href="tel:+12269887694">
        <span>Call for a Free Quote</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, opacity: 0.8 }}>
          (226) 988-7694 →
        </span>
      </a>
    </>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <LogoMark size={42} dark />
              <Wordmark dark />
            </div>
            <p className="footer-tagline">Hardwood, vinyl &amp; tile installed by hand — across Waterloo Region.</p>
            <div style={{ marginTop: 24, display: 'flex', gap: 12 }}>
              <a className="btn btn-on-dark" href="tel:+12269887694">Call (226) 988-7694</a>
            </div>
          </div>
          <div className="footer-col">
            <h4>Service Areas</h4>
            <ul>
              <li>Kitchener</li>
              <li>Waterloo</li>
              <li>Cambridge</li>
              <li>Guelph</li>
              <li>Elmira &amp; rural KW</li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Sky Flooring</h4>
            <ul>
              <li><a href="#/home" onClick={(e) => { e.preventDefault(); navigate('home'); }}>Home</a></li>
              <li><a href="#/services" onClick={(e) => { e.preventDefault(); navigate('services'); }}>Services</a></li>
              <li><a href="#/gallery" onClick={(e) => { e.preventDefault(); navigate('gallery'); }}>Gallery</a></li>
              <li><a href="#/about" onClick={(e) => { e.preventDefault(); navigate('about'); }}>About</a></li>
              <li><a href="#/contact" onClick={(e) => { e.preventDefault(); navigate('contact'); }}>Contact</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Get in touch</h4>
            <ul>
              <li><a href="tel:+12269887694">(226) 988-7694</a></li>
              <li>Mon–Sat · 8a–8p</li>
              <li>Owner: Diyako</li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>© 2026 Sky Flooring · Owner-operated · Fully insured</span>
          <span>Kitchener · Waterloo · Cambridge · Guelph</span>
        </div>
      </div>
    </footer>
  );
}

// Reveal-on-scroll (scroll-listener based; IO unreliable in some iframe contexts)
function Reveal({ children, delay = 0, as = 'div', className = '', ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0;
    const check = () => {
      raf = 0;
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      if (r.top < vh - 40 && r.bottom > 0) { setShown(true); cleanup(); }
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(check); };
    const cleanup = () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    // Initial check (after layout)
    requestAnimationFrame(check);
    // Safety fallback — show after 600ms regardless
    const t = setTimeout(() => setShown(true), 600);
    return () => { cleanup(); clearTimeout(t); if (raf) cancelAnimationFrame(raf); };
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className={'reveal ' + (shown ? 'in ' : '') + className} style={{ transitionDelay: delay + 'ms' }} {...rest}>
      {children}
    </Tag>
  );
}

// Photo with subtle zoom on scroll
function ParallaxPhoto({ src, alt, className = '', style = {}, loading = 'lazy', decoding = 'async' }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onScroll = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const p = (r.top + r.height/2 - vh/2) / vh; // -1..1
      const y = Math.max(-30, Math.min(30, p * 30));
      el.style.setProperty('--py', y + 'px');
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <div ref={ref} className={'parallax ' + className} style={{ overflow: 'hidden', ...style }}>
      <img src={src} alt={alt} loading={loading} decoding={decoding} style={{ width: '100%', height: '100%', objectFit: 'cover', transform: 'translateY(var(--py, 0))', willChange: 'transform' }} />
    </div>
  );
}

// SVG icons (small set)
const Icon = {
  Plank: () => (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
      <rect x="3" y="6" width="26" height="5" rx="1"/>
      <rect x="3" y="13.5" width="26" height="5" rx="1"/>
      <rect x="3" y="21" width="26" height="5" rx="1"/>
      <line x1="11" y1="6" x2="11" y2="11"/>
      <line x1="20" y1="13.5" x2="20" y2="18.5"/>
      <line x1="14" y1="21" x2="14" y2="26"/>
    </svg>
  ),
  Tile: () => (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
      <rect x="4" y="4" width="10" height="10" rx="1"/>
      <rect x="18" y="4" width="10" height="10" rx="1"/>
      <rect x="4" y="18" width="10" height="10" rx="1"/>
      <rect x="18" y="18" width="10" height="10" rx="1"/>
    </svg>
  ),
  Refresh: () => (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M27 16a11 11 0 1 1-3.5-8"/>
      <polyline points="27 5 27 12 20 12"/>
    </svg>
  ),
  Layers: () => (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="m16 4 12 6-12 6L4 10l12-6Z"/>
      <path d="M4 16l12 6 12-6"/>
      <path d="M4 22l12 6 12-6"/>
    </svg>
  ),
  Check: () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
  ),
  Pin: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><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"/></svg>
  ),
  Star: () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><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"/></svg>
  ),
  Quote: () => (
    <svg width="34" height="28" viewBox="0 0 34 28" fill="currentColor" opacity="0.18"><path d="M0 28V16.8C0 7.5 5.5 1.6 14 0v5.4C9 7 6.4 10.6 6.4 16h7.6V28H0zm20 0V16.8C20 7.5 25.5 1.6 34 0v5.4c-5 1.6-7.6 5.2-7.6 10.6H34V28H20z"/></svg>
  ),
};

// Reveal helpers shared
window.Sky = { useHashRoute, navigate, Nav, Footer, Reveal, ParallaxPhoto, LogoMark, Wordmark, Icon };
