/* ─────────────────────────────────────────────────────────────────────────
   Menu Factory — Landing + Dashboard + Root App
   ───────────────────────────────────────────────────────────────────────── */

const { useState: useStateF, useEffect: useEffectF, useRef: useRefF } = React;

function useMobile() {
  const [m, setM] = useStateF(() => window.innerWidth < 768);
  useEffectF(() => {
    const fn = () => setM(window.innerWidth < 768);
    window.addEventListener('resize', fn);
    return () => window.removeEventListener('resize', fn);
  }, []);
  return m;
}

/* ── Root App ──────────────────────────────────────────────────── */
function FactoryApp() {
  const [profile, setProfile] = useStateF(() => {
    try { return JSON.parse(localStorage.getItem('factoryProfile') || 'null'); } catch { return null; }
  });
  const [screen, setScreen] = useStateF(() => profile ? 'dashboard' : 'landing');
  const [authMode, setAuthMode] = useStateF(null); // 'signin' | null
  const [showPricing, setShowPricing] = useStateF(false);

  useEffectF(() => {
    if (profile) {
      localStorage.setItem('factoryProfile', JSON.stringify(profile));
      const rid = profile.restaurantId || window.factorySlug?.(profile.brand?.name?.es) || 'restaurante';
      localStorage.setItem('MF_' + rid, JSON.stringify(profile));
    } else {
      localStorage.removeItem('factoryProfile');
    }
  }, [profile]);

  const handleAuthSuccess = (p) => {
    setAuthMode(null);
    if (p?.restaurantId) {
      setProfile(p);
      setScreen('dashboard');
    } else {
      setScreen('wizard');
    }
  };

  if (screen === 'wizard') {
    return <window.FactoryWizard
      onCancel={() => setScreen('landing')}
      onComplete={async (data) => {
        try {
          const id = window.MF_publishRestaurant
            ? await window.MF_publishRestaurant(data)
            : data.restaurantId;
          const fu = typeof firebase !== 'undefined' ? firebase.auth?.().currentUser : null;
          const userInfo = fu ? {
            name:     fu.displayName || fu.email?.split('@')[0] || 'Usuario',
            email:    fu.email || '',
            uid:      fu.uid,
            avatar:   fu.photoURL || null,
            provider: fu.providerData?.[0]?.providerId || 'email',
          } : (data.user || { name: 'Usuario', email: '' });
          setProfile({ ...data, restaurantId: id, user: userInfo });
        } catch (e) {
          console.warn('[factory] publish failed, saving local only:', e);
          setProfile(data);
        }
        setScreen('dashboard');
      }} />;
  }

  if (screen === 'dashboard' && profile) {
    return <window.MFDashboard
      profile={profile}
      onSignOut={() => {
        if (typeof firebase !== 'undefined' && firebase.auth) {
          firebase.auth().signOut().catch(() => {});
        }
        setProfile(null);
        setScreen('landing');
      }}
      onEditBrand={() => setScreen('wizard')} />;
  }

  if (showPricing) {
    return (
      <window.MFPricingPage
        onStart={() => {
          setShowPricing(false);
          setScreen('wizard');
        }}
        onSignIn={() => {
          setShowPricing(false);
          setAuthMode('signin');
        }}
        onBack={() => setShowPricing(false)}
      />
    );
  }

  return (
    <>
      <window.MFLanding
        onStart={() => setScreen('wizard')}
        onSignIn={() => setAuthMode('signin')}
        onShowPricing={() => setShowPricing(true)}
      />
      {authMode === 'signin' && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 100 }}>
          <window.MFSignIn
            initialMode="signin"
            onClose={() => setAuthMode(null)}
            onSuccess={handleAuthSuccess} />
        </div>
      )}
      <window.LandingAIAssistant />
    </>
  );
}

/* ── Landing ───────────────────────────────────────────────────── */
function Landing({ onStart, onSignIn, onShowPricing }) {
  const mobile = useMobile();
  return (
    <div style={{ minHeight: '100vh', minHeight: '100dvh', display: 'flex', flexDirection: 'column' }}>
      {/* Top nav */}
      <nav style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: mobile ? '16px 20px' : '24px 56px', borderBottom: '1px solid var(--line)',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1 }}>
          <div className="serif" style={{ fontSize: 20, fontStyle: 'italic', letterSpacing: '-0.01em' }}>
            menú <span style={{ color: 'var(--mu)' }}>factory</span>
          </div>
          <span style={{ fontSize: 9, letterSpacing: '0.1em', opacity: 0.45, fontStyle: 'normal', marginTop: 2 }}>by sinapsys</span>
        </div>
        <div style={{ display: 'flex', gap: mobile ? 8 : 24, alignItems: 'center', fontSize: 14 }}>
          {!mobile && <a style={{ color: 'var(--mu)', cursor: 'pointer' }} onClick={onShowPricing}>Precios</a>}
          {!mobile && <a style={{ color: 'var(--mu)' }} href="#how">Cómo funciona</a>}
          {!mobile && <a style={{ color: 'var(--mu)' }} href="#showcase">Ejemplos</a>}
          <button className="btn ghost" onClick={onSignIn}>{mobile ? 'Entrar' : 'Iniciar sesión'}</button>
          <button className="btn" onClick={onStart}>{mobile ? 'Empezar' : 'Empezar gratis'}</button>
        </div>
      </nav>

      {/* Hero */}
      <section style={{
        flex: 1, display: 'grid',
        gridTemplateColumns: mobile ? '1fr' : '1.1fr 0.9fr',
        gap: mobile ? 0 : 80,
        padding: mobile ? '40px 20px 56px' : '80px 56px',
        alignItems: 'center',
      }}>
        <div className="fade-up">
          <div className="eyebrow" style={{ marginBottom: 24 }}>Menú digital · Onboarding automatizado</div>
          <h1 className="hero-title">
            Tu menú digital, <em>en cinco minutos</em>.
          </h1>
          <p className="lead" style={{ marginTop: 28, fontSize: mobile ? 16 : 19 }}>
            Sube tu logo y tu PDF. Extraemos tus colores, leemos cada plato y
            te entregamos un menú listo para tus mesas — con panel de pedidos,
            cocina y cuentas.
          </p>
          <div style={{ display: 'flex', gap: 12, marginTop: 36, flexWrap: 'wrap' }}>
            <button className="btn lg" onClick={onStart} style={{ flex: mobile ? 1 : 'none' }}>Empezar gratis →</button>
            <button className="btn ghost lg" onClick={onSignIn} style={{ flex: mobile ? 1 : 'none' }}>Ya tengo cuenta</button>
          </div>

          {!mobile && (
            <div style={{ display: 'flex', gap: 32, marginTop: 48, fontSize: 13, color: 'var(--mu)' }}>
              <Pill icon="✦" text="Gemini Vision extrae tu menú" />
              <Pill icon="◐" text="Paleta automática desde tu logo" />
              <Pill icon="✓" text="Sin código ni configuración" />
            </div>
          )}
        </div>

        {/* Phone preview — hidden on mobile */}
        {!mobile && (
          <div style={{ display: 'flex', justifyContent: 'center', position: 'relative' }}>
            <div style={{
              position: 'absolute', inset: '-40px',
              background: 'radial-gradient(circle, rgba(0,0,0,0.04), transparent 70%)',
              pointerEvents: 'none',
            }} />
            <div style={{ transform: 'scale(0.95)' }}>
              <window.FactoryPhone
                palette={window.FactoryPalette.defaultPalette()}
                name="El Mesón"
                tagline="Cuisine & Folklor"
                items={window.FactoryData.SAMPLE_MENU.items.slice(0, 3)} />
            </div>
          </div>
        )}
      </section>

      {/* "How it works" strip */}
      <section id="how" style={{
        padding: mobile ? '36px 20px 48px' : '56px 56px 80px', borderTop: '1px solid var(--line)',
        background: 'var(--paper)',
      }}>
        <div className="eyebrow" style={{ marginBottom: 24 }}>Tres pasos</div>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : 'repeat(3, 1fr)', gap: mobile ? 28 : 40 }}>
          {[
            { n: '01', t: 'Sube tu logo', d: 'Extraemos automáticamente tu paleta de colores. Cada cuenta recibe un tema único basado en tu marca.' },
            { n: '02', t: 'Sube tu menú en PDF', d: 'Nuestra IA lee cada plato, descripción y precio. Tú revisas y editas lo que quieras antes de publicar.' },
            { n: '03', t: 'Recibe pedidos', d: 'Comparte un QR por mesa. Tus comensales ordenan, tu cocina cocina, tu staff cobra. Sin fricción.' },
          ].map(s => (
            <div key={s.n}>
              <div className="mono" style={{ fontSize: 12, color: 'var(--mu)', marginBottom: 14 }}>{s.n}</div>
              <h3 className="serif" style={{ fontSize: 26, fontStyle: 'italic', margin: 0, fontWeight: 400 }}>{s.t}</h3>
              <p style={{ marginTop: 12, color: 'var(--mu)', fontSize: 14, textWrap: 'pretty' }}>{s.d}</p>
            </div>
          ))}
        </div>
      </section>

      {/* Footer */}
      <footer style={{ padding: mobile ? '24px 20px' : '32px 56px', borderTop: '1px solid var(--line)',
        display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--mu)', flexWrap: 'wrap', gap: 12 }}>
        <div>
          © 2026 Menú Factory · Hecho en México
          <div style={{ fontSize: 10, opacity: 0.55, marginTop: 2, letterSpacing: '0.06em' }}>by sinapsys</div>
        </div>
        <div style={{ display: 'flex', gap: 18 }}>
          <a>Términos</a><a>Privacidad</a><a>Soporte</a>
        </div>
      </footer>
    </div>
  );
}

function Pill({ icon, text }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ color: 'var(--ink)' }}>{icon}</span>
      <span>{text}</span>
    </div>
  );
}

/* ── Sign-in modal ─────────────────────────────────────────────── */
function SignInModal({ onClose, onSuccess }) {
  const [tab, setTab]               = useStateF('google');  // 'google' | 'email' | 'phone'
  const [email, setEmail]           = useStateF('');
  const [password, setPassword]     = useStateF('');
  const [phone, setPhone]           = useStateF('');
  const [smsCode, setSmsCode]       = useStateF('');
  const [phoneStep, setPhoneStep]   = useStateF('enter');   // 'enter' | 'verify'
  const [confirmResult, setConfirm] = useStateF(null);
  const [busy, setBusy]             = useStateF(false);
  const [phoneErr, setPhoneErr]     = useStateF('');
  const verifierRef                 = useRefF(null);

  const doGoogle = async () => {
    setBusy(true);
    await new Promise(r => setTimeout(r, 1000));
    try {
      const saved = JSON.parse(localStorage.getItem('factoryProfile') || 'null');
      if (saved) return onSuccess(saved);
    } catch {}
    onSuccess(demoProfile());
  };

  const doEmail = async () => {
    if (!email || !password) return;
    setBusy(true);
    await new Promise(r => setTimeout(r, 700));
    try {
      const saved = JSON.parse(localStorage.getItem('factoryProfile') || 'null');
      if (saved) return onSuccess(saved);
    } catch {}
    onSuccess(demoProfile(email));
  };

  const sendSMS = async () => {
    if (!phone.trim()) return;
    setBusy(true);
    setPhoneErr('');
    try {
      if (!verifierRef.current) {
        verifierRef.current = new firebase.auth.RecaptchaVerifier('factory-recaptcha', {
          size: 'invisible',
          callback: () => {},
        });
        await verifierRef.current.render();
      }
      const fullPhone = phone.trim().startsWith('+') ? phone.trim() : `+52${phone.trim().replace(/\D/g, '')}`;
      const confirmation = await firebase.auth().signInWithPhoneNumber(fullPhone, verifierRef.current);
      setConfirm(confirmation);
      setPhoneStep('verify');
    } catch (err) {
      setPhoneErr(err.message || 'Error al enviar el código. Verifica el número.');
      verifierRef.current = null;
    } finally {
      setBusy(false);
    }
  };

  const verifyCode = async () => {
    if (!smsCode.trim() || !confirmResult) return;
    setBusy(true);
    setPhoneErr('');
    try {
      const cred = await confirmResult.confirm(smsCode.trim());
      const u    = cred.user;
      try {
        const saved = JSON.parse(localStorage.getItem('factoryProfile') || 'null');
        if (saved) return onSuccess(saved);
      } catch {}
      onSuccess(demoProfile(u.phoneNumber || 'usuario'));
    } catch (_) {
      setPhoneErr('Código incorrecto. Intenta de nuevo.');
    } finally {
      setBusy(false);
    }
  };

  const TABS = [['google','Google'],['email','Email'],['phone','Celular 📱']];

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(10,10,10,0.32)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      zIndex: 10,
    }} onClick={onClose}>
      <div className="card" style={{ width: 440, padding: 32 }} onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 20 }}>
          <div>
            <div className="eyebrow">Bienvenido de vuelta</div>
            <h2 className="serif" style={{ fontSize: 28, fontStyle: 'italic', margin: '6px 0 0', fontWeight: 400 }}>
              Iniciar sesión
            </h2>
          </div>
          <button onClick={onClose} style={{ fontSize: 20, color: 'var(--mu)' }}>×</button>
        </div>

        {/* Tab bar */}
        <div style={{ display: 'flex', border: '1px solid var(--line-2)', borderRadius: 'var(--r-md)', overflow: 'hidden', marginBottom: 24 }}>
          {TABS.map(([id, label]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              flex: 1, padding: '9px 4px', fontSize: 13,
              background: tab === id ? 'var(--ink)' : 'transparent',
              color: tab === id ? '#fff' : 'var(--mu)',
              fontWeight: tab === id ? 500 : 400,
              borderRight: id !== 'phone' ? '1px solid var(--line-2)' : 'none',
              transition: 'all 150ms',
            }}>
              {label}
            </button>
          ))}
        </div>

        {/* Invisible reCAPTCHA container */}
        <div id="factory-recaptcha" />

        {/* Google tab */}
        {tab === 'google' && (
          <>
            <button className="btn ghost lg" disabled={busy} onClick={doGoogle}
              style={{ width: '100%', gap: 14, justifyContent: 'flex-start', paddingLeft: 22 }}>
              <svg width="20" height="20" viewBox="0 0 48 48">
                <path fill="#FFC107" d="M43.6 20.1H42V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3l5.7-5.7C34.2 6.1 29.4 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.6-.4-3.9z"/>
                <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.6 16 18.9 13 24 13c3.1 0 5.8 1.2 7.9 3l5.7-5.7C34.2 6.1 29.4 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/>
                <path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.5-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.6 39.6 16.2 44 24 44z"/>
                <path fill="#1976D2" d="M43.6 20.1H42V20H24v8h11.3c-.8 2.2-2.1 4.1-3.9 5.6l6.2 5.2C41.2 35.9 44 30.5 44 24c0-1.3-.1-2.6-.4-3.9z"/>
              </svg>
              {busy ? 'Conectando…' : 'Continuar con Google'}
            </button>
            <p style={{ fontSize: 12, color: 'var(--mu)', marginTop: 20, textAlign: 'center' }}>
              ¿No tienes cuenta? <button onClick={onClose} style={{ color: 'var(--ink)', textDecoration: 'underline' }}>Empieza aquí</button>
            </p>
          </>
        )}

        {/* Email tab */}
        {tab === 'email' && (
          <>
            <input className="input" type="email" value={email}
              onChange={e => setEmail(e.target.value)} placeholder="correo@restaurante.com" style={{ marginBottom: 10 }} autoFocus />
            <input className="input" type="password" value={password}
              onChange={e => setPassword(e.target.value)} placeholder="Contraseña" />
            <button className="btn" disabled={busy || !email || !password} onClick={doEmail}
              style={{ width: '100%', marginTop: 16 }}>
              {busy ? 'Verificando…' : 'Entrar'}
            </button>
          </>
        )}

        {/* Phone tab */}
        {tab === 'phone' && (
          <>
            {phoneStep === 'enter' && (
              <>
                <div style={{ fontSize: 13, color: 'var(--mu)', marginBottom: 14, lineHeight: 1.5 }}>
                  Te enviaremos un código SMS para verificar tu número.
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <div style={{
                    padding: '0 14px', background: 'var(--paper)', border: '1px solid var(--line-2)',
                    borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center',
                    fontSize: 14, color: 'var(--mu)', whiteSpace: 'nowrap',
                  }}>+52</div>
                  <input className="input" type="tel" value={phone}
                    onChange={e => setPhone(e.target.value)}
                    placeholder="10 dígitos" style={{ flex: 1 }} autoFocus
                    onKeyDown={e => e.key === 'Enter' && sendSMS()} />
                </div>
                {phoneErr && <div style={{ fontSize: 12, color: '#c0392b', marginTop: 8 }}>{phoneErr}</div>}
                <button className="btn" disabled={busy || !phone.trim()} onClick={sendSMS}
                  style={{ width: '100%', marginTop: 16 }}>
                  {busy ? 'Enviando…' : 'Enviar código SMS →'}
                </button>
              </>
            )}

            {phoneStep === 'verify' && (
              <>
                <div style={{ fontSize: 13, color: 'var(--mu)', marginBottom: 14, lineHeight: 1.5 }}>
                  Ingresa el código de 6 dígitos que enviamos a <strong style={{ color: 'var(--ink)' }}>{phone.startsWith('+') ? phone : `+52 ${phone}`}</strong>.
                </div>
                <input className="input" type="text" inputMode="numeric" value={smsCode}
                  onChange={e => setSmsCode(e.target.value)} placeholder="Código de 6 dígitos"
                  maxLength={6} autoFocus
                  onKeyDown={e => e.key === 'Enter' && verifyCode()} />
                {phoneErr && <div style={{ fontSize: 12, color: '#c0392b', marginTop: 8 }}>{phoneErr}</div>}
                <button className="btn" disabled={busy || smsCode.length < 6} onClick={verifyCode}
                  style={{ width: '100%', marginTop: 16 }}>
                  {busy ? 'Verificando…' : 'Verificar código →'}
                </button>
                <button onClick={() => { setPhoneStep('enter'); setSmsCode(''); setPhoneErr(''); verifierRef.current = null; }}
                  style={{ width: '100%', marginTop: 10, fontSize: 12, color: 'var(--mu)' }}>
                  ← Cambiar número
                </button>
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
}

function demoProfile(email = 'demo@meson.mx') {
  return {
    user: { name: email.split('@')[0], email, avatar: null, provider: 'email' },
    brand: {
      name: { es: 'El Mesón de Tata Vasco', en: 'El Mesón de Tata Vasco' },
      tagline: { es: 'Cuisine & Folklor', en: 'Cuisine & Folklor' },
      subtitle: 'Est. 1985 · Pátzcuaro, Michoacán',
      palette: window.FactoryPalette.defaultPalette(),
    },
    menu: window.FactoryData.SAMPLE_MENU,
    logoUrl: null,
    restaurantId: 'el-meson-de-tata-vasco',
  };
}

/* ── Dashboard ─────────────────────────────────────────────────── */
function Dashboard({ profile, onSignOut, onEditBrand }) {
  const { user, brand, menu, logoUrl } = profile;
  const slug = window.factorySlug(brand.name.es) || 'mi-restaurante';
  const url = `${slug}.menu.app`;
  const [tab, setTab] = useStateF('overview');
  const mobile = useMobile();

  const initials = user.name.slice(0, 2).toUpperCase();

  const NAV_TABS = [
    ['overview', 'Resumen',  '◐'],
    ['menu',     'Menú',     '✦'],
    ['brand',    'Marca',    '◇'],
    ['console',  'Consola',  '❯'],
    ['orders',   'Pedidos',  '○'],
    ['tables',   'Mesas',    '⊞'],
    ['settings', 'Ajustes',  '✱'],
  ];

  return (
    <div style={{ minHeight: '100vh', minHeight: '100dvh', display: 'grid', gridTemplateColumns: mobile ? '1fr' : '240px 1fr' }}>
      {/* Sidebar — desktop only */}
      {!mobile && <aside style={{
        background: 'var(--paper)', borderRight: '1px solid var(--line)',
        padding: 24, display: 'flex', flexDirection: 'column', gap: 24,
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1 }}>
          <div className="serif" style={{ fontSize: 18, fontStyle: 'italic' }}>
            menú <span style={{ color: 'var(--mu)' }}>factory</span>
          </div>
          <span style={{ fontSize: 9, letterSpacing: '0.1em', opacity: 0.45, fontStyle: 'normal', marginTop: 2 }}>by sinapsys</span>
        </div>

        <div style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '12px',
          background: 'var(--bg)', borderRadius: 'var(--r-md)' }}>
          {logoUrl ? (
            <img src={logoUrl} style={{ width: 34, height: 34, objectFit: 'contain',
              background: brand.palette.bg, borderRadius: 8, padding: 4 }} />
          ) : (
            <div style={{ width: 34, height: 34, borderRadius: 8,
              background: brand.palette.gold, color: brand.palette.bg,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 600 }}>
              {brand.name.es[0]}
            </div>
          )}
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {brand.name.es}
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--mu)' }}>{url}</div>
          </div>
        </div>

        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {NAV_TABS.map(([id, label, glyph]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '9px 12px', borderRadius: 8, textAlign: 'left',
              background: tab === id ? 'var(--bg)' : 'transparent',
              fontSize: 14, color: tab === id ? 'var(--ink)' : 'var(--mu)',
              fontWeight: tab === id ? 500 : 400,
            }}>
              <span style={{ width: 16 }}>{glyph}</span>{label}
            </button>
          ))}
        </nav>

        <div style={{ flex: 1 }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 8 }}>
          <div style={{
            width: 30, height: 30, borderRadius: '50%',
            background: 'var(--ink)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontWeight: 500,
          }}>{initials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {user.name}
            </div>
            <div style={{ fontSize: 11, color: 'var(--mu)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {user.email}
            </div>
          </div>
          <button onClick={onSignOut} style={{ fontSize: 12, color: 'var(--mu)' }}>Salir</button>
        </div>
      </aside>}

      {/* Main */}
      <main style={{
        padding: mobile ? '20px 16px' : '40px 48px',
        paddingBottom: mobile ? 80 : undefined,
        overflow: 'auto',
      }}>
        {/* Mobile top bar */}
        {mobile && (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1 }}>
              <div className="serif" style={{ fontSize: 17, fontStyle: 'italic' }}>
                menú <span style={{ color: 'var(--mu)' }}>factory</span>
              </div>
              <span style={{ fontSize: 9, letterSpacing: '0.1em', opacity: 0.45, fontStyle: 'normal', marginTop: 2 }}>by sinapsys</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--mu)' }}>{brand.name.es}</div>
              <button onClick={onSignOut} style={{ fontSize: 12, color: 'var(--mu)', border: '1px solid var(--line-2)', borderRadius: 8, padding: '4px 10px' }}>Salir</button>
            </div>
          </div>
        )}
        {tab === 'overview' && <OverviewTab profile={profile} url={url} slug={slug} />}
        {tab === 'menu'     && <MenuTab menu={menu} />}
        {tab === 'brand'    && <BrandTab brand={brand} onEdit={onEditBrand} />}
        {tab === 'console'  && <ConsoleTab profile={profile} />}
        {(tab === 'orders' || tab === 'tables' || tab === 'settings') && <ComingSoonTab tab={tab} />}
      </main>

      {/* Mobile bottom tab bar */}
      {mobile && (
        <div style={{
          position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 200,
          background: 'var(--paper)', borderTop: '1px solid var(--line)',
          display: 'flex', paddingBottom: 'env(safe-area-inset-bottom, 4px)',
        }}>
          {NAV_TABS.slice(0, 5).map(([id, label, glyph]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center',
              padding: '10px 0 8px', gap: 3, background: 'none',
              color: tab === id ? 'var(--ink)' : 'var(--mu-2)',
            }}>
              <span style={{ fontSize: 17, lineHeight: 1 }}>{glyph}</span>
              <span style={{ fontSize: 9, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{label}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function OverviewTab({ profile, url, slug }) {
  const { brand, menu } = profile;
  const mobile = useMobile();
  const rid = profile.restaurantId || slug;
  const guestUrl = `MENU structure/index.html?restaurant=${rid}&table=M-01`;
  const adminUrl = `MENU structure/index.html?restaurant=${rid}&staff=1`;
  return (
    <div>
      <div className="eyebrow">Resumen</div>
      <h1 className="serif" style={{ fontSize: mobile ? 28 : 40, fontStyle: 'italic', fontWeight: 400, margin: '8px 0 0' }}>
        Hola, <em>{brand.name.es}</em>.
      </h1>
      <p className="lead" style={{ marginTop: 8, fontSize: mobile ? 14 : undefined }}>
        Tu menú: <span className="mono" style={{ color: 'var(--ink)' }}>{url}</span>
      </p>

      {/* Two big cards */}
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 16, marginTop: 28 }}>
        <ViewCard
          title="Vista de comensal"
          subtitle="Lo que ven tus clientes al escanear el QR"
          chip="Público"
          accent={brand.palette.gold}
          href={guestUrl}
        >
          <MiniPhone palette={brand.palette} brand={brand} menu={menu} />
        </ViewCard>

        <ViewCard
          title="Panel admin"
          subtitle="Pedidos, cocina, mesas y cobro"
          chip="Privado"
          accent="var(--ink)"
          href={adminUrl}
        >
          <MiniAdmin palette={brand.palette} brand={brand} />
        </ViewCard>
      </div>

      {/* Stats strip */}
      <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: 12 }}>
        <Stat label="Platos publicados" value={menu.items.length} />
        <Stat label="Categorías" value={menu.categories.length} />
        <Stat label="Pedidos hoy" value="—" hint="Empieza compartiendo tu QR" />
        <Stat label="Mesas activas" value="—" />
      </div>

      {/* Quick actions */}
      <div style={{ marginTop: 24, padding: 20, border: '1px dashed var(--line-2)', borderRadius: 'var(--r-md)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500 }}>Comparte tu menú</div>
          <div style={{ fontSize: 12, color: 'var(--mu)', marginTop: 2 }}>
            Imprime el QR y pégalo en tus mesas. Cada mesa tiene su propia URL.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn ghost">Descargar QRs</button>
          <button className="btn">Abrir menú</button>
        </div>
      </div>
    </div>
  );
}

function ViewCard({ title, subtitle, chip, accent, href, children }) {
  return (
    <a href={href} target="_blank" rel="noreferrer" className="card" style={{
      padding: 24, display: 'flex', flexDirection: 'column', gap: 16,
      textDecoration: 'none', color: 'inherit',
      transition: 'transform 200ms ease, box-shadow 200ms ease',
      position: 'relative', overflow: 'hidden',
    }}
    onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 18px 40px -28px rgba(0,0,0,0.18)'; }}
    onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div className="eyebrow" style={{ color: accent }}>{chip}</div>
          <h3 className="serif" style={{ fontSize: 24, fontStyle: 'italic', fontWeight: 400, margin: '6px 0 0' }}>{title}</h3>
          <p style={{ fontSize: 13, color: 'var(--mu)', margin: '4px 0 0' }}>{subtitle}</p>
        </div>
        <div style={{ fontSize: 18, color: 'var(--mu)' }}>↗</div>
      </div>
      <div style={{ height: 220, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'var(--bg)', borderRadius: 'var(--r-md)', overflow: 'hidden' }}>
        {children}
      </div>
    </a>
  );
}

function MiniPhone({ palette, brand, menu }) {
  return (
    <div style={{
      width: 160, height: 200, borderRadius: 14,
      background: palette.bg, color: palette.tx,
      padding: 14, fontFamily: 'var(--serif)',
      border: `1px solid ${palette.lineStrong}`,
      transform: 'scale(0.95)',
    }}>
      <div style={{ textAlign: 'center', borderBottom: `1px solid ${palette.line}`, paddingBottom: 8 }}>
        <div style={{ fontSize: 7, letterSpacing: '0.3em', color: palette.gold, textTransform: 'uppercase', fontFamily: 'var(--sans)' }}>
          {brand.tagline.es}
        </div>
        <div style={{ fontSize: 13, fontStyle: 'italic', marginTop: 4 }}>{brand.name.es}</div>
      </div>
      <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
        {menu.items.slice(0, 3).map(i => (
          <div key={i.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, fontFamily: 'var(--sans)' }}>
            <span style={{ color: palette.tx, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 90 }}>{typeof i.name === 'object' ? (i.name.es || i.name.en || '') : (i.name || '')}</span>
            <span style={{ color: palette.gold }}>${i.price}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function MiniAdmin({ palette, brand }) {
  return (
    <div style={{ width: 240, padding: 12, background: '#fff', border: '1px solid var(--line)', borderRadius: 10,
      fontFamily: 'var(--sans)', fontSize: 9 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid var(--line)', paddingBottom: 6 }}>
        <span style={{ color: 'var(--ink)', fontWeight: 600 }}>Pedidos · Hoy</span>
        <span style={{ color: 'var(--mu)' }}>{new Date().toLocaleDateString('es-MX')}</span>
      </div>
      {[
        { m: 'M-04', d: 'Mole · Agua', t: 'Cocina', c: palette.gold },
        { m: 'M-12', d: 'Cochinita · Mezcal', t: 'Listo', c: '#2f7a3a' },
        { m: 'M-07', d: 'Guacamole · Flan', t: 'Por cobrar', c: '#b45309' },
      ].map((o, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '36px 1fr auto', gap: 6, padding: '6px 0', borderBottom: '1px solid var(--line)' }}>
          <span style={{ fontWeight: 600 }}>{o.m}</span>
          <span style={{ color: 'var(--mu)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{o.d}</span>
          <span style={{ color: o.c, fontWeight: 500 }}>● {o.t}</span>
        </div>
      ))}
    </div>
  );
}

function Stat({ label, value, hint }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ fontSize: 11, color: 'var(--mu)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{label}</div>
      <div className="serif" style={{ fontSize: 32, fontWeight: 400, margin: '4px 0 0' }}>{value}</div>
      {hint && <div style={{ fontSize: 11, color: 'var(--mu)', marginTop: 4 }}>{hint}</div>}
    </div>
  );
}

function MenuTab({ menu }) {
  return (
    <div>
      <div className="eyebrow">Menú</div>
      <h1 className="serif" style={{ fontSize: 40, fontStyle: 'italic', fontWeight: 400, margin: '8px 0 24px' }}>
        {menu.items.length} platos
      </h1>
      {menu.categories.map(cat => (
        <div key={cat.id} style={{ marginBottom: 28 }}>
          <h3 className="serif" style={{ fontSize: 20, fontStyle: 'italic', margin: '0 0 10px' }}>{cat.name.es}</h3>
          <div className="card" style={{ overflow: 'hidden' }}>
            {menu.items.filter(i => i.category === cat.id).map((it, idx, arr) => (
              <div key={it.id} style={{ padding: '14px 18px', display: 'flex', justifyContent: 'space-between', gap: 14,
                borderTop: idx === 0 ? 'none' : '1px solid var(--line)' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500, fontSize: 14 }}>{typeof it.name === 'object' ? (it.name.es || it.name.en || '') : (it.name || '')}</div>
                  <div style={{ fontSize: 12, color: 'var(--mu)', marginTop: 2 }}>{(() => { const d = it.description || it.desc; return typeof d === 'object' ? (d.es || d.en || '') : (d || ''); })()}</div>
                </div>
                <div className="mono" style={{ fontSize: 14, fontWeight: 600 }}>${it.price}</div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function BrandTab({ brand, onEdit }) {
  const p = brand.palette;
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div className="eyebrow">Marca</div>
          <h1 className="serif" style={{ fontSize: 40, fontStyle: 'italic', fontWeight: 400, margin: '8px 0 0' }}>
            Identidad visual
          </h1>
        </div>
        <button className="btn ghost" onClick={onEdit}>Editar marca</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginTop: 28 }}>
        <div className="card" style={{ padding: 24 }}>
          <div className="eyebrow">Nombre</div>
          <div className="serif" style={{ fontSize: 24, fontStyle: 'italic', marginTop: 6 }}>{brand.name.es}</div>
          <div className="eyebrow" style={{ marginTop: 18 }}>Tagline</div>
          <div style={{ marginTop: 4 }}>{brand.tagline.es}</div>
          <div className="eyebrow" style={{ marginTop: 18 }}>Subtítulo</div>
          <div style={{ marginTop: 4 }}>{brand.subtitle}</div>
        </div>

        <div className="card" style={{ padding: 24 }}>
          <div className="eyebrow">Paleta de color</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8, marginTop: 12 }}>
            {[['gold',p.gold],['goldLight',p.goldLight],['goldPale',p.goldPale],['goldDeep',p.goldDeep],['bg',p.bg]].map(([k,c]) => (
              <div key={k}>
                <div style={{ aspectRatio: '1', borderRadius: 10, background: c, border: '1px solid rgba(0,0,0,0.06)' }} />
                <div className="mono" style={{ fontSize: 9, marginTop: 6, color: 'var(--mu)', textAlign: 'center' }}>{c}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function ComingSoonTab({ tab }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      minHeight: '50vh', textAlign: 'center' }}>
      <div className="eyebrow">{tab}</div>
      <h2 className="serif" style={{ fontSize: 28, fontStyle: 'italic', fontWeight: 400, marginTop: 8 }}>
        Próximamente
      </h2>
      <p style={{ color: 'var(--mu)', maxWidth: 360, marginTop: 8 }}>
        Esta sección estará disponible en la próxima fase. Por ahora puedes usar el panel
        admin del motor desde la pestaña Resumen.
      </p>
    </div>
  );
}

/* ── Console tab ───────────────────────────────────────────────── */
function _generateFiles(brand, menu) {
  const date = new Date().toISOString().split('T')[0];
  const name = brand.name.es;
  const p    = brand.palette;

  const menuJs =
    `/* Generated for ${name} — ${date} */\n` +
    `/* Paste at the bottom of MENU structure/menu.js */\n\n` +
    `window.CATEGORIES = ${JSON.stringify(menu.categories, null, 2)};\n\n` +
    `window.MENU_ITEMS = ${JSON.stringify(menu.items.map(i => ({ ...i, descEn: i.description })), null, 2)};\n\n` +
    `window.STR.brand   = ${JSON.stringify(brand.name)};\n` +
    `window.STR.tagline = ${JSON.stringify(brand.tagline)};\n` +
    `window.MENU_ITEMS_STATIC = JSON.parse(JSON.stringify(window.MENU_ITEMS));\n`;

  const stylesOverrideCss =
    `/* Brand override for ${name} — ${date} */\n` +
    `/* Append at the end of MENU structure/styles.css */\n` +
    `/* OR save as brand-override.css and load it after styles.css in index.html */\n\n` +
    `:root {\n` +
    `  --bg:          ${p.bg         || '#0b0805'};\n` +
    `  --s1:          ${p.s1         || '#15110a'};\n` +
    `  --s2:          ${p.s2         || '#1f1a11'};\n` +
    `  --s3:          ${p.s3         || '#2a2418'};\n` +
    `  --s4:          ${p.s4         || '#38301f'};\n` +
    `  --gold:        ${p.gold       || '#c8923a'};\n` +
    `  --gold-light:  ${p.goldLight  || '#e5b86a'};\n` +
    `  --gold-pale:   ${p.goldPale   || '#f5dfa0'};\n` +
    `  --gold-deep:   ${p.goldDeep   || '#8a6326'};\n` +
    `  --tx:          ${p.tx         || '#f0e8d8'};\n` +
    `  --mu:          ${p.mu         || '#a09070'};\n` +
    `  --di:          ${p.di         || '#6a5a48'};\n` +
    `  --fa:          ${p.fa         || '#3a3020'};\n` +
    `  --line:        ${p.line       || 'rgba(245,223,160,0.08)'};\n` +
    `  --line-strong: ${p.lineStrong || 'rgba(245,223,160,0.18)'};\n` +
    `}\n`;

  return [
    { name: 'menu.js',              content: menuJs,             desc: 'Menú del restaurante' },
    { name: 'styles-override.css',  content: stylesOverrideCss,  desc: 'Paleta de marca' },
  ];
}

function ConsoleTab({ profile }) {
  const { brand, menu }             = profile;
  const [files, setFiles]           = useStateF(() => _generateFiles(brand, menu));
  const [selected, setSelected]     = useStateF(null);
  const [copied, setCopied]         = useStateF(null);
  const [aiStatus, setAiStatus]     = useStateF('idle'); // 'idle' | 'busy' | 'done' | 'error'

  const copyFile = (f) => {
    navigator.clipboard.writeText(f.content).then(() => {
      setCopied(f.name);
      setTimeout(() => setCopied(null), 2000);
    });
  };

  const downloadFile = (f) => {
    const a   = document.createElement('a');
    a.href    = URL.createObjectURL(new Blob([f.content], { type: 'text/plain' }));
    a.download = f.name;
    a.click();
    URL.revokeObjectURL(a.href);
  };

  const downloadAll = () => files.forEach(f => downloadFile(f));

  const enhanceWithAI = async () => {
    setAiStatus('busy');
    try {
      const prompt =
        `Restaurante: ${brand.name.es}\nTagline: ${brand.tagline.es}\n\n` +
        `Mejora las descripciones de los platillos del siguiente menú. ` +
        `Devuelve EXACTAMENTE el mismo JSON con los mismos IDs, categorías, nombres y precios, solo cambia las descripciones.\n\n` +
        JSON.stringify(menu, null, 2);
      const text     = await window._geminiGenerate({
        prompt,
        systemInstruction: 'Eres un experto en marketing gastronómico. Mejoras descripciones de menús de restaurante para hacerlas más apetitosas y atractivas, manteniendo la misma estructura JSON.',
        responseMimeType: 'application/json',
      });
      const enhanced = JSON.parse(text);
      const menuJs =
        `// Menu data — enhanced by Gemini 2.5 Flash-Lite\nwindow.MENU_DATA = ${JSON.stringify(enhanced, null, 2)};`;
      const stylesOverrideCss =
        `/* Brand palette — ${brand.name.es} */\n:root {\n` +
        `  --brand-primary: ${brand.palette.gold};\n` +
        `  --brand-light: ${brand.palette.goldLight};\n` +
        `  --brand-pale: ${brand.palette.goldPale};\n` +
        `  --brand-deep: ${brand.palette.goldDeep};\n` +
        `  --brand-bg: ${brand.palette.bg};\n}\n`;
      setFiles([
        { name: 'menu.js',             content: menuJs,            desc: 'Menú mejorado por IA' },
        { name: 'styles-override.css', content: stylesOverrideCss, desc: 'Paleta de marca' },
      ]);
      setSelected(null);
      setAiStatus('done');
    } catch (_) {
      setAiStatus('error');
    }
  };

  return (
    <div>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <div className="eyebrow">Consola de despliegue</div>
          <h1 className="serif" style={{ fontSize: 40, fontStyle: 'italic', fontWeight: 400, margin: '8px 0 4px' }}>
            MENU structure
          </h1>
          <p style={{ fontSize: 13, color: 'var(--mu)', maxWidth: 560, marginTop: 6 }}>
            Archivos generados para <span className="mono">{brand.name.es}</span>. Descárgalos y reemplaza los originales en la carpeta{' '}
            <span className="mono">MENU structure/</span>, luego despliega con{' '}
            <span className="mono">firebase deploy --only hosting:tatavasco</span>.
          </p>
        </div>
        <div style={{ display: 'flex', gap: 10, flexShrink: 0 }}>
          {aiStatus === 'done' && (
            <div style={{ fontSize: 12, color: '#2f7a3a', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4 }}>
              ✓ Mejorado con IA
            </div>
          )}
          {aiStatus === 'error' && (
            <div style={{ fontSize: 12, color: '#c0392b' }}>Error — intenta de nuevo</div>
          )}
          {aiStatus !== 'done' && (
            <button className="btn" onClick={enhanceWithAI} disabled={aiStatus === 'busy'}>
              {aiStatus === 'busy' ? '✦ Mejorando con IA…' : '✦ Mejorar con IA'}
            </button>
          )}
        </div>
      </div>

      {/* AI status banner */}
      {aiStatus === 'busy' && (
        <div style={{
          padding: '12px 18px', background: 'var(--paper)', border: '1px solid var(--line)',
          borderRadius: 'var(--r-md)', marginBottom: 20,
          display: 'flex', alignItems: 'center', gap: 12, fontSize: 13, color: 'var(--mu)',
        }}>
          <div className="spin" style={{
            width: 18, height: 18, borderRadius: '50%',
            border: '2px solid var(--line)', borderTopColor: 'var(--ink)',
          }} />
          Gemini está mejorando las descripciones de tus platillos…
        </div>
      )}

      {/* Layout: file list + code viewer */}
      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 20, minHeight: 420 }}>
        {/* File list */}
        <div className="card" style={{ overflow: 'hidden', alignSelf: 'start' }}>
          <div style={{
            padding: '10px 16px', borderBottom: '1px solid var(--line)',
            fontSize: 11, color: 'var(--mu)', letterSpacing: '0.1em', textTransform: 'uppercase',
          }}>
            Archivos generados
          </div>

          {files.map(f => (
            <div key={f.name}
              onClick={() => setSelected(f)}
              style={{
                padding: '13px 16px', cursor: 'pointer',
                background: selected?.name === f.name ? 'var(--bg)' : 'transparent',
                borderBottom: '1px solid var(--line)',
                transition: 'background 120ms',
              }}>
              <div className="mono" style={{ fontSize: 13, fontWeight: 500 }}>{f.name}</div>
              <div style={{ fontSize: 11, color: 'var(--mu)', marginTop: 3 }}>{f.desc}</div>
            </div>
          ))}

          <div style={{ padding: 16 }}>
            <div style={{ fontSize: 11, color: 'var(--mu)', marginBottom: 10, lineHeight: 1.6 }}>
              <strong style={{ display: 'block', marginBottom: 4 }}>Instrucciones:</strong>
              1. Descarga los archivos<br/>
              2. Reemplaza en <span className="mono">MENU structure/</span><br/>
              3. <span className="mono">firebase deploy</span>
            </div>
            <button className="btn ghost" onClick={downloadAll}
              style={{ width: '100%', fontSize: 12 }}>
              ↓ Descargar todo
            </button>
          </div>
        </div>

        {/* Code viewer */}
        <div className="card" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 420 }}>
          {selected ? (
            <>
              <div style={{
                padding: '11px 16px', borderBottom: '1px solid var(--line)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                flexShrink: 0,
              }}>
                <span className="mono" style={{ fontSize: 13, fontWeight: 500 }}>{selected.name}</span>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="btn ghost" style={{ fontSize: 12 }}
                    onClick={() => copyFile(selected)}>
                    {copied === selected.name ? '✓ Copiado' : 'Copiar'}
                  </button>
                  <button className="btn" style={{ fontSize: 12 }}
                    onClick={() => downloadFile(selected)}>
                    ↓ Descargar
                  </button>
                </div>
              </div>
              <pre style={{
                flex: 1, overflowY: 'auto', padding: '16px 20px', margin: 0,
                fontFamily: 'var(--mono)', fontSize: 12, lineHeight: 1.65,
                color: 'var(--mu)', background: 'var(--bg)',
                whiteSpace: 'pre-wrap', wordBreak: 'break-word', maxHeight: 480,
              }}>
                {selected.content}
              </pre>
            </>
          ) : (
            <div style={{
              flex: 1, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
              color: 'var(--mu)', gap: 10, padding: 32, textAlign: 'center',
            }}>
              <div style={{ fontSize: 28 }}>❯_</div>
              <div style={{ fontSize: 14 }}>Selecciona un archivo para ver su contenido</div>
              <div style={{ fontSize: 12, opacity: 0.7 }}>
                Haz clic en <span className="mono">menu.js</span> o <span className="mono">styles-override.css</span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.FactoryAppRoot = FactoryApp;
