/* Login screen + identity hook. Visual inspirado no dash-clone Login.tsx (Grid Station). */
const { useState: useAS, useEffect: useAE, useCallback: useAC, useMemo: useAM, useRef: useAR } = React;

function useIdentity() {
  const [state, setState] = useAS({ loading: true, identity: null, error: null });

  const reload = useAC(async () => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const id = await window.CCApi.fetchIdentity({ force: true });
      setState({ loading: false, identity: id, error: null });
    } catch (e) {
      setState({ loading: false, identity: null, error: e.message || 'failed' });
    }
  }, []);

  useAE(() => { reload(); }, [reload]);

  return { ...state, reload, signOut: () => { window.CCApi.signOut(); setState({ loading: false, identity: null, error: null }); } };
}

function LoginGreeting() {
  return useAM(() => {
    const h = new Date().getHours();
    if (h < 5) return 'Boa madrugada';
    if (h < 12) return 'Bom dia';
    if (h < 18) return 'Boa tarde';
    return 'Boa noite';
  }, []);
}

function LoginClock() {
  const [t, setT] = useAS(() => new Date());
  useAE(() => {
    const id = setInterval(() => setT(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const p = (n) => String(n).padStart(2, '0');
  return `${p(t.getHours())}:${p(t.getMinutes())}:${p(t.getSeconds())}`;
}

function LoginPreviewStat({ label, value, trend, accent }) {
  const positive = trend && !trend.startsWith('-');
  return (
    <div style={{
      position: 'relative', borderRadius: 10, padding: '10px 12px',
      background: 'linear-gradient(145deg, rgba(30,41,59,0.6), rgba(15,23,42,0.55))',
      border: '1px solid rgba(34,197,94,0.12)',
      backdropFilter: 'blur(4px)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span className="mono" style={{ fontSize: 9, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.5)' }}>{label}</span>
        {trend && (
          <span className="mono" style={{ fontSize: 9, color: positive ? '#10b981' : '#ef4444' }}>{trend}</span>
        )}
      </div>
      <div style={{
        marginTop: 4, fontSize: 19, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.15,
        color: accent ? 'var(--green)' : 'var(--text)',
      }}>{value}</div>
      <svg viewBox="0 0 100 14" preserveAspectRatio="none" style={{ marginTop: 6, width: '100%', height: 12 }} aria-hidden="true">
        <path d="M0 10 L15 8 L30 9 L45 5 L60 7 L75 4 L90 6 L100 3"
              stroke={accent ? '#22c55e' : 'rgba(52,211,153,0.6)'} strokeWidth="1.2" fill="none" />
      </svg>
    </div>
  );
}

function LoginScreen({ onLogged }) {
  const emailRef = useAR(null);
  const passwordRef = useAR(null);
  const [loading, setLoading] = useAS(false);
  const [error, setError] = useAS(null);
  const [emailValue, setEmailValue] = useAS('');
  const [pwValue, setPwValue] = useAS('');
  const [emailFocus, setEmailFocus] = useAS(false);
  const [pwFocus, setPwFocus] = useAS(false);
  const [showPw, setShowPw] = useAS(false);
  const [shake, setShake] = useAS(false);
  const [capsOn, setCapsOn] = useAS(false);
  const greeting = LoginGreeting();
  const clock = LoginClock();
  const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent || '');

  async function submit(e) {
    e.preventDefault();
    const email = emailRef.current?.value || emailValue;
    const password = passwordRef.current?.value || pwValue;
    if (!email || !password) {
      setError('Preencha email e senha');
      setShake(true); setTimeout(() => setShake(false), 480);
      return;
    }
    setLoading(true); setError(null);
    try {
      await window.CCApi.signIn({ email, password });
      onLogged?.();
    } catch (err) {
      setError(humanizeError(err.message || 'Falha no login'));
      setShake(true); setTimeout(() => setShake(false), 480);
    } finally {
      setLoading(false);
    }
  }

  function onPwKey(e) {
    setCapsOn(e.getModifierState?.('CapsLock') ?? false);
  }

  return (
    <main style={{
      minHeight: '100vh', position: 'relative', overflow: 'hidden',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }} className="login-root">
      <div className="bg-layers" aria-hidden="true">
        <div className="bg-glow" />
        <div className="bg-dots" />
        <div className="bg-vlines" />
        <div className="bg-scan" />
        <div className="bg-vignette" />
      </div>

      <section style={{
        position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', width: '100%', maxWidth: 440, padding: '32px 24px',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 32 }}>
          <img src="assets/igreen-logo.png" alt="iGreen Energy" style={{
            height: 38, width: 'auto', objectFit: 'contain',
            filter: 'drop-shadow(0 0 20px rgba(34,197,94,0.35))',
          }} />
          <div style={{ lineHeight: 1.25 }}>
            <div style={{ fontSize: 15, fontWeight: 600 }}>Suporte ao Gestor<span style={{ color: 'var(--green)' }}>.</span></div>
            <div className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.22em', marginTop: 2 }}>
              CONEXÃO GREEN
            </div>
          </div>
        </div>

        <form onSubmit={submit} noValidate
              className={shake ? 'login-shake' : ''}
              style={{ width: '100%' }}>
          <div className="card card-topline" style={{
            position: 'relative', padding: 28, borderRadius: 14, overflow: 'hidden',
            boxShadow: '0 30px 80px -20px rgba(0,0,0,0.65), 0 0 0 1px rgba(34,197,94,0.06), inset 0 1px 0 rgba(255,255,255,0.04)',
          }}>
            <span aria-hidden="true" style={{
              position: 'absolute', top: -96, right: -96, width: 256, height: 256, borderRadius: '50%',
              background: 'radial-gradient(closest-side, rgba(34,197,94,0.22), transparent 70%)',
              pointerEvents: 'none', opacity: 0.6,
            }} />

            <div style={{ position: 'relative' }}>
              <h3 style={{ margin: 0, fontSize: 28, lineHeight: 1, letterSpacing: '-0.02em', fontWeight: 300 }}>
                Entrar<span style={{ color: 'var(--green)' }}>.</span>
              </h3>
              <p style={{ margin: '8px 0 0', fontSize: 12.5, color: 'rgba(255,255,255,0.50)' }}>
                Use suas credenciais para acessar o painel.
              </p>
            </div>

            <FloatField id="login-email" label="E-MAIL CORPORATIVO"
                        focused={emailFocus} hasValue={emailValue.length > 0} hasError={!!error}
                        style={{ marginTop: 22 }}>
              <input ref={emailRef} id="login-email" name="email" type="email" autoComplete="username" required
                     value={emailValue}
                     onChange={(e) => { setEmailValue(e.target.value); if (error) setError(null); }}
                     onFocus={() => setEmailFocus(true)} onBlur={() => setEmailFocus(false)}
                     disabled={loading}
                     style={floatInputStyle} />
            </FloatField>

            <FloatField id="login-pw" label="SENHA"
                        focused={pwFocus} hasValue={pwValue.length > 0} hasError={!!error}
                        style={{ marginTop: 14 }}
                        right={
                          <button type="button" tabIndex={-1}
                                  onClick={() => setShowPw(v => !v)}
                                  className="mono"
                                  style={{
                                    background: 'transparent', border: 'none',
                                    color: 'rgba(255,255,255,0.55)', fontSize: 10.5,
                                    letterSpacing: '0.22em', padding: '0 12px', cursor: 'pointer',
                                  }}>
                            {showPw ? 'OCULTAR' : 'MOSTRAR'}
                          </button>
                        }>
              <input ref={passwordRef} id="login-pw" name="password"
                     type={showPw ? 'text' : 'password'}
                     autoComplete="current-password" required
                     value={pwValue}
                     onChange={(e) => { setPwValue(e.target.value); if (error) setError(null); }}
                     onFocus={() => setPwFocus(true)} onBlur={() => setPwFocus(false)}
                     onKeyDown={onPwKey} onKeyUp={onPwKey}
                     disabled={loading}
                     style={{ ...floatInputStyle, paddingRight: 80 }} />
            </FloatField>

            {capsOn && (
              <div className="mono" style={{
                marginTop: 8, fontSize: 10.5, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.65)',
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#f59e0b' }} />
                Caps Lock ativo
              </div>
            )}

            <div style={{ minHeight: 20, marginTop: 6 }} aria-live="polite">
              {error && (
                <p className="mono" style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 10.5, letterSpacing: '0.18em', color: '#ef4444', margin: 0 }}>
                  <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#ef4444' }} />
                  {error}
                </p>
              )}
            </div>

            <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
              <button type="submit" disabled={loading || !emailValue || !pwValue}
                      style={{
                        position: 'relative', overflow: 'hidden',
                        display: 'inline-flex', alignItems: 'center', gap: 10,
                        padding: '11px 24px', borderRadius: 999,
                        border: 'none', cursor: (loading || !emailValue || !pwValue) ? 'not-allowed' : 'pointer',
                        background: 'linear-gradient(180deg, #22c55e 0%, #16a34a 100%)',
                        color: '#06170d', fontSize: 13, fontWeight: 600, letterSpacing: 0.2,
                        boxShadow: '0 8px 24px -8px rgba(34,197,94,0.55), inset 0 1px 0 rgba(255,255,255,0.35)',
                        opacity: (loading || !emailValue || !pwValue) ? 0.55 : 1,
                        transition: 'transform 100ms ease, opacity 140ms ease',
                      }}
                      onMouseDown={e => e.currentTarget.style.transform = 'scale(0.98)'}
                      onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
                      onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
                {loading ? 'Verificando…' : 'Acessar'}
                <span style={{ fontSize: 16, lineHeight: 1 }}>→</span>
              </button>
            </div>
          </div>

          <p className="mono" style={{ marginTop: 20, fontSize: 9.5, letterSpacing: '0.28em', color: 'rgba(255,255,255,0.25)', textAlign: 'center' }}>
            © iGREEN ENERGY · USO INTERNO
          </p>
        </form>
      </section>

      <style>{`
        @keyframes login-shake {
          0%,100% { transform: translateX(0); }
          20% { transform: translateX(-6px); }
          40% { transform: translateX(5px); }
          60% { transform: translateX(-3px); }
          80% { transform: translateX(2px); }
        }
        .login-shake { animation: login-shake .42s cubic-bezier(.36,.07,.19,.97); }
      `}</style>
    </main>
  );
}

function FloatField({ id, label, children, focused, hasValue, hasError, right, style }) {
  const floated = focused || hasValue;
  const ring = hasError ? 'rgba(239,68,68,0.6)' : focused ? 'rgba(34,197,94,0.55)' : 'rgba(255,255,255,0.10)';
  const glow = hasError
    ? '0 0 0 3px rgba(239,68,68,0.12)'
    : focused
      ? '0 0 0 3px rgba(34,197,94,0.14), 0 0 30px -10px rgba(34,197,94,0.35)'
      : 'none';
  return (
    <div style={{
      position: 'relative', borderRadius: 10,
      background: 'rgba(255,255,255,0.03)',
      border: `1px solid ${ring}`,
      boxShadow: glow,
      transition: 'border-color 280ms ease, box-shadow 280ms ease',
      ...style,
    }}>
      <label htmlFor={id} className="mono" style={{
        position: 'absolute', left: 14, pointerEvents: 'none',
        top: floated ? 8 : 16,
        fontSize: floated ? 9.5 : 11.5,
        color: hasError ? 'rgba(239,68,68,0.85)' : (focused ? 'rgba(52,211,153,0.9)' : 'rgba(255,255,255,0.45)'),
        letterSpacing: '0.22em', transition: 'top 220ms ease, font-size 220ms ease, color 220ms ease',
      }}>
        {label}
      </label>
      {children}
      {right && (
        <div style={{ position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)' }}>
          {right}
        </div>
      )}
    </div>
  );
}

const floatInputStyle = {
  width: '100%', background: 'transparent', border: 'none', outline: 'none',
  paddingTop: 18, paddingBottom: 6, paddingLeft: 14, paddingRight: 14,
  fontSize: 14, color: 'var(--text)', fontFamily: 'inherit',
  caretColor: 'var(--green)',
};

function humanizeError(msg) {
  const m = (msg || '').toLowerCase();
  if (m.includes('invalid login') || m.includes('invalid credentials')) return 'Credenciais inválidas.';
  if (m.includes('email not confirmed')) return 'E-mail ainda não confirmado.';
  if (m.includes('rate')) return 'Muitas tentativas. Tente novamente em instantes.';
  if (m.includes('network') || m.includes('failed to fetch')) return 'Sem conexão com o servidor de autenticação.';
  return 'Não foi possível entrar. Verifique suas credenciais.';
}

window.useIdentity = useIdentity;
window.LoginScreen = LoginScreen;
