/* ============================================
   SQUISHY SKIN ETC. — Shared Components
   ============================================ */

/* Scroll Animation Hook */
function useScrollAnimation() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight + 40) {
      requestAnimationFrame(() => el.classList.add('animate-in'));
      return;
    }
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('animate-in');
          observer.unobserve(entry.target);
        }
      },
      { threshold: 0.05, rootMargin: '0px 0px -20px 0px' }
    );
    observer.observe(el);
    const fallback = setTimeout(() => el.classList.add('animate-in'), 1500);
    return () => { observer.disconnect(); clearTimeout(fallback); };
  }, []);
  return ref;
}

/* Parallax Scroll Hook — moves element slower than scroll for depth */
function useParallax(speed = 0.3) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    /* Disable parallax on mobile for performance */
    const isMobile = window.matchMedia('(max-width: 768px)').matches;
    if (isMobile) return;
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const scrollY = window.scrollY;
        const rect = el.getBoundingClientRect();
        /* Only apply when element is in/near viewport */
        if (rect.bottom > -200 && rect.top < window.innerHeight + 200) {
          el.style.transform = `translateY(${scrollY * speed}px) scale(1.06)`;
        }
        ticking = false;
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [speed]);
  return ref;
}

/* Animated Counter Hook — counts up from 0 to target when visible */
function AnimatedCounter({ target, suffix = '', duration = 1800 }) {
  const [count, setCount] = React.useState(0);
  const [started, setStarted] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !started) {
          setStarted(true);
          observer.unobserve(el);
        }
      },
      { threshold: 0.3 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [started]);

  React.useEffect(() => {
    if (!started) return;
    const numTarget = parseInt(target);
    if (isNaN(numTarget)) { setCount(target); return; }
    const startTime = performance.now();
    const animate = (now) => {
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1);
      /* Ease out cubic */
      const eased = 1 - Math.pow(1 - progress, 3);
      setCount(Math.round(eased * numTarget));
      if (progress < 1) requestAnimationFrame(animate);
    };
    requestAnimationFrame(animate);
  }, [started, target, duration]);

  return (
    <span ref={ref}>{typeof target === 'string' && isNaN(parseInt(target)) ? target : count}{suffix}</span>
  );
}

/* Page Transition Wrapper */
function PageTransition({ children, pageKey }) {
  const [displayChildren, setDisplayChildren] = React.useState(children);
  const [transitionClass, setTransitionClass] = React.useState('page-enter-active');
  const prevKeyRef = React.useRef(pageKey);

  /* Always show latest children when pageKey hasn't changed (e.g. tweak updates) */
  if (prevKeyRef.current === pageKey && displayChildren !== children) {
    setDisplayChildren(children);
  }

  React.useEffect(() => {
    if (prevKeyRef.current === pageKey) return;
    prevKeyRef.current = pageKey;
    /* Exit current page */
    setTransitionClass('page-exit');
    const exitTimer = setTimeout(() => {
      setDisplayChildren(children);
      setTransitionClass('page-enter');
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          setTransitionClass('page-enter-active');
        });
      });
    }, 280);
    return () => clearTimeout(exitTimer);
  }, [pageKey, children]);

  return (
    <div className={`page-transition ${transitionClass}`}>
      {displayChildren}
    </div>
  );
}

/* Animated Section Wrapper */
function AnimatedSection({ children, className = '', style = {}, delay = 0 }) {
  const ref = useScrollAnimation();
  return (
    <div ref={ref} className={`scroll-animate ${delay ? 'delay-' + delay : ''} ${className}`} style={style}>
      {children}
    </div>
  );
}

/* Blob Background Shape */
function BlobShape({ style, variant = 1 }) {
  return <div className={variant === 2 ? 'blob blob-2' : 'blob'} style={style}></div>;
}

/* Placeholder Image */
function PlaceholderImage({ label, style = {}, height = 300 }) {
  return (
    <div className="placeholder-img" style={{ minHeight: height, ...style }}>
      <span>{label || 'Image Placeholder'}</span>
    </div>
  );
}

/* Star Rating */
function StarRating({ count = 5 }) {
  return (
    <div className="stars-row">
      {Array.from({ length: count }).map((_, i) => (
        <svg key={i} className="star-icon" viewBox="0 0 20 20" fill="currentColor">
          <path d="M10 1l2.39 4.84 5.34.78-3.87 3.77.91 5.33L10 13.28l-4.77 2.44.91-5.33L2.27 6.62l5.34-.78z" />
        </svg>
      ))}
    </div>
  );
}

/* ============================================
   NAVIGATION
   ============================================ */
function Navigation({ currentPage, setCurrentPage }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  const navLinks = ['Home', 'Services', 'About', 'Gallery', 'Contact'];

  const navigate = (page) => {
    setCurrentPage(page);
    setMobileOpen(false);
    window.scrollTo({ top: 0 });
  };

  const navStyle = {
    position: 'sticky',
    top: 0,
    zIndex: 999,
    background: '#fff',
    borderBottom: scrolled ? '2px solid rgba(244,167,187,0.3)' : '2px solid transparent',
    transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
    boxShadow: scrolled ? '0 2px 20px rgba(0,0,0,0.04)' : 'none',
  };

  return (
    <>
      <nav style={navStyle}>
        <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 72 }}>
          <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10 }} onClick={() => navigate('Home')}>
            <img src="uploads/squishyskinlogo.png" alt="Squishy Skin Etc." style={{ height: 80, width: 80, borderRadius: '50%', objectFit: 'cover' }} />
          </div>
          {/* Desktop Links */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 32 }} className="nav-desktop">
            {navLinks.map(link => (
              <a key={link} onClick={() => navigate(link)}
                style={{
                  fontWeight: currentPage === link ? 700 : 500,
                  fontSize: 15,
                  color: currentPage === link ? 'var(--pink)' : 'var(--black)',
                  cursor: 'pointer',
                  transition: 'color 0.2s',
                  fontFamily: 'var(--font-body)',
                }}>
                {link}
              </a>
            ))}
            <a href="https://squishyskin.setmore.com/" target="_blank" rel="noopener noreferrer"
              className="btn btn-pink" style={{ padding: '10px 26px', fontSize: 14 }}>
              Book Now
            </a>
          </div>
          {/* Mobile Hamburger */}
          <button className="nav-hamburger" onClick={() => setMobileOpen(!mobileOpen)}
            style={{ display: 'none', padding: 8 }} aria-label="Menu">
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--black)" strokeWidth="2.5" strokeLinecap="round">
              {mobileOpen ? (
                <><line x1="6" y1="6" x2="18" y2="18"/><line x1="6" y1="18" x2="18" y2="6"/></>
              ) : (
                <><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></>
              )}
            </svg>
          </button>
        </div>
      </nav>

      {/* Mobile Menu Overlay */}
      {mobileOpen && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 1001, background: '#fff',
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          justifyContent: 'center', gap: 32, animation: 'fadeIn 0.25s ease',
        }}>
          <button onClick={() => setMobileOpen(false)}
            style={{ position: 'absolute', top: 20, right: 20, padding: 8 }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--black)" strokeWidth="2.5" strokeLinecap="round">
              <line x1="6" y1="6" x2="18" y2="18"/><line x1="6" y1="18" x2="18" y2="6"/>
            </svg>
          </button>
          <img src="uploads/squishyskinlogo.png" alt="Squishy Skin" style={{ width: 72, height: 72, borderRadius: '50%' }} />
          {navLinks.map(link => (
            <a key={link} onClick={() => navigate(link)}
              style={{
                fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 28,
                color: currentPage === link ? 'var(--pink)' : 'var(--black)', cursor: 'pointer',
              }}>
              {link}
            </a>
          ))}
          <a href="https://squishyskin.setmore.com/" target="_blank" rel="noopener noreferrer"
            className="btn btn-pink" style={{ marginTop: 8, padding: '16px 48px', fontSize: 16 }}>
            Book Now
          </a>
        </div>
      )}

      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @media (max-width: 900px) {
          .nav-desktop { display: none !important; }
          .nav-hamburger { display: flex !important; }
        }
      `}</style>
    </>
  );
}

/* ============================================
   FOOTER
   ============================================ */
function Footer({ setCurrentPage }) {
  const navigate = (page) => { setCurrentPage(page); window.scrollTo({ top: 0 }); };
  return (
    <footer style={{ background: 'var(--black)', color: '#fff', padding: '64px 0 32px' }}>
      <div className="container">
        <div style={{ textAlign: 'center', marginBottom: 48 }}>
          <img src="uploads/squishyskinlogo.png" alt="Squishy Skin Etc." loading="lazy"
            style={{ width: 72, height: 72, borderRadius: '50%', margin: '0 auto', filter: 'invert(1)' }} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 40, marginBottom: 48 }}>
          {/* Quick Links */}
          <div>
            <h4 style={{ fontSize: 14, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 20, color: 'var(--pink)' }}>Quick Links</h4>
            {['Home','Services','About','Gallery','Contact'].map(link => (
              <a key={link} onClick={() => navigate(link)}
                style={{ display: 'block', color: 'rgba(255,255,255,0.7)', fontSize: 15, marginBottom: 12, cursor: 'pointer', transition: 'color 0.2s' }}
                onMouseEnter={e => e.target.style.color = '#fff'}
                onMouseLeave={e => e.target.style.color = 'rgba(255,255,255,0.7)'}>
                {link}
              </a>
            ))}
          </div>
          {/* Contact */}
          <div>
            <h4 style={{ fontSize: 14, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 20, color: 'var(--pink)' }}>Contact</h4>
            <p style={{ color: 'rgba(255,255,255,0.7)', fontSize: 15, lineHeight: 1.7, marginBottom: 8 }}>
              7404 King George Blvd, Suite 200<br/>Surrey, BC V3W 1N6
            </p>
            <p style={{ color: 'rgba(255,255,255,0.7)', fontSize: 15, marginBottom: 8 }}>
              <a href="tel:+16046217783" style={{ color: 'rgba(255,255,255,0.7)' }}>+1 604 621 7783</a>
            </p>
            <p style={{ fontSize: 15 }}>
              <a href="https://www.instagram.com/squishyskinwellness" target="_blank" rel="noopener noreferrer"
                style={{ color: 'var(--pink)' }}>@squishyskinwellness</a>
            </p>
          </div>
          {/* Hours */}
          <div>
            <h4 style={{ fontSize: 14, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 20, color: 'var(--pink)' }}>Hours</h4>
            <p style={{ color: 'rgba(255,255,255,0.7)', fontSize: 15, lineHeight: 1.8 }}>
              Monday - Friday: 10am - 7pm<br/>
              Saturday: 10am - 5pm<br/>
              Sunday: Closed
            </p>
          </div>
        </div>
        {/* Divider + Copyright */}
        <div style={{ borderTop: '2px solid var(--pink)', paddingTop: 24 }}>
          <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: 13, textAlign: 'center', marginBottom: 8 }}>
            &copy; {new Date().getFullYear()} Squishy Skin Etc. All rights reserved.
          </p>
          <p style={{ color: 'rgba(255,255,255,0.4)', fontSize: 12, textAlign: 'center' }}>
            $40 cancellation fee applies to appointments cancelled without 24 hours notice.
          </p>
        </div>
      </div>
    </footer>
  );
}

/* ============================================
   PHONE FLOAT BUTTON
   ============================================ */
function PhoneFloatButton() {
  return (
    <a href="tel:+16046217783" className="phone-float" aria-label="Call us">
      <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/>
      </svg>
    </a>
  );
}

/* ============================================
   CTA SECTION (reused on multiple pages)
   ============================================ */
function CTASection({ heading = "Ready for Smooth Skin?", subtext = "Book your appointment online in seconds.", bgColor = "var(--pink)" }) {
  return (
    <div className="section" style={{ background: bgColor, textAlign: 'center', padding: '80px 0' }}>
      <div className="container">
        <AnimatedSection>
          <h2 style={{ fontSize: 44, color: '#fff', marginBottom: 16 }}>{heading}</h2>
          <p style={{ fontSize: 18, color: 'rgba(255,255,255,0.85)', marginBottom: 36, maxWidth: 500, margin: '0 auto 36px' }}>{subtext}</p>
          <div style={{ display: 'flex', gap: 16, justifyContent: 'center', alignItems: 'center', flexWrap: 'wrap' }}>
            <a href="https://squishyskin.setmore.com/" target="_blank" rel="noopener noreferrer"
              className="btn btn-outline-white">Book on Setmore</a>
            <a href="tel:+16046217783" style={{ color: '#fff', fontSize: 16, fontWeight: 600 }}>+1 604 621 7783</a>
          </div>
        </AnimatedSection>
      </div>
    </div>
  );
}

/* Export to window */
Object.assign(window, {
  useScrollAnimation, useParallax, AnimatedSection, AnimatedCounter, PageTransition,
  BlobShape, PlaceholderImage, StarRating, Navigation, Footer, PhoneFloatButton, CTASection
});
