// media.jsx — sección Fotografía + Audiovisual con producción/postproducción y galerías
const { useState: __mes, useEffect: __mee, useRef: __mer } = React;

/* ════════════════════════════════════════════════════════
   MEDIA — wrapper con dos disciplinas
   ════════════════════════════════════════════════════════ */
function Media({ t }) {
  const [remote, setRemote] = __mes(null);

  // Carga del admin (media_items). Si falla, usamos el i18n como fallback.
  __mee(() => {
    let alive = true;
    fetch('api/media.php', { credentials: 'same-origin' })
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (!alive || !d || !d.ok || !d.data) return;
        const photoOk = Array.isArray(d.data.photo) && d.data.photo.length > 0;
        const videoOk = Array.isArray(d.data.video) && d.data.video.length > 0;
        if (photoOk || videoOk) setRemote(d.data);
      })
      .catch(() => {});
    return () => { alive = false; };
  }, []);

  // Mezcla: si el admin tiene items, sobreescribe la galería del i18n
  const photoBlock = remote && remote.photo && remote.photo.length
    ? { ...t.photo, gallery: remote.photo } : t.photo;
  const videoBlock = remote && remote.video && remote.video.length
    ? { ...t.video, gallery: remote.video } : t.video;

  return (
    <section id="media" style={{ position: 'relative', paddingTop: 80, paddingBottom: 80 }}>
      <div className="wrap">
        <div className="reveal" style={{ marginBottom: 56 }}>
          <div className="kicker" style={{ marginBottom: 18 }}>
            <span className="dot"></span>{t.media_eye}
          </div>
          <h2 className="display" style={{
            fontSize: 'clamp(56px, 8vw, 120px)', lineHeight: 0.9,
            maxWidth: '20ch', fontWeight: 700
          }}>
            {t.media_title_1} <span className="irid-text" style={{ fontStyle: 'italic' }}>{t.media_title_2}</span>
          </h2>
          <p style={{ marginTop: 22, fontSize: 18, maxWidth: 720, color: 'var(--ink)' }}>
            {t.media_sub}
          </p>
        </div>

        <MediaDiscipline t={t} block={photoBlock} kind="photo" />
        <div className="media-sep" />
        <MediaDiscipline t={t} block={videoBlock} kind="video" />
      </div>
    </section>
  );
}

/* ════════════════════════════════════════════════════════
   MEDIA DISCIPLINE — un bloque (fotografía o audiovisual)
   ════════════════════════════════════════════════════════ */
function MediaDiscipline({ block, kind }) {
  const accent = kind === 'photo' ? 'var(--magenta)' : 'var(--azure)';
  const accentName = kind === 'photo' ? 'magenta' : 'azure';

  return (
    <div className="media-block" style={{ marginBottom: 56 }}>
      {/* Encabezado: kicker enorme + intro */}
      <div className="media-head" style={{
        display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 56,
        alignItems: 'end', marginBottom: 40
      }}>
        <div className="reveal">
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em',
            textTransform: 'uppercase', color: accent, fontWeight: 700,
            marginBottom: 14
          }}>
            <span style={{
              display: 'inline-block', width: 8, height: 8, borderRadius: '50%',
              background: accent, boxShadow: `0 0 12px ${accent}`
            }} />
            {block.eyebrow}
          </div>
          <h3 className="display" style={{
            fontSize: 'clamp(40px, 6vw, 84px)', fontWeight: 700,
            lineHeight: 0.95, letterSpacing: '-0.03em'
          }}>
            <Icon name={kind === 'photo' ? 'camera' : 'video'} size={48} color={accent} style={{ marginRight: 12 }} />
            {block.title}
          </h3>
        </div>
        <div className="reveal" style={{ paddingBottom: 6 }}>
          <p style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--ink)', maxWidth: 460 }}>
            {block.lead}
          </p>
        </div>
      </div>

      {/* Producción + Postproducción */}
      <div className="media-phases" style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 40
      }}>
        {block.phases.map((p, i) => (
          <div key={i} className="reveal media-phase chrome-card" style={{ padding: 28 }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              marginBottom: 14
            }}>
              <span className={`badge ${accentName}`} style={{
                display: 'inline-block', padding: '4px 10px', borderRadius: 999,
                background: accent, color: 'white',
                fontFamily: 'var(--font-mono)', fontSize: 10,
                letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 700
              }}>{p.tag}</span>
              <Icon name={p.icon} size={20} color={accent} />
            </div>
            <h4 className="display" style={{
              fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em',
              marginBottom: 10
            }}>{p.title}</h4>
            <p style={{ fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink-dim)', marginBottom: 16 }}>
              {p.body}
            </p>
            <ul style={{ listStyle: 'none', display: 'flex', flexWrap: 'wrap', gap: 6, padding: 0 }}>
              {p.items.map(it => (
                <li key={it} className="chip" style={{ fontSize: 10 }}>{it}</li>
              ))}
            </ul>
          </div>
        ))}
      </div>

      {/* Galería — solo se renderiza si hay items con imagen real */}
      {Array.isArray(block.gallery) && block.gallery.length > 0 && (
        <>
          <div className="reveal" style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            marginBottom: 18, gap: 12, flexWrap: 'wrap'
          }}>
            <div className="kicker">{block.gallery_label}</div>
            <a href="#contact" style={{
              textDecoration: 'none', color: 'var(--ink)',
              fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em',
              textTransform: 'uppercase', fontWeight: 700,
              display: 'inline-flex', alignItems: 'center', gap: 6
            }}>
              {block.gallery_cta} <Icon name="arrow-up-right" size={14} />
            </a>
          </div>
          <div className="media-gallery">
            {block.gallery.map((g, i) => (
              <MediaTile key={i} item={g} kind={kind} index={i} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

/* ════════════════════════════════════════════════════════
   MEDIA TILE — celda visual (placeholder generativo)
   Si llega item.image se usa la imagen; si no, gradiente animado.
   ════════════════════════════════════════════════════════ */
function MediaTile({ item, kind, index }) {
  const palettes = kind === 'photo'
    ? [
        ['#FF3EA5', '#9D5BFF', '#4361FF'],
        ['#FFD93E', '#FF6B1A', '#FF3EA5'],
        ['#2DD4FF', '#4361FF', '#9D5BFF'],
        ['#C8FF3E', '#FFD93E', '#FF6B1A'],
        ['#FF3EA5', '#FF6B1A', '#FFD93E'],
        ['#9D5BFF', '#2DD4FF', '#C8FF3E'],
      ]
    : [
        ['#0a1a3a', '#4361FF', '#2DD4FF'],
        ['#1a0a2a', '#9D5BFF', '#FF3EA5'],
        ['#2a0a1a', '#FF6B1A', '#FFD93E'],
        ['#0a2a1a', '#21C97A', '#C8FF3E'],
        ['#0a1a3a', '#2DD4FF', '#C8FF3E'],
        ['#1a0a2a', '#FF3EA5', '#FFD93E'],
      ];
  const p = palettes[index % palettes.length];
  const isWide = item.span === 'wide';
  return (
    <a href="#contact" className="reveal media-tile chrome-card"
       style={{
         gridColumn: isWide ? 'span 2' : 'span 1',
         aspectRatio: isWide ? '2 / 1' : '4 / 5',
         position: 'relative', overflow: 'hidden',
         padding: 0, textDecoration: 'none', color: 'var(--ink)',
         display: 'block'
       }}>
      {item.image ? (
        <img src={item.image} alt={item.title || ''} loading="lazy"
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      ) : (
        <div style={{
          position: 'absolute', inset: 0,
          background: `conic-gradient(from ${(index * 47) % 360}deg at 50% 50%,
            ${p[0]} 0deg, ${p[1]} 120deg, ${p[2]} 240deg, ${p[0]} 360deg)`,
          backgroundSize: '180% 180%',
          animation: `iridShift ${10 + index}s linear infinite`,
          filter: 'saturate(1.15)',
        }} />
      )}
      {/* Overlay con datos */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        padding: 20,
        background: 'linear-gradient(to top, rgba(20,20,32,0.78), transparent)',
        color: 'white',
        display: 'flex', justifyContent: 'space-between', alignItems: 'end',
        gap: 12
      }}>
        <div>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.16em',
            textTransform: 'uppercase', opacity: 0.85, marginBottom: 4
          }}>{item.tag}</div>
          <div className="display" style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>
            {item.title}
          </div>
        </div>
        <Icon name="arrow-up-right" size={18} color="white" />
      </div>
    </a>
  );
}

Object.assign(window, { Media });
