// Session guard — signs out after 5 minutes of inactivity with a 30-second warning popup.

const IDLE_MS    = 4.5 * 60 * 1000;  // show warning after 4m30s of inactivity
const WARN_SECS  = 30;                // countdown duration in seconds

const SessionGuard = () => {
  const { signOut } = useAuth();
  const [warning, setWarning] = React.useState(false);
  const [secs,    setSecs]    = React.useState(WARN_SECS);

  // Use a single ref object so closures always see fresh values
  const r = React.useRef({ warning: false, idle: null, countdown: null });

  // Keep signOut fresh in ref so the interval can call it
  const signOutRef = React.useRef(signOut);
  React.useEffect(() => { signOutRef.current = signOut; }, [signOut]);

  // Start (or restart) the idle countdown
  const schedule = () => {
    clearTimeout(r.current.idle);
    r.current.idle = setTimeout(() => {
      // Idle threshold reached — show warning and start 30-second countdown
      r.current.warning = true;
      setWarning(true);
      let n = WARN_SECS;
      setSecs(n);
      clearInterval(r.current.countdown);
      r.current.countdown = setInterval(() => {
        n -= 1;
        setSecs(n);
        if (n <= 0) {
          clearInterval(r.current.countdown);
          signOutRef.current();
        }
      }, 1000);
    }, IDLE_MS);
  };

  // Any user activity resets the idle timer (unless warning is already showing)
  const onActivity = () => {
    if (r.current.warning) return;
    schedule();
  };

  const staySignedIn = () => {
    clearInterval(r.current.countdown);
    r.current.warning = false;
    setWarning(false);
    setSecs(WARN_SECS);
    schedule();
  };

  const signOutNow = () => {
    clearTimeout(r.current.idle);
    clearInterval(r.current.countdown);
    signOutRef.current();
  };

  React.useEffect(() => {
    schedule();
    const EVENTS = ['mousemove','mousedown','keydown','touchstart','scroll','click'];
    EVENTS.forEach(e => document.addEventListener(e, onActivity, { passive: true }));
    return () => {
      EVENTS.forEach(e => document.removeEventListener(e, onActivity));
      clearTimeout(r.current.idle);
      clearInterval(r.current.countdown);
    };
  }, []);

  if (!warning) return null;

  const pct = (secs / WARN_SECS) * 100;
  const urgent = secs <= 10;

  return (
    <>
      {/* Backdrop */}
      <div style={{
        position: 'fixed', inset: 0,
        background: 'rgba(0,0,0,0.5)',
        zIndex: 500,
        backdropFilter: 'blur(3px)',
        animation: 'fadeIn 0.2s ease',
      }}/>

      {/* Modal */}
      <div style={{
        position: 'fixed',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: Math.min(400, window.innerWidth - 32),
        background: 'var(--card)',
        border: '1px solid var(--line)',
        borderRadius: 20,
        padding: '32px 28px 28px',
        zIndex: 501,
        boxShadow: 'var(--shadow-lg)',
        animation: 'scaleIn 0.2s cubic-bezier(0.2, 0.8, 0.2, 1)',
        textAlign: 'center',
      }}>

        {/* Icon */}
        <div style={{
          width: 56, height: 56, borderRadius: '50%',
          background: urgent ? 'var(--coral-soft)' : 'var(--amber-soft)',
          border: `1px solid ${urgent ? 'var(--coral)' : 'var(--amber)'}`,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 24, marginBottom: 16,
          transition: 'background 0.3s, border-color 0.3s',
        }}>
          {urgent ? '⚠️' : '⏱'}
        </div>

        <h3 style={{ fontSize: 20, fontWeight: 500, margin: '0 0 8px', color: 'var(--ink)' }}>
          Still there?
        </h3>
        <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: '0 0 24px', lineHeight: 1.6 }}>
          You've been inactive for a while. You'll be signed out automatically in
        </p>

        {/* Countdown */}
        <div style={{
          fontSize: 48, fontWeight: 600, lineHeight: 1,
          color: urgent ? 'var(--coral)' : 'var(--ink)',
          fontFamily: 'var(--font-mono)',
          marginBottom: 16,
          transition: 'color 0.3s',
        }}>
          {secs}
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 20 }}>seconds</div>

        {/* Progress bar */}
        <div style={{
          height: 4, borderRadius: 2,
          background: 'var(--line)',
          marginBottom: 28, overflow: 'hidden',
        }}>
          <div style={{
            height: '100%', borderRadius: 2,
            background: urgent ? 'var(--coral)' : 'var(--amber)',
            width: `${pct}%`,
            transition: 'width 0.9s linear, background 0.3s',
          }}/>
        </div>

        {/* Buttons */}
        <div style={{ display: 'flex', gap: 10 }}>
          <button
            className="btn btn-ghost"
            onClick={signOutNow}
            style={{ flex: 1 }}
          >
            Sign out now
          </button>
          <button
            className="btn btn-primary"
            onClick={staySignedIn}
            style={{ flex: 1 }}
          >
            Stay signed in
          </button>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { SessionGuard });
