/* Login screen — minimalista.
   • SVG orb HeyDigi fullscreen background com parallax do cursor
   • Logo Digidelta AI grande, centrado
   • Auth via @digidelta.pt (SSO Microsoft real)
   • "Modo demo" expansível com utilizadores reais de colaboradores
   • Sem topbar/footer/telemetria. */

const LoginScreen = ({ onLogin, fadingOut }) => {
  const [pickedUser, setPickedUser] = React.useState(null);
  const [msBusy, setMsBusy] = React.useState(false);
  const [demoOpen, setDemoOpen] = React.useState(false);
  const [demoUsers, setDemoUsers] = React.useState([]);
  // Parallax: -1..+1 normalizado da posição do cursor
  const [parallax, setParallax] = React.useState({ x: 0, y: 0 });

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

  // Carregar utilizadores reais da BD para o modo demo
  React.useEffect(() => {
    fetch('/api/demo-users')
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(data => { if (data?.users?.length) setDemoUsers(data.users); })
      .catch(() => {});
  }, []);

  const handlePick = (user) => {
    if (pickedUser) return;
    setPickedUser(user.id);
    setTimeout(() => onLogin(user), 520);
  };

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

  // Track cursor for parallax
  React.useEffect(() => {
    const onMove = (e) => {
      const x = (e.clientX / window.innerWidth) * 2 - 1;
      const y = (e.clientY / window.innerHeight) * 2 - 1;
      setParallax({ x, y });
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);

  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 LAYERS ── */}
      {/* Vignette subtil para profundidade */}
      <div aria-hidden style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at center, rgba(99,102,241,0.06), transparent 60%)',
        pointerEvents: 'none',
      }} />

      {/* ── CENTRE STACK ── */}
      <main style={{
        position: 'absolute', inset: 0, zIndex: 2,
        display: 'grid', placeItems: 'center',
        padding: '40px 24px',
      }}>
        <div style={{
          width: 560, maxWidth: '94vw',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 36,
          transform: pickedUser ? 'scale(0.98)' : 'scale(1)',
          opacity: pickedUser ? 0.55 : 1,
          transition: 'transform 0.38s ease, opacity 0.38s ease',
        }}>

          {/* Logo Digidelta + AI lockup — fixo, sem parallax (foreground estável) */}
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 22,
              filter: 'drop-shadow(0 12px 40px rgba(99,102,241,0.22))',
            }}>
              <img
                src="assets/digidelta-light.png"
                alt="Digidelta"
                style={{
                  width: 320, maxWidth: '60vw',
                  height: 'auto',
                }}
              />
              <div style={{
                fontFamily: 'var(--font-display, "Rajdhani"), Inter, sans-serif',
                fontSize: 84, fontWeight: 600,
                letterSpacing: '0.04em',
                color: 'transparent',
                backgroundImage: 'linear-gradient(135deg, #22d3ee 0%, #a78bfa 50%, #ec4899 100%)',
                WebkitBackgroundClip: 'text',
                backgroundClip: 'text',
                lineHeight: 1,
                paddingLeft: 18,
                borderLeft: '2px solid rgba(148,163,184,0.25)',
              }}>
                AI
              </div>
            </div>
            <div style={{
              fontSize: 11, color: '#64748b',
              fontFamily: 'var(--font-mono, ui-monospace)',
              letterSpacing: '0.32em', textTransform: 'uppercase',
              whiteSpace: 'nowrap',
              marginTop: 8,
            }}>
              AI Workspace · v1.0
            </div>
          </div>

          {_urlError && (
            <div style={{
              width: '100%', maxWidth: 460,
              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. Contacta o administrador.'
                : 'Erro de autenticação. Tenta de novo.'}
            </div>
          )}

          {/* Auth section */}
          <div style={{ width: '100%', maxWidth: 460, display: 'flex', flexDirection: 'column', gap: 14 }}>

            {/* Microsoft / @digidelta.pt button */}
            <button
              onClick={handleMs}
              disabled={msBusy || !!pickedUser}
              style={{
                width: '100%', padding: '15px 18px',
                display: 'flex', alignItems: 'center', gap: 14,
                background: msBusy ? 'rgba(255,255,255,0.06)' : '#fff',
                color: msBusy ? '#94a3b8' : '#0f172a',
                border: '1px solid rgba(148,163,184,0.18)',
                borderRadius: 10,
                cursor: msBusy ? 'wait' : (pickedUser ? 'default' : 'pointer'),
                transition: 'transform 0.18s, box-shadow 0.18s, background 0.18s',
                boxShadow: '0 14px 40px -16px rgba(0,0,0,0.55)',
              }}
              onMouseEnter={e => !msBusy && !pickedUser && (e.currentTarget.style.transform = 'translateY(-1px)')}
              onMouseLeave={e => (e.currentTarget.style.transform = 'none')}
            >
              <svg width="22" height="22" 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, textAlign: 'left', lineHeight: 1.25 }}>
                <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-0.005em' }}>
                  {msBusy ? 'A contactar Microsoft…' : 'Entrar com a tua conta @digidelta.pt'}
                </div>
                <div style={{ fontSize: 11, color: msBusy ? '#64748B' : '#64748B', marginTop: 2 }}>
                  Single Sign-On via Microsoft 365
                </div>
              </div>
              {msBusy && (
                <span style={{
                  width: 16, height: 16, borderRadius: '50%',
                  border: '2px solid #94a3b8', borderTopColor: 'transparent',
                  animation: 'login-spin 0.7s linear infinite',
                }} />
              )}
            </button>

            {/* "Modo demo" expansível */}
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <button
                onClick={() => setDemoOpen(v => !v)}
                disabled={!!pickedUser}
                style={{
                  background: 'transparent', border: 'none',
                  color: '#64748B', fontSize: 11.5,
                  fontFamily: 'var(--font-mono, ui-monospace)',
                  letterSpacing: '0.12em', textTransform: 'uppercase',
                  cursor: pickedUser ? 'default' : 'pointer',
                  padding: '6px 10px',
                  display: 'inline-flex', alignItems: 'center', gap: 7,
                  whiteSpace: 'nowrap',
                  transition: 'color 0.18s',
                }}
                onMouseEnter={e => !pickedUser && (e.currentTarget.style.color = '#cbd5e1')}
                onMouseLeave={e => (e.currentTarget.style.color = '#64748B')}
              >
                <span style={{
                  display: 'inline-block', transform: demoOpen ? 'rotate(90deg)' : 'rotate(0)',
                  transition: 'transform 0.2s ease', fontSize: 9,
                }}>▸</span>
                Modo demo
              </button>
            </div>

            {/* Demo cards (collapsed by default) */}
            <div style={{
              maxHeight: demoOpen ? 360 : 0,
              opacity: demoOpen ? 1 : 0,
              overflow: demoOpen ? 'auto' : 'hidden',
              transition: 'max-height 0.32s ease, opacity 0.28s ease',
              display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              {demoUsers.length === 0 && (
                <div style={{ color: '#475569', fontSize: 11, textAlign: 'center', padding: '8px 0',
                  fontFamily: 'var(--font-mono, ui-monospace)' }}>
                  A carregar utilizadores…
                </div>
              )}
              {demoUsers.map(u => {
                const isPicked = pickedUser === u.id;
                const avatarBg = u.tipo === 'admin' || u.tipo === 'c_suite'
                  ? 'linear-gradient(135deg, #22d3ee, #6366f1)'
                  : u.tipo === 'director'
                  ? 'linear-gradient(135deg, #a78bfa, #ec4899)'
                  : u.tipo === 'manager'
                  ? 'linear-gradient(135deg, #6366f1, #8b5cf6)'
                  : 'linear-gradient(135deg, #f59e0b, #ef4444)';
                return (
                  <button
                    key={u.id}
                    onClick={() => handlePick(u)}
                    disabled={!!pickedUser}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '10px 12px',
                      background: isPicked ? 'rgba(34,211,238,0.14)' : 'rgba(15,23,42,0.55)',
                      border: `1px solid ${isPicked ? '#22d3ee' : 'rgba(148,163,184,0.14)'}`,
                      borderRadius: 9,
                      cursor: pickedUser ? 'default' : 'pointer',
                      transition: 'all 0.18s',
                      textAlign: 'left',
                      backdropFilter: 'blur(6px)',
                      position: 'relative', overflow: 'hidden',
                    }}
                    onMouseEnter={e => !pickedUser && !isPicked && (e.currentTarget.style.background = 'rgba(148,163,184,0.08)')}
                    onMouseLeave={e => !isPicked && (e.currentTarget.style.background = 'rgba(15,23,42,0.55)')}
                  >
                    <div style={{
                      width: 34, height: 34, borderRadius: '50%',
                      background: avatarBg,
                      display: 'grid', placeItems: 'center',
                      fontWeight: 700, fontSize: 11, color: '#0a0e1a',
                      fontFamily: 'var(--font-display, Inter)', letterSpacing: '0.02em',
                      flexShrink: 0,
                    }}>{u.iniciais}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 600, color: '#F1F5F9', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {u.nome} <span style={{ color: '#64748B', fontWeight: 400 }}>— {u.cargo}</span>
                      </div>
                      <div style={{ fontSize: 10.5, color: '#64748B', marginTop: 1, fontFamily: 'var(--font-mono, ui-monospace)' }}>
                        {u.empresa} · {u.accessLabel}
                      </div>
                    </div>
                    <span style={{
                      padding: '3px 7px', borderRadius: 4,
                      fontSize: 9, fontFamily: 'var(--font-mono, ui-monospace)',
                      fontWeight: 700, letterSpacing: '0.08em',
                      background: `${u.badgeColor}22`,
                      color: u.badgeColor,
                      border: `1px solid ${u.badgeColor}40`,
                      flexShrink: 0,
                    }}>{u.badge}</span>
                    {isPicked && (
                      <span style={{
                        position: 'absolute', left: 0, top: 0, bottom: 0, width: 3,
                        background: '#22d3ee',
                        boxShadow: '0 0 12px rgba(34,211,238,0.6)',
                      }} />
                    )}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </main>

      {/* Picked → flash overlay */}
      {pickedUser && (
        <div aria-hidden style={{
          position: 'absolute', inset: 0, zIndex: 5,
          background: 'radial-gradient(ellipse at center, rgba(99,102,241,0.22), transparent 70%)',
          animation: 'login-flash 0.5s ease',
          pointerEvents: 'none',
        }} />
      )}

      <style>{`
        @keyframes login-spin { to { transform: rotate(360deg); } }
        @keyframes login-flash {
          0% { opacity: 0; }
          50% { opacity: 1; }
          100% { opacity: 0.4; }
        }
        @keyframes login-orb-spin {
          0%   { transform: rotate(0deg) scale(1); }
          15%  { transform: rotate(28deg) scale(1.04); }
          32%  { transform: rotate(115deg) scale(0.97); }
          50%  { transform: rotate(180deg) scale(1.06); }
          68%  { transform: rotate(248deg) scale(0.98); }
          85%  { transform: rotate(330deg) scale(1.03); }
          100% { transform: rotate(360deg) scale(1); }
        }
        @keyframes login-orb-pulse {
          0%, 100% { opacity: 0.92; filter: brightness(1) saturate(1); }
          25%      { opacity: 1;    filter: brightness(1.18) saturate(1.15); }
          50%      { opacity: 0.78; filter: brightness(0.85) saturate(0.9); }
          75%      { opacity: 1;    filter: brightness(1.12) saturate(1.1); }
        }
        @media (prefers-reduced-motion: reduce) {
          [style*="login-orb-spin"] { animation: none !important; }
        }
      `}</style>
    </div>
  );
};

window.LoginScreen = LoginScreen;
