// js/components/common/Login.jsx
// Tela de login — Supabase Auth + resolveUserFromAuth.
// Movido de index.html em Fase 5 do refactor (2026-04-29): L714-L803
// Deps runtime: sb (window.sb), resolveUserFromAuth (window.resolveUserFromAuth — auth.js),
//               window.__ZNX_NEW_AUTH_ENABLED__
(function() {
  'use strict';
  const {useState} = React;

  // CÓPIA EXATA do index.html L714-L803
  function Login({onLogin,allUsers,setExtraUsers}){
    const[user,setUser]=useState('');
    const[pass,setPass]=useState('');
    const[err,setErr]=useState('');
    // [TD-H1 20260429] handleLegacy + upgradeToBcrypt removidos — __ZNX_NEW_AUTH_ENABLED__ hardcoded true;
    // Sprint AUTH Fase 2 — fluxo via Supabase Auth
    async function handleNew(e){
      e.preventDefault();
      setErr('');
      try{
        const{data:authData,error:authError}=await sb.auth.signInWithPassword({email:user,password:pass});
        if(authError){
          console.warn('[ZNX-AUTH-ERROR] signInWithPassword:',authError);
          // [BUG-FIX 20260512 v203] Sentry — rastreia tentativas falhas (UX issues OU brute-force/credential stuffing)
          if(typeof Sentry!=='undefined') Sentry.captureMessage('[ZNX-AUTH] signInWithPassword failed',{level:'warning',tags:{flow:'login',step:'signIn'},extra:{userInput:user,errorMessage:authError.message,errorCode:authError.status}});
          const msg=authError.message||'';
          if(msg.toLowerCase().includes('invalid')||msg.toLowerCase().includes('credentials')||msg.toLowerCase().includes('email not confirmed')){
            setErr('Email ou senha incorretos');
          }else{
            setErr('Erro de conexão com servidor. Tente novamente em instantes.');
          }
          return;
        }
        const appUser=await resolveUserFromAuth(authData.user.id);
        if(!appUser){
          console.warn('[ZNX-AUTH-ERROR] resolveUserFromAuth retornou null para',authData.user.id);
          // [BUG-FIX 20260512 v203] Sentry — auth.users existe mas app_users não tem registro (cadastro incompleto)
          if(typeof Sentry!=='undefined') Sentry.captureMessage('[ZNX-AUTH] resolveUserFromAuth returned null',{level:'warning',tags:{flow:'login',step:'resolveAppUser'},extra:{authUserId:authData.user.id,userInput:user}});
          setErr('Usuário não configurado para novo login. Contacte o admin.');
          return;
        }
        onLogin(appUser);
      }catch(err){
        console.error('[ZNX-AUTH-ERROR] exception no fluxo novo:',err);
        setErr('Erro inesperado. Tente novamente.');
      }
    }
    // [TD-H1 20260429] router removido — handleNew é o único fluxo
    return(
      <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',background:'#F0F2F5'}}>
        <div style={{width:380}}>
          <div style={{textAlign:'center',marginBottom:40}}>
            <div style={{fontSize:36,fontWeight:800,color:'#2563EB',letterSpacing:4}}>ZAYNEX</div>
            <div style={{color:'#9CA3AF',fontSize:13,letterSpacing:2,marginTop:4}}>DISTRIBUIDORA DE PERFUMES ÁRABES</div>
            <div style={{width:60,height:2,background:'linear-gradient(90deg,transparent,#2563EB,transparent)',margin:'16px auto 0'}}/>
          </div>
          <div className="card">
            <form onSubmit={handleNew} style={{display:'flex',flexDirection:'column',gap:16}}>
              <div className="form-group">
                <label>{window.__ZNX_NEW_AUTH_ENABLED__?'Email':'Usuário'}</label>
                <input type={window.__ZNX_NEW_AUTH_ENABLED__?'email':'text'} autoComplete={window.__ZNX_NEW_AUTH_ENABLED__?'email':'username'} value={user} onChange={e=>setUser(e.target.value)} placeholder={window.__ZNX_NEW_AUTH_ENABLED__?'Digite seu email':'Digite seu usuário'} autoFocus/>
              </div>
              <div className="form-group">
                <label>Senha</label>
                <input type="password" value={pass} onChange={e=>setPass(e.target.value)} placeholder="Digite sua senha"/>
              </div>
              {err&&<div style={{color:'#DC2626',fontSize:13,textAlign:'center'}}>{err}</div>}
              <button type="submit" className="btn-gold" style={{padding:'12px',marginTop:4,fontSize:15}}>Entrar</button>
            </form>
          </div>
        </div>
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.Login = Login;
  window.Login = Login;

  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.Login = true;

})();
