import { useContext, useEffect, useState } from 'react';
import { LogIn, X } from 'lucide-react';
import { subscribeUnauthorized } from './api';
import { AuthContext } from './AuthGate';
import { canLeaveCurrentScreen } from './navigationGuard';

// Shell-level pointer shown when any `/api` request returns 401 (#295 session-auth). Rather than teach
// every screen's error path to special-case 401, the request client emits one app-wide signal (auth.ts)
// and this single banner subscribes — DRY, and it renders regardless of which screen triggered it.
//
// It stays PASSIVE: a background 401 must not yank the user mid-edit, so it only surfaces the banner. The
// "Sign in" affordance consults the unsaved-changes guard before flipping the gate to the login screen, so
// a dirty draft isn't silently discarded.
export function UnauthorizedBanner() {
  const [visible, setVisible] = useState(false);
  const { requireLogin } = useContext(AuthContext);

  useEffect(() => subscribeUnauthorized(() => setVisible(true)), []);

  if (!visible) {
    return null;
  }

  const signIn = () => {
    if (!canLeaveCurrentScreen()) {
      return;
    }
    setVisible(false);
    requireLogin();
  };

  return (
    <div className="ctv-auth-banner" role="alert">
      <LogIn aria-hidden="true" size={15} />
      <span className="ctv-auth-banner-text">Your session has expired or you are signed out.</span>
      <button className="ctv-auth-banner-link ctv-press" onClick={signIn} type="button">
        Sign in
      </button>
      <button aria-label="Dismiss" className="ctv-auth-banner-dismiss ctv-press" onClick={() => setVisible(false)} type="button">
        <X aria-hidden="true" size={14} />
      </button>
    </div>
  );
}
