/* Login screen — minimalista.
   • SVG orb HeyDigi fullscreen background com parallax do cursor
   • Logo Digidelta AI grande, centrado
   • Auth via @digidelta.pt (SSO Microsoft real)
   • Sem topbar/footer/telemetria. */

const LoginScreen = ({ onLogin, fadingOut }) => {
  const [msBusy, setMsBusy] = React.useState(false);
  const [pendingUser, setPendingUser] = React.useState(null);
  const [requestState, setRequestState] = React.useState(null); // null | 'sending' | 'sent' | 'error'

  // Detectar erros vindos do callback OAuth2
  const _urlError = new URLSearchParams(window.location.search).get('error');

  // Se unauthorized, verificar se há pedido de acesso pendente na sessão
  React.useEffect(() => {
    if (_urlError === 'unauthorized') {
      fetch('/api/auth/pending').then(r => r.ok ? r.json() : null).then(d => { if (d) setPendingUser(d); }).catch(() => {});
    }
  }, []);

  const handleMs = () => {
    setMsBusy(true);
    window.location.href = '/auth/login';
  };

  const handleRequestAccess = async () => {
    setRequestState('sending');
    try {
      const r = await fetch('/api/auth/request-access', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
      setRequestState(r.ok ? 'sent' : 'error');
    } catch { setRequestState('error'); }
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: '#05070d',
      color: '#E5E7EB',
      fontFamily: 'var(--font-body, Inter), system-ui, sans-serif',
      overflow: 'hidden',
      opacity: fadingOut ? 0 : 1,
      transition: 'opacity 0.42s ease',
    }}>
      {/* ── BACKGROUND VIDEO ── loop contínuo */}
      <video
        aria-hidden
        autoPlay
        loop
        muted
        playsInline
        preload="auto"
        style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover',
          zIndex: 0,
          pointerEvents: 'none',
        }}
      >
        <source src="assets/login-bg.mp4" type="video/mp4" />
      </video>

      {/* Gradient subtil só para legibilidade do texto no fundo */}
      <div aria-hidden style={{
        position: 'absolute', inset: 0, zIndex: 1,
        background: 'linear-gradient(180deg, rgba(5,7,13,0.15) 0%, rgba(5,7,13,0.35) 100%)',
        pointerEvents: 'none',
      }} />

      {/* ── LOGO ── centrado em altura e largura do viewport */}
      <img
        src="assets/logo-digidelta.svg"
        alt="Digidelta"
        style={{
          position: 'absolute',
          top: '50%', left: '50%',
          transform: 'translate(-50%, -50%)',
          zIndex: 2,
          width: 560, maxWidth: '88vw',
          height: 'auto',
          filter: 'drop-shadow(0 10px 32px rgba(0,0,0,0.5))',
          pointerEvents: 'none',
        }}
      />

      {/* ── BLOCO INFERIOR ── começa logo abaixo do logo. CTAs centrados em altura entre base do logo e topo do disclaimer */}
      <main style={{
        position: 'absolute', left: 0, right: 0,
        top: 'calc(50% + 80px)', bottom: 0,
        zIndex: 2,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        padding: '0 24px 16px',
      }}>

        {_urlError && (
          <div style={{ width: '100%', maxWidth: 460, marginBottom: 12 }}>
            <div style={{
              padding: '10px 16px',
              background: 'rgba(239,68,68,0.12)',
              border: '1px solid rgba(239,68,68,0.28)',
              borderRadius: 8,
              fontSize: 13,
              color: '#fca5a5',
              textAlign: 'center',
              lineHeight: 1.5,
            }}>
              {_urlError === 'unauthorized'
                ? 'Acesso não autorizado.'
                : 'Erro de autenticação. Tenta de novo.'}
            </div>
            {_urlError === 'unauthorized' && pendingUser && (
              <div style={{ marginTop: 10, textAlign: 'center' }}>
                {requestState === 'sent' ? (
                  <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)', padding: '8px 0' }}>
                    ✓ Pedido enviado. Aguarda aprovação do administrador.
                  </div>
                ) : (
                  <button
                    onClick={handleRequestAccess}
                    disabled={requestState === 'sending'}
                    style={{
                      background: 'rgba(255,255,255,0.07)',
                      border: '1px solid rgba(255,255,255,0.3)',
                      borderRadius: 8,
                      color: '#fff',
                      fontSize: 12,
                      padding: '8px 18px',
                      cursor: requestState === 'sending' ? 'wait' : 'pointer',
                      opacity: requestState === 'sending' ? 0.6 : 1,
                      backdropFilter: 'blur(6px)',
                    }}
                  >
                    {requestState === 'sending' ? 'A enviar…' : requestState === 'error' ? '✗ Erro — tenta de novo' : 'Pedir acesso'}
                  </button>
                )}
              </div>
            )}
          </div>
        )}

        {/* Auth section — flex:1 centra os CTAs em altura entre topo do bloco (base do logo) e topo do disclaimer */}
        <div style={{
          flex: 1,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          width: '100%',
        }}>
          <div style={{
            display: 'flex', flexDirection: 'row', alignItems: 'stretch',
            gap: 14, flexWrap: 'wrap', justifyContent: 'center',
            width: '100%', maxWidth: 560,
          }}>

            {/* Microsoft / @digidelta.pt — colaboradores */}
            <button
              onClick={handleMs}
              disabled={msBusy}
              style={{
                flex: '1 1 240px', minWidth: 0,
                padding: '12px 16px',
                display: 'flex', alignItems: 'center', gap: 12,
                background: 'rgba(255,255,255,0.04)',
                color: '#fff',
                border: '1px solid rgba(255,255,255,0.85)',
                borderRadius: 12,
                cursor: msBusy ? 'wait' : 'pointer',
                transition: 'transform 0.18s, background 0.18s',
                backdropFilter: 'blur(6px)',
                WebkitBackdropFilter: 'blur(6px)',
                boxShadow: '0 14px 40px -16px rgba(0,0,0,0.55)',
                opacity: msBusy ? 0.7 : 1,
                textAlign: 'left',
              }}
              onMouseEnter={e => {
                if (msBusy) return;
                e.currentTarget.style.transform = 'translateY(-1px)';
                e.currentTarget.style.background = 'rgba(255,255,255,0.10)';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.transform = 'none';
                e.currentTarget.style.background = 'rgba(255,255,255,0.04)';
              }}
            >
              <svg width="18" height="18" viewBox="0 0 20 20" aria-hidden style={{ flexShrink: 0 }}>
                <rect x="1" y="1" width="8" height="8" fill="#F25022" />
                <rect x="11" y="1" width="8" height="8" fill="#7FBA00" />
                <rect x="1" y="11" width="8" height="8" fill="#00A4EF" />
                <rect x="11" y="11" width="8" height="8" fill="#FFB900" />
              </svg>
              <div style={{ flex: 1, fontSize: 13, fontWeight: 600, letterSpacing: '-0.005em', color: '#fff' }}>
                {msBusy ? 'A contactar Microsoft…' : 'Login Colaboradores'}
              </div>
              {msBusy && (
                <span style={{
                  width: 14, height: 14, borderRadius: '50%',
                  border: '2px solid rgba(255,255,255,0.85)', borderTopColor: 'transparent',
                  animation: 'login-spin 0.7s linear infinite',
                }} />
              )}
            </button>

            {/* CTA — não és da Digidelta? */}
            <a
              href="https://www.digidelta.pt"
              target="_blank"
              rel="noopener noreferrer"
              style={{
                flex: '1 1 240px', minWidth: 0,
                padding: '12px 16px',
                display: 'flex', alignItems: 'center', gap: 12,
                background: 'transparent',
                color: '#fff',
                border: '1px dashed rgba(255,255,255,0.55)',
                borderRadius: 12,
                cursor: 'pointer',
                transition: 'transform 0.18s, background 0.18s, border-color 0.18s',
                backdropFilter: 'blur(6px)',
                WebkitBackdropFilter: 'blur(6px)',
                textDecoration: 'none',
                textAlign: 'left',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.transform = 'translateY(-1px)';
                e.currentTarget.style.background = 'rgba(255,255,255,0.06)';
                e.currentTarget.style.borderColor = 'rgba(255,255,255,0.85)';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.transform = 'none';
                e.currentTarget.style.background = 'transparent';
                e.currentTarget.style.borderColor = 'rgba(255,255,255,0.55)';
              }}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden style={{ flexShrink: 0, color: 'rgba(255,255,255,0.85)' }}>
                <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.6" fill="none"/>
                <path d="M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.7.3-1 .8-1 1.5V14" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round"/>
                <circle cx="12" cy="17" r="1" fill="currentColor"/>
              </svg>
              <div style={{ flex: 1, fontSize: 13, fontWeight: 600, letterSpacing: '-0.005em', color: '#fff' }}>
                Não és da Digidelta?
              </div>
            </a>

          </div>
        </div>

        {/* Disclaimer — antes do copyright, no fundo do bloco */}
        <div style={{
          fontSize: 11, lineHeight: 1.5, maxWidth: 720,
          textAlign: 'center',
          color: 'rgba(255,255,255,0.55)',
          padding: '0 16px',
          marginBottom: 8,
        }}>
          O acesso a esta plataforma é restrito a colaboradores da Digidelta. Toda a actividade é registada para fins de segurança e conformidade. Os dados tratados nesta plataforma estão sujeitos à política de privacidade interna e ao RGPD.
        </div>

        {/* Copyright — linha fina no fundo */}
        <div style={{
          textAlign: 'center',
          fontSize: 10, color: 'rgba(255,255,255,0.4)',
          letterSpacing: '0.04em',
        }}>
          © 2026 Digidelta · Todos os direitos reservados · AI Workspace v1.0
        </div>
      </main>


      <style>{`
        @keyframes login-spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
};

window.LoginScreen = LoginScreen;
