/* ============================================================
   CRUIG — Autenticação (login usuário + Google + admin separado)
   ------------------------------------------------------------
   ⚙️  INTEGRAÇÃO BACKEND (ver "Guia de Integração.html"):
   O botão Google usa Google Identity Services. No protótipo ele
   simula o login. Em produção, o dev troca `simulateGoogle` pela
   chamada real ao GIS + verificação do token no Worker.
   ============================================================ */

/* Logo "G" oficial do Google (4 cores) */
function GoogleG({size=20}){
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" aria-hidden="true" style={{flexShrink:0}}>
      <path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.6 2.4 30.1 0 24 0 14.6 0 6.4 5.4 2.5 13.3l7.9 6.1C12.3 13.2 17.7 9.5 24 9.5z"/>
      <path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.5 3-2.2 5.5-4.7 7.2l7.3 5.7C43.9 38 46.5 31.8 46.5 24.5z"/>
      <path fill="#FBBC05" d="M10.4 28.6c-.5-1.5-.8-3-.8-4.6s.3-3.1.8-4.6l-7.9-6.1C.9 16.5 0 20.1 0 24s.9 7.5 2.5 10.7l7.9-6.1z"/>
      <path fill="#34A853" d="M24 48c6.1 0 11.2-2 14.9-5.4l-7.3-5.7c-2 1.4-4.6 2.2-7.6 2.2-6.3 0-11.7-3.7-13.6-9.9l-7.9 6.1C6.4 42.6 14.6 48 24 48z"/>
    </svg>
  );
}

function GoogleButton({onClick, label="Continuar com Google", busy}){
  return (
    <button onClick={onClick} disabled={busy} style={{
      display:'flex', alignItems:'center', justifyContent:'center', gap:12, width:'100%',
      padding:'13px 18px', borderRadius:'var(--r-pill)', border:'1.5px solid var(--line-strong)',
      background:'#fff', fontFamily:'var(--body)', fontWeight:600, fontSize:15, color:'#3c4043',
      cursor: busy?'wait':'pointer', transition:'all .15s', boxShadow:'var(--sh-sm)'}}
      onMouseEnter={e=>{ if(!busy){e.currentTarget.style.boxShadow='var(--sh-md)'; e.currentTarget.style.borderColor='#c9c2a6';} }}
      onMouseLeave={e=>{ e.currentTarget.style.boxShadow='var(--sh-sm)'; e.currentTarget.style.borderColor='var(--line-strong)'; }}>
      {busy ? <span className="spin" style={{width:18,height:18,border:'2.5px solid #ddd',borderTopColor:'#4285F4',borderRadius:'50%',display:'inline-block'}}></span> : <GoogleG/>}
      {busy? 'Conectando ao Google…' : label}
    </button>
  );
}

/* ---------- Login de usuário (Criador / Empresa) ---------- */
function LoginModal({onClose, go}){
  const [role,setRole] = useState('creator');
  const [mode,setMode] = useState('login'); // login | signup
  const [busy,setBusy] = useState(false);

  /* PROTÓTIPO: simula o fluxo do Google (sem GOOGLE_CLIENT_ID configurado). */
  const simulateGoogle = ()=>{
    setBusy(true);
    setTimeout(()=>{ setBusy(false); go(role); }, 1400);
  };

  /* PRODUÇÃO: Google Identity Services → valida o token no Worker (/api/auth/google). */
  const realGoogle = ()=>{
    if(typeof google==='undefined' || !google.accounts){ simulateGoogle(); return; }
    setBusy(true);
    google.accounts.id.initialize({
      client_id: window.CRUIG_CONFIG.GOOGLE_CLIENT_ID,
      callback: async (resp)=>{
        try{
          const {user} = await CruigAPI.post('/auth/google', {credential: resp.credential, role});
          go(user.role);
        }catch(e){
          setBusy(false);
          alert('Falha no login com Google: '+e.message);
        }
      },
    });
    google.accounts.id.prompt((notification)=>{
      if(notification.isNotDisplayed() || notification.isSkippedMoment()) setBusy(false);
    });
  };

  const handleGoogle = CruigAPI.isGoogleConfigured() ? realGoogle : simulateGoogle;

  return (
    <Modal open onClose={onClose} width={440}>
      <div style={{textAlign:'center', marginBottom:20}}>
        <Logo variant="green" height={30} style={{margin:'0 auto 16px'}}/>
        <h3 style={{fontSize:23}}>{mode==='login'?'Entrar na Cruig':'Criar sua conta'}</h3>
        <p className="faint" style={{fontSize:14, marginTop:6}}>{mode==='login'?'Acesse seu painel':'Comece grátis em segundos'}</p>
      </div>

      {/* Tipo de conta */}
      <div style={{display:'flex', gap:6, background:'var(--beige-deep)', borderRadius:'var(--r-pill)', padding:5, marginBottom:20}}>
        {[['creator','Sou criador'],['company','Sou empresa']].map(([k,l])=>(
          <button key={k} onClick={()=>setRole(k)} style={{flex:1, padding:'9px', borderRadius:'var(--r-pill)', fontWeight:700, fontSize:13.5,
            background: role===k?'#fff':'transparent', color: role===k?'var(--green-dark)':'var(--ink-soft)', boxShadow: role===k?'var(--sh-sm)':'none', transition:'all .15s'}}>{l}</button>
        ))}
      </div>

      {/* Google — método primário */}
      <GoogleButton onClick={handleGoogle} busy={busy} label={mode==='login'?'Entrar com Google':'Cadastrar com Google'}/>

      <div style={{display:'flex', alignItems:'center', gap:12, margin:'18px 0'}}>
        <div style={{flex:1, height:1, background:'var(--line)'}}></div>
        <span className="faint" style={{fontSize:12.5, fontWeight:600}}>ou com e-mail</span>
        <div style={{flex:1, height:1, background:'var(--line)'}}></div>
      </div>

      <div className="field" style={{marginBottom:13}}><label>E-mail</label><input className="input" placeholder="voce@email.com"/></div>
      <div className="field" style={{marginBottom:18}}><label>Senha</label><input className="input" type="password" placeholder="••••••••"/></div>
      <button className="btn btn-lime btn-block btn-lg" onClick={()=>go(role)}>{mode==='login'?'Entrar':'Criar conta'}<Icon name="arrow" size={18}/></button>

      <p className="faint" style={{fontSize:13.5, textAlign:'center', marginTop:18}}>
        {mode==='login'
          ? <>Não tem conta? <button onClick={()=>setMode('signup')} style={{color:'var(--lime-700)', fontWeight:700}}>Cadastre-se</button></>
          : <>Já tem conta? <button onClick={()=>setMode('login')} style={{color:'var(--lime-700)', fontWeight:700}}>Entrar</button></>}
      </p>
    </Modal>
  );
}

/* ---------- Login ADMIN separado (admin.cruig.com.br) ---------- */
function AdminLogin({onLogin, onExit}){
  const [busy,setBusy] = useState(false);
  const [err,setErr] = useState('');

  const realGoogle = ()=>{
    if(typeof google==='undefined' || !google.accounts){
      setErr('Login com Google indisponível neste navegador.');
      return;
    }
    setBusy(true); setErr('');
    google.accounts.id.initialize({
      client_id: window.CRUIG_CONFIG.GOOGLE_CLIENT_ID,
      callback: async (resp)=>{
        try{
          const {user} = await CruigAPI.post('/auth/google', {credential: resp.credential, role: 'admin'});
          onLogin(user);
        }catch(e){
          setBusy(false);
          setErr(e.message);
        }
      },
    });
    google.accounts.id.prompt((notification)=>{
      if(notification.isNotDisplayed() || notification.isSkippedMoment()) setBusy(false);
    });
  };

  return (
    <div style={{minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:24,
      background:'radial-gradient(circle at 50% 0%, #0a4f10, var(--green-dark) 60%)'}}>
      <div style={{width:'100%', maxWidth:400}}>
        <div style={{textAlign:'center', marginBottom:24}}>
          <Logo variant="white" height={32} style={{margin:'0 auto 22px'}}/>
          <div style={{display:'inline-flex', alignItems:'center', gap:8, background:'rgba(255,255,255,.1)', color:'#fff', padding:'7px 16px', borderRadius:'var(--r-pill)', fontSize:13, fontWeight:700}}>
            <Icon name="lock" size={15}/> Área restrita · Administração
          </div>
        </div>
        <div className="card" style={{padding:32, borderRadius:'var(--r-xl)'}}>
          <h3 style={{fontSize:21, textAlign:'center', marginBottom:6}}>Painel Administrativo</h3>
          <p className="faint" style={{fontSize:13.5, textAlign:'center', marginBottom:24}}>admin.cruig.com.br</p>
          {err && <p style={{color:'var(--danger)', fontSize:13, marginBottom:14, textAlign:'center'}}>{err}</p>}
          <GoogleButton onClick={realGoogle} busy={busy} label="Entrar com Google"/>
          <div style={{marginTop:18, padding:'12px 14px', borderRadius:12, background:'var(--beige-deep)', display:'flex', gap:10}}>
            <Icon name="verified" size={16} style={{color:'var(--lime-700)', flexShrink:0, marginTop:1}}/>
            <p className="faint" style={{fontSize:12, lineHeight:1.5}}>Apenas contas cadastradas como administrador têm acesso. Cada login é validado no servidor.</p>
          </div>
        </div>
        <p style={{textAlign:'center', marginTop:20}}><button onClick={onExit} style={{color:'rgba(255,255,255,.7)', fontSize:13.5, fontWeight:600}}>← Voltar ao site</button></p>
      </div>
    </div>
  );
}

/* ---------- Modal de conexão de rede social (OAuth) ---------- */
function SocialConnectModal({platform, onClose, onConnected}){
  const [stage,setStage] = useState('intro'); // intro | auth | done
  const [live,setLive] = useState(false);
  const meta = {
    instagram:{label:'Instagram', color:'#d6388a', scope:'Conta Profissional ou Criador'},
    tiktok:{label:'TikTok', color:'#111', scope:'Login Kit + Display API'},
    youtube:{label:'YouTube', color:'#e23', scope:'Canal do YouTube'},
  }[platform];

  // Se houver sessão real (login Google já configurado), usa o OAuth de verdade.
  useEffect(()=>{
    CruigAPI.get('/social/me').then(()=>setLive(true)).catch(()=>setLive(false));
  },[]);

  const connect = ()=>{
    if(live){ location.href = CruigAPI.socialStartUrl(platform); return; }
    // PROTÓTIPO: simula o fluxo OAuth (sem sessão real).
    setStage('auth');
    setTimeout(()=>{ setStage('done'); setTimeout(()=>{ onConnected(platform); }, 1100); }, 1500);
  };
  return (
    <Modal open onClose={stage==='auth'?()=>{}:onClose} width={420}>
      {stage==='done' ? (
        <div style={{textAlign:'center', padding:'10px 0'}}>
          <div style={{width:70,height:70,borderRadius:'50%',background:'var(--lime)',display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 16px'}}><Icon name="check" size={36} sw={3} style={{color:'var(--green-dark)'}}/></div>
          <h3 style={{fontSize:21}}>{meta.label} conectado!</h3>
          <p className="faint" style={{fontSize:14, marginTop:8}}>Seus números reais já estão sincronizando via API.</p>
        </div>
      ) : (
        <div style={{textAlign:'center'}}>
          <div style={{width:62,height:62,borderRadius:16,background:meta.color,display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 18px'}}>
            <PlatIcon type={platform} size={30}/>
          </div>
          <h3 style={{fontSize:21, marginBottom:8}}>Conectar {meta.label}</h3>
          <p className="muted" style={{fontSize:14, lineHeight:1.55, marginBottom:8}}>
            Você será levado ao {meta.label} para autorizar a Cruig a ler suas métricas <b>reais</b> (seguidores, engajamento, alcance).
          </p>
          <p className="faint" style={{fontSize:12.5, marginBottom:22}}>Requer: {meta.scope}</p>
          <button className="btn btn-dark btn-block btn-lg" onClick={connect} disabled={stage==='auth'} style={{background:meta.color}}>
            {stage==='auth' ? <><span className="spin" style={{width:18,height:18,border:'2.5px solid rgba(255,255,255,.3)',borderTopColor:'#fff',borderRadius:'50%',display:'inline-block'}}></span>Autorizando…</> : <>Autorizar {meta.label}</>}
          </button>
          <p className="faint" style={{fontSize:11.5, marginTop:14, display:'flex', gap:6, alignItems:'center', justifyContent:'center'}}><Icon name="lock" size={12}/> Conexão segura via OAuth oficial · não pedimos sua senha</p>
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, {GoogleG, GoogleButton, LoginModal, AdminLogin, SocialConnectModal});
