// screens/Galeria.jsx — LA HOME: vitrina/galería de las piezas de La Vid.
//
// Concepto: muro de museo nocturno. Las piezas SON la interfaz — la última
// generación abre la sala a ancho completo y el resto respira en mosaico de dos
// columnas. Nada de tarjetas con bordes: la obra a sangre, el nombre del diseño
// en Fraunces itálica solo al abrir el visor. El estado vacío ENSEÑA: marcos
// fantasma con los nombres de los 8 diseños invitan a generar la primera pieza.
//
// Persistencia: SOLO el dispositivo (galeriaDB/IndexedDB). El servidor no
// guarda nada — lo que no esté aquí, no existe.

function ChipGPU() {
  const [estado, setEstado] = React.useState(null);
  const [liberando, setLiberando] = React.useState(false);

  const refrescar = React.useCallback(() => {
    window.estudioAPI.gpuEstado().then(setEstado).catch(() => setEstado(null));
  }, []);

  React.useEffect(() => {
    refrescar();
    const t = setInterval(refrescar, 30000);
    return () => clearInterval(t);
  }, [refrescar]);

  if (!estado) return null;
  const viva = estado.comfyui_vivo;
  const pct = estado.vram && estado.vram.pct != null ? estado.vram.pct : null;

  const liberar = async () => {
    if (!viva || liberando) return;
    setLiberando(true);
    try { await window.estudioAPI.gpuLiberar(true); } catch {}
    setLiberando(false);
    refrescar();
  };

  return (
    <button onClick={liberar} title={viva ? 'Tocar para liberar la VRAM' : 'GPU en reposo'}
      style={{
        display: 'flex', alignItems: 'center', gap: 6,
        height: 28, padding: '0 10px', borderRadius: 14,
        background: 'rgba(255,255,255,0.04)',
        border: '1px solid rgba(255,255,255,0.08)',
        cursor: viva ? 'pointer' : 'default',
      }}>
      <div style={{
        width: 6, height: 6, borderRadius: '50%',
        background: liberando ? '#FBBF24' : (viva ? '#86EFAC' : 'rgba(232,220,196,0.4)'),
        boxShadow: viva ? '0 0 8px rgba(134,239,172,0.5)' : 'none',
        animation: liberando ? 'hlbreathe 1s ease-in-out infinite' : 'none',
      }} />
      <span style={{
        fontFamily: 'var(--hl-font-mono)', fontSize: 9, letterSpacing: 1,
        color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase',
      }}>
        {liberando ? 'Liberando' : (viva ? (pct != null ? `GPU ${pct}%` : 'GPU activa') : 'GPU libre')}
      </span>
    </button>
  );
}

// Marco de una pieza en el muro. `hero` = la última generación, a ancho completo.
function MarcoPieza({ pieza, hero, onAbrir, retraso }) {
  return (
    <button onClick={() => onAbrir(pieza)} style={{
      display: 'block', width: '100%', padding: 0, border: 'none',
      background: 'transparent', cursor: 'pointer',
      breakInside: 'avoid', marginBottom: 10,
      animation: `hlfadeUp 0.6s cubic-bezier(0.22,1,0.36,1) ${retraso}s both`,
    }}>
      <img src={pieza.imagen} alt={pieza.titulo} loading="lazy" style={{
        width: '100%', display: 'block',
        aspectRatio: '1080 / 1350', objectFit: 'cover',
        borderRadius: hero ? 18 : 12,
        boxShadow: hero
          ? '0 24px 60px rgba(8,5,26,0.8), 0 0 0 1px rgba(221,214,254,0.08)'
          : '0 10px 30px rgba(8,5,26,0.6)',
      }} />
      {hero && (
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          padding: '10px 4px 0',
        }}>
          <span style={{
            fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
            fontSize: 16, color: 'var(--parchment, #E8DCC4)', letterSpacing: -0.3,
          }}>{pieza.titulo}</span>
          <span style={{
            fontFamily: 'var(--hl-font-mono)', fontSize: 9, letterSpacing: 1,
            color: 'rgba(255,255,255,0.3)', textTransform: 'uppercase',
          }}>{new Date(pieza.creadaEn).toLocaleDateString('es-ES', { day: 'numeric', month: 'long' })}</span>
        </div>
      )}
    </button>
  );
}

// Estado vacío que ENSEÑA: los 8 diseños como marcos fantasma de la sala.
function SalaVacia({ onGenerar }) {
  const disenos = ['Velo Clásico', 'Filete Refinado', 'Ficha Dorada', 'Nobleza Imperial',
                   'La Palabra Primero', 'Cielo Sereno', 'Vidriera', 'Mitad y Mitad'];
  return (
    <div style={{ padding: '8px 0 32px' }}>
      <div style={{ columnCount: 2, columnGap: 10 }}>
        {disenos.map((n, i) => (
          <div key={n} style={{
            breakInside: 'avoid', marginBottom: 10,
            aspectRatio: '1080 / 1350',
            height: i % 3 === 1 ? undefined : undefined,
            borderRadius: 12,
            border: '1px dashed rgba(221,214,254,0.14)',
            display: 'flex', alignItems: 'flex-end',
            padding: 14,
            background: `linear-gradient(${160 + i * 12}deg, rgba(168,85,247,${0.04 + (i % 4) * 0.012}) 0%, rgba(8,5,26,0) 70%)`,
            animation: `hlfadeUp 0.6s cubic-bezier(0.22,1,0.36,1) ${0.08 * i}s both`,
          }}>
            <span style={{
              fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
              fontSize: 14, color: 'rgba(232,220,196,0.35)', letterSpacing: -0.2,
              lineHeight: 1.2,
            }}>{n}</span>
          </div>
        ))}
      </div>
      <div style={{ textAlign: 'center', marginTop: 26 }}>
        <div style={{
          fontFamily: 'var(--hl-font-display)', fontSize: 21, fontWeight: 300,
          color: 'rgba(255,255,255,0.85)', letterSpacing: -0.4, marginBottom: 6,
        }}>La sala espera su primera obra.</div>
        <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.45)', marginBottom: 18 }}>
          Ocho diseños de La Vid listos para componer.
        </div>
        <button onClick={onGenerar} style={{
          height: 48, padding: '0 28px', borderRadius: 15, border: 'none',
          background: 'linear-gradient(135deg, #B45EFF 0%, #7C3AED 50%, #4F1FCB 100%)',
          color: '#fff', fontSize: 15, fontWeight: 600,
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2, cursor: 'pointer',
          boxShadow: '0 10px 30px rgba(168,85,247,0.35)',
        }}>Generar la primera pieza</button>
      </div>
    </div>
  );
}

// Visor a pantalla completa: la obra, su ficha y las acciones.
function VisorPieza({ pieza, onCerrar, onEliminar, onRetocar }) {
  const [confirmando, setConfirmando] = React.useState(false);
  // El muro trae la miniatura; aquí se pide la pieza COMPLETA (PNG + A4) a la
  // galería Postgres. Mientras llega, se enseña la miniatura como placeholder.
  const [completa, setCompleta] = React.useState(null);

  React.useEffect(() => {
    let viva = true;
    window.galeriaDB.obtener(pieza.id)
      .then(d => { if (viva) setCompleta(d); })
      .catch(() => {});
    return () => { viva = false; };
  }, [pieza.id]);

  const imagen = (completa && completa.imagen) || pieza.imagen;

  const descargar = () => window.descargarDataURL(
    imagen, `lavid-${pieza.tipo}-${new Date(pieza.creadaEn).toISOString().slice(0, 10)}.png`);

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 60,
      background: 'rgba(4,2,14,0.94)',
      backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
      display: 'flex', flexDirection: 'column',
      animation: 'hlfade 0.25s ease both',
    }}>
      <div style={{ height: 'calc(var(--safe-top, 44px) + 6px)', flexShrink: 0 }} />
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '6px 18px 10px', flexShrink: 0,
      }}>
        <div>
          <div style={{
            fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
            fontSize: 19, color: '#fff', letterSpacing: -0.4,
          }}>{pieza.titulo}</div>
          <div style={{
            fontFamily: 'var(--hl-font-mono)', fontSize: 9.5, letterSpacing: 1,
            color: 'rgba(255,255,255,0.4)', textTransform: 'uppercase', marginTop: 3,
          }}>{pieza.subtitulo} · {new Date(pieza.creadaEn).toLocaleDateString('es-ES', { day: 'numeric', month: 'long', year: 'numeric' })}</div>
        </div>
        <button onClick={onCerrar} style={{
          width: 34, height: 34, borderRadius: 10, border: 'none',
          background: 'rgba(255,255,255,0.07)', color: 'rgba(255,255,255,0.75)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
            <path d="M2 2l10 10M12 2L2 12" />
          </svg>
        </button>
      </div>

      <div style={{
        flex: 1, overflow: 'hidden', display: 'flex',
        alignItems: 'center', justifyContent: 'center', padding: '4px 18px 8px',
        minHeight: 0,
      }}>
        <img src={imagen} alt={pieza.titulo} style={{
          maxWidth: '100%', maxHeight: '100%', width: 'auto', height: 'auto',
          objectFit: 'contain',
          borderRadius: 14, boxShadow: '0 30px 80px rgba(0,0,0,0.7)',
          filter: completa ? 'none' : 'blur(2px)',
          transition: 'filter 0.3s ease',
        }} />
      </div>

      <div style={{
        flexShrink: 0, display: 'flex', gap: 10,
        padding: '16px 18px calc(14px + var(--safe-bottom, 16px))',
      }}>
        <button onClick={descargar} style={{
          flex: 1, height: 48, borderRadius: 14, border: 'none',
          background: 'linear-gradient(135deg, #B45EFF 0%, #4F1FCB 100%)',
          color: '#fff', fontSize: 14, fontWeight: 600,
          fontFamily: 'var(--hl-font-ui)', cursor: 'pointer', letterSpacing: -0.2,
        }}>Descargar PNG</button>
        {onRetocar && (
          <button onClick={() => onRetocar(pieza)} title="Retocar" style={{
            height: 48, padding: '0 15px', borderRadius: 14,
            border: '1px solid rgba(221,214,254,0.25)', background: 'transparent',
            color: 'var(--hl-accent-light)', fontSize: 13.5, fontWeight: 500,
            fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 7,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 20h9" /><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" />
            </svg>
            Retocar
          </button>
        )}
        <button onClick={() => confirmando ? (onEliminar(pieza), onCerrar()) : setConfirmando(true)}
          style={{
            height: 48, padding: '0 16px', borderRadius: 14,
            border: `1px solid ${confirmando ? 'rgba(177,74,96,0.7)' : 'rgba(255,255,255,0.12)'}`,
            background: confirmando ? 'rgba(177,74,96,0.18)' : 'transparent',
            color: confirmando ? '#E89AA9' : 'rgba(255,255,255,0.5)',
            fontSize: 13, fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
          }}>{confirmando ? '¿Seguro?' : 'Eliminar'}</button>
      </div>
    </div>
  );
}

function GaleriaScreen({ onGenerar, onHolyrics, onAjustes, onProfile, onRetocar }) {
  const [piezas, setPiezas] = React.useState(null);   // null = cargando
  const [abierta, setAbierta] = React.useState(null);

  const recargar = React.useCallback(() => {
    window.galeriaDB.listar().then(setPiezas).catch(() => setPiezas([]));
  }, []);
  React.useEffect(recargar, [recargar]);

  const eliminar = async (pieza) => {
    await window.galeriaDB.borrar(pieza.id);
    recargar();
  };

  const hero = piezas && piezas.length > 0 ? piezas[0] : null;
  const resto = piezas && piezas.length > 1 ? piezas.slice(1) : [];

  return (
    <div style={{
      height: '100%', overflowY: 'auto', overflowX: 'hidden',
      background: 'linear-gradient(180deg, #0C0724 0%, #08051A 50%, #04020E 100%)',
      position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: -140, left: '30%', width: 360, height: 360,
        borderRadius: '50%', filter: 'blur(150px)', opacity: 0.16, pointerEvents: 'none',
        background: 'radial-gradient(circle, #A855F7, transparent 70%)',
      }} />

      <div style={{ height: 'calc(var(--safe-top, 44px) + 14px)' }} />

      <div style={{ position: 'relative', zIndex: 2, padding: '14px 16px 40px' }}>
        {/* Cabecera de sala */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', padding: '0 4px' }}>
          <div>
            <div style={{
              fontFamily: 'var(--hl-font-mono)', fontSize: 10,
              color: 'var(--hl-accent-light)', letterSpacing: 2.2,
              textTransform: 'uppercase', fontWeight: 500, marginBottom: 7,
            }}>Estudio La Vid</div>
            <div style={{
              fontFamily: 'var(--hl-font-display)', fontSize: 40, fontWeight: 300,
              color: '#fff', letterSpacing: -1.4, lineHeight: 0.98,
            }}>La <span style={{ fontStyle: 'italic', fontWeight: 400 }}>galería</span></div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, marginTop: 2 }}>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={onAjustes} title="Ajustes del estudio" style={{
                width: 34, height: 34, borderRadius: 10, border: 'none',
                background: 'rgba(255,255,255,0.05)', color: 'rgba(255,255,255,0.6)',
                cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="3" />
                  <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
                </svg>
              </button>
              <button onClick={onHolyrics} title="HolyLyrics" style={{
                width: 34, height: 34, borderRadius: 10, border: 'none',
                background: 'rgba(255,255,255,0.05)', color: 'rgba(255,255,255,0.6)',
                cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M9 18V5l12-2v13" /><circle cx="6" cy="18" r="3" /><circle cx="18" cy="16" r="3" />
                </svg>
              </button>
              <button onClick={onProfile} title="Perfil" style={{
                width: 34, height: 34, borderRadius: 10, border: 'none',
                background: 'rgba(255,255,255,0.05)', color: 'rgba(255,255,255,0.6)',
                cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" />
                </svg>
              </button>
            </div>
            <ChipGPU />
          </div>
        </div>

        {/* CTA flotante de generación — siempre visible bajo la cabecera */}
        {piezas && piezas.length > 0 && (
          <button onClick={onGenerar} style={{
            marginTop: 18, marginBottom: 18, width: '100%', height: 50,
            borderRadius: 15, border: 'none',
            background: 'linear-gradient(135deg, #B45EFF 0%, #7C3AED 50%, #4F1FCB 100%)',
            color: '#fff', fontSize: 15, fontWeight: 600,
            fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2, cursor: 'pointer',
            boxShadow: '0 10px 30px rgba(168,85,247,0.32)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
          }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M8 2v12M2 8h12" stroke="white" strokeWidth="2" strokeLinecap="round" />
            </svg>
            Generar nueva pieza
          </button>
        )}

        {/* El muro */}
        {piezas === null && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '40px 4px',
            color: 'rgba(255,255,255,0.4)', fontSize: 13,
          }}>
            <div style={{
              width: 14, height: 14, borderRadius: '50%',
              border: '2px solid rgba(168,85,247,0.4)', borderTopColor: 'var(--hl-accent-1)',
              animation: 'hlspin 0.7s linear infinite',
            }} />
            Abriendo la sala…
          </div>
        )}

        {piezas && piezas.length === 0 && (
          <div style={{ marginTop: 22 }}>
            <SalaVacia onGenerar={onGenerar} />
          </div>
        )}

        {hero && (
          <MarcoPieza pieza={hero} hero onAbrir={setAbierta} retraso={0.05} />
        )}
        {resto.length > 0 && (
          // CSS Grid (no columnCount): el orden visual = orden del array. Con
          // columnCount, CSS rellena una columna entera antes que la otra y el
          // usuario clicaba una posición que no correspondía a esa pieza.
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14,
            alignItems: 'start',
          }}>
            {resto.map((p, i) => (
              <MarcoPieza key={p.id} pieza={p} hero={false} onAbrir={setAbierta}
                retraso={0.08 + i * 0.05} />
            ))}
          </div>
        )}
      </div>

      {abierta && (
        <VisorPieza pieza={abierta} onCerrar={() => setAbierta(null)} onEliminar={eliminar}
          onRetocar={onRetocar ? (p) => { setAbierta(null); onRetocar(p); } : null} />
      )}
    </div>
  );
}

Object.assign(window, { GaleriaScreen });
