// Vyuu admin console — Login (dummy auth for prototype handoff).
//
// Any non-empty email + password ≥ 4 chars is accepted, OR clicking any of
// the SSO buttons (Microsoft / Google / Okta) auto-authenticates after a
// short fake-redirect spinner. The whole point is to demo the surface to
// the dev / Figma team — there is no real backend.
const { Mail, Lock, ArrowRight, Sun: SunAuth, Moon: MoonAuth, Loader2 } = window.LucideReact;

const MicrosoftLogo = ({size=18}) => (
  <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
    <path d="M0 0h11v11H0z" fill="#F25022"/>
    <path d="M13 0h11v11H13z" fill="#7FBA00"/>
    <path d="M0 13h11v11H0z" fill="#00A4EF"/>
    <path d="M13 13h11v11H13z" fill="#FFB900"/>
  </svg>
);
const GoogleLogo = ({size=18}) => (
  <svg width={size} height={size} viewBox="0 0 48 48" aria-hidden="true">
    <path fill="#FFC107" d="M43.6 20.5H42V20.4H24v7.2h11.3c-1.5 4.2-5.5 7.2-10.3 7.2-6.1 0-11-4.9-11-11s4.9-11 11-11c2.8 0 5.4 1.1 7.4 2.8l5.1-5.1C34.6 7.5 29.6 5.4 24 5.4c-10.3 0-18.6 8.3-18.6 18.6S13.7 42.6 24 42.6c10.3 0 18.6-8.3 18.6-18.6 0-1.2-.1-2.4-.4-3.5z"/>
    <path fill="#FF3D00" d="M7.3 14.7l5.9 4.3c1.6-3.9 5.4-6.6 9.8-6.6 2.8 0 5.4 1.1 7.4 2.8l5.1-5.1C34.6 7.5 29.6 5.4 24 5.4 16.3 5.4 9.7 9.6 7.3 14.7z"/>
    <path fill="#4CAF50" d="M24 42.6c5.5 0 10.4-2 14.2-5.5l-5.6-5.4c-2 1.6-4.6 2.6-7.6 2.6-4.7 0-8.7-3-10.3-7.1l-5.9 4.5C9.5 38.3 16.2 42.6 24 42.6z"/>
    <path fill="#1976D2" d="M43.6 20.5H42V20.4H24v7.2h11.3c-.7 2-2 3.7-3.7 4.9l5.6 5.4c-.4.4 6.4-4.7 6.4-13.5 0-1.2-.1-2.4-.4-3.5z"/>
  </svg>
);
const OktaLogo = ({size=18}) => (
  <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
    <circle cx="12" cy="12" r="10" fill="none" stroke="#007DC1" strokeWidth="4"/>
  </svg>
);

const ChakravyuhaLogin = ({size=44, color='#FBF8F1'}) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none">
    <path d="M24 4 A20 20 0 1 1 9.86 9.86" stroke={color} strokeWidth="2.4" strokeLinecap="round"/>
    <path d="M38 24 A14 14 0 1 1 14.1 14.1" stroke={color} strokeWidth="2.2" strokeLinecap="round" opacity="0.78"/>
    <path d="M16 24 A8 8 0 1 1 31.66 26.2" stroke={color} strokeWidth="2" strokeLinecap="round" opacity="0.58"/>
    <circle cx="24" cy="24" r="2.4" fill={color}/>
  </svg>
);

const Login = ({onAuth, mode, setMode}) => {
  const [email, setEmail] = React.useState('admin@llp.in');
  const [password, setPassword] = React.useState('');
  const [remember, setRemember] = React.useState(true);
  const [phase, setPhase] = React.useState('idle'); // idle | submitting | sso-microsoft | sso-google | sso-okta
  const [err, setErr] = React.useState('');

  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const validPassword = password.length >= 4;
  const canSubmit = validEmail && validPassword && phase === 'idle';

  const finish = (name) => {
    try {
      localStorage.setItem('vyuu-auth', '1');
      localStorage.setItem('vyuu-user', JSON.stringify({ name, email, signedInAt: Date.now() }));
    } catch {}
    onAuth({ name, email });
  };

  const submit = (e) => {
    e?.preventDefault?.();
    if (!canSubmit) {
      if (!validEmail) setErr('Enter a valid work email.');
      else if (!validPassword) setErr('Password must be at least 4 characters (any value works in demo).');
      return;
    }
    setErr('');
    setPhase('submitting');
    setTimeout(() => {
      const namePart = email.split('@')[0].replace(/[._-]+/g, ' ');
      const name = namePart.split(' ').map(s => s[0]?.toUpperCase() + s.slice(1)).join(' ') || 'Krishna';
      finish(name);
    }, 600);
  };

  const sso = (provider) => {
    setErr('');
    setPhase('sso-' + provider);
    setTimeout(() => {
      const name = provider === 'microsoft' ? 'Krishna Iyer' : provider === 'google' ? 'Meera Nair' : 'Arjun Desai';
      const ssoEmail = provider === 'microsoft' ? 'krishna@llp.in' : provider === 'google' ? 'meera.nair@llp.in' : 'arjun.d@llp.in';
      try {
        localStorage.setItem('vyuu-auth', '1');
        localStorage.setItem('vyuu-user', JSON.stringify({ name, email: ssoEmail, signedInAt: Date.now(), provider }));
      } catch {}
      onAuth({ name, email: ssoEmail, provider });
    }, 1100);
  };

  const flipMode = () => {
    const next = mode === 'dark' ? 'light' : 'dark';
    if (window.__setTheme) window.__setTheme(next);
    if (setMode) setMode(next);
  };

  const overlay = phase.startsWith('sso-') ? (
    <div style={{position:'fixed', inset:0, background:`${theme.bg}EE`, display:'flex', alignItems:'center', justifyContent:'center', zIndex:200, flexDirection:'column', gap:18}}>
      <Loader2 size={28} color={theme.orangeDeep} style={{animation:'spin 1s linear infinite'}}/>
      <div style={{font:'500 13px/1.4 Inter, sans-serif', color:theme.muted, letterSpacing:0.2}}>
        Redirecting to {phase === 'sso-microsoft' ? 'Microsoft' : phase === 'sso-google' ? 'Google' : 'Okta'}…
      </div>
    </div>
  ) : null;

  return (
    <div style={{minHeight:'100vh', background:theme.bg, color:theme.ink, display:'flex', alignItems:'center', justifyContent:'center', padding:'40px 24px', position:'relative', fontFamily:theme.sans}}>
      <style>{`@keyframes spin { from {transform:rotate(0)} to {transform:rotate(360deg)} }`}</style>

      {/* Mode toggle pinned top-right */}
      <button onClick={flipMode} title={mode==='dark'?'Switch to day':'Switch to night'} style={{
        position:'absolute', top:24, right:24, display:'inline-flex', alignItems:'center', gap:6,
        padding:'7px 11px', background:theme.panel, border:`1px solid ${theme.line}`, borderRadius:8,
        color:theme.muted, fontSize:12, fontWeight:500, cursor:'pointer', fontFamily:theme.sans,
      }}>
        {mode==='dark' ? <SunAuth size={14} strokeWidth={1.8}/> : <MoonAuth size={14} strokeWidth={1.8}/>}
        <span>{mode==='dark'?'Day':'Night'}</span>
      </button>

      {/* Demo-mode pill pinned top-left */}
      <div style={{position:'absolute', top:24, left:24, display:'inline-flex', alignItems:'center', gap:8, padding:'5px 12px', background:theme.orangeSoft, color:theme.orangeDeep, borderRadius:999, fontSize:10.5, fontWeight:600, letterSpacing:1.5, textTransform:'uppercase'}}>
        <span style={{width:6, height:6, borderRadius:999, background:theme.orangeDeep, display:'inline-block'}}/>
        Demo · any creds work
      </div>

      <div style={{width:'100%', maxWidth:440}}>
        {/* Lockup */}
        <div style={{display:'flex', alignItems:'center', justifyContent:'center', gap:12, marginBottom:32}}>
          <div style={{width:46, height:46, borderRadius:11, background:theme.orangeDeep, display:'flex', alignItems:'center', justifyContent:'center', boxShadow:`0 2px 10px ${theme.orangeDeep}30`}}>
            <ChakravyuhaLogin size={28} color={theme.onPrimary}/>
          </div>
          <div>
            <div style={{fontFamily:theme.serif, fontSize:24, color:theme.ink, fontWeight:500, letterSpacing:-0.4, lineHeight:1}}>Vyuu</div>
            <div style={{fontSize:10, color:theme.muted, letterSpacing:2.2, textTransform:'uppercase', marginTop:3, fontWeight:600}}>AI Shield</div>
          </div>
        </div>

        {/* Card */}
        <div style={{background:theme.panel, border:`1px solid ${theme.line}`, borderRadius:14, padding:32}}>
          <div style={{fontSize:10, letterSpacing:2.5, textTransform:'uppercase', color:theme.orangeDeep, fontWeight:600, marginBottom:6}}>Sign in</div>
          <h1 style={{fontFamily:theme.serif, fontSize:26, color:theme.ink, fontWeight:500, margin:'0 0 6px', letterSpacing:-0.3}}>Welcome back to Vyuu.</h1>
          <p style={{fontSize:13, color:theme.muted, margin:'0 0 24px', lineHeight:1.5}}>Govern every prompt, tool call, and agent run from one calm console.</p>

          <form onSubmit={submit}>
            <label style={{display:'block', fontSize:11, fontWeight:600, color:theme.muted, textTransform:'uppercase', letterSpacing:1.4, marginBottom:6}}>Work email</label>
            <div style={{position:'relative', marginBottom:16}}>
              <Mail size={14} color={theme.muted} style={{position:'absolute', left:12, top:13}}/>
              <input value={email} onChange={e=>setEmail(e.target.value)} type="email" autoComplete="email" placeholder="you@company.com" style={{
                width:'100%', padding:'10px 12px 10px 36px', border:`1px solid ${theme.line}`, borderRadius:8,
                fontFamily:theme.sans, fontSize:13.5, color:theme.ink, background:theme.bg, outline:'none',
              }}/>
            </div>

            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6}}>
              <label style={{fontSize:11, fontWeight:600, color:theme.muted, textTransform:'uppercase', letterSpacing:1.4}}>Password</label>
              <button type="button" onClick={()=>alert('Stub: would email a reset link to ' + (email||'your address') + '.')} style={{background:'transparent', border:'none', color:theme.orangeDeep, fontSize:11.5, fontWeight:500, cursor:'pointer', fontFamily:theme.sans}}>Forgot?</button>
            </div>
            <div style={{position:'relative', marginBottom:14}}>
              <Lock size={14} color={theme.muted} style={{position:'absolute', left:12, top:13}}/>
              <input value={password} onChange={e=>setPassword(e.target.value)} type="password" autoComplete="current-password" placeholder="Any 4+ characters in demo" style={{
                width:'100%', padding:'10px 12px 10px 36px', border:`1px solid ${theme.line}`, borderRadius:8,
                fontFamily:theme.sans, fontSize:13.5, color:theme.ink, background:theme.bg, outline:'none',
              }}/>
            </div>

            <label style={{display:'flex', alignItems:'center', gap:8, fontSize:12.5, color:theme.muted, marginBottom:18, cursor:'pointer'}}>
              <input type="checkbox" checked={remember} onChange={e=>setRemember(e.target.checked)} style={{accentColor:theme.orangeDeep}}/>
              Keep me signed in for 30 days
            </label>

            {err && (
              <div style={{padding:'9px 12px', background:theme.dangerTint || '#F4E2D9', border:`1px solid ${theme.terracottaSoft}`, color:theme.terracottaInk, borderRadius:8, fontSize:12.5, marginBottom:14}}>
                {err}
              </div>
            )}

            <button type="submit" disabled={!canSubmit} style={{
              width:'100%', display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
              padding:'12px 16px', borderRadius:8,
              border:`1px solid ${theme.orangeDeep}`,
              background: canSubmit ? theme.orangeDeep : theme.line,
              color: canSubmit ? theme.onPrimary : theme.muted,
              fontSize:14, fontWeight:600, cursor:canSubmit?'pointer':'not-allowed',
              fontFamily:theme.sans, letterSpacing:0.1,
              boxShadow: canSubmit ? '0 2px 8px rgba(168, 88, 32, 0.25)' : 'none',
              transition:'filter .15s',
            }}>
              {phase === 'submitting'
                ? <><Loader2 size={15} style={{animation:'spin 1s linear infinite'}}/> Signing in…</>
                : <>Sign in <ArrowRight size={15} strokeWidth={1.8}/></>}
            </button>
          </form>

          {/* Divider */}
          <div style={{display:'flex', alignItems:'center', gap:12, margin:'24px 0 16px', color:theme.muted, fontSize:11, letterSpacing:1.4, textTransform:'uppercase', fontWeight:600}}>
            <div style={{flex:1, height:1, background:theme.lineSoft}}/>
            <span>or continue with</span>
            <div style={{flex:1, height:1, background:theme.lineSoft}}/>
          </div>

          {/* SSO buttons */}
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8}}>
            <button type="button" onClick={()=>sso('microsoft')} style={ssoBtn()}>
              <MicrosoftLogo size={16}/> <span>Microsoft</span>
            </button>
            <button type="button" onClick={()=>sso('google')} style={ssoBtn()}>
              <GoogleLogo size={16}/> <span>Google</span>
            </button>
            <button type="button" onClick={()=>sso('okta')} style={ssoBtn()}>
              <OktaLogo size={16}/> <span>Okta</span>
            </button>
          </div>

          <div style={{marginTop:22, paddingTop:18, borderTop:`1px solid ${theme.lineSoft}`, fontSize:11.5, color:theme.muted, textAlign:'center', lineHeight:1.5}}>
            Need access? <a href="#" onClick={e=>{e.preventDefault();alert('Stub: would open the Vyuu access-request form.')}} style={{color:theme.orangeDeep, fontWeight:500, textDecoration:'none'}}>Talk to your admin</a>.
          </div>
        </div>

        <div style={{textAlign:'center', marginTop:18, fontSize:11, color:theme.subtle, letterSpacing:0.2}}>
          © Vyuu · BFSI · v1.3.2 · Privacy · Status
        </div>
      </div>

      {overlay}
    </div>
  );
};

const ssoBtn = () => ({
  display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
  padding:'10px 12px', borderRadius:8,
  border:`1px solid ${theme.line}`, background:theme.bg,
  color:theme.ink, fontSize:13, fontWeight:500, cursor:'pointer', fontFamily:theme.sans,
  transition:'filter .15s',
});

Object.assign(window, {Login});
