// ─────────────────────────────────────────────────────────────
// LifeWheel Coach — sign in screen.
// Brutalism dialect: cream/dark paper toggle, mono caps,
// brutalist form, bracket buttons. Auto-redirects on auth state.
// ─────────────────────────────────────────────────────────────

function LWLogin() {
  const { c: cBase, fonts: fontsBase, t } = useLW();
  const { isMobile } = useViewport();
  const [brutMode, setBrutMode] = window.LWBrutal.useBrutMode();
  const c = window.LWBrutal.makeC(cBase, brutMode);
  const fonts = { ...fontsBase, ...window.LWBrutal.fonts };
  const lang = window.LWLang ? window.LWLang.lang() : 'en';
  const isRu = lang === 'ru';

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [resetSent, setResetSent] = useState(false);

  // If already signed in, bounce. SPA: prefer route.params.next; fall
  // back to ?next= query for legacy direct loads.
  useEffect(() => {
    if (!window.LWAuth) return;
    const unsub = window.LWAuth.onAuthChanged((u) => {
      if (u) {
        let next = null;
        if (window.LWRouter) {
          const r = window.LWRouter.parseRoute();
          if (r && r.params) next = r.params.next;
        }
        if (!next) next = new URLSearchParams(window.location.search).get('next');
        if (window.LWRouter && next) {
          if (next.startsWith('#')) {
            window.location.replace(window.location.pathname + window.location.search + next);
          } else {
            const mapped = window.LWRouter.legacyHrefToHash(next);
            if (mapped) {
              window.location.replace(window.location.pathname + window.location.search + mapped);
            } else {
              window.location.replace(next);
            }
          }
        } else if (window.LWRouter) {
          window.LWRouter.navigate('dashboard', null, { replace: true });
        } else {
          window.location.replace(next || 'Dashboard.html');
        }
      }
    });
    return unsub;
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password || submitting) return;
    setSubmitting(true); setError(null);
    try {
      await window.LWAuth.signIn({ email: email.trim(), password });
    } catch (err) {
      setError(prettyAuthErrorLogin(err));
      setSubmitting(false);
    }
  };

  const handleReset = async () => {
    if (!email) {
      setError(t('auth.reset_need_email'));
      return;
    }
    setError(null);
    try {
      await firebase.auth().sendPasswordResetEmail(email.trim());
      setResetSent(true);
    } catch (err) {
      setError(prettyAuthErrorLogin(err));
    }
  };

  const handleApple = async () => {
    if (submitting) return;
    setSubmitting(true); setError(null);
    try {
      await window.LWAuth.signInWithApple();
    } catch (err) {
      // Popup-closed-by-user is intentional; don't show as an error.
      if (err && err.code === 'auth/popup-closed-by-user') {
        setSubmitting(false);
        return;
      }
      setError(prettyAuthErrorLogin(err));
      setSubmitting(false);
    }
  };

  const Atmosphere = window.LWBrutal.Atmosphere;
  const Styles = window.LWBrutal.Styles;
  const ModeToggle = window.LWBrutal.ModeToggle;
  const LWMark = window.LWBrutal.LWMark;

  return (
    <div style={{
      minHeight: '100vh', position: 'relative', overflow: 'hidden',
      background: c.bg, color: c.textPrimary,
      fontFamily: fonts.mono,
    }}>
      <Atmosphere c={c} brutMode={brutMode} />
      <div style={{ position: 'relative', zIndex: 1, minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
        {/* Top strip — mark + lang + mode toggles */}
        <div style={{
          padding: isMobile ? '14px 20px' : '16px 32px',
          borderBottom: `1.5px solid ${c.ink}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
        }}>
          <a href="#/signup" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
            <LWMark c={c} size={26} />
            <span style={{
              fontFamily: fonts.mono, fontSize: 14, fontWeight: 700, color: c.ink,
              letterSpacing: '0.04em', textTransform: 'uppercase',
            }}>
              LifeWheel<span style={{ color: c.textTertiary, marginLeft: 6 }}>.coach</span>
            </span>
          </a>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <ModeToggle c={c} fonts={fonts} brutMode={brutMode} setBrutMode={setBrutMode} />
            {window.LangToggle && <window.LangToggle c={c} fonts={fonts} />}
          </div>
        </div>

        {/* Centered card */}
        <div style={{
          flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '48px 20px',
        }}>
          <div className="lwb-reveal" style={{
            width: '100%', maxWidth: 460,
            background: c.card, border: `1.5px solid ${c.ink}`, borderRadius: 2,
            boxShadow: `6px 6px 0 0 ${c.ink}`,
            padding: isMobile ? '32px 26px' : '40px 36px',
            position: 'relative',
          }}>
            <div style={{ marginBottom: 18 }}>
              <span className="br-marker">§ {isRu ? 'ВХОД' : 'SIGN IN'}</span>
            </div>
            <h1 style={{
              fontFamily: fonts.mono, fontSize: isMobile ? 28 : 36, fontWeight: 700,
              lineHeight: 1.05, letterSpacing: '-0.02em', color: c.ink,
              margin: 0, marginBottom: 4, textTransform: 'uppercase',
            }}>
              {isRu ? 'С возвращением,' : 'Welcome'}<br />
              <span style={{
                color: c.accentInk,
                textDecoration: 'underline',
                textDecorationColor: c.accentInk,
                textDecorationThickness: '3px',
                textUnderlineOffset: '8px',
                textDecorationSkipInk: 'none',
              }}>{isRu ? 'коуч.' : 'back, coach.'}</span>
            </h1>
            <div style={{ height: 1.5, background: c.ink, width: 64, marginTop: 16, marginBottom: 18 }} />
            <p className="br-note" style={{ marginBottom: 28 }}>
              {isRu ? 'Открой портал, чтобы посмотреть, как клиенты прожили эту неделю.' : 'Open the workspace to see how your clients lived this week.'}
            </p>

            <button type="button" onClick={handleApple} disabled={submitting} style={{
              width: '100%',
              padding: '14px 18px',
              marginBottom: 14,
              background: c.ink,
              color: c.bg,
              border: `1.5px solid ${c.ink}`,
              borderRadius: 2,
              boxShadow: `3px 3px 0 0 ${c.ink}`,
              fontFamily: fonts.mono, fontSize: 13, fontWeight: 800,
              letterSpacing: '0.06em', textTransform: 'uppercase',
              cursor: submitting ? 'progress' : 'pointer',
              opacity: submitting ? 0.7 : 1,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            }}>
              <span aria-hidden style={{ fontSize: 16, lineHeight: 1, fontFamily: '-apple-system, BlinkMacSystemFont, "Apple Color Emoji", sans-serif' }}></span>
              {t('auth.continue_with_apple')}
            </button>

            <div style={{
              display: 'flex', alignItems: 'center', gap: 10, margin: '4px 0 14px',
              fontFamily: fonts.mono, fontSize: 10, fontWeight: 700,
              letterSpacing: '0.16em', textTransform: 'uppercase', color: c.textTertiary,
            }}>
              <span style={{ flex: 1, height: 1.5, background: c.borderDefault }} />
              {t('auth.or_with_email')}
              <span style={{ flex: 1, height: 1.5, background: c.borderDefault }} />
            </div>

            <form onSubmit={handleSubmit} style={{ display: 'grid', gap: 12 }}>
              <input
                className="br-input"
                type="email" required autoFocus autoComplete="email"
                placeholder={t('auth.email_placeholder')}
                value={email} onChange={(e) => setEmail(e.target.value)}
                style={{ padding: '14px 16px', fontFamily: fonts.mono, fontSize: 14, color: c.ink, outline: 'none', width: '100%' }}
              />
              <input
                className="br-input"
                type="password" required minLength={6} autoComplete="current-password"
                placeholder={t('auth.password')}
                value={password} onChange={(e) => setPassword(e.target.value)}
                style={{ padding: '14px 16px', fontFamily: fonts.mono, fontSize: 14, color: c.ink, outline: 'none', width: '100%' }}
              />
              <button type="submit" disabled={submitting} className="br-cta" style={{
                padding: '14px 18px', marginTop: 4, fontSize: 13,
                background: submitting ? c.textTertiary : c.accent,
                cursor: submitting ? 'progress' : 'pointer',
                opacity: submitting ? 0.7 : 1,
              }}>
                [ {(submitting ? t('auth.signing_in') : t('auth.sign_in_arrow')).toUpperCase()} → ]
              </button>
            </form>

            {error && (
              <div style={{
                marginTop: 16, padding: '12px 14px',
                background: window.LWBrutal.hexToRgba(c.error, 0.10),
                border: `1.5px solid ${c.error}`,
                color: c.error, fontFamily: fonts.mono, fontSize: 12,
                letterSpacing: '0.04em', textTransform: 'uppercase',
              }}>! {error}</div>
            )}
            {resetSent && (
              <div style={{
                marginTop: 16, padding: '12px 14px',
                background: window.LWBrutal.hexToRgba(c.accent, 0.10),
                border: `1.5px solid ${c.accent}`,
                color: c.accentInk, fontFamily: fonts.mono, fontSize: 12,
                letterSpacing: '0.04em', textTransform: 'uppercase',
              }}>✓ {t('auth.reset_sent')}</div>
            )}

            <div style={{
              marginTop: 26, paddingTop: 18,
              borderTop: `1.5px dashed ${c.borderDefault}`,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14,
              fontFamily: fonts.mono, fontSize: 11, fontWeight: 600,
              letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>
              <button type="button" onClick={handleReset} className="lwb-link-hover" style={{
                background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                color: c.textSecondary, textDecoration: 'underline', fontSize: 11, fontFamily: fonts.mono,
                letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
              }}>{t('auth.forgot_password')}</button>
              <a href="#/signup" className="lwb-link-hover" style={{ color: c.textSecondary, textDecoration: 'underline', textUnderlineOffset: 3 }}>
                {t('auth.need_account')} →
              </a>
            </div>
          </div>
        </div>

        {/* Footer caption */}
        <div style={{
          padding: '20px 20px 24px', textAlign: 'center',
          fontFamily: fonts.mono, fontSize: 11, color: c.textTertiary,
          letterSpacing: '0.10em', textTransform: 'uppercase',
        }}>
          —— {t('auth.coaches_only')} ——
        </div>
      </div>
      <Styles c={c} fonts={fonts} />
    </div>
  );
}

function prettyAuthErrorLogin(err) {
  const code = err && err.code ? err.code : '';
  switch (code) {
    case 'auth/invalid-email':         return "That email doesn't look right.";
    case 'auth/user-not-found':        return "We don't have an account for that email — sign up below.";
    case 'auth/wrong-password':        return 'Wrong password. Try again or use "Forgot password".';
    case 'auth/invalid-credential':    return 'Email or password is incorrect.';
    case 'auth/too-many-requests':     return 'Too many attempts — wait a moment, then try again.';
    case 'auth/network-request-failed': return 'Network hiccup — check your connection and try again.';
    case 'auth/operation-not-allowed': return 'Email sign-in is not enabled on the server. Tell your admin.';
    default: return (err && err.message) || 'Something went wrong. Try again.';
  }
}
