import React, { useState, useEffect } from "react";
import AppRoutes from "./routes/AppRoutes.tsx";
import useAuthStore from "./store/authStore.ts";
import { startSessionWatch } from "./services/sessionActivity.ts";

export default function App() {
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const hydrateSession = useAuthStore((state) => state.hydrateSession);
  const logout = useAuthStore((state) => state.logout);
  const isLoggedIn = useAuthStore((state) => state.isLoggedIn);

  // Custom non-blocking global toast notifications state
  interface CustomToast {
    id: number;
    message: string;
  }
  const [toasts, setToasts] = useState<CustomToast[]>([]);

  interface ActiveConfirm {
    message: string;
    onConfirm: () => void;
    onCancel?: () => void;
    isReadOnly?: boolean;
  }
  const [activeConfirm, setActiveConfirm] = useState<ActiveConfirm | null>(null);

  useEffect(() => {
    hydrateSession();

    const handleAuthExpired = () => logout();
    window.addEventListener("aams-auth-expired", handleAuthExpired);

    return () => {
      window.removeEventListener("aams-auth-expired", handleAuthExpired);
    };
  }, [hydrateSession, logout]);

  // Sliding session: keep the token fresh while the user is active, and sign
  // out only after a period of inactivity (idle timeout) — not on a fixed
  // 1-hour wall clock. Runs only while logged in.
  useEffect(() => {
    if (!isLoggedIn) return;
    const stop = startSessionWatch(() => {
      logout();
      window.dispatchEvent(
        new CustomEvent("aams-alert", { detail: "Signed out due to inactivity." }),
      );
    });
    return stop;
  }, [isLoggedIn, logout]);

  // Expose secure global aamsConfirm helper
  useEffect(() => {
    (window as any).aamsConfirm = (
      message: string,
      onConfirm: () => void,
      onCancel?: () => void
    ) => {
      window.dispatchEvent(
        new CustomEvent("aams-confirm", {
          detail: {
            message,
            onConfirm,
            onCancel,
            isReadOnly: false,
          },
        })
      );
    };
  }, []);

  useEffect(() => {
    const handleAlertEvent = (e: Event) => {
      const customEvent = e as CustomEvent<string>;
      const msg = customEvent.detail;
      const id = Date.now();
      
      // Push new toast notification
      setToasts((prev) => [...prev, { id, message: msg }]);
      
      // Auto-expire each toast notification after 5 seconds
      setTimeout(() => {
        setToasts((prev) => prev.filter((t) => t.id !== id));
      }, 5000);
    };

    const handleConfirmEvent = (e: Event) => {
      const customEvent = e as CustomEvent<ActiveConfirm>;
      if (customEvent.detail) {
        setActiveConfirm(customEvent.detail);
      }
    };

    window.addEventListener("aams-alert", handleAlertEvent);
    window.addEventListener("aams-confirm", handleConfirmEvent);
    
    return () => {
      window.removeEventListener("aams-alert", handleAlertEvent);
      window.removeEventListener("aams-confirm", handleConfirmEvent);
    };
  }, []);

  const dismissToast = (id: number) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  };

  return (
    <>
      <AppRoutes
        sidebarCollapsed={sidebarCollapsed}
        setSidebarCollapsed={setSidebarCollapsed}
        activeConfirm={activeConfirm}
        setActiveConfirm={setActiveConfirm}
      />

      {/* Global toast container — always mounted, visible on every page */}
      <div
        role="region"
        aria-label="Notifications"
        className="fixed top-6 right-6 z-[999] flex flex-col gap-3 max-w-sm w-full p-4 pointer-events-none"
      >
        {toasts.map((toast) => {
          const isError = toast.message.startsWith("Access Denied");
          return (
            <div
              key={toast.id}
              role={isError ? "alert" : "status"}
              aria-live={isError ? "assertive" : "polite"}
              className={`pointer-events-auto rounded-xl shadow-xl border p-4 flex items-start gap-3 animate-in slide-in-from-bottom-5 fade-in duration-300 ${
                isError ? "bg-red-900/90 border-red-700/50 text-red-100" : "bg-slate-900 border-slate-700/50 text-white"
              }`}
            >
              <div className={`w-6 h-6 rounded-full flex items-center justify-center shrink-0 mt-0.5 ${
                isError ? "bg-red-500/20 text-red-400" : "bg-teal-500/20 text-teal-400"
              }`}>
                <span className="material-symbols-rounded text-base font-bold">{isError ? "error" : "notifications_active"}</span>
              </div>
              <div className="flex-1 min-w-0">
                <p className={`text-xs font-semibold tracking-wide uppercase font-mono mb-1 ${
                  isError ? "text-red-400" : "text-teal-400"
                }`}>
                  {isError ? "Access Denied" : "System Notification"}
                </p>
                <p className={`text-xs font-sans leading-relaxed font-medium ${
                  isError ? "text-red-200" : "text-slate-100"
                }`}>{toast.message}</p>
              </div>
              <button
                onClick={() => dismissToast(toast.id)}
                className={`transition-colors cursor-pointer shrink-0 mt-0.5 ${
                  isError ? "text-red-400 hover:text-red-200" : "text-slate-500 hover:text-white"
                }`}
              >
                <span className="material-symbols-rounded text-sm">close</span>
              </button>
            </div>
          );
        })}
      </div>
    </>
  );
}
