/* AUTH · Orgullo Millonario — login / register / forgot · Liquid Glass
   Route guards + sesión demo en OM-Auth (localStorage). */
const {useState,useRef,useEffect}=React;
const PAGE=document.body.dataset.page||'login';

const I={
  user:<><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></>,
  mail:<><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></>,
  lock:<><rect x="4" y="11" width="16" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></>,
  eye:<><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6Z"/><circle cx="12" cy="12" r="2.5"/></>,
  eyeoff:<><path d="M3 3l18 18M10.5 10.6a2.5 2.5 0 0 0 3 3M6.5 6.6C4 8.2 2 12 2 12s3.5 6 10 6c1.7 0 3.2-.4 4.5-1M9.8 5.2A9.6 9.6 0 0 1 12 5c6.5 0 10 6 10 6a17 17 0 0 1-2.2 2.9"/></>,
  arrow:<path d="M5 12h14M13 6l6 6-6 6"/>,
  back:<path d="M19 12H5M11 6l-6 6 6 6"/>,
};
const Ic=({n,s=18,c=""})=><svg viewBox="0 0 24 24" width={s} height={s} className={c} fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{I[n]}</svg>;

function Field({icon,type='text',value,onChange,placeholder,reveal,onReveal,onEnter}){
  return <label className="flex items-center gap-3 bg-white/[.06] border border-white/12 rounded-2xl px-4 py-3.5 focus-within:border-river/60 transition-colors">
    <span className="text-mut flex-none"><Ic n={icon} s={17}/></span>
    <input type={type} value={value} onChange={e=>onChange(e.target.value)} onKeyDown={e=>e.key==='Enter'&&onEnter&&onEnter()} placeholder={placeholder}
      className="flex-1 bg-transparent text-[14px] font-medium outline-none placeholder:text-dim min-w-0"/>
    {onReveal&&<button type="button" onClick={onReveal} className="press text-mut hover:text-ink flex-none"><Ic n={reveal?'eyeoff':'eye'} s={17}/></button>}
  </label>;
}

function Shell({children,title,sub}){
  return <div className="relative min-h-[100dvh] flex items-center justify-center px-4 py-8">
    <div className="blob w-[520px] h-[520px] -top-40 -left-24" style={{background:'radial-gradient(circle,#8d0917,transparent 70%)',opacity:.55,animation:'drift1 18s ease-in-out infinite'}}/>
    <div className="blob w-[440px] h-[440px] -bottom-40 -right-24" style={{background:'radial-gradient(circle,#3b1d6e,transparent 70%)',opacity:.5,animation:'drift2 22s ease-in-out infinite'}}/>
    <div className="blob w-[360px] h-[360px] top-1/4 right-1/3" style={{background:'radial-gradient(circle,#5a4008,transparent 70%)',opacity:.35,animation:'drift1 26s ease-in-out infinite'}}/>
    <main className="relative z-10 w-full max-w-[420px]">
      <div className="glass-deep rounded-glass p-6 md:p-8 rise">
        <div className="flex flex-col items-center text-center mb-6">
          <img src="assets/logo-om.webp" alt="OM" className="w-14 h-16 object-contain mb-3 drop-shadow-[0_6px_18px_rgba(224,30,47,.4)]"/>
          <h1 className="font-disp text-[26px] md:text-[30px] leading-[.95] tracking-[.5px]">{title}</h1>
          <p className="text-mut text-[12.5px] mt-2 max-w-[300px]">{sub}</p>
        </div>
        {children}
      </div>
      <p className="text-center font-mono text-[8px] tracking-[1.5px] text-dim mt-5">ORGULLO MILLONARIO ® 2026 · <a href="index.html" className="text-river2">VOLVER AL SITIO</a></p>
    </main>
  </div>;
}

const btnPrimary={background:'linear-gradient(160deg,#ff2e3e,#8d0917)',boxShadow:'0 12px 30px -8px rgba(224,30,47,.6)'};

function SocialRow(){
  const toast=t=>{const el=document.getElementById('mini-toast');el.textContent=t;el.style.opacity=1;clearTimeout(window.__mt);window.__mt=setTimeout(()=>el.style.opacity=0,2200);};
  return <>
    <div className="flex items-center gap-3 my-5"><i className="h-px flex-1 bg-white/12"/><span className="font-mono text-[8px] tracking-[2px] text-dim">O CONTINUÁ CON</span><i className="h-px flex-1 bg-white/12"/></div>
    <div className="grid grid-cols-2 gap-2.5">
      {[['Google','G'],['Apple','']].map(([n,g])=>(
        <button key={n} onClick={()=>toast('Acceso con '+n+' — conectá el proveedor en producción')} className="press glass rounded-2xl py-3 text-[12.5px] font-bold flex items-center justify-center gap-2 text-ink">
          <span className="font-disp text-[15px]">{g}</span>{n}</button>))}
    </div>
  </>;
}

function Login(){
  const [email,setEmail]=useState('');const [pass,setPass]=useState('');const [show,setShow]=useState(false);
  const [err,setErr]=useState('');const [loading,setLoading]=useState(false);
  const submit=()=>{setErr('');setLoading(true);
    Promise.resolve(OMAuth.loginCloud?OMAuth.loginCloud(email,pass):OMAuth.login(email,pass)).then(r=>{if(r.ok){location.href='dashboard.html';}else{setErr(r.error);setLoading(false);}});};
  return <Shell title="Acceso a Hinchas" sub="Ingresá para gestionar tus viajes, coleccionar figuritas y acceder a beneficios exclusivos.">
    <div className="flex flex-col gap-3">
      <Field icon="mail" type="email" value={email} onChange={setEmail} placeholder="Correo electrónico" onEnter={submit}/>
      <Field icon="lock" type={show?'text':'password'} value={pass} onChange={setPass} placeholder="Contraseña" reveal={show} onReveal={()=>setShow(!show)} onEnter={submit}/>
      <div className="flex justify-end -mt-1"><a href="forgot.html" className="font-mono text-[10px] text-river2 tracking-[.5px]">¿Olvidaste tu contraseña?</a></div>
      {err&&<div className="text-[12px] text-river2 bg-river/10 border border-river/30 rounded-xl px-3 py-2">{err}</div>}
      <button onClick={submit} disabled={loading} className="press rounded-2xl py-3.5 text-[14px] font-bold text-white flex items-center justify-center gap-2 mt-1" style={btnPrimary}>{loading?'Ingresando…':<>INGRESAR <Ic n="arrow" s={16}/></>}</button>
    </div>
    <SocialRow/>
    <p className="text-center text-[12px] text-mut mt-6">¿No tenés cuenta? <a href="register.html" className="text-river2 font-bold">Registrate</a></p>
  </Shell>;
}

function Register(){
  const [nombre,setNombre]=useState('');const [email,setEmail]=useState('');const [pass,setPass]=useState('');const [show,setShow]=useState(false);
  const [err,setErr]=useState('');const [loading,setLoading]=useState(false);
  const submit=()=>{setErr('');setLoading(true);
    const ref=new URLSearchParams(location.search).get('ref')||'';
    Promise.resolve(OMAuth.registerCloud?OMAuth.registerCloud({nombre,email,pass,ref}):OMAuth.register({nombre,email,pass,ref})).then(r=>{if(r.ok){location.href='dashboard.html';}else{setErr(r.error);setLoading(false);}});};
  const refCode=new URLSearchParams(location.search).get('ref');
  return <Shell title="Sumate a la Banda" sub="Creá tu cuenta gratis y empezá a coleccionar, viajar y ganar premios con la hinchada.">
    {refCode&&<div className="mb-4 rounded-2xl px-4 py-3 text-[12px] flex items-center gap-2.5" style={{background:'rgba(255,207,62,.12)',border:'1px solid rgba(255,207,62,.35)',color:'#ffcf3e'}}><span className="text-[15px]">🎁</span><span><b>Invitación de {refCode}</b> — registrate y recibís <b>1.000 créditos</b> de bienvenida.</span></div>}
    <div className="flex flex-col gap-3">
      <Field icon="user" value={nombre} onChange={setNombre} placeholder="Nombre completo" onEnter={submit}/>
      <Field icon="mail" type="email" value={email} onChange={setEmail} placeholder="Correo electrónico" onEnter={submit}/>
      <Field icon="lock" type={show?'text':'password'} value={pass} onChange={setPass} placeholder="Creá una contraseña" reveal={show} onReveal={()=>setShow(!show)} onEnter={submit}/>
      {err&&<div className="text-[12px] text-river2 bg-river/10 border border-river/30 rounded-xl px-3 py-2">{err}</div>}
      <button onClick={submit} disabled={loading} className="press rounded-2xl py-3.5 text-[14px] font-bold text-white flex items-center justify-center gap-2 mt-1" style={btnPrimary}>{loading?'Creando cuenta…':<>CREAR MI CUENTA <Ic n="arrow" s={16}/></>}</button>
    </div>
    <SocialRow/>
    <p className="text-center text-[12px] text-mut mt-6">¿Ya sos parte? <a href="login.html" className="text-river2 font-bold">Iniciá sesión</a></p>
  </Shell>;
}

function Forgot(){
  const [email,setEmail]=useState('');const [sent,setSent]=useState(false);
  const submit=()=>{if(/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email))setSent(true);};
  return <Shell title="Recuperar acceso" sub={sent?'Si el correo existe, te enviamos un enlace para restablecer tu contraseña.':'Ingresá tu correo y te enviaremos instrucciones para volver a entrar.'}>
    {sent
      ?<div className="flex flex-col items-center gap-4">
        <div className="w-14 h-14 rounded-full grid place-items-center text-green-400 text-[26px]" style={{background:'rgba(34,197,94,.15)',border:'1px solid rgba(34,197,94,.4)'}}>✓</div>
        <a href="login.html" className="press rounded-2xl py-3.5 w-full text-center text-[14px] font-bold text-white" style={btnPrimary}>Volver a ingresar</a>
      </div>
      :<div className="flex flex-col gap-3">
        <Field icon="mail" type="email" value={email} onChange={setEmail} placeholder="Correo electrónico" onEnter={submit}/>
        <button onClick={submit} className="press rounded-2xl py-3.5 text-[14px] font-bold text-white flex items-center justify-center gap-2 mt-1" style={btnPrimary}>ENVIAR ENLACE <Ic n="arrow" s={16}/></button>
        <a href="login.html" className="press flex items-center justify-center gap-2 text-[12px] text-mut hover:text-ink mt-1"><Ic n="back" s={15}/> Volver</a>
      </div>}
  </Shell>;
}

const PAGES={login:Login,register:Register,forgot:Forgot};
const Comp=PAGES[PAGE]||Login;
ReactDOM.createRoot(document.getElementById('root')).render(<><Comp/><div id="mini-toast" className="fixed left-1/2 -translate-x-1/2 bottom-8 z-[90] glass rounded-2xl px-5 py-3 text-[13px] font-semibold pointer-events-none transition-opacity duration-300" style={{opacity:0}}></div></>);
