/* ============================================================
   Páginas públicas — María Paula Muriel Photography
   ============================================================ */

/* ——————————————————— Navegación pública ——————————————————— */
function PublicNav({ go, route, onHero }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const navigatingRef = React.useRef(false);
  React.useEffect(() => {
    if (!open) return;
    const scrollY = window.scrollY || window.pageYOffset || 0;
    const previousOverflow = document.body.style.overflow;
    const previousPosition = document.body.style.position;
    const previousTop = document.body.style.top;
    const previousWidth = document.body.style.width;
    const previousLeft = document.body.style.left;
    const previousRight = document.body.style.right;
    const previousTouchAction = document.body.style.touchAction;
    const previousOverscroll = document.documentElement.style.overscrollBehavior;
    const previousHtmlOverflow = document.documentElement.style.overflow;
    document.documentElement.style.overflow = 'hidden';
    document.documentElement.style.overscrollBehavior = 'none';
    document.body.style.overflow = 'hidden';
    document.body.style.position = 'fixed';
    document.body.style.top = `-${scrollY}px`;
    document.body.style.left = '0';
    document.body.style.right = '0';
    document.body.style.width = '100%';
    document.body.style.touchAction = 'none';
    return () => {
      document.documentElement.style.overflow = previousHtmlOverflow;
      document.documentElement.style.overscrollBehavior = previousOverscroll;
      document.body.style.overflow = previousOverflow;
      document.body.style.position = previousPosition;
      document.body.style.top = previousTop;
      document.body.style.left = previousLeft;
      document.body.style.right = previousRight;
      document.body.style.width = previousWidth;
      document.body.style.touchAction = previousTouchAction;
      if (!navigatingRef.current) window.scrollTo(0, scrollY);
      navigatingRef.current = false;
    };
  }, [open]);
  React.useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 30);
    fn(); window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);
  const solid = scrolled || !onHero;
  const links = [
    { id: 'home', label: 'Inicio' },
    { id: 'gallery', label: 'Galería' },
    { id: 'about', label: 'Sobre mí' },
  ];
  return (
    <header style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      transition: 'all .35s', padding: solid ? '12px 0' : '20px 0',
      background: solid ? 'rgba(250,247,245,.82)' : 'transparent',
      backdropFilter: solid ? 'blur(14px)' : 'none',
      borderBottom: solid ? '1px solid var(--line)' : '1px solid transparent' }}>
      <div className="wrap" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div onClick={() => go('home')} style={{ cursor: 'pointer', transform: solid ? 'scale(.86)' : 'scale(1)', transformOrigin: 'left center', transition: 'transform .35s' }}>
          <Logo />
        </div>
        <nav className="nav-links" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          {links.map(l => (
            <button key={l.id} onClick={() => go(l.id)} style={{
              background: 'none', border: 'none', padding: '8px 16px', fontSize: 14, fontWeight: 500,
              color: route === l.id ? 'var(--rose-deep)' : 'var(--ink-2)', position: 'relative' }}>
              {l.label}
              {route === l.id && <span style={{ position: 'absolute', bottom: 2, left: '50%', transform: 'translateX(-50%)', width: 5, height: 5, borderRadius: '50%', background: 'var(--rose)' }} />}
            </button>
          ))}
          <button className="btn btn-dark btn-sm" style={{ marginLeft: 10 }} onClick={() => go('login')}>
            <Icon name="lock" size={15} /> Acceder
          </button>
        </nav>
        <button className="nav-burger" onClick={() => setOpen(true)} style={{ display: 'none', background: 'none', border: 'none', color: 'var(--ink)' }}>
          <Icon name="menu" size={26} />
        </button>
      </div>
      {open && (
        <div className="animate-fadeIn" onTouchMove={e => e.preventDefault()} onWheel={e => e.preventDefault()} style={{ position: 'fixed', inset: 0, width: '100vw', height: '100dvh', background: '#faf7f5', opacity: 1, zIndex: 999, padding: 28, touchAction: 'none', overflow: 'hidden' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Logo />
            <button onClick={() => setOpen(false)} style={{ background: 'none', border: 'none', color: 'var(--ink)' }}><Icon name="close" size={28} /></button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 50 }}>
            {links.map(l => (
              <button key={l.id} onClick={() => { navigatingRef.current = true; go(l.id); setOpen(false); }} className="serif" style={{ background: 'none', border: 'none', textAlign: 'left', fontSize: 34, fontWeight: 500, color: 'var(--ink)', padding: '10px 0' }}>{l.label}</button>
            ))}
            <button className="btn btn-dark btn-lg" style={{ marginTop: 24 }} onClick={() => { navigatingRef.current = true; go('login'); setOpen(false); }}><Icon name="lock" size={16} /> Acceder al panel</button>
          </div>
        </div>
      )}
    </header>
  );
}

/* ——————————————————— Footer ——————————————————— */
function Footer({ go }) {
  return (
    <footer style={{ background: 'var(--ink)', color: 'rgba(255,255,255,.7)', padding: '64px 0 36px', marginTop: 0 }}>
      <div className="wrap">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 40, justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div style={{ maxWidth: 320 }}>
            <Logo dark />
            <p style={{ marginTop: 18, lineHeight: 1.7, fontSize: 14, color: 'rgba(255,255,255,.6)' }}>
              Fotografías que transforman instantes en memoria visual.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 56, flexWrap: 'wrap' }}>
            <div>
              <p className="eyebrow" style={{ color: 'rgba(255,255,255,.4)', marginBottom: 16 }}>Explorar</p>
              {[['Galería','gallery'],['Sobre mí','about'],['Acceder','login']].map(([t,p]) => (
                <button key={p} onClick={() => go(p)} style={{ display: 'block', background: 'none', border: 'none', color: 'rgba(255,255,255,.72)', padding: '6px 0', fontSize: 14 }}>{t}</button>
              ))}
            </div>
            <div>
              <p className="eyebrow" style={{ color: 'rgba(255,255,255,.4)', marginBottom: 16 }}>Contacto</p>
              <p style={{ margin: '6px 0', fontSize: 14, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="mail" size={15} /> mariapaulatweb@gmail.com</p>
              <p style={{ margin: '6px 0', fontSize: 14, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="user" size={15} /> @mariapaula9902</p>
            </div>
          </div>
        </div>
        <div style={{ borderTop: '1px solid rgba(255,255,255,.12)', marginTop: 44, paddingTop: 24, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, fontSize: 12.5, color: 'rgba(255,255,255,.45)' }}>
          <span>© 2026 María Paula Muriel Triana · Todos los derechos reservados</span>
          <span style={{ fontFamily: 'var(--script)', fontSize: 22, color: 'rgba(255,255,255,.55)' }}>María Paula Muriel</span>
        </div>
      </div>
    </footer>
  );
}

/* ——————————————————— Landing ——————————————————— */
function Landing({ go, photos: photosProp, loadingData }) {
  const pub = (photosProp || window.PHOTOS).filter(p => p.status === 'published');
  const featured = pub.slice(0, 6);
  const heroPhoto = pub[0];
  const thumbPhoto = pub[Math.min(4, pub.length - 1)] || pub[0];
  const aboutPhoto = { tone: 'rose', o: 'v', cat: 'retratos', title: 'María Paula Muriel' };
  const cols = window.COLLECTIONS.map((name) => {
    const collectionPhotos = pub.filter(p => p.col === name);
    return {
      name,
      photo: collectionPhotos[0],
      count: collectionPhotos.length,
    };
  }).filter(c => c.count > 0).slice(0, 3);
  return (
    <div>
      {/* HERO */}
      <section id="top" style={{ position: 'relative', paddingTop: 150, paddingBottom: 90, overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -120, right: -100, width: 460, height: 460, borderRadius: '50%',
          background: 'radial-gradient(circle, var(--rose-soft), transparent 70%)', opacity: .75, pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', bottom: -80, left: -120, width: 380, height: 380, borderRadius: '50%',
          background: 'radial-gradient(circle, var(--sky-soft), transparent 70%)', opacity: .75, pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', top: '38%', right: '34%', width: 260, height: 260, borderRadius: '50%',
          background: 'radial-gradient(circle, var(--green-soft), transparent 70%)', opacity: .6, pointerEvents: 'none' }} />
        <div className="wrap hero-grid" style={{ display: 'grid', gridTemplateColumns: '1.05fr .95fr', gap: 56, alignItems: 'center', position: 'relative' }}>
          <div className="animate-fadeUp">
            <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 22 }}>
              <TriDots size={7} /> Portafolio de fotografía
            </div>
            <h1 className="serif" style={{ margin: 0, fontSize: 'clamp(46px, 6vw, 82px)', fontWeight: 500, lineHeight: 1.02, letterSpacing: '-.01em', color: 'var(--ink)' }}>
              Una mirada<br /><span style={{ fontStyle: 'italic', color: 'var(--rose-deep)' }}>artística</span> para<br />capturar lo cotidiano.
            </h1>
            <p style={{ marginTop: 26, fontSize: 17.5, lineHeight: 1.65, color: 'var(--ink-2)', maxWidth: 440 }}>
              Cada imagen cuenta una historia sin decir una palabra. Bienvenida al archivo visual de María Paula Muriel.
            </p>
            <div style={{ display: 'flex', gap: 14, marginTop: 34, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-lg" onClick={() => go('gallery', { from: 'home', anchor: 'top' })}><Icon name="gallery" size={17} /> Ver galería</button>
            </div>
          </div>
          <div className="hero-photo animate-fadeUp" style={{ position: 'relative', animationDelay: '.22s' }}>
            <div style={{ position: 'relative', boxShadow: 'var(--sh-lg)', borderRadius: 'var(--r-lg)' }}>
              <PhotoFrame photo={heroPhoto} ratio="4 / 5" temp={!heroPhoto?.image_url} wmStyle="white" rounded="var(--r-lg)" />
            </div>
            <div style={{ position: 'absolute', bottom: -22, left: -28, background: 'var(--surface)', borderRadius: 'var(--r-md)', boxShadow: 'var(--sh-md)', padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10, animation: 'floaty 5s ease-in-out infinite' }}>
              <PhotoFrame photo={thumbPhoto} ratio="1/1" label={false} wm={false} temp={false} rounded="10px" style={{ width: 44 }} />
              <div style={{ lineHeight: 1.3 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700 }}>{pub.length > 0 ? '+' + pub.length + ' obras' : 'Portafolio'}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{pub.length > 0 ? 'en tu archivo' : 'en crecimiento'}</div>
              </div>
            </div>
            <Sparkle size={26} color="var(--sand)" style={{ position: 'absolute', top: -16, right: 28 }} />
            <Sparkle size={16} color="var(--rose)" delay={1.2} style={{ position: 'absolute', top: 60, right: -14 }} />
          </div>
        </div>
      </section>

      {/* DESTACADAS */}
      <section id="featured" className="wrap" style={{ padding: '40px 32px 80px' }}>
        <SectionHead eyebrow="Selección" title="Fotografías destacadas" sub="Una muestra del trabajo más reciente del archivo." />
        <div className="masonry" style={{ marginTop: 36 }}>
          {featured.map((p, i) => (
            <button key={p.id} onClick={() => go('photo', { id: p.id, from: 'home' })} className="masonry-item stag" style={{ background: 'none', border: 'none', padding: 0, display: 'block', '--d': `${i * .07}s` }}>
              <PhotoFrame photo={p} hover temp={false} />
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '12px 4px 0' }}>
                <span className="serif" style={{ fontSize: 19, fontStyle: 'italic', color: 'var(--ink)' }}>{p.title}</span>
                <span style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.1em' }}>{catLabel(p.cat)}</span>
              </div>
            </button>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 44 }}>
          <button className="btn btn-ghost btn-lg" onClick={() => go('gallery', { from: 'home', anchor: 'featured' })}>Ver galería completa <Icon name="arrowRight" size={16} /></button>
        </div>
      </section>

      {/* COLECCIONES */}
      <section id="collections" style={{ background: 'var(--cream)', padding: '84px 0' }}>
        <div className="wrap">
          <SectionHead eyebrow="Series" title="Colecciones" sub="Cuerpos de trabajo agrupados por mirada y momento." />
          <div className="coll-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 26, marginTop: 36 }}>
            {cols.map((c, i) => (
              <button key={c.name} onClick={() => go('gallery', { col: c.name })} className="coll-card stag" style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', overflow: 'hidden', padding: 0, textAlign: 'left', boxShadow: 'var(--sh-sm)', transition: 'transform .3s, box-shadow .3s', '--d': `${i*.1}s` }}>
                <PhotoFrame photo={c.photo} label={false} temp={false} rounded="0" hover />
                <div style={{ padding: '18px 20px 22px' }}>
                  <h3 className="serif" style={{ margin: 0, fontSize: 24, fontWeight: 500, color: 'var(--ink)' }}>{c.name}</h3>
                  <p style={{ margin: '6px 0 0', fontSize: 13, color: 'var(--ink-3)' }}>{c.count} fotografías</p>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* SOBRE MÍ (breve) */}
      <section className="wrap about-strip" style={{ padding: '88px 32px', display: 'grid', gridTemplateColumns: '.85fr 1.15fr', gap: 56, alignItems: 'center' }}>
        <div style={{ position: 'relative' }}>
          <PhotoFrame photo={aboutPhoto} ratio="4 / 5" temp label wm={false} rounded="var(--r-lg)" style={{ boxShadow: 'var(--sh-md)' }} />
          <Sparkle size={20} color="var(--sand)" style={{ position: 'absolute', bottom: 18, right: -10 }} />
        </div>
        <div>
          <div className="eyebrow" style={{ marginBottom: 18 }}>Sobre María Paula</div>
          <h2 className="serif" style={{ margin: 0, fontSize: 'clamp(32px,4vw,46px)', fontWeight: 500, lineHeight: 1.1, color: 'var(--ink)' }}>
            Fotografío con <span style={{ fontStyle: 'italic', color: 'var(--rose-deep)' }}>intención</span>, ternura y carácter.
          </h2>
          <p style={{ marginTop: 22, fontSize: 16.5, lineHeight: 1.7, color: 'var(--ink-2)', maxWidth: 520 }}>
            Mi trabajo busca la honestidad de los gestos pequeños y la fuerza de la luz natural. Cada serie es una conversación entre el instante y la mirada.
          </p>
          <div style={{ marginTop: 28, display: 'flex', alignItems: 'center', gap: 18 }}>
            <button className="btn btn-dark" onClick={() => go('about')}>Conocer más</button>
            <Signature text="María Paula Muriel" size={36} color="var(--ink-3)" />
          </div>
        </div>
      </section>

      {/* CTA */}
      <section id="gallery-cta" style={{ padding: '0 0 88px' }}>
        <div className="wrap">
          <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--r-xl)', background: 'linear-gradient(125deg, var(--rose-tint), var(--sky-tint) 60%, var(--sand-tint))', padding: 'clamp(40px,6vw,72px)', textAlign: 'center', border: '1px solid var(--line)' }}>
            <Sparkle size={22} color="var(--rose)" style={{ position: 'absolute', top: 30, left: '12%' }} />
            <Sparkle size={16} color="var(--sand)" delay={1} style={{ position: 'absolute', bottom: 34, right: '14%' }} />
            <Sparkle size={14} color="var(--sky)" delay={2} style={{ position: 'absolute', top: 48, right: '24%' }} />
            <h2 className="serif" style={{ margin: 0, fontSize: 'clamp(30px,4.5vw,52px)', fontWeight: 500, lineHeight: 1.08, color: 'var(--ink)' }}>
              ¿Lista para ver el mundo<br /><span style={{ fontStyle: 'italic', color: 'var(--rose-deep)' }}>a través de mi lente?</span>
            </h2>
            <div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 30, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-lg" onClick={() => go('gallery', { from: 'home', anchor: 'gallery-cta' })}><Icon name="gallery" size={17} /> Explorar galería</button>
            </div>
          </div>
        </div>
      </section>

      <Footer go={go} />
    </div>
  );
}

function SectionHead({ eyebrow, title, sub, center }) {
  return (
    <div style={{ textAlign: center ? 'center' : 'left', maxWidth: center ? 620 : 'none', margin: center ? '0 auto' : 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: center ? 'center' : 'flex-start', marginBottom: 12 }}>
        <TriDots size={6} />
        <span className="eyebrow">{eyebrow}</span>
      </div>
      <h2 className="serif" style={{ margin: 0, fontSize: 'clamp(30px,4vw,46px)', fontWeight: 500, lineHeight: 1.08, color: 'var(--ink)' }}>{title}</h2>
      {sub && <p style={{ margin: '12px 0 0', fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.6 }}>{sub}</p>}
    </div>
  );
}

function catLabel(id) { return (window.CATEGORIES.find(c => c.id === id) || {}).label || ''; }

Object.assign(window, { PublicNav, Footer, Landing, SectionHead, catLabel });
