/* global React, PAOLA_DATA */
// Shared components: Nav, Footer, Hero, Reveal, Marquee, helpers

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* --- Reveal on scroll --- */
function Reveal({ children, delay = 0, className = '', as = 'div' }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShown(true); io.disconnect(); }
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return <Tag ref={ref} className={`reveal ${shown ? 'in' : ''} ${delay ? 'reveal-d'+delay : ''} ${className}`}>{children}</Tag>;
}

/* --- Nav --- */
function Nav({ route, go, dark, onOpenMenu }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const navClass = `nav ${scrolled ? 'scrolled' : ''} ${(!scrolled && !dark) ? 'light' : ''}`;
  const link = (id, label) => (
    <a href={'#'+id} onClick={(e)=>{e.preventDefault(); go(id);}} className={route===id?'active':''}>{label}</a>
  );
  return (
    <header className={navClass}>
      <a href="#home" onClick={(e)=>{e.preventDefault(); go('home');}} className="brand">
        PAOLA GARCÍA
        <small>FOTÓGRAFA PROFESIONAL</small>
      </a>
      <nav className="nav-links">
        {link('home', 'Inicio')}
        {link('portfolio', 'Portafolio')}
        {link('about', 'Sobre mí')}
        {link('contact', 'Contacto')}
      </nav>
      <a href="#contact" onClick={(e)=>{e.preventDefault(); go('contact');}} className="nav-cta">Agenda tu sesión</a>
      <div className="nav-burger" onClick={onOpenMenu}><span></span><span></span></div>
    </header>
  );
}

/* --- Fullscreen menu (mobile + accessory) --- */
function FullMenu({ open, onClose, go }) {
  return (
    <div className={`menu-overlay ${open?'open':''}`}>
      <nav>
        {[
          ['home','Inicio'],
          ['portfolio','Portafolio'],
          ['about','Sobre mí'],
          ['contact','Contacto'],
        ].map(([id,label], i) => (
          <a key={id} onClick={(e)=>{e.preventDefault(); go(id); onClose();}} href={'#'+id}>
            <span>{label}</span>
            <span className="idx">0{i+1}</span>
          </a>
        ))}
      </nav>
      <div className="menu-foot">
        <span>SABANETA · ANTIOQUIA</span>
        <span>@{PAOLA_DATA.contact.instagram}</span>
        <span>{PAOLA_DATA.contact.whatsappPretty}</span>
      </div>
    </div>
  );
}

/* --- Marquee --- */
function Marquee({ items }) {
  const all = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {all.map((t, i) => <span key={i}>{t}</span>)}
      </div>
    </div>
  );
}

/* --- Footer --- */
function Footer({ go }) {
  const c = PAOLA_DATA.contact;
  return (
    <footer>
      <div className="foot-top">
        <div>
          <h3>Manifesto</h3>
          <div className="word">Hagamos <em>eternos</em><br/>tus recuerdos.</div>
        </div>
        <div>
          <h3>Navegación</h3>
          <a onClick={()=>go('home')}>Inicio</a>
          <a onClick={()=>go('portfolio')}>Portafolio</a>
          <a onClick={()=>go('about')}>Sobre mí</a>
          <a onClick={()=>go('contact')}>Contacto</a>
        </div>
        <div>
          <h3>Studio</h3>
          <span>{c.studio}</span>
          <span>Medellín · Colombia</span>
          <span>{c.horario}</span>
        </div>
        <div>
          <h3>Contacto</h3>
          <a href={c.instagramUrl} target="_blank" rel="noreferrer">Instagram ↗</a>
          <a href={`https://wa.me/57${c.whatsapp}`} target="_blank" rel="noreferrer">WhatsApp ↗</a>
          <a href={`mailto:${c.email}`}>{c.email}</a>
        </div>
      </div>
      <div className="foot-bottom">
        <span>© 2026 Paola García · Todos los derechos reservados</span>
        <span>Colecciona momentos de amor</span>
      </div>
    </footer>
  );
}

/* --- Floating WhatsApp --- */
function WhatsAppFloat() {
  const c = PAOLA_DATA.contact;
  const phone = String(c.whatsappPretty || c.whatsapp || '').replace(/\D/g, '');
  if (!phone) return null;
  const message = c.whatsappMessage || 'Hola Paola, quiero recibir información sobre una sesión fotográfica.';
  const href = `https://wa.me/${phone}?text=${encodeURIComponent(message)}`;
  return (
    <a
      className="wa-float"
      href={href}
      target="_blank"
      rel="noreferrer"
      aria-label="Escribir por WhatsApp"
      title="Escribir por WhatsApp"
    >
      <span className="wa-float-icon" aria-hidden="true">✆</span>
      <span className="wa-float-label">WhatsApp</span>
    </a>
  );
}

/* --- Hero --- */
function Hero({ go, heroCopy }) {
  const ref = useRef(null);
  const [loaded, setLoaded] = useState(false);
  const slides = Array.isArray(PAOLA_DATA.hero.slides)
    ? PAOLA_DATA.hero.slides.filter(Boolean)
    : (PAOLA_DATA.hero.main ? [PAOLA_DATA.hero.main] : []);
  const hasSlides = slides.length > 0;
  const [idx, setIdx] = useState(0);

  useEffect(() => {
    const t = setTimeout(() => setLoaded(true), 80);
    return () => clearTimeout(t);
  }, []);

  // Auto-advance slides
  useEffect(() => {
    if (slides.length <= 1) return;
    const t = setInterval(() => setIdx(i => (i + 1) % slides.length), 5500);
    return () => clearInterval(t);
  }, [slides.length]);

  // Parallax
  useEffect(() => {
    const onScroll = () => {
      if (!ref.current) return;
      const y = window.scrollY;
      ref.current.querySelectorAll('.h-bg').forEach(bg => {
        bg.style.setProperty('--py', `${y * 0.25}px`);
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <section className={`hero ${loaded?'loaded':''}`} ref={ref}>
      {slides.map((src, i) => (
        <div
          key={src}
          className={`h-bg ${i===idx?'active':''}`}
          style={{ backgroundImage: `url(${src})` }}
        ></div>
      ))}
      {hasSlides && <div className="hero-meta">N° 0{idx+1} · COLECCIÓN 2026</div>}
      <div className="hero-inner">
        <div className="hero-tag">FOTÓGRAFA PROFESIONAL — MEDELLÍN</div>
        <h1 className="hero-title">
          {heroCopy.line1}<br/><em>{heroCopy.line2}</em>
        </h1>
        <div className="hero-foot">
          <p className="hero-sub">{heroCopy.sub}</p>
          <button className="btn btn-light" onClick={()=>go('portfolio')}>
            <span className="arr"></span>
            Ver portafolio
          </button>
        </div>
      </div>
      {hasSlides && (
        <div className="hero-dots">
          {slides.map((_, i) => (
            <button
              key={i}
              className={`dot ${i===idx?'active':''}`}
              onClick={()=>setIdx(i)}
              aria-label={`Slide ${i+1}`}
            ></button>
          ))}
        </div>
      )}
      <div className="hero-scroll">
        <span>SCROLL</span>
        <span className="line"></span>
      </div>
    </section>
  );
}

/* --- Lightbox --- */
function Lightbox({ items, index, onClose, onPrev, onNext }) {
  const touchStart = useRef(null);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') onPrev();
      if (e.key === 'ArrowRight') onNext();
    };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose, onPrev, onNext]);

  const handleTouchStart = (e) => {
    touchStart.current = e.touches[0].clientX;
  };
  const handleTouchEnd = (e) => {
    if (touchStart.current === null) return;
    const dx = e.changedTouches[0].clientX - touchStart.current;
    if (Math.abs(dx) > 50) {
      dx < 0 ? onNext() : onPrev();
    }
    touchStart.current = null;
  };

  const item = items[index];
  return (
    <div
      className="lightbox open"
      onClick={onClose}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      <button className="lb-close" onClick={(e)=>{e.stopPropagation(); onClose();}}>cerrar</button>
      <button className="lb-nav lb-prev" onClick={(e)=>{e.stopPropagation(); onPrev();}}>← anterior</button>
      <button className="lb-nav lb-next" onClick={(e)=>{e.stopPropagation(); onNext();}}>siguiente →</button>
      <img src={item.src.replace('w=1400','w=2200')} alt={item.label} onClick={(e)=>e.stopPropagation()} />
      <div className="lb-caption">{item.label} — {index+1} / {items.length}</div>
    </div>
  );
}

Object.assign(window, { Reveal, Nav, FullMenu, Marquee, Footer, WhatsAppFloat, Hero, Lightbox });
