// screens/Estudio.jsx — El estudio: compone una pieza REAL contra el backend.
//
// Tres pasos: 1) qué pieza (célula o evento, catálogo ADORNADO del backend),
// 2) sus datos (célula real + diseño con nombre propio / campos del evento),
// 3) el fondo (ambiente IA · idea propia redactada por claude · foto subida).
// Generar = POST /componer → polling → la pieza vuelve en base64, se guarda en
// la galería del DISPOSITIVO y se ofrece la descarga. El servidor no retiene nada.

const ESTUDIO_INPUT = (foco) => ({
  width: '100%', height: 46, padding: '0 14px',
  background: foco ? 'rgba(168,85,247,0.08)' : 'rgba(255,255,255,0.04)',
  border: `1px solid ${foco ? 'rgba(192,132,252,0.5)' : 'rgba(255,255,255,0.07)'}`,
  borderRadius: 12, color: '#fff', fontSize: 15,
  fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2,
  outline: 'none', transition: 'all 0.2s ease', boxSizing: 'border-box',
});

function PasosEstudio({ paso }) {
  return (
    <div style={{ display: 'flex', gap: 5 }}>
      {[0, 1, 2].map(i => (
        <div key={i} style={{
          height: 3, borderRadius: 2, width: i === paso ? 20 : 12,
          background: i <= paso ? 'var(--hl-accent-1)' : 'rgba(255,255,255,0.15)',
          transition: 'all 0.3s ease',
        }} />
      ))}
    </div>
  );
}

// Tarjeta de elección adornada (pieza, diseño, ambiente) — nombre propio +
// descripción; la clave técnica nunca se enseña.
function OpcionAdornada({ nombre, descripcion, activa, onElegir, compacta }) {
  return (
    <button onClick={onElegir} style={{
      textAlign: 'left', width: '100%',
      padding: compacta ? '11px 13px' : '14px 15px',
      background: activa ? 'rgba(168,85,247,0.12)' : 'rgba(255,255,255,0.03)',
      border: `1px solid ${activa ? 'rgba(192,132,252,0.45)' : 'rgba(255,255,255,0.07)'}`,
      borderRadius: 13, cursor: 'pointer', transition: 'all 0.16s ease',
    }}>
      <div style={{
        fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
        fontSize: compacta ? 14.5 : 16, fontWeight: 400,
        color: activa ? 'var(--hl-accent-light)' : 'rgba(255,255,255,0.92)',
        letterSpacing: -0.3, marginBottom: descripcion ? 4 : 0,
      }}>{nombre}</div>
      {descripcion && (
        <div style={{
          fontSize: 11.5, color: 'rgba(255,255,255,0.42)', lineHeight: 1.45,
          letterSpacing: -0.1,
        }}>{descripcion}</div>
      )}
    </button>
  );
}

function EstudioScreen({ onBack, onGuardada }) {
  const [catalogo, setCatalogo] = React.useState(null);
  const [celulas, setCelulas] = React.useState([]);
  const [errorCarga, setErrorCarga] = React.useState(null);

  const [paso, setPaso] = React.useState(0);
  const [foco, setFoco] = React.useState(null);

  // Paso 0 — qué pieza
  const [tipoPieza, setTipoPieza] = React.useState(null); // 'celula' | tipo de evento
  // Paso 1 — datos
  const [celula, setCelula] = React.useState(null);
  const [diseno, setDiseno] = React.useState(null);       // clave v1..v8
  // Ajustes finos del composer (variables dinámicas): velo, brillo, colores.
  // Vacío = el diseño usa sus defaults de siempre.
  const [ajustes, setAjustes] = React.useState({});
  const [verAjustes, setVerAjustes] = React.useState(false);
  const [campos, setCampos] = React.useState({});
  // Datos de célula EDITABLES: elegir una célula los precarga, pero todo lo que
  // el composer pinta (nombre, horario, dirección, anfitrión) se puede cambiar.
  const [datosCelula, setDatosCelula] = React.useState({
    nombre: '', horario: '', direccion: '', anfitrion: '',
  });
  const elegirCelula = (c) => {
    setCelula(c);
    setDatosCelula({
      nombre: c.nombre || '', horario: c.horario || '',
      direccion: c.direccion || '', anfitrion: c.anfitrion || '',
    });
  };
  // Paso 2 — fondo
  const [modoFondo, setModoFondo] = React.useState('ambiente'); // ambiente|idea|foto|ninguno
  const [ambiente, setAmbiente] = React.useState(null);
  const [idea, setIdea] = React.useState('');
  const [promptRedactado, setPromptRedactado] = React.useState(null);
  const [redactando, setRedactando] = React.useState(false);
  const [fondoClave, setFondoClave] = React.useState(null);
  const [fondoPreview, setFondoPreview] = React.useState(null);
  const [generandoFondo, setGenerandoFondo] = React.useState(null); // texto de estado
  // Generación final
  const [generando, setGenerando] = React.useState(null);  // texto de estado
  const [resultado, setResultado] = React.useState(null);  // pieza guardada
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    Promise.all([window.estudioAPI.composers(), window.estudioAPI.celulas()])
      .then(([c, ce]) => { setCatalogo(c); setCelulas(ce.celulas || []); })
      .catch(e => setErrorCarga(e.message));
  }, []);

  const esCelula = tipoPieza === 'celula';
  const plantilla = catalogo && !esCelula
    ? (catalogo.plantillas_evento || []).find(p => p.clave === tipoPieza) : null;

  const puedeAvanzar0 = !!tipoPieza;
  const puedeAvanzar1 = esCelula
    ? (!!diseno && ['nombre', 'horario', 'direccion', 'anfitrion']
        .every(k => (datosCelula[k] || '').trim().length > 0))
    : !!plantilla && plantilla.campos.every(c =>
        c.tipo === 'select' || (campos[c.clave] || '').trim().length > 0);

  // ── Fondo: generar con IA (ambiente o idea redactada) ─────────────────────
  const generarFondo = async () => {
    setError(null);
    const clave = `app-${Date.now().toString(36)}`;
    try {
      let cuerpo;
      if (modoFondo === 'ambiente') {
        if (!ambiente) return;
        cuerpo = { clave, ambiente };
      } else {
        if (!promptRedactado) return;
        cuerpo = { clave, prompt: promptRedactado };
      }
      setGenerandoFondo('Encolando…');
      const { trabajo_id } = await window.estudioAPI.generarFondo(cuerpo);
      const d = await window.estudioAPI.esperarTrabajo(trabajo_id, (e) => {
        setGenerandoFondo(e === 'procesando'
          ? 'Generando el fondo (la GPU puede tardar 1-2 min)…' : 'En cola…');
      });
      setFondoClave(clave);
      setFondoPreview(d.imagen || null);
      setGenerandoFondo(null);
    } catch (e) {
      setGenerandoFondo(null);
      setError(e.message);
    }
  };

  const redactar = async () => {
    if (idea.trim().length < 4 || redactando) return;
    setError(null);
    setRedactando(true);
    try {
      const d = await window.estudioAPI.redactarPrompt(idea.trim(), tipoPieza);
      setPromptRedactado(d.prompt);
    } catch (e) { setError(e.message); }
    setRedactando(false);
  };

  const subirFoto = (archivo) => {
    if (!archivo) return;
    setError(null);
    const lector = new FileReader();
    lector.onload = async () => {
      const clave = `foto-${Date.now().toString(36)}`;
      try {
        setGenerandoFondo('Subiendo tu foto…');
        await window.estudioAPI.subirFoto(clave, lector.result);
        setFondoClave(clave);
        setFondoPreview(lector.result);
        setGenerandoFondo(null);
      } catch (e) {
        setGenerandoFondo(null);
        setError(e.message);
      }
    };
    lector.readAsDataURL(archivo);
  };

  // ── Generar la pieza final ────────────────────────────────────────────────
  const generarPieza = async () => {
    setError(null);
    setGenerando('Encolando…');
    try {
      // Célula: van los campos SUELTOS (editados por el usuario), no la clave —
      // así lo que se ve en el formulario es exactamente lo que el composer pinta.
      // Solo se mandan los ajustes que el usuario tocó (los demás = defaults).
      const ajustesLimpios = Object.fromEntries(
        Object.entries(ajustes).filter(([, v]) => v !== undefined && v !== '' && v !== null));
      const datos = esCelula
        ? { ...datosCelula, estilo: diseno,
            ...(Object.keys(ajustesLimpios).length ? { ajustes: ajustesLimpios } : {}) }
        : { ...campos };
      const fondo = modoFondo === 'ninguno' ? null : fondoClave;
      const { trabajo_id } = await window.estudioAPI.componer(
        esCelula ? 'celula' : tipoPieza, datos, fondo, true);
      const d = await window.estudioAPI.esperarTrabajo(trabajo_id, (e) => {
        setGenerando(e === 'procesando' ? 'Componiendo la pieza…' : 'En cola…');
      });

      const nombreDiseno = esCelula
        ? (catalogo.disenos_celula.find(x => x.clave === diseno) || {}).nombre
        : plantilla.nombre;
      const pieza = {
        id: trabajo_id,
        creadaEn: Date.now(),
        tipo: esCelula ? 'celula' : tipoPieza,
        titulo: nombreDiseno || 'Pieza La Vid',
        subtitulo: esCelula ? `Célula ${datosCelula.nombre}` : 'Evento',
        imagen: d.imagen,
      };
      // Persistencia ÚNICA: el dispositivo. El servidor purga su copia en minutos.
      await window.galeriaDB.guardar(pieza);
      setResultado(pieza);
      setGenerando(null);
    } catch (e) {
      setGenerando(null);
      setError(e.message);
    }
  };

  // ── Pantalla de resultado ─────────────────────────────────────────────────
  if (resultado) {
    return (
      <div style={{
        height: '100%', display: 'flex', flexDirection: 'column',
        background: 'linear-gradient(180deg, #0C0724 0%, #08051A 55%, #04020E 100%)',
      }}>
        <div style={{ height: 'calc(var(--safe-top, 44px) + 16px)' }} />
        <div style={{ textAlign: 'center', padding: '4px 24px 14px' }}>
          <div style={{
            fontFamily: 'var(--hl-font-mono)', fontSize: 9.5, letterSpacing: 2,
            color: 'var(--candlelight, #F5C56B)', textTransform: 'uppercase', marginBottom: 8,
          }}>Guardada en tu galería</div>
          <div style={{
            fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
            fontSize: 26, fontWeight: 300, color: '#fff', letterSpacing: -0.6,
          }}>{resultado.titulo}</div>
        </div>
        <div style={{
          flex: 1, overflow: 'hidden', display: 'flex',
          alignItems: 'center', justifyContent: 'center', padding: '0 26px',
        }}>
          <img src={resultado.imagen} alt={resultado.titulo} style={{
            maxWidth: '100%', maxHeight: '100%', borderRadius: 16,
            boxShadow: '0 30px 80px rgba(0,0,0,0.7), 0 0 0 1px rgba(221,214,254,0.1)',
            animation: 'hlpop 0.5s cubic-bezier(0.34,1.56,0.64,1) both',
          }} />
        </div>
        <div style={{
          flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 10,
          padding: '18px 20px calc(14px + var(--safe-bottom, 16px))',
        }}>
          <button onClick={() => window.descargarDataURL(
            resultado.imagen, `lavid-${resultado.tipo}.png`)} style={{
            height: 50, borderRadius: 15, border: 'none',
            background: 'linear-gradient(135deg, #B45EFF 0%, #4F1FCB 100%)',
            color: '#fff', fontSize: 15, fontWeight: 600,
            fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
          }}>Descargar PNG</button>
          <div style={{ display: 'flex', gap: 10 }}>
            <button onClick={() => {
              setResultado(null); setPaso(0); setTipoPieza(null); setCelula(null);
              setDiseno(null); setCampos({}); setFondoClave(null); setFondoPreview(null);
              setPromptRedactado(null); setIdea(''); setAmbiente(null);
            }} style={{
              flex: 1, height: 44, borderRadius: 13,
              border: '1px solid rgba(255,255,255,0.12)', background: 'transparent',
              color: 'rgba(255,255,255,0.65)', fontSize: 13.5, fontWeight: 500,
              fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
            }}>Otra pieza</button>
            <button onClick={onGuardada} style={{
              flex: 1, height: 44, borderRadius: 13,
              border: '1px solid rgba(255,255,255,0.12)', background: 'transparent',
              color: 'rgba(255,255,255,0.65)', fontSize: 13.5, fontWeight: 500,
              fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
            }}>A la galería</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden',
      background: 'linear-gradient(180deg, #0C0724 0%, #08051A 55%, #04020E 100%)',
      position: 'relative',
    }}>
      {/* Cabecera */}
      <div style={{ flexShrink: 0 }}>
        <div style={{ height: 'calc(var(--safe-top, 44px) + 8px)' }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 20px 12px' }}>
          <button onClick={paso === 0 ? onBack : () => setPaso(p => p - 1)} style={{
            width: 36, height: 36, borderRadius: 10, border: 'none', padding: 0,
            background: 'rgba(255,255,255,0.05)', color: 'rgba(255,255,255,0.7)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="15 18 9 12 15 6" />
            </svg>
          </button>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: 'var(--hl-font-display)', fontSize: 20, fontWeight: 400,
              color: '#fff', letterSpacing: -0.5, fontStyle: 'italic',
            }}>El estudio</div>
          </div>
          <PasosEstudio paso={paso} />
        </div>
        <div style={{ height: 1, background: 'rgba(255,255,255,0.05)' }} />
      </div>

      {/* Contenido */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '0 20px' }}>
        {errorCarga && (
          <div style={{
            marginTop: 24, padding: '14px 16px', borderRadius: 13,
            background: 'rgba(177,74,96,0.12)', border: '1px solid rgba(177,74,96,0.3)',
            color: '#E8B4BE', fontSize: 13, lineHeight: 1.5,
          }}>No llego al estudio: {errorCarga}</div>
        )}
        {!catalogo && !errorCarga && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '28px 0',
            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 el estudio…
          </div>
        )}

        {/* PASO 0 — qué pieza */}
        {catalogo && paso === 0 && (
          <div className="hl-stagger" style={{ padding: '22px 0 24px' }}>
            <div style={{
              fontFamily: 'var(--hl-font-ui)', fontSize: 17, fontWeight: 600,
              color: '#fff', letterSpacing: -0.4, marginBottom: 18,
            }}>¿Qué pieza compone hoy?</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              <OpcionAdornada nombre="Célula"
                descripcion="La ficha de un grupo de hogar, en uno de los ocho diseños de La Vid."
                activa={tipoPieza === 'celula'} onElegir={() => setTipoPieza('celula')} />
              {(catalogo.plantillas_evento || []).map(p => (
                <OpcionAdornada key={p.clave} nombre={p.nombre} descripcion={p.descripcion}
                  activa={tipoPieza === p.clave} onElegir={() => setTipoPieza(p.clave)} />
              ))}
            </div>
          </div>
        )}

        {/* PASO 1 — datos */}
        {catalogo && paso === 1 && esCelula && (
          <div className="hl-stagger" style={{ padding: '22px 0 24px' }}>
            <div style={{
              fontFamily: 'var(--hl-font-ui)', fontSize: 17, fontWeight: 600,
              color: '#fff', letterSpacing: -0.4, marginBottom: 6,
            }}>La célula</div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.45)', marginBottom: 14 }}>
              Elige una para precargar sus datos — luego edita lo que quieras.
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 20 }}>
              {celulas.map(c => (
                <OpcionAdornada key={c.clave} compacta nombre={c.nombre}
                  descripcion={`${c.horario} · ${c.direccion}`}
                  activa={celula && celula.clave === c.clave}
                  onElegir={() => elegirCelula(c)} />
              ))}
            </div>

            {/* Lo que el composer pinta, EDITABLE campo a campo */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 13, marginBottom: 24 }}>
              {[['nombre', 'Nombre de la célula'], ['horario', 'Horario'],
                ['direccion', 'Dirección'], ['anfitrion', 'Anfitrión']].map(([k, etiqueta]) => (
                <div key={k}>
                  <label style={{
                    display: 'block', fontFamily: 'var(--hl-font-mono)', fontSize: 9.5,
                    color: 'rgba(255,255,255,0.45)', letterSpacing: 1.5,
                    textTransform: 'uppercase', marginBottom: 7,
                  }}>{etiqueta}</label>
                  <input type="text" value={datosCelula[k]}
                    onChange={e => setDatosCelula(prev => ({ ...prev, [k]: e.target.value }))}
                    onFocus={() => setFoco('c-' + k)} onBlur={() => setFoco(null)}
                    style={ESTUDIO_INPUT(foco === 'c-' + k)} />
                </div>
              ))}
            </div>
            <div style={{
              fontFamily: 'var(--hl-font-ui)', fontSize: 17, fontWeight: 600,
              color: '#fff', letterSpacing: -0.4, marginBottom: 6,
            }}>El diseño</div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.45)', marginBottom: 14 }}>
              Ocho miradas de la misma casa. Elige cómo se viste la pieza.
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 9 }}>
              {(catalogo.disenos_celula || []).map(d => (
                <OpcionAdornada key={d.clave} compacta nombre={d.nombre}
                  descripcion={d.descripcion}
                  activa={diseno === d.clave} onElegir={() => setDiseno(d.clave)} />
              ))}
            </div>

            {/* Ajustes finos del composer (variables dinámicas) — plegable */}
            {diseno && (
              <div style={{ marginTop: 18 }}>
                <button onClick={() => setVerAjustes(v => !v)} style={{
                  display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                  padding: '10px 2px', background: 'none', border: 'none', cursor: 'pointer',
                }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--hl-accent-light)" strokeWidth="2" strokeLinecap="round"
                    style={{ transform: verAjustes ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s' }}>
                    <polyline points="9 18 15 12 9 6" />
                  </svg>
                  <span style={{
                    fontFamily: 'var(--hl-font-mono)', fontSize: 10, letterSpacing: 1.5,
                    textTransform: 'uppercase', color: 'var(--hl-accent-light)',
                  }}>Ajustes finos del diseño</span>
                  {Object.keys(ajustes).length > 0 && (
                    <span style={{
                      marginLeft: 'auto', fontSize: 9, fontFamily: 'var(--hl-font-mono)',
                      color: 'var(--candlelight, #F5C56B)',
                    }}>{Object.keys(ajustes).length} activos</span>
                  )}
                </button>
                <div style={{
                  display: 'grid', gridTemplateRows: verAjustes ? '1fr' : '0fr',
                  transition: 'grid-template-rows 0.28s cubic-bezier(0.22,1,0.36,1)',
                }}>
                  <div style={{ overflow: 'hidden' }}>
                    <div style={{ padding: '8px 2px 0' }}>
                      {/* Sliders de velo y brillo */}
                      {[
                        { k: 'velo', et: 'Intensidad del velo', min: 0.15, max: 0.6, paso: 0.01, def: 0.4 },
                        { k: 'brillo', et: 'Brillo de la foto', min: 45, max: 90, paso: 1, def: 70 },
                      ].map(s => {
                        const v = ajustes[s.k] !== undefined ? ajustes[s.k] : s.def;
                        return (
                          <div key={s.k} style={{ marginBottom: 14 }}>
                            <div style={{
                              display: 'flex', justifyContent: 'space-between',
                              fontFamily: 'var(--hl-font-mono)', fontSize: 9.5, letterSpacing: 1,
                              textTransform: 'uppercase', color: 'rgba(255,255,255,0.45)', marginBottom: 7,
                            }}>
                              <span>{s.et}</span>
                              {ajustes[s.k] !== undefined && (
                                <button onClick={() => setAjustes(p => { const n = { ...p }; delete n[s.k]; return n; })}
                                  style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.4)', cursor: 'pointer', fontSize: 9 }}>↺</button>
                              )}
                            </div>
                            <input type="range" min={s.min} max={s.max} step={s.paso} value={v}
                              onChange={e => setAjustes(p => ({ ...p, [s.k]: s.k === 'brillo' ? parseInt(e.target.value) : parseFloat(e.target.value) }))}
                              style={{
                                width: '100%', height: 3, appearance: 'none', WebkitAppearance: 'none',
                                borderRadius: 2, cursor: 'pointer',
                                background: `linear-gradient(90deg, var(--hl-accent-1) ${((v - s.min) / (s.max - s.min)) * 100}%, rgba(255,255,255,0.1) ${((v - s.min) / (s.max - s.min)) * 100}%)`,
                              }} />
                          </div>
                        );
                      })}
                      {/* Color del velo */}
                      <div style={{ marginTop: 4 }}>
                        <div style={{
                          fontFamily: 'var(--hl-font-mono)', fontSize: 9.5, letterSpacing: 1,
                          textTransform: 'uppercase', color: 'rgba(255,255,255,0.45)', marginBottom: 9,
                        }}>Color del velo</div>
                        <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
                          {[['', 'Violeta'], ['#1E7A3C', 'Verde'], ['#B14A60', 'Vino'], ['#1E5A8A', 'Azul'], ['#9A6A1E', 'Ámbar']].map(([c, n]) => {
                            const on = (ajustes.color_primario || '') === c;
                            return (
                              <button key={n} onClick={() => setAjustes(p => {
                                const next = { ...p };
                                if (c === '') delete next.color_primario; else next.color_primario = c;
                                return next;
                              })} title={n} style={{
                                width: 32, height: 32, borderRadius: 9, cursor: 'pointer',
                                background: c || '#6B46C1',
                                border: on ? '2px solid #fff' : '1px solid rgba(255,255,255,0.2)',
                              }} />
                            );
                          })}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {catalogo && paso === 1 && !esCelula && plantilla && (
          <div className="hl-stagger" style={{ padding: '22px 0 24px' }}>
            <div style={{
              fontFamily: 'var(--hl-font-ui)', fontSize: 17, fontWeight: 600,
              color: '#fff', letterSpacing: -0.4, marginBottom: 4,
            }}>{plantilla.nombre}</div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.45)', marginBottom: 18 }}>
              {plantilla.descripcion}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {plantilla.campos.filter(c => c.tipo !== 'select').map(c => (
                <div key={c.clave}>
                  <label style={{
                    display: 'block', fontFamily: 'var(--hl-font-mono)', fontSize: 9.5,
                    color: 'rgba(255,255,255,0.45)', letterSpacing: 1.5,
                    textTransform: 'uppercase', marginBottom: 7,
                  }}>{c.etiqueta}</label>
                  <input type="text" value={campos[c.clave] || ''}
                    placeholder={c.ayuda || ''}
                    onChange={e => setCampos(prev => ({ ...prev, [c.clave]: e.target.value }))}
                    onFocus={() => setFoco(c.clave)} onBlur={() => setFoco(null)}
                    style={ESTUDIO_INPUT(foco === c.clave)} />
                </div>
              ))}
            </div>
          </div>
        )}

        {/* PASO 2 — el fondo */}
        {catalogo && paso === 2 && (
          <div className="hl-stagger" style={{ padding: '22px 0 24px' }}>
            <div style={{
              fontFamily: 'var(--hl-font-ui)', fontSize: 17, fontWeight: 600,
              color: '#fff', letterSpacing: -0.4, marginBottom: 6,
            }}>El fondo</div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.45)', marginBottom: 16 }}>
              Un ambiente generado, tu propia idea o una foto tuya.
            </div>

            <div style={{
              display: 'flex', marginBottom: 18, padding: 3,
              background: 'rgba(255,255,255,0.04)',
              border: '1px solid rgba(255,255,255,0.07)', borderRadius: 12,
            }}>
              {[['ambiente', 'Ambientes'], ['idea', 'Mi idea'], ['foto', 'Mi foto'], ['ninguno', 'Sin fondo']].map(([id, lbl]) => (
                <button key={id} onClick={() => { setModoFondo(id); setError(null); }} style={{
                  flex: 1, height: 33, borderRadius: 9, border: 'none',
                  background: modoFondo === id ? 'rgba(168,85,247,0.2)' : 'transparent',
                  color: modoFondo === id ? 'var(--hl-accent-light)' : 'rgba(255,255,255,0.45)',
                  fontFamily: 'var(--hl-font-ui)', fontSize: 12, fontWeight: 500,
                  cursor: 'pointer', transition: 'all 0.18s ease', letterSpacing: -0.2,
                }}>{lbl}</button>
              ))}
            </div>

            {modoFondo === 'ambiente' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                {(catalogo.ambientes || []).map(a => (
                  <OpcionAdornada key={a.clave} compacta nombre={a.nombre}
                    descripcion={a.descripcion}
                    activa={ambiente === a.clave} onElegir={() => setAmbiente(a.clave)} />
                ))}
              </div>
            )}

            {modoFondo === 'idea' && (
              <div>
                <label style={{
                  display: 'block', fontFamily: 'var(--hl-font-mono)', fontSize: 9.5,
                  color: 'rgba(255,255,255,0.45)', letterSpacing: 1.5,
                  textTransform: 'uppercase', marginBottom: 7,
                }}>Describe la escena con tus palabras</label>
                <textarea value={idea} rows={3}
                  placeholder="Un amanecer sobre la huerta, una mesa con pan y velas…"
                  onChange={e => { setIdea(e.target.value); setPromptRedactado(null); }}
                  style={{ ...ESTUDIO_INPUT(false), height: 'auto', padding: '12px 14px', resize: 'none', lineHeight: 1.55 }} />
                <button onClick={redactar} disabled={redactando || idea.trim().length < 4} style={{
                  marginTop: 10, height: 42, padding: '0 18px', borderRadius: 12,
                  border: '1px solid rgba(221,214,254,0.25)',
                  background: 'rgba(168,85,247,0.1)',
                  color: 'var(--hl-accent-light)', fontSize: 13, fontWeight: 500,
                  fontFamily: 'var(--hl-font-ui)',
                  cursor: redactando ? 'wait' : 'pointer',
                  opacity: idea.trim().length < 4 ? 0.4 : 1,
                }}>{redactando ? 'El estudio redacta…' : 'Redactar con el estudio'}</button>
                {promptRedactado && (
                  <div style={{
                    marginTop: 12, padding: '12px 14px', borderRadius: 12,
                    background: 'rgba(245,197,107,0.06)',
                    border: '1px solid rgba(245,197,107,0.2)',
                  }}>
                    <div style={{
                      fontFamily: 'var(--hl-font-mono)', fontSize: 9, letterSpacing: 1.5,
                      color: 'var(--candlelight, #F5C56B)', textTransform: 'uppercase', marginBottom: 6,
                    }}>Encargo listo para el taller</div>
                    <div style={{
                      fontSize: 12, color: 'rgba(255,255,255,0.6)', lineHeight: 1.5,
                      maxHeight: 88, overflowY: 'auto',
                    }}>{promptRedactado}</div>
                    <button onClick={async () => {
                      // La idea redactada pasa al catálogo: reutilizable siempre.
                      try {
                        const clave = `idea-${Date.now().toString(36)}`;
                        await window.estudioAPI.guardarAmbiente({
                          clave, nombre: idea.trim().slice(0, 48),
                          descripcion: idea.trim(), prompt: promptRedactado,
                        });
                        const c = await window.estudioAPI.composers();
                        setCatalogo(c);
                      } catch (e) { setError(e.message); }
                    }} style={{
                      marginTop: 10, height: 32, padding: '0 12px', borderRadius: 9,
                      border: '1px solid rgba(245,197,107,0.35)', background: 'transparent',
                      color: 'var(--candlelight, #F5C56B)', fontSize: 11.5,
                      fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
                    }}>Guardar como ambiente del catálogo</button>
                  </div>
                )}
              </div>
            )}

            {modoFondo === 'foto' && (
              <div>
                <label htmlFor="foto-fondo" style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center',
                  justifyContent: 'center', gap: 8, height: 110,
                  border: '1px dashed rgba(221,214,254,0.3)', borderRadius: 14,
                  cursor: 'pointer', color: 'rgba(255,255,255,0.55)', fontSize: 13,
                }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <rect x="3" y="3" width="18" height="18" rx="3" />
                    <circle cx="8.5" cy="8.5" r="1.5" /><path d="M21 15l-5-5L5 21" />
                  </svg>
                  Elegir una foto del carrete
                </label>
                <input id="foto-fondo" type="file" accept="image/*" style={{ display: 'none' }}
                  onChange={e => subirFoto(e.target.files && e.target.files[0])} />
              </div>
            )}

            {modoFondo === 'ninguno' && (
              <div style={{
                padding: '14px 16px', borderRadius: 13,
                background: 'rgba(255,255,255,0.025)',
                border: '1px solid rgba(255,255,255,0.06)',
                fontSize: 12.5, color: 'rgba(255,255,255,0.5)', lineHeight: 1.5,
              }}>La pieza usará el fondo propio del diseño (velo y degradado de La Vid).</div>
            )}

            {/* Estado / preview del fondo */}
            {generandoFondo && (
              <div style={{
                display: 'flex', alignItems: 'center', gap: 10, marginTop: 16,
                color: 'rgba(255,255,255,0.5)', fontSize: 12.5,
              }}>
                <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',
                }} />
                {generandoFondo}
              </div>
            )}
            {(modoFondo === 'ambiente' || modoFondo === 'idea') && !generandoFondo && !fondoPreview && (
              <button onClick={generarFondo}
                disabled={modoFondo === 'ambiente' ? !ambiente : !promptRedactado}
                style={{
                  marginTop: 16, width: '100%', height: 46, borderRadius: 13, border: 'none',
                  background: (modoFondo === 'ambiente' ? ambiente : promptRedactado)
                    ? 'rgba(168,85,247,0.18)' : 'rgba(255,255,255,0.05)',
                  color: (modoFondo === 'ambiente' ? ambiente : promptRedactado)
                    ? 'var(--hl-accent-light)' : 'rgba(255,255,255,0.3)',
                  fontSize: 14, fontWeight: 600,
                  fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
                }}>Generar el fondo</button>
            )}
            {fondoPreview && !generandoFondo && (
              <div style={{ marginTop: 16 }}>
                <img src={fondoPreview} alt="Fondo" style={{
                  width: '100%', borderRadius: 14, display: 'block',
                  boxShadow: '0 14px 40px rgba(0,0,0,0.5)',
                }} />
                <button onClick={() => { setFondoPreview(null); setFondoClave(null); setPromptRedactado(null); }}
                  style={{
                    marginTop: 10, height: 36, padding: '0 14px', borderRadius: 10,
                    border: '1px solid rgba(255,255,255,0.12)', background: 'transparent',
                    color: 'rgba(255,255,255,0.55)', fontSize: 12,
                    fontFamily: 'var(--hl-font-ui)', cursor: 'pointer',
                  }}>Cambiar el fondo</button>
              </div>
            )}
          </div>
        )}

        {error && (
          <div style={{
            margin: '4px 0 20px', padding: '12px 14px', borderRadius: 12,
            background: 'rgba(177,74,96,0.12)', border: '1px solid rgba(177,74,96,0.3)',
            color: '#E8B4BE', fontSize: 12.5, lineHeight: 1.5,
          }}>{error}</div>
        )}
      </div>

      {/* CTA inferior */}
      <div style={{
        flexShrink: 0, padding: '12px 20px',
        paddingBottom: 'calc(12px + var(--safe-bottom, 16px))',
        background: 'rgba(8,5,26,0.7)',
        backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
        borderTop: '1px solid rgba(255,255,255,0.05)',
      }}>
        {paso < 2 ? (
          <button disabled={paso === 0 ? !puedeAvanzar0 : !puedeAvanzar1}
            onClick={() => setPaso(p => p + 1)}
            style={{
              width: '100%', height: 52, borderRadius: 16, border: 'none',
              background: (paso === 0 ? puedeAvanzar0 : puedeAvanzar1)
                ? 'linear-gradient(135deg, #B45EFF 0%, #7C3AED 50%, #4F1FCB 100%)'
                : 'rgba(255,255,255,0.06)',
              color: (paso === 0 ? puedeAvanzar0 : puedeAvanzar1) ? '#fff' : 'rgba(255,255,255,0.3)',
              fontSize: 15, fontWeight: 600, fontFamily: 'var(--hl-font-ui)',
              cursor: (paso === 0 ? puedeAvanzar0 : puedeAvanzar1) ? 'pointer' : 'not-allowed',
              letterSpacing: -0.2,
            }}>Continuar</button>
        ) : generando ? (
          <div style={{
            height: 52, borderRadius: 16,
            background: 'rgba(168,85,247,0.1)', border: '1px solid rgba(168,85,247,0.25)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
          }}>
            <div style={{
              width: 18, height: 18, borderRadius: '50%',
              border: '2px solid rgba(168,85,247,0.35)', borderTopColor: 'var(--hl-accent-1)',
              animation: 'hlspin 0.8s linear infinite',
            }} />
            <span style={{
              fontFamily: 'var(--hl-font-mono)', fontSize: 11, letterSpacing: 1.5,
              color: 'var(--hl-accent-light)', textTransform: 'uppercase',
            }}>{generando}</span>
          </div>
        ) : (
          (() => {
            // Sin fondo elegido se compone con el del diseño; con modo IA/foto
            // hace falta haberlo generado o subido antes de componer.
            const lista = modoFondo === 'ninguno' || !!fondoClave;
            return (
              <button onClick={generarPieza} disabled={!lista}
                style={{
                  width: '100%', height: 52, borderRadius: 16, border: 'none',
                  background: lista
                    ? 'linear-gradient(135deg, #B45EFF 0%, #7C3AED 50%, #4F1FCB 100%)'
                    : 'rgba(255,255,255,0.06)',
                  color: lista ? '#fff' : 'rgba(255,255,255,0.3)',
                  fontSize: 15, fontWeight: 600,
                  fontFamily: 'var(--hl-font-ui)',
                  cursor: lista ? 'pointer' : 'not-allowed', letterSpacing: -0.2,
                  boxShadow: lista ? '0 10px 30px rgba(168,85,247,0.35)' : 'none',
                }}>Componer la pieza</button>
            );
          })()
        )}
      </div>
    </div>
  );
}

Object.assign(window, { EstudioScreen });
