/* ============================================================
   Galería · Detalle · Sobre mí — María Paula Muriel Photography
   ============================================================ */

/* ——————————————————— Galería pública ——————————————————— */
function Gallery({ go, photos: photosProp, loadingData, params = {} }) {
  const [filter, setFilter] = React.useState(params.col ? `col:${params.col}` : 'todos');
  const [localLoading, setLocalLoading] = React.useState(true);
  React.useEffect(() => { const t = setTimeout(() => setLocalLoading(false), 750); return () => clearTimeout(t); }, []);
  React.useEffect(() => { setFilter(params.col ? `col:${params.col}` : 'todos'); }, [params.col]);
  React.useEffect(() => { setLocalLoading(true); const t = setTimeout(() => setLocalLoading(false), 450); return () => clearTimeout(t); }, [filter]);

  const loading = localLoading || Boolean(loadingData && window.MPM_DB?.enabled);
  const pub = (photosProp || window.PHOTOS).filter(p => p.status === 'published');
  const chips = [
    { id: 'todos', label: 'Todas' },
    ...window.COLLECTIONS.map(name => ({ id: `col:${name}`, label: name, collection: true })),
    ...window.CATEGORIES,
    { id: 'fav', label: 'Favoritos' },
  ];
  const shown = pub.filter(p => {
    if (filter === 'todos') return true;
    if (filter === 'fav') return p.fav;
    if (filter.startsWith('col:')) return p.col === filter.slice(4);
    return p.cat === filter;
  });
  const selectedCollection = filter.startsWith('col:') ? filter.slice(4) : '';
  const landingAnchor = selectedCollection ? 'collections' : 'top';

  return (
    <div style={{ paddingTop: 110, minHeight: '100vh' }}>
      <div className="wrap">
        <div style={{ textAlign: 'center', padding: '24px 0 8px' }}>
          <div className="eyebrow" style={{ marginBottom: 12, display: 'inline-flex', alignItems: 'center', gap: 9 }}><TriDots size={6} /> Archivo visual</div>
          <h1 className="serif" style={{ margin: 0, fontSize: 'clamp(40px,5.5vw,68px)', fontWeight: 500, color: 'var(--ink)' }}>Galería</h1>
          <p style={{ margin: '12px auto 0', maxWidth: 460, color: 'var(--ink-2)', fontSize: 16, lineHeight: 1.6 }}>
            Una colección curada de momentos. Toca cualquier fotografía para ampliarla.
          </p>
          <button className="btn btn-soft btn-sm" onClick={() => go('home', {}, landingAnchor)} style={{ marginTop: 18 }}>
            <Icon name="arrowLeft" size={15} /> Volver al inicio
          </button>
        </div>

        {/* Filtros */}
        <div className="gallery-filters" style={{ display: 'flex', gap: 9, justifyContent: 'center', flexWrap: 'wrap', margin: '34px 0 30px', padding: '6px 0' }}>
          {chips.map(c => {
            const active = filter === c.id;
            const dot = c.tone ? toneVar(c.tone) : null;
            return (
              <button key={c.id} onClick={() => setFilter(c.id)} style={{
                border: '1px solid', borderColor: active ? 'transparent' : 'var(--line-2)',
                background: active ? 'var(--ink)' : 'rgba(255,255,255,.7)', backdropFilter: 'blur(8px)',
                color: active ? '#fff' : 'var(--ink-2)', padding: '9px 16px', borderRadius: 999,
                fontSize: 13.5, fontWeight: 600, transition: 'all .22s', display: 'inline-flex', alignItems: 'center', gap: 7 }}>
                {dot && <span style={{ width: 8, height: 8, borderRadius: '50%', background: dot, boxShadow: active ? `0 0 0 2px rgba(255,255,255,.25)` : 'none' }} />}
                {c.collection && <Icon name="layers" size={13} />}
                {c.id === 'fav' && <Icon name="heart" size={13} fill={active ? '#fff' : 'var(--rose)'} stroke={active ? 0 : 0} />}
                {c.label}
              </button>
            );
          })}
        </div>

        {/* Grid */}
        {loading ? (
          <div className="masonry" style={{ paddingBottom: 80 }}>
            {Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="masonry-item skeleton" style={{ aspectRatio: ['3/4','3/2','1/1'][i%3], borderRadius: 'var(--r-md)' }} />
            ))}
          </div>
        ) : shown.length === 0 ? (
          <EmptyState title="Aún no hay fotografías aquí" sub="Prueba con otra categoría o vuelve pronto: el archivo crece constantemente." />
        ) : (
          <div className="masonry" style={{ paddingBottom: 90 }}>
            {shown.map((p, i) => (
              <button key={p.id} onClick={() => go('photo', { id: p.id, fromFilter: filter })} className="masonry-item stag" style={{ background: 'none', border: 'none', padding: 0, display: 'block', '--d': `${Math.min(i*.05,.4)}s` }}>
                <div style={{ position: 'relative' }}>
                  <PhotoFrame photo={p} hover temp={false} />
                  {p.fav && <span style={{ position: 'absolute', top: 10, right: 10, zIndex: 4, background: 'rgba(255,255,255,.85)', borderRadius: '50%', width: 28, height: 28, display: 'grid', placeItems: 'center', backdropFilter: 'blur(3px)' }}><Icon name="heart" size={14} fill="var(--rose)" stroke={0} /></span>}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '11px 4px 0' }}>
                  <span className="serif" style={{ fontSize: 18, fontStyle: 'italic', color: 'var(--ink)' }}>{p.title}</span>
                  <span style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.1em' }}>{catLabel(p.cat)}</span>
                </div>
              </button>
            ))}
          </div>
        )}
      </div>
      <Footer go={go} />
    </div>
  );
}

/* ——————————————————— Detalle de fotografía ——————————————————— */
function PhotoDetail({ go, params, photos: photosProp }) {
  const pub = (photosProp || window.PHOTOS).filter(p => p.status === 'published');
  const idx = Math.max(0, pub.findIndex(p => p.id === params.id));
  const p = pub[idx];
  const prev = pub[(idx - 1 + pub.length) % pub.length];
  const next = pub[(idx + 1) % pub.length];
  React.useEffect(() => { window.scrollTo({ top: 0 }); }, [params.id]);
  if (!p) return null;

  const fmtDate = new Date(p.date).toLocaleDateString('es-ES', { day: 'numeric', month: 'long', year: 'numeric' });
  const backToHome = params.from === 'home';
  const fromFilter = params.fromFilter || '';
  const fromCollection = fromFilter.startsWith('col:') ? fromFilter.slice(4) : '';

  return (
    <div style={{ paddingTop: 96, minHeight: '100vh', background: 'var(--surface-2)' }}>
      <div className="wrap" style={{ padding: '20px 32px 0' }}>
        <button className="btn btn-soft btn-sm" onClick={() => backToHome ? go('home', {}, 'featured') : go('gallery', fromCollection ? { col: fromCollection } : {})}><Icon name="arrowLeft" size={15} /> {backToHome ? 'Volver al inicio' : 'Volver a la galería'}</button>
      </div>
      <div className="wrap detail-grid" style={{ display: 'grid', gridTemplateColumns: '1.55fr .85fr', gap: 48, padding: '28px 32px 70px', alignItems: 'start' }}>
        <div className="animate-fadeUp" style={{ position: 'relative' }}>
          <PhotoFrame photo={p} temp={false} wmStyle="white" rounded="var(--r-lg)" style={{ boxShadow: 'var(--sh-lg)' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 18 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => go('photo', { id: prev.id, fromFilter })}><Icon name="chevLeft" size={16} /> Anterior</button>
            <button className="btn btn-ghost btn-sm" onClick={() => go('photo', { id: next.id, fromFilter })}>Siguiente <Icon name="chevRight" size={16} /></button>
          </div>
        </div>
        <div style={{ position: 'sticky', top: 110 }}>
          <span className="badge" style={{ background: 'var(--rose-soft)', color: 'var(--rose-deep)' }}>{catLabel(p.cat)}</span>
          <h1 className="serif" style={{ margin: '16px 0 0', fontSize: 'clamp(32px,4vw,46px)', fontWeight: 500, lineHeight: 1.1, color: 'var(--ink)' }}>{p.title}</h1>
          <p style={{ margin: '16px 0 0', fontSize: 16.5, lineHeight: 1.7, color: 'var(--ink-2)' }}>{p.desc}</p>
          <div style={{ marginTop: 26, borderTop: '1px solid var(--line)', paddingTop: 22, display: 'grid', gap: 14 }}>
            {[['Categoría', catLabel(p.cat)], ['Colección', p.col], ['Fecha', fmtDate], ['Resolución', p.res + ' px']].map(([k,v]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14 }}>
                <span style={{ color: 'var(--ink-3)' }}>{k}</span>
                <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{v}</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 26, padding: 16, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <Signature text="MP Muriel" size={30} color="var(--ink)" />
            <span style={{ fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.4 }}>Imagen firmada y optimizada para web</span>
          </div>
        </div>
      </div>
      <Footer go={go} />
    </div>
  );
}

/* ——————————————————— Sobre mí (editable, enfoque profesional) ——————————————————— */
function About({ go, about }) {
  const a = about || window.DEFAULT_ABOUT;
  const blockTones = ['rose', 'sky', 'green'];
  const coverPhoto = { tone: a.photoTone || 'rose', o: 'v', cat: 'retratos', title: '' };
  return (
    <div style={{ paddingTop: 110, minHeight: '100vh' }}>
      <div className="wrap" style={{ padding: '20px 32px 0' }}>
        <button className="btn btn-soft btn-sm" onClick={() => window.history.length > 1 ? window.history.back() : go('home')}>
          <Icon name="arrowLeft" size={15} /> Volver
        </button>
      </div>
      <div className="wrap about-hero" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center', padding: '28px 32px 72px' }}>
        <div className="animate-fadeUp">
          <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
            <TriDots size={7} /> {a.intro}
          </div>
          <h1 className="serif" style={{ margin: 0, fontSize: 'clamp(40px,5vw,64px)', fontWeight: 500, lineHeight: 1.05, color: 'var(--ink)' }}>
            {a.title1}<br /><span style={{ fontStyle: 'italic', color: 'var(--rose-deep)' }}>{a.title2}</span>
          </h1>
          <p style={{ marginTop: 24, fontSize: 17, lineHeight: 1.75, color: 'var(--ink-2)', maxWidth: 480 }}>{a.bioLead}</p>
          <p style={{ marginTop: 16, fontSize: 17, lineHeight: 1.75, color: 'var(--ink-2)', maxWidth: 480 }}>{a.bio2}</p>
          <Signature text="María Paula Muriel" size={46} color="var(--ink)" style={{ marginTop: 22 }} />
        </div>
        <div style={{ position: 'relative' }}>
          <PhotoFrame photo={coverPhoto} ratio="4 / 5" temp={true} wmStyle="white" rounded="var(--r-lg)" style={{ boxShadow: 'var(--sh-lg)' }} />
          <div style={{ position: 'absolute', top: -18, left: -22, background: 'var(--surface)', borderRadius: 'var(--r-md)', boxShadow: 'var(--sh-md)', padding: '10px 16px', fontSize: 12.5, fontWeight: 600, animation: 'floaty 5s ease-in-out infinite' }}>
            <span style={{ color: 'var(--ink-3)', fontWeight: 500 }}>Imagen de portada</span><br />editable desde el panel
          </div>
          <Sparkle size={20} color="var(--green)" style={{ position: 'absolute', bottom: 30, right: -10 }} />
          <Sparkle size={14} color="var(--sky)" delay={1} style={{ position: 'absolute', top: 40, left: -12 }} />
        </div>
      </div>

      {/* Cómo trabajo */}
      <section style={{ background: 'var(--cream)', padding: '80px 0' }}>
        <div className="wrap">
          <SectionHead center eyebrow="Enfoque artístico" title="Cómo trabajo" sub="Los principios que guían cada fotografía del archivo." />
          <div className="style-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 24, marginTop: 40 }}>
            {a.work.map((b, i) => {
              const t = blockTones[i % 3];
              return (
                <div key={i} className="card stag" style={{ padding: 28, '--d': `${i*.1}s` }}>
                  <div style={{ width: 50, height: 50, borderRadius: 'var(--r-sm)', background: `var(--${t}-tint)`, display: 'grid', placeItems: 'center', marginBottom: 18 }}>
                    <Icon name={b.icon} size={24} style={{ color: toneDeep(t) }} />
                  </div>
                  <h3 className="serif" style={{ margin: 0, fontSize: 24, fontWeight: 500, color: 'var(--ink)' }}>{b.t}</h3>
                  <p style={{ margin: '8px 0 0', fontSize: 14.5, lineHeight: 1.6, color: 'var(--ink-2)' }}>{b.d}</p>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="wrap" style={{ padding: '72px 32px', textAlign: 'center' }}>
        <TriDots size={8} style={{ justifyContent: 'center', marginBottom: 18 }} />
        <h2 className="serif" style={{ margin: 0, fontSize: 'clamp(28px,4vw,42px)', fontWeight: 500, color: 'var(--ink)', lineHeight: 1.1 }}>
          Explora el <span style={{ fontStyle: 'italic', color: 'var(--rose-deep)' }}>archivo visual</span>
        </h2>
        <div style={{ marginTop: 26 }}>
          <button className="btn btn-primary btn-lg" onClick={() => go('gallery', { from: 'home', anchor: 'top' })}><Icon name="gallery" size={17} /> Ver la galería</button>
        </div>
      </section>
      <Footer go={go} />
    </div>
  );
}

Object.assign(window, { Gallery, PhotoDetail, About });
