// mnm-auth.jsx — Login + Register + Onboarding (3 steps)
const { useState } = React;

/* ─── ENTRY METHOD ICONS (20px) ──────────────────────────────────────────────── */
const IcForm  = ()=><svg width="20" height="20" viewBox="0 0 20 20" fill="none"><rect x="4" y="3" width="12" height="15" rx="2" stroke="currentColor" strokeWidth="1.4"/><path d="M7.5 7.5h5M7.5 10.5h5M7.5 13.5h3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>;
const IcBubble= ()=><svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M17 9.5C17 13.09 13.87 16 10 16H8.5L5 18V16H3C2.45 16 2 15.55 2 15V6C2 5.45 2.45 5 3 5H17V9.5Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M6 9.5h8M6 12h5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;
const IcMicSm = ()=><svg width="20" height="20" viewBox="0 0 20 20" fill="none"><rect x="7" y="2" width="6" height="9" rx="3" stroke="currentColor" strokeWidth="1.4"/><path d="M4 10.5C4 13.54 6.69 16 10 16s6-2.46 6-5.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/><path d="M10 16v3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>;
const IcFolder= ()=><svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M2 7V15a2 2 0 002 2h12a2 2 0 002-2V8a2 2 0 00-2-2H9.5L8 4H4a2 2 0 00-2 3z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>;
const IcBank  = ()=><svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M10 3L18 7.5H2L10 3z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M2 7.5h16M2 17h16" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/><path d="M5 8v9M10 8v9M15 8v9" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>;
const IcMsg   = ()=><svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M18 10C18 14.42 14.42 18 10 18C8.72 18 7.5 17.66 6.44 17.07L2 18L2.93 13.56C2.34 12.5 2 11.28 2 10C2 5.58 5.58 2 10 2C14.42 2 18 5.58 18 10z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>;

/* ─── ONBOARDING STEP 1 ICONS (24px) ────────────────────────────────────────── */
const IcSeedling = ()=><svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M12 22V13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/><path d="M12 13C12 13 7.5 11 5.5 6C10 4 14.5 7 12 13z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M12 17C12 17 16.5 15 18.5 10C14 8 9.5 11 12 17z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg>;
const IcTrendUp  = ()=><svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M3 17L9 11L13 15L21 7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><path d="M15 7h6v6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>;
const IcBuildings= ()=><svg width="24" height="24" viewBox="0 0 24 24" fill="none"><rect x="2" y="9" width="9" height="13" rx="1" stroke="currentColor" strokeWidth="1.4"/><rect x="11" y="4" width="11" height="18" rx="1" stroke="currentColor" strokeWidth="1.4"/><path d="M5 13h3M5 17h3M14 8h5M14 12h5M14 16h5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;

/* ─── AUTH SHELL ─────────────────────────────────────────────────────────────── */
function AuthShell({ onBack, title, subtitle, children }) {
  return (
    <div style={{height:'100vh',background:'var(--bg)',display:'flex',flexDirection:'column',overflow:'hidden'}}>
      {/* Top bar */}
      <div style={{padding:'16px 28px',display:'flex',alignItems:'center',justifyContent:'space-between',borderBottom:'1px solid var(--border)',flexShrink:0}}>
        <button onClick={onBack} style={{display:'flex',alignItems:'center',gap:'6px',background:'none',border:'none',color:'var(--t2)',cursor:'pointer',fontSize:'13px',fontFamily:'var(--font)'}}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M10 3L6 8L10 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          Volver
        </button>
        <div style={{display:'flex',alignItems:'center',gap:'8px'}}>
          <div style={{width:'28px',height:'28px',background:'var(--accent)',borderRadius:'8px',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'10px',fontWeight:800,color:'var(--accent-text)'}}>MN</div>
          <span style={{fontSize:'13px',fontWeight:700,color:'var(--t1)'}}>Mi Negocio en Números</span>
        </div>
        <div style={{width:'60px'}}/>
      </div>

      {/* Form area */}
      <div style={{flex:1,overflowY:'auto',display:'flex',alignItems:'flex-start',justifyContent:'center',padding:'40px 20px 40px'}}>
        <div style={{width:'100%',maxWidth:'420px',animation:'fadeInUp 0.3s ease'}}>
          <h1 style={{fontSize:'26px',fontWeight:800,color:'var(--t1)',marginBottom:'6px',letterSpacing:'-0.02em'}}>{title}</h1>
          {subtitle && <p style={{fontSize:'14px',color:'var(--t2)',marginBottom:'28px',lineHeight:1.55}}>{subtitle}</p>}
          {children}
        </div>
      </div>
    </div>
  );
}

/* ─── OAUTH BUTTONS ──────────────────────────────────────────────────────────── */
function OAuthButtons({ label }) {
  const base = {width:'100%',padding:'11px',borderRadius:'100px',fontSize:'13.5px',fontWeight:600,cursor:'pointer',fontFamily:'var(--font)',display:'flex',alignItems:'center',justifyContent:'center',gap:'10px',transition:'opacity 0.15s'};
  return (
    <div style={{display:'flex',flexDirection:'column',gap:'10px'}}>
      <button onClick={()=>{}} style={{...base,background:'var(--surf-2)',border:'1px solid var(--border-2)',color:'var(--t1)'}}>
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.616z" fill="#4285F4"/><path d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A9 9 0 0 0 9 18z" fill="#34A853"/><path d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A9 9 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" fill="#FBBC05"/><path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A9 9 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/></svg>
        {label} con Google
      </button>
    </div>
  );
}

/* ─── DIVIDER ────────────────────────────────────────────────────────────────── */
function Divider() {
  return (
    <div style={{display:'flex',alignItems:'center',gap:'12px',margin:'18px 0'}}>
      <div style={{flex:1,height:'1px',background:'var(--border)'}}/>
      <span style={{fontSize:'12px',color:'var(--t3)'}}>o continúa con email</span>
      <div style={{flex:1,height:'1px',background:'var(--border)'}}/>
    </div>
  );
}

/* ─── FIELD ──────────────────────────────────────────────────────────────────── */
function Field({label,type='text',value,onChange,placeholder,error}) {
  return (
    <div style={{marginBottom:'14px'}}>
      <label style={{fontSize:'12px',fontWeight:600,color:'var(--t2)',display:'block',marginBottom:'6px'}}>{label}</label>
      <input type={type} value={value} onChange={e=>onChange(e.target.value)}
        placeholder={placeholder}
        style={{width:'100%',padding:'11px 14px',borderRadius:'var(--radius-sm)',fontSize:'13.5px',borderColor:error?'var(--s-red)':'var(--border)'}}/>
      {error&&<p style={{fontSize:'11.5px',color:'var(--s-red)',margin:'5px 0 0'}}>{error}</p>}
    </div>
  );
}

/* ─── LOGIN ──────────────────────────────────────────────────────────────────── */
function LoginPage({ onBack, onSuccess, onRegister }) {
  const [email,setEmail] = useState('');
  const [pass,setPass]   = useState('');
  const [err,setErr]     = useState('');

  const submit = ()=>{
    if(!email.trim()||!pass.trim()){setErr('Completa todos los campos');return;}
    onSuccess();
  };

  return (
    <AuthShell onBack={onBack} title="Iniciar sesión" subtitle="Bienvenido de vuelta a tu dashboard financiero.">
      <OAuthButtons label="Continuar"/>
      <Divider/>
      <Field label="Email" type="email" value={email} onChange={setEmail} placeholder="tu@empresa.com"/>
      <Field label="Contraseña" type="password" value={pass} onChange={setPass} placeholder="••••••••"/>
      {err&&<p style={{fontSize:'12px',color:'var(--s-red)',marginBottom:'12px'}}>{err}</p>}
      <button onClick={submit} style={{width:'100%',padding:'12px',borderRadius:'100px',background:'var(--accent)',border:'none',color:'var(--accent-text)',fontSize:'14px',fontWeight:700,cursor:'pointer',fontFamily:'var(--font)',marginBottom:'16px'}}>
        Iniciar sesión
      </button>
      <p style={{fontSize:'13px',color:'var(--t3)',textAlign:'center'}}>
        ¿No tienes cuenta? <button onClick={onRegister} style={{color:'var(--accent)',background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font)',fontSize:'13px',fontWeight:600}}>Créala gratis</button>
      </p>
      <div style={{marginTop:'20px',padding:'14px',background:'var(--surf-2)',borderRadius:'var(--radius-sm)',border:'1px solid var(--border)'}}>
        <p style={{fontSize:'12px',color:'var(--t3)',margin:'0 0 8px',fontWeight:600}}>Demo rápido</p>
        <p style={{fontSize:'12px',color:'var(--t3)',margin:'0 0 10px',lineHeight:1.5}}>Accede sin crear cuenta para explorar el prototipo.</p>
        <button onClick={onSuccess} style={{width:'100%',padding:'9px',borderRadius:'100px',background:'none',border:'1px solid var(--border-2)',color:'var(--t2)',fontSize:'12.5px',fontWeight:600,cursor:'pointer',fontFamily:'var(--font)'}}>
          Acceder como demo →
        </button>
      </div>
    </AuthShell>
  );
}

/* ─── REGISTER ───────────────────────────────────────────────────────────────── */
function RegisterPage({ onBack, onSuccess, onLogin }) {
  const [nombre,setNombre]   = useState('');
  const [email,setEmail]     = useState('');
  const [pass,setPass]       = useState('');
  const [errors,setErrors]   = useState({});

  const submit = ()=>{
    const e={};
    if(!nombre.trim()) e.nombre='Requerido';
    if(!email.trim()) e.email='Requerido';
    if(pass.length<6) e.pass='Mínimo 6 caracteres';
    setErrors(e);
    if(!Object.keys(e).length) onSuccess();
  };

  return (
    <AuthShell onBack={onBack} title="Crea tu cuenta gratis" subtitle="Sin tarjeta de crédito. Empieza en 2 minutos.">
      <OAuthButtons label="Registrarme"/>
      <Divider/>
      <Field label="Nombre completo" value={nombre} onChange={setNombre} placeholder="Ana García" error={errors.nombre}/>
      <Field label="Email" type="email" value={email} onChange={setEmail} placeholder="tu@empresa.com" error={errors.email}/>
      <Field label="Contraseña" type="password" value={pass} onChange={setPass} placeholder="Mínimo 6 caracteres" error={errors.pass}/>
      <button onClick={submit} style={{width:'100%',padding:'12px',borderRadius:'100px',background:'var(--accent)',border:'none',color:'var(--accent-text)',fontSize:'14px',fontWeight:700,cursor:'pointer',fontFamily:'var(--font)',marginBottom:'12px',marginTop:'4px'}}>
        Crear cuenta →
      </button>
      <p style={{fontSize:'11.5px',color:'var(--t3)',textAlign:'center',lineHeight:1.5,marginBottom:'14px'}}>Al registrarte aceptas los Términos de Servicio y la Política de Privacidad.</p>
      <p style={{fontSize:'13px',color:'var(--t3)',textAlign:'center'}}>
        ¿Ya tienes cuenta? <button onClick={onLogin} style={{color:'var(--accent)',background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font)',fontSize:'13px',fontWeight:600}}>Inicia sesión</button>
      </p>
    </AuthShell>
  );
}

/* ─── ONBOARDING ─────────────────────────────────────────────────────────────── */
const VERTICALS = ['Restaurante / Food service','Retail / E-commerce','Servicios profesionales','SaaS / Tech','Manufactura','Salud y bienestar','Educación','Construcción','Otro'];
const ENTRY_METHODS = [
  {id:'form', icon:<IcForm/>,   label:'Formulario manual',     desc:'Lleno los campos paso a paso.'},
  {id:'chat', icon:<IcBubble/>, label:'Chat con IA',           desc:'La IA me pregunta y yo respondo.'},
  {id:'voice',icon:<IcMicSm/>, label:'Nota de voz',           desc:'Grabo un audio describiendo mis números.'},
  {id:'file', icon:<IcFolder/>, label:'Importar archivo',      desc:'Subo un CSV o Excel de mi contabilidad.'},
  {id:'bank', icon:<IcBank/>,   label:'Conectar banco',        desc:'Open Banking — el banco más seguro.'},
  {id:'wp',   icon:<IcMsg/>,    label:'WhatsApp',              desc:'Mando fotos o texto a nuestro número.'},
];

function OnboardingPage({ onComplete, onSkip }) {
  const [step,setStep]         = useState(0);
  const [etapa,setEtapa]       = useState('');
  const [vertical,setVertical] = useState('');
  const [metodo,setMetodo]     = useState('');

  const STEPS = [
    {
      title:'¿En qué etapa está tu empresa?',
      subtitle:'Configuramos tu dashboard según esto.',
      content:(
        <div style={{display:'flex',flexDirection:'column',gap:'10px'}}>
          {[
            {id:'pre',  icon:<IcSeedling/>, l:'Todavía no facturo (pre-revenue)',d:'Estoy construyendo o validando la idea'},
            {id:'op',   icon:<IcTrendUp/>,  l:'Ya facturo (en operación)',d:'Tengo ventas, aunque sean irregulares'},
            {id:'multi',icon:<IcBuildings/>,l:'Tengo varias empresas',d:'Administro más de una entidad o marca'},
          ].map(o=>(
            <button key={o.id} onClick={()=>setEtapa(o.id)} style={{
              display:'flex',alignItems:'center',gap:'14px',padding:'14px 18px',
              borderRadius:'var(--radius)',border:`1px solid ${etapa===o.id?'var(--accent-border)':'var(--border)'}`,
              background:etapa===o.id?'var(--accent-bg)':'var(--surf-2)',
              cursor:'pointer',textAlign:'left',fontFamily:'var(--font)',
              boxShadow:etapa===o.id?'0 0 0 1px var(--accent-border)':'none',
              transition:'all 0.15s',
            }}>
              <span style={{color:etapa===o.id?'var(--accent)':'var(--t3)',lineHeight:0,flexShrink:0}}>{o.icon}</span>
              <div>
                <p style={{fontSize:'14px',fontWeight:600,color:'var(--t1)',margin:'0 0 3px'}}>{o.l}</p>
                <p style={{fontSize:'12px',color:'var(--t2)',margin:0}}>{o.d}</p>
              </div>
            </button>
          ))}
        </div>
      ),
      canNext: !!etapa,
    },
    {
      title:'¿En qué industria operas?',
      subtitle:'Pre-seleccionamos los KPIs más relevantes para tu sector.',
      content:(
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'8px'}}>
          {VERTICALS.map(v=>(
            <button key={v} onClick={()=>setVertical(v)} style={{
              padding:'12px 14px',borderRadius:'var(--radius-sm)',
              border:`1px solid ${vertical===v?'var(--accent-border)':'var(--border)'}`,
              background:vertical===v?'var(--accent-bg)':'var(--surf-2)',
              color:vertical===v?'var(--accent)':'var(--t2)',
              fontSize:'12.5px',fontWeight:vertical===v?600:400,cursor:'pointer',
              textAlign:'left',fontFamily:'var(--font)',transition:'all 0.12s',
            }}>{v}</button>
          ))}
        </div>
      ),
      canNext: !!vertical,
    },
    {
      title:'¿Cómo prefieres ingresar tus datos?',
      subtitle:'Puedes cambiar esto en cualquier momento.',
      content:(
        <div style={{display:'flex',flexDirection:'column',gap:'8px'}}>
          {ENTRY_METHODS.map(m=>(
            <button key={m.id} onClick={()=>setMetodo(m.id)} style={{
              display:'flex',alignItems:'center',gap:'14px',padding:'12px 16px',
              borderRadius:'var(--radius-sm)',border:`1px solid ${metodo===m.id?'var(--accent-border)':'var(--border)'}`,
              background:metodo===m.id?'var(--accent-bg)':'var(--surf-2)',
              cursor:'pointer',textAlign:'left',fontFamily:'var(--font)',
              transition:'all 0.12s',
            }}>
            <span style={{color:metodo===m.id?'var(--accent)':'var(--t3)',lineHeight:0}}>{m.icon}</span>
              <div>
                <p style={{fontSize:'13.5px',fontWeight:600,color:metodo===m.id?'var(--accent)':'var(--t1)',margin:'0 0 2px'}}>{m.label}</p>
                <p style={{fontSize:'11.5px',color:'var(--t2)',margin:0}}>{m.desc}</p>
              </div>
            </button>
          ))}
        </div>
      ),
      canNext: !!metodo,
    },
  ];

  const cur = STEPS[step];

  return (
    <div style={{height:'100vh',background:'var(--bg)',display:'flex',flexDirection:'column',overflow:'hidden'}}>
      {/* Top bar */}
      <div style={{padding:'16px 28px',display:'flex',alignItems:'center',justifyContent:'space-between',borderBottom:'1px solid var(--border)',flexShrink:0}}>
        <div style={{display:'flex',alignItems:'center',gap:'8px'}}>
          <div style={{width:'28px',height:'28px',background:'var(--accent)',borderRadius:'8px',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'10px',fontWeight:800,color:'var(--accent-text)'}}>MN</div>
          <span style={{fontSize:'13px',fontWeight:700,color:'var(--t1)'}}>Configuración inicial</span>
        </div>
        <div style={{display:'flex',gap:'6px',alignItems:'center'}}>
          {STEPS.map((_,i)=>(
            <div key={i} style={{width:i===step?24:8,height:8,borderRadius:'100px',background:i<=step?'var(--accent)':'var(--surf-3)',transition:'all 0.25s'}}/>
          ))}
          <span style={{fontSize:'12px',color:'var(--t3)',marginLeft:'6px'}}>Paso {step+1} de {STEPS.length}</span>
        </div>
        <button onClick={onSkip} style={{fontSize:'12px',color:'var(--t3)',background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font)'}}>Omitir →</button>
      </div>

      <div style={{flex:1,overflowY:'auto',display:'flex',alignItems:'flex-start',justifyContent:'center',padding:'36px 20px'}}>
        <div style={{width:'100%',maxWidth:'480px',animation:'fadeInUp 0.25s ease'}}>
          <h2 style={{fontSize:'24px',fontWeight:800,color:'var(--t1)',marginBottom:'8px',letterSpacing:'-0.02em'}}>{cur.title}</h2>
          <p style={{fontSize:'14px',color:'var(--t2)',marginBottom:'24px'}}>{cur.subtitle}</p>
          {cur.content}
          <div style={{display:'flex',gap:'10px',marginTop:'28px',justifyContent:'space-between'}}>
            {step>0
              ? <button onClick={()=>setStep(s=>s-1)} style={{padding:'11px 20px',borderRadius:'100px',background:'none',border:'1px solid var(--border-2)',color:'var(--t2)',fontSize:'13.5px',fontWeight:600,cursor:'pointer',fontFamily:'var(--font)'}}>← Atrás</button>
              : <div/>}
            <button onClick={()=>step<STEPS.length-1?setStep(s=>s+1):onComplete()} disabled={!cur.canNext} style={{
              padding:'11px 28px',borderRadius:'100px',
              background:cur.canNext?'var(--accent)':'var(--surf-3)',
              border:'none',color:cur.canNext?'var(--accent-text)':'var(--t3)',
              fontSize:'13.5px',fontWeight:700,cursor:cur.canNext?'pointer':'default',fontFamily:'var(--font)',
              transition:'all 0.15s',
            }}>
              {step<STEPS.length-1?'Continuar →':'Ir a mi dashboard →'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage, RegisterPage, OnboardingPage });
