/* Portal login modal — abre ao clicar em "Acessar portal" */

function PortalModal({ open, onClose }) {
  const [email, setEmail] = React.useState("");
  const [pwd, setPwd] = React.useState("");
  const [mode, setMode] = React.useState("login"); // login | sso | mfa
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape" && open) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const submit = (e) => {
    e?.preventDefault?.();
    setLoading(true);
    setTimeout(() => { setLoading(false); setMode("mfa"); }, 900);
  };

  return <div
    onClick={onClose}
    style={{
      position:"fixed", inset:0, zIndex:100, background:"rgba(14,17,24,0.62)",
      backdropFilter:"blur(8px)", display:"flex", alignItems:"center", justifyContent:"center",
      padding:24, animation:"fadeIn 200ms cubic-bezier(0.2,0,0,1)",
    }}>
    <style>{`@keyframes fadeIn{from{opacity:0}to{opacity:1}}
    @keyframes slideUp{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
    .portal-input:focus{outline:none;border-color:${BRAND[500]};box-shadow:0 0 0 3px ${BRAND[600]}22;}`}</style>
    <div onClick={e=>e.stopPropagation()} style={{
      background:"white", width:"100%", maxWidth:960, borderRadius:14, overflow:"hidden",
      display:"grid", gridTemplateColumns:"1fr 1.1fr", minHeight:560,
      boxShadow:"0 40px 80px rgba(0,0,0,0.3)", animation:"slideUp 240ms cubic-bezier(0.2,0,0,1)",
    }}>
      {/* Left: brand pane */}
      <div style={{background:BRAND.ink950, color:"white", padding:"40px 36px", display:"flex", flexDirection:"column", justifyContent:"space-between", position:"relative", overflow:"hidden"}}>
        <div style={{position:"absolute", inset:0, backgroundImage:`linear-gradient(${BRAND.ink900} 1px, transparent 1px), linear-gradient(90deg, ${BRAND.ink900} 1px, transparent 1px)`, backgroundSize:"56px 56px", opacity:0.45}}/>
        <div style={{position:"relative"}}>
          <Lockup size={24} color="white" symbolColor={BRAND[300]}/>
        </div>
        <div style={{position:"relative"}}>
          <Mono color={BRAND[300]}>Portal do cliente</Mono>
          <div style={{fontFamily:"'Fraunces'", fontWeight:300, fontSize:40, lineHeight:1.05, letterSpacing:"-0.025em", marginTop:14}}>
            Suas carteiras,<br/><span style={{fontStyle:"italic", fontWeight:400}}>sempre verificadas.</span>
          </div>
          <p style={{fontSize:13.5, lineHeight:1.6, color:BRAND.ink300, marginTop:20, maxWidth:340}}>
            Acesso exclusivo para clientes Prolastro. Autenticação por e-mail corporativo com 2FA obrigatório.
          </p>
        </div>
        <div style={{position:"relative", display:"flex", gap:18, paddingTop:20, borderTop:`1px solid ${BRAND.ink900}`}}>
          <Mono color={BRAND.ink500}>SOC 2 Type II</Mono>
          <Mono color={BRAND.ink500}>·</Mono>
          <Mono color={BRAND.ink500}>LGPD</Mono>
          <Mono color={BRAND.ink500}>·</Mono>
          <Mono color={BRAND.ink500}>BACEN 4893</Mono>
        </div>
      </div>

      {/* Right: form */}
      <div style={{padding:"48px 48px", display:"flex", flexDirection:"column", justifyContent:"center"}}>
        <button onClick={onClose} aria-label="Fechar" style={{position:"absolute", top:20, right:20, background:"transparent", border:"none", cursor:"pointer", fontSize:24, color:BRAND.ink500, width:32, height:32, display:"flex", alignItems:"center", justifyContent:"center"}}>×</button>

        {mode === "login" && <>
          <div style={{fontFamily:"'Fraunces'", fontWeight:400, fontSize:28, letterSpacing:"-0.02em", color:BRAND.ink900}}>Entrar</div>
          <p style={{fontSize:14, color:BRAND.ink700, marginTop:8}}>Use seu e-mail corporativo.</p>
          <form onSubmit={submit} style={{marginTop:28, display:"flex", flexDirection:"column", gap:16}}>
            <div>
              <label style={{fontSize:12, fontWeight:500, color:BRAND.ink700, display:"block", marginBottom:6}}>E-mail corporativo</label>
              <input type="email" required autoFocus value={email} onChange={e=>setEmail(e.target.value)} placeholder="voce@empresa.com.br" className="portal-input" style={{width:"100%", padding:"11px 14px", border:`1px solid ${BRAND.ink200}`, borderRadius:8, fontSize:14, fontFamily:"inherit", background:BRAND.paper, transition:"all 120ms"}}/>
            </div>
            <div>
              <div style={{display:"flex", justifyContent:"space-between", marginBottom:6}}>
                <label style={{fontSize:12, fontWeight:500, color:BRAND.ink700}}>Senha</label>
                <a href="#" style={{fontSize:12, color:BRAND[600], textDecoration:"none"}}>Esqueci minha senha</a>
              </div>
              <input type="password" required value={pwd} onChange={e=>setPwd(e.target.value)} placeholder="••••••••" className="portal-input" style={{width:"100%", padding:"11px 14px", border:`1px solid ${BRAND.ink200}`, borderRadius:8, fontSize:14, fontFamily:"inherit", background:BRAND.paper, transition:"all 120ms"}}/>
            </div>
            <button type="submit" disabled={loading} style={{
              padding:"14px 20px", background:loading?BRAND[500]:BRAND[600], color:"white", border:"none", borderRadius:8,
              fontSize:14, fontWeight:500, fontFamily:"inherit", cursor: loading?"wait":"pointer", marginTop:8,
              display:"flex", alignItems:"center", justifyContent:"center", gap:10, transition:"all 120ms"
            }}>{loading ? "Verificando…" : "Continuar →"}</button>
          </form>
          <div style={{display:"flex", alignItems:"center", gap:14, margin:"28px 0 20px"}}>
            <div style={{flex:1, height:1, background:BRAND.ink200}}/>
            <Mono muted>ou</Mono>
            <div style={{flex:1, height:1, background:BRAND.ink200}}/>
          </div>
          <button onClick={()=>setMode("sso")} style={{padding:"11px 16px", background:"transparent", border:`1px solid ${BRAND.ink200}`, borderRadius:8, fontSize:13.5, fontWeight:500, color:BRAND.ink900, cursor:"pointer", fontFamily:"inherit", display:"flex", alignItems:"center", justifyContent:"center", gap:10}}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
            Entrar com SSO corporativo
          </button>
          <p style={{fontSize:12, color:BRAND.ink500, marginTop:28, textAlign:"center"}}>
            Primeiro acesso? <a href="#contato" onClick={onClose} style={{color:BRAND[600], textDecoration:"none"}}>Fale com seu admin da gestora.</a>
          </p>
        </>}

        {mode === "sso" && <>
          <button onClick={()=>setMode("login")} style={{background:"transparent", border:"none", color:BRAND[600], fontSize:13, cursor:"pointer", padding:0, marginBottom:24, display:"flex", alignItems:"center", gap:4, fontFamily:"inherit"}}>← Voltar</button>
          <div style={{fontFamily:"'Fraunces'", fontWeight:400, fontSize:28, letterSpacing:"-0.02em"}}>Single sign-on</div>
          <p style={{fontSize:14, color:BRAND.ink700, marginTop:8}}>Será redirecionado ao provedor da sua gestora.</p>
          <div style={{marginTop:24, display:"flex", flexDirection:"column", gap:10}}>
            {[["Okta","okta"],["Azure AD · Microsoft","azure"],["Google Workspace","google"]].map(([l,k])=>(
              <button key={k} onClick={submit} style={{padding:"14px 16px", background:BRAND.paper, border:`1px solid ${BRAND.ink200}`, borderRadius:8, fontSize:14, fontWeight:500, color:BRAND.ink900, cursor:"pointer", fontFamily:"inherit", display:"flex", alignItems:"center", justifyContent:"space-between"}}>
                <span>Continuar com {l}</span>
                <span style={{color:BRAND.ink500}}>→</span>
              </button>
            ))}
          </div>
        </>}

        {mode === "mfa" && <>
          <div style={{fontFamily:"'Fraunces'", fontWeight:400, fontSize:28, letterSpacing:"-0.02em"}}>Código de verificação</div>
          <p style={{fontSize:14, color:BRAND.ink700, marginTop:8}}>Enviamos 6 dígitos para {email || "seu e-mail"}. Válido por 5 minutos.</p>
          <div style={{marginTop:32, display:"flex", gap:8, justifyContent:"center"}}>
            {[...Array(6)].map((_,i)=>(
              <input key={i} maxLength={1} className="portal-input" style={{width:48, height:56, textAlign:"center", fontSize:22, fontFamily:"'JetBrains Mono'", border:`1px solid ${BRAND.ink200}`, borderRadius:8, background:BRAND.paper}}/>
            ))}
          </div>
          <button onClick={onClose} style={{marginTop:32, padding:"14px 20px", background:BRAND[600], color:"white", border:"none", borderRadius:8, fontSize:14, fontWeight:500, fontFamily:"inherit", cursor:"pointer"}}>Entrar no portal →</button>
          <button onClick={()=>setMode("login")} style={{marginTop:14, background:"transparent", border:"none", color:BRAND.ink500, fontSize:12.5, cursor:"pointer", fontFamily:"inherit"}}>Reenviar código</button>
        </>}
      </div>
    </div>
  </div>;
}

Object.assign(window, { PortalModal });
