// zeus-publish.jsx — Publish flow with draft autosave

function StepContact({ t, form, setForm, onBack, onPublish, inputStyle, labelStyle }) {
  const [geoStatus, setGeoStatus] = React.useState('idle');
  const [autoFilled, setAutoFilled] = React.useState(false);

  React.useEffect(() => {
    const lastPhone = localStorage.getItem('zeus_seller_phone') || '';
    if (lastPhone) {
      const known = getKnownSellers()[lastPhone.replace(/\s/g,'')];
      setForm(f => ({ ...f, phone: lastPhone, name: known?.name || f.name, city: known?.city || f.city }));
      if (known?.name) setAutoFilled(true);
    }
  }, []);

  const handlePhoneChange = (val) => {
    setForm(f => ({ ...f, phone: val }));
    const clean = val.replace(/\s/g,'');
    if (clean.length >= 9) {
      const known = getKnownSellers()[clean];
      if (known?.name) { setForm(f => ({ ...f, phone: val, name: known.name, city: known.city || f.city })); setAutoFilled(true); }
      else setAutoFilled(false);
    } else setAutoFilled(false);
  };

  const detectCity = () => {
    if (!navigator.geolocation) return;
    setGeoStatus('loading');
    navigator.geolocation.getCurrentPosition(async (pos) => {
      try {
        const res = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${pos.coords.latitude}&lon=${pos.coords.longitude}&format=json`);
        const data = await res.json();
        const city = data.address?.city || data.address?.town || data.address?.village || '';
        if (city) { setForm(f => ({ ...f, city })); setGeoStatus('done'); }
        else setGeoStatus('error');
      } catch { setGeoStatus('error'); }
    }, () => setGeoStatus('error'));
  };

  const saveAndPublish = () => {
    saveSellerProfile(form.phone || '', form.name || '', form.city || '');
    onPublish();
  };

  const allFilled = form.name && form.phone;

  return (
    <div>
      <h2 style={{ fontSize:24, fontWeight:800, color:t.text, marginBottom:20 }}>📞 Paso 3: Tus datos</h2>

      {autoFilled && (
        <div style={{ background:t.accentLight, border:`1px solid ${t.accent}`, borderRadius:14, padding:'12px 18px', marginBottom:18, display:'flex', alignItems:'center', gap:10 }}>
          <span style={{ fontSize:22 }}>✅</span>
          <div>
            <div style={{ fontWeight:800, fontSize:15, color:t.text }}>¡Datos recordados!</div>
            <div style={{ fontSize:13, color:t.textMid }}>Revisalos y confirma.</div>
          </div>
        </div>
      )}

      <label style={labelStyle}>Tu teléfono</label>
      <input
        type="tel"
        name="phone"
        autoComplete="tel"
        inputMode="tel"
        enterKeyHint="next"
        value={form.phone||''}
        onChange={e=>handlePhoneChange(e.target.value)}
        placeholder="Ej: 612 345 678"
        style={{...inputStyle, fontSize:20, letterSpacing:2}}
      />

      <label style={labelStyle}>Tu nombre</label>
      <input
        name="name"
        autoComplete="name"
        autoCapitalize="words"
        enterKeyHint="next"
        value={form.name||''}
        onChange={e=>setForm(f=>({...f,name:e.target.value}))}
        placeholder="Ej: María García"
        style={inputStyle}
      />

      <label style={labelStyle}>
        Tu ciudad
        <button onClick={detectCity} style={{ marginLeft:10, background:'none', border:'none', cursor:'pointer', fontSize:13, color:t.primary, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
          {geoStatus==='loading' ? '⏳ Detectando…' : geoStatus==='done' ? '✓ Detectada' : '📍 Detectar'}
        </button>
      </label>
      <input
        name="city"
        autoComplete="address-level2"
        autoCapitalize="words"
        enterKeyHint="done"
        value={form.city||''}
        onChange={e=>setForm(f=>({...f,city:e.target.value}))}
        placeholder="Ej: Madrid"
        style={inputStyle}
      />

      <div style={{ background:t.accentLight, borderRadius:12, padding:'10px 14px', marginBottom:18 }}>
        <p style={{ fontSize:13, color:t.accent, fontWeight:600 }}>🔒 Recordaremos tu nombre para la próxima vez.</p>
      </div>

      <div style={{ display:'flex', gap:10 }}>
        <button onClick={onBack} style={{ flex:1, background:'none', color:t.primary, border:`2px solid ${t.primary}`, cursor:'pointer', padding:'16px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>← Atrás</button>
        <button onClick={saveAndPublish} disabled={!allFilled} style={{ flex:2, background:allFilled?t.primary:t.border, color:'#fff', border:'none', cursor:allFilled?'pointer':'not-allowed', padding:'16px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
          {allFilled ? '¡Publicar ahora! 🎉' : 'Completa los datos'}
        </button>
      </div>
    </div>
  );
}

function Publish({ t, setPage }) {
  const draft = React.useMemo(() => loadDraft(), []);

  const [step, setStep] = React.useState(1);
  const [photos, setPhotos] = React.useState([]);
  const [imageBase64, setImageBase64] = React.useState(null);
  const [aiResult, setAiResult] = React.useState(null);
  const [form, setForm] = React.useState(() => ({
    title: draft?.title || '',
    price: draft?.price || '',
    cat: draft?.cat || '',
    desc: draft?.desc || '',
    size: draft?.size || '',
    name: draft?.name || '',
    phone: draft?.phone || '',
    city: draft?.city || '',
  }));
  const [published, setPublished] = React.useState(false);
  const [notifRequested, setNotifRequested] = React.useState(false);
  const fileRef = React.useRef();
  const MAX_PHOTOS = 6;
  const [showVideo, setShowVideo] = React.useState(false);

  // Auto-save draft every time form changes
  React.useEffect(() => {
    const id = setTimeout(() => saveDraft(form), 800);
    return () => clearTimeout(id);
  }, [form]);

  const inputStyle = { width:'100%', padding:'14px 18px', fontSize:17, borderRadius:12, border:`2px solid ${t.border}`, background:t.card, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:14 };
  const labelStyle = { fontSize:16, fontWeight:700, color:t.text, marginBottom:6, display:'block', marginTop:4 };

  const handleFiles = (files) => {
    Array.from(files).slice(0, MAX_PHOTOS - photos.length).forEach(file => {
      const reader = new FileReader();
      reader.onload = (e) => {
        const dataUrl = e.target.result;
        const base64 = dataUrl.split(',')[1];
        setPhotos(prev => {
          const updated = [...prev, { dataUrl, base64 }];
          if (updated.length === 1) setImageBase64(base64);
          return updated;
        });
      };
      reader.readAsDataURL(file);
    });
  };

  const handleAiResult = (result) => {
    setAiResult(result);
    setForm(f => ({
      ...f,
      title: result.titulo || f.title,
      price: result.precio_recomendado?.toString() || f.price,
      cat: result.categoria || f.cat,
      desc: result.descripcion || f.desc,
      size: result.size || f.size,
    }));
  };

  const compressForStorage = (dataUrl) => new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      const MAX=600; let w=img.width, h=img.height;
      if (w>MAX||h>MAX) { if(w>h){h=Math.round(h*MAX/w);w=MAX;}else{w=Math.round(w*MAX/h);h=MAX;} }
      const canvas=document.createElement('canvas'); canvas.width=w; canvas.height=h;
      canvas.getContext('2d').drawImage(img,0,0,w,h);
      resolve(canvas.toDataURL('image/jpeg',0.6));
    };
    img.onerror = () => resolve(dataUrl);
    img.src = dataUrl;
  });

  const handleFinalPublish = async () => {
    const mainPhoto = photos[0]?.dataUrl || null;
    const compressedPhoto = mainPhoto ? await compressForStorage(mainPhoto) : null;
    // Comprimir todas las fotos para guardarlas
    const allPhotos = [];
    for (let i = 0; i < photos.length; i++) {
      const compressed = photos[i]?.dataUrl ? await compressForStorage(photos[i].dataUrl) : null;
      if (compressed) allPhotos.push({ dataUrl: compressed });
    }
    const saved = addProduct({
      title: form.title, price: Number(form.price)||0,
      cat: form.cat||'Otros', desc: form.desc,
      sellerName: form.name, phone: form.phone,
      city: form.city, seller: abbreviateName(form.name),
      location: form.city,
      photo: compressedPhoto,   // foto principal (compatibilidad)
      photos: allPhotos,        // todas las fotos
    });
    if (saved) {
      clearDraft();
      setPublished(true);
      // Request notification permission after first publish
      if (!notifRequested) {
        setNotifRequested(true);
        const granted = await requestNotificationPermission();
        if (granted) sendBrowserNotification('Zeus Ventas', `"${form.title}" ha sido publicado. Te avisaremos cuando haya novedades.`);
      }
    } else {
      alert('No se pudo guardar. Borra anuncios antiguos desde Admin.');
    }
  };

  const reset = () => {
    setPublished(false); setStep(1);
    setForm({ title:'', price:'', cat:'', desc:'', name:'', phone:'', city:'' });
    setPhotos([]); setImageBase64(null); setAiResult(null);
  };

  if (published) return (
    <div style={{ background:t.bg, minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div style={{ textAlign:'center', maxWidth:500 }}>
        <div style={{ fontSize:72 }}>🎉</div>
        <h2 className="zv-big-title" style={{ fontSize:'clamp(28px,6vw,40px)', fontWeight:900, color:t.text, marginTop:20 }}>¡Anuncio publicado!</h2>
        {photos.length > 0 && (
          <div style={{ display:'flex', gap:8, justifyContent:'center', marginTop:18, flexWrap:'wrap' }}>
            {photos.slice(0,3).map((p,i) => <img key={i} src={p.dataUrl} style={{ width:72, height:72, borderRadius:12, objectFit:'cover' }} />)}
          </div>
        )}
        <p style={{ fontSize:18, color:t.textMid, marginTop:14, lineHeight:1.5 }}>Tu artículo ya está visible en la web.<br/>Te avisaremos cuando haya actividad.</p>
        <div style={{ display:'flex', gap:12, marginTop:32, flexWrap:'wrap', justifyContent:'center' }}>
          <button onClick={() => setPage('seller')} style={{ background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'16px 28px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>Ver mis anuncios</button>
          <button onClick={reset} style={{ background:'none', color:t.primary, border:`2px solid ${t.primary}`, cursor:'pointer', padding:'16px 28px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>Publicar otro</button>
        </div>
      </div>
    </div>
  );

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'40px 24px' }}>
      <div style={{ maxWidth:640, margin:'0 auto' }}>
        <h1 className="zv-big-title" style={{ fontSize:'clamp(32px,6vw,44px)', fontWeight:900, color:t.text, marginBottom:6 }}>Empezar a vender</h1>
        <p style={{ fontSize:17, color:t.textMid, marginBottom:14 }}>Solo 3 pasos. No publicamos nada sin tu permiso.</p>

        {/* Tranquilidad para mayores */}
        <div style={{ background:t.bgAlt, borderRadius:12, padding:'12px 16px', marginBottom: draft && step===1 ? 8 : 24, display:'flex', alignItems:'center', gap:10 }}>
          <span style={{ fontSize:18 }}>🤝</span>
          <p style={{ fontSize:13, color:t.textMid, lineHeight:1.5, margin:0, flex:1 }}>
            ¿Te lía? Llama al <a href={'tel:+34' + WA_NUMBER.slice(2)} style={{ color:t.primary, fontWeight:700, textDecoration:'none' }}>699 601 627</a> y te lo hago yo por teléfono. Sin compromiso.
          </p>
        </div>

        {draft && step === 1 && (
          <div style={{ background:t.accentLight, border:`1px solid ${t.accent}`, borderRadius:14, padding:'12px 18px', marginBottom:24, display:'flex', alignItems:'center', gap:10, flexWrap:'wrap' }}>
            <span style={{ fontSize:20 }}>💾</span>
            <div style={{ flex:1 }}>
              <div style={{ fontWeight:800, fontSize:14, color:t.text }}>Borrador guardado automáticamente</div>
              {draft.title && <div style={{ fontSize:13, color:t.textMid }}>"{draft.title}" — {timeSince(draft.savedAt)}</div>}
            </div>
            <button onClick={() => { clearDraft(); setForm({title:'',price:'',cat:'',desc:'',name:'',phone:'',city:''}); }} style={{ background:'none', border:`1px solid ${t.accent}`, borderRadius:100, padding:'4px 12px', fontSize:12, color:t.accent, cursor:'pointer', fontFamily:'Outfit,sans-serif', fontWeight:700 }}>Descartar</button>
          </div>
        )}

        {/* Progress */}
        <div style={{ display:'flex', gap:8, marginBottom:32 }}>
          {[1,2,3].map(s=>(
            <div key={s} style={{ flex:1, height:6, borderRadius:100, background: s<=step ? t.primary : t.border, transition:'background 0.3s' }} />
          ))}
        </div>

        {/* Step 1 — Photos */}
        {step === 1 && (
          <div>
            <h2 style={{ fontSize:24, fontWeight:800, color:t.text, marginBottom:6 }}>📸 Paso 1: Fotos</h2>
            <p style={{ fontSize:15, color:t.textMid, marginBottom:18 }}>Hasta {MAX_PHOTOS} fotos. La primera se analiza con IA.</p>
            <input ref={fileRef} type="file" accept="image/*" multiple capture="environment" style={{ display:'none' }} onChange={e=>handleFiles(e.target.files)} />

            <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, marginBottom:14 }}>
              {photos.map((p,i) => (
                <div key={i} style={{ position:'relative', borderRadius:12, overflow:'hidden', aspectRatio:'1' }}>
                  <img src={p.dataUrl} style={{ width:'100%', height:'100%', objectFit:'cover' }} />
                  {i===0 && <div style={{ position:'absolute', top:6, left:6, background:t.primary, color:'#fff', fontSize:11, fontWeight:700, borderRadius:100, padding:'2px 8px' }}>Principal</div>}
                  <button onClick={() => { const next=photos.filter((_,j)=>j!==i); setPhotos(next); if(i===0) setImageBase64(next[0]?.base64||null); }}
                    style={{ position:'absolute', top:6, right:6, background:'rgba(0,0,0,0.6)', color:'#fff', border:'none', borderRadius:'50%', width:26, height:26, cursor:'pointer', fontSize:13 }}>✕</button>
                </div>
              ))}
              {photos.length < MAX_PHOTOS && (
                <div onClick={() => fileRef.current.click()} style={{ aspectRatio:'1', borderRadius:12, border:`2px dashed ${t.primary}`, background:t.bgAlt, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', cursor:'pointer', gap:4 }}>
                  <div style={{ fontSize:photos.length===0?40:26, color:t.primary }}>+</div>
                  <div style={{ fontSize:12, fontWeight:700, color:t.primary }}>{photos.length===0?'Añadir':'Más'}</div>
                </div>
              )}
            </div>

            {/* Botón de vídeo */}
            {photos.length < MAX_PHOTOS && (
              <button onClick={() => setShowVideo(true)} style={{
                width:'100%', padding:'14px 18px', marginBottom:12,
                background:'#1a1a2e', color:'#fff', border:'2px solid #7c3aed',
                borderRadius:14, fontSize:15, fontWeight:800, cursor:'pointer',
                fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', justifyContent:'center', gap:10,
              }}>
                <span style={{ fontSize:22 }}>🎬</span>
                Obtener fotos de un vídeo
                <span style={{ fontSize:12, opacity:0.7, fontWeight:400 }}>Graba o sube un vídeo</span>
              </button>
            )}

            {photos.length === 0 && (
              <div onClick={() => fileRef.current.click()} style={{ borderRadius:20, border:`3px dashed ${t.primary}`, background:t.bgAlt, cursor:'pointer', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'40px 24px', marginBottom:14 }}>
                <div style={{ fontSize:48, marginBottom:10 }}>📷</div>
                <div style={{ fontSize:20, fontWeight:800, color:t.text, marginBottom:4 }}>Toca para añadir fotos</div>
                <div style={{ fontSize:15, color:t.textMid }}>Hasta 6 fotos · La IA valora automáticamente</div>
              </div>
            )}

            {photos.length > 0 && <p style={{ fontSize:13, color:t.textLight, marginBottom:14, textAlign:'center' }}>{photos.length}/{MAX_PHOTOS} fotos</p>}
            {imageBase64 && <AIValuation t={t} imageBase64={imageBase64} onResult={handleAiResult} />}

            <button onClick={() => setStep(2)} disabled={photos.length===0} style={{ background:photos.length>0?t.primary:t.border, color:'#fff', border:'none', cursor:photos.length>0?'pointer':'not-allowed', padding:'16px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif', width:'100%' }}>
              {photos.length===0 ? 'Añade una foto para continuar' : 'Continuar →'}
            </button>
          </div>
        )}

        {/* VideoCapture modal */}
        {showVideo && (
          <VideoCapture
            t={t}
            onPhotosExtracted={(newPhotos, aiData) => {
              const available = MAX_PHOTOS - photos.length;
              const toAdd = newPhotos.slice(0, available);
              setPhotos(prev => {
                const updated = [...prev, ...toAdd];
                if (prev.length === 0 && updated.length > 0) setImageBase64(updated[0].base64);
                return updated;
              });
              // Auto-rellenar campos con datos IA si están vacíos
              if (aiData) {
                setForm(prev => ({
                  ...prev,
                  titulo: prev.titulo || aiData.objeto || '',
                  descripcion: prev.descripcion || aiData.descripcion || '',
                  condicion: aiData.condicion || prev.condicion || 'Buen estado',
                  precio: prev.precio || String(Math.round((aiData.precioMin + aiData.precioMax) / 2)) || '',
                }));
              }
              setShowVideo(false);
            }}
            onClose={() => setShowVideo(false)}
          />
        )}

        {/* Step 2 — Details */}
        {step === 2 && (
          <div>
            <h2 style={{ fontSize:24, fontWeight:800, color:t.text, marginBottom:6 }}>📝 Paso 2: Detalles</h2>
            {aiResult && <p style={{ fontSize:15, color:t.accent, fontWeight:600, marginBottom:20 }}>🤖 La IA rellenó el formulario. Puedes editarlo.</p>}
            {photos.length>0 && <div style={{ display:'flex', gap:8, marginBottom:20, flexWrap:'wrap' }}>{photos.slice(0,3).map((p,i)=><img key={i} src={p.dataUrl} style={{ width:72, height:72, borderRadius:10, objectFit:'cover' }} />)}</div>}

            <label style={labelStyle}>¿Qué vendes?</label>
            <input
              value={form.title}
              onChange={e=>setForm({...form,title:e.target.value})}
              placeholder="Ej: Sillón vintage"
              autoCapitalize="sentences"
              enterKeyHint="next"
              style={inputStyle}
            />

            <label style={labelStyle}>Categoría</label>
            <select value={form.cat} onChange={e=>setForm({...form,cat:e.target.value})} style={{...inputStyle, appearance:'none', cursor:'pointer'}}>
              <option value="">Selecciona una categoría</option>
              {cats.slice(1).map(c=><option key={c}>{c}</option>)}
            </select>

            <label style={labelStyle}>Precio (€)</label>
            <input
              type="number"
              inputMode="decimal"
              enterKeyHint="next"
              min="0"
              value={form.price}
              onChange={e=>setForm({...form,price:e.target.value})}
              placeholder="Ej: 50"
              style={inputStyle}
            />
            {aiResult && <p style={{ fontSize:13, color:t.textLight, marginTop:-10, marginBottom:14 }}>Rango sugerido: {aiResult.precio_min}€ – {aiResult.precio_max}€</p>}

            {form.price && (
              <div style={{ background:t.accentLight, borderRadius:12, padding:'10px 16px', marginBottom:14, display:'flex', justifyContent:'space-between', flexWrap:'wrap', gap:8 }}>
                <span style={{ fontSize:14, color:t.accent }}>Tú recibirás aprox.</span>
                <span style={{ fontSize:18, fontWeight:900, color:t.primary }}>{Math.round((Number(form.price) * (1 - commissionRate(Number(form.price))))*100)/100}€</span>
              </div>
            )}

            <label style={labelStyle}>Descripción (opcional)</label>
            <textarea
              value={form.desc}
              onChange={e=>setForm({...form,desc:e.target.value})}
              placeholder="Describe el estado, dimensiones, historia del objeto…"
              autoCapitalize="sentences"
              style={{...inputStyle, minHeight:100, borderRadius:14, resize:'vertical'}}
            />

            <label style={labelStyle}>📦 ¿Cuánto pesa o cómo de grande es? (para el envío)</label>
            <p style={{ fontSize:13, color:t.textLight, marginTop:-8, marginBottom:12, lineHeight:1.5 }}>
              No te preocupes si dudas — si nos equivocamos al recibirlo, lo ajustamos sin problema.
            </p>
            <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:18 }}>
              {[
                { id:'pequeno',    dot:'🟢', label:'Pequeño',    price:'7,90€',  desc:'Cabe en caja de zapatos. Lo levanta un niño.', ej:'Vajilla, libros, ropa, herramientas pequeñas' },
                { id:'mediano',    dot:'🟡', label:'Mediano',    price:'13,90€', desc:'Caja grande. Pesa como una compra del súper.', ej:'Lámpara, microondas, robot de cocina, bolso grande' },
                { id:'grande',     dot:'🟠', label:'Grande',     price:'24,90€', desc:'Hay que llevarlo entre dos personas.',         ej:'Televisor, bicicleta, silla, horno, palos de golf' },
                { id:'voluminoso', dot:'🔴', label:'Voluminoso', price:'A medida', desc:'Mueble grande o muy pesado. Hace falta furgoneta.', ej:'Armario, sofá, lavadora, mesa grande, piano' },
              ].map(s => {
                const sel = form.size === s.id;
                return (
                  <div
                    key={s.id}
                    onClick={()=>setForm({...form, size:s.id})}
                    style={{
                      background: sel ? t.accentLight : t.card,
                      border: `2px solid ${sel ? t.primary : t.border}`,
                      borderRadius:14,
                      padding:'14px 16px',
                      cursor:'pointer',
                      display:'flex',
                      gap:14,
                      alignItems:'flex-start',
                      transition:'all 0.15s',
                    }}
                  >
                    <div style={{ fontSize:24, lineHeight:1, marginTop:2 }}>{s.dot}</div>
                    <div style={{ flex:1 }}>
                      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:4, flexWrap:'wrap', gap:6 }}>
                        <span style={{ fontSize:15, fontWeight:800, color:t.text }}>{s.label}</span>
                        <span style={{ fontSize:14, fontWeight:700, color:t.primary }}>{s.price}</span>
                      </div>
                      <div style={{ fontSize:13, color:t.text, marginBottom:3, fontStyle:'italic' }}>{s.desc}</div>
                      <div style={{ fontSize:12, color:t.textLight, lineHeight:1.4 }}>Ej: {s.ej}</div>
                    </div>
                    <div style={{
                      width:22, height:22, borderRadius:'50%',
                      border:`2px solid ${sel ? t.primary : t.border}`,
                      background: sel ? t.primary : 'transparent',
                      flex:'0 0 auto',
                      display:'flex', alignItems:'center', justifyContent:'center',
                      color:'#fff', fontSize:14, fontWeight:900,
                    }}>
                      {sel ? '✓' : ''}
                    </div>
                  </div>
                );
              })}
            </div>

            <div style={{ display:'flex', gap:10 }}>
              <button onClick={()=>setStep(1)} style={{ flex:1, background:'none', color:t.primary, border:`2px solid ${t.primary}`, cursor:'pointer', padding:'16px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>← Atrás</button>
              <button onClick={()=>setStep(3)} disabled={!form.title||!form.price} style={{ flex:2, background:(form.title&&form.price)?t.primary:t.border, color:'#fff', border:'none', cursor:(form.title&&form.price)?'pointer':'not-allowed', padding:'16px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>Continuar →</button>
            </div>
          </div>
        )}

        {/* Step 3 — Contact */}
        {step === 3 && (
          <StepContact t={t} form={form} setForm={setForm} onBack={() => setStep(2)} onPublish={handleFinalPublish} inputStyle={inputStyle} labelStyle={labelStyle} />
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Publish, StepContact });
