import React, { useState, useEffect } from "react";
import { 
  UserCheck, 
  ShieldCheck, 
  Key, 
  Lock, 
  Building2, 
  User, 
  X, 
  Check, 
  Search, 
  Sparkles,
  ArrowRight,
  LogOut,
  BadgeCheck,
  Cpu,
  DollarSign,
  Users,
  Layers,
  Database,
  Mail,
  RefreshCw,
  UserPlus,
  Globe,
  ExternalLink,
  KeyRound,
  ShieldAlert
} from "lucide-react";
import { Employee } from "../types";
import { supabaseService } from "../services/supabaseService";
import { medianOauthService, MedianSsoUser, MEDIAN_SSO_PROVIDER_URL } from "../services/medianOauthService";
import { ssoService, SsoUserPayload } from "../services/ssoService";

interface LoginModalProps {
  isOpen: boolean;
  onClose: () => void;
  employees: Employee[];
  currentUser: Employee;
  onSelectUser: (user: Employee) => void;
}

export function getDirectorateName(position: string, division: string): string {
  const pos = position.toUpperCase();
  const div = division.toUpperCase();

  if (pos.includes("CEO") || div.includes("EXECUTIVE")) return "Executive Office (CEO)";
  if (pos.includes("CFO") || div.includes("BENDAHARA") || div.includes("AKUNTANSI")) return "Direktorat Keuangan (CFO)";
  if (pos.includes("CTO") || div.includes("DEVELOPER") || div.includes("IT")) return "Direktorat IT (CTO)";
  if (pos.includes("CHR") || pos.includes("HEAD OF HR") || div.includes("PAYROLL") || div.includes("REKRUTMEN")) return "Direktorat Human Resources (CHR)";
  return "Direktorat Operasional (COO)";
}

export function getAllowedTabsForUser(user: Employee): Array<"dashboard" | "umk" | "travel" | "employees" | "attendance" | "org" | "workflows" | "rkap" | "finance" | "dms" | "procurement" | "cto" | "governance" | "saas" | "portal"> {
  const pos = user.position.toUpperCase();
  const dir = getDirectorateName(user.position, user.division);

  // CEO / Super Admin
  if (pos.includes("CEO") || user.id === "emp-ceo-01") {
    return ["dashboard", "umk", "travel", "employees", "attendance", "governance", "dms", "procurement", "workflows", "finance", "rkap", "org"];
  }

  // CTO / IT Director
  if (pos.includes("CTO") || dir.includes("CTO")) {
    return ["dashboard", "umk", "travel", "employees", "attendance", "governance", "dms", "procurement", "finance", "workflows", "org"];
  }

  // CFO / Finance Director
  if (pos.includes("CFO") || dir.includes("CFO")) {
    return ["dashboard", "umk", "travel", "employees", "attendance", "governance", "dms", "procurement", "finance", "rkap", "workflows", "org"];
  }

  // CHR / HR Director
  if (pos.includes("CHR") || pos.includes("HEAD OF HR") || dir.includes("CHR")) {
    return ["dashboard", "umk", "travel", "employees", "attendance", "governance", "dms", "procurement", "finance", "org", "workflows"];
  }

  // COO / Operational Director
  if (pos.includes("COO") || dir.includes("COO")) {
    return ["dashboard", "umk", "travel", "employees", "attendance", "governance", "dms", "procurement", "finance", "workflows", "rkap", "org"];
  }

  // Supervisors & Managers
  if (pos.includes("MANAGER") || pos.includes("SUPERVISOR") || pos.includes("HEAD")) {
    return ["dashboard", "umk", "travel", "employees", "attendance", "governance", "dms", "procurement", "finance", "workflows", "org"];
  }

  // Staff Default Access
  return ["dashboard", "umk", "travel", "employees", "attendance", "governance", "dms", "procurement", "finance", "workflows"];
}

export default function LoginModal({
  isOpen,
  onClose,
  employees,
  currentUser,
  onSelectUser
}: LoginModalProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [inputNip, setInputNip] = useState("");
  const [inputPassword, setInputPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  // Supabase Auth States
  const [supaEmail, setSupaEmail] = useState("");
  const [supaPassword, setSupaPassword] = useState("");
  const [supaMode, setSupaMode] = useState<"login" | "signup">("login");
  const [supaMessage, setSupaMessage] = useState<{ text: string; isError: boolean } | null>(null);
  const [isSupaAuthenticating, setIsSupaAuthenticating] = useState(false);
  const [activeToken, setActiveToken] = useState<string | null>(null);

  // Median ID SSO OAuth States
  const [isMedianSsoLoading, setIsMedianSsoLoading] = useState(false);
  const [medianSsoUser, setMedianSsoUser] = useState<MedianSsoUser | null>(null);
  const [medianSsoMessage, setMedianSsoMessage] = useState<{ text: string; isError: boolean } | null>(null);

  useEffect(() => {
    if (isOpen) {
      const token = localStorage.getItem("supabase_auth_token");
      setActiveToken(token);
      const storedSso = medianOauthService.getStoredSession();
      setMedianSsoUser(storedSso);
    }
  }, [isOpen]);

  // OAuth postMessage listener for Median Cloud Django SSO (https://auth.median-cloud.web.id)
  useEffect(() => {
    const handleOauthMessage = (event: MessageEvent) => {
      if (event.origin !== window.location.origin) return;
      if (event.data && (event.data.type === "OAUTH_AUTH_SUCCESS" || event.data.type === "MEDIAN_SSO_SUCCESS")) {
        const token = event.data.token || event.data.jwt || event.data.access_token;
        
        let ssoUser: SsoUserPayload;
        if (event.data.ssoUser) {
          ssoUser = event.data.ssoUser;
        } else if (token) {
          const verification = ssoService.verifyToken(token);
          if (verification.payload) {
            ssoUser = ssoService.mapClaimsToSsoUser(verification.payload);
          } else {
            ssoUser = {
              ssoId: `django-usr-${Date.now()}`,
              name: "Tenant User",
              email: "",
              nip: "",
              nik: "",
              position: "Tenant User",
              division: "Tenant",
              providerUrl: MEDIAN_SSO_PROVIDER_URL,
              authenticatedAt: new Date().toISOString()
            };
          }
        } else {
          ssoUser = {
            ssoId: `django-usr-${Date.now()}`,
            name: "Tenant User",
            email: "",
            nip: "",
            nik: "",
            position: "Tenant User",
            division: "Tenant",
            providerUrl: MEDIAN_SSO_PROVIDER_URL,
            authenticatedAt: new Date().toISOString()
          };
        }

        // Synchronize with App State and LocalStorage via ssoService
        const { matchedEmployee } = ssoService.syncSessionWithAppState(ssoUser, employees, token);

        setMedianSsoUser(ssoUser);
        setIsMedianSsoLoading(false);
        setMedianSsoMessage({
          text: `Autentikasi SSO Berhasil! Terhubung sebagai ${ssoUser.name} (${ssoUser.email})`,
          isError: false
        });

        onSelectUser(matchedEmployee);
        setTimeout(() => onClose(), 800);
      }
    };

    window.addEventListener("message", handleOauthMessage);
    return () => window.removeEventListener("message", handleOauthMessage);
  }, [employees, currentUser, onSelectUser, onClose]);

  const handleTriggerMedianSso = async () => {
    setIsMedianSsoLoading(true);
    setMedianSsoMessage(null);

    const popup = await ssoService.launchOauthPopup(
      (user, token) => {
        const { matchedEmployee } = ssoService.syncSessionWithAppState(user, employees, token);
        setMedianSsoUser(user);
        setIsMedianSsoLoading(false);
        setMedianSsoMessage({
          text: `Autentikasi SSO Berhasil! Terhubung sebagai ${user.name} (${user.email})`,
          isError: false
        });
        onSelectUser(matchedEmployee);
        setTimeout(() => onClose(), 800);
      },
      (errorMsg) => {
        setIsMedianSsoLoading(false);
        setMedianSsoMessage({ text: errorMsg, isError: true });
      }
    );

    // Fallback timer if popup closed or blocked
    if (popup) {
      const checkClosedTimer = setInterval(() => {
        if (popup.closed) {
          clearInterval(checkClosedTimer);
          setIsMedianSsoLoading(false);
        }
      }, 1000);
    }
  };

  const handleDirectRedirectSso = async () => {
    try {
      setIsMedianSsoLoading(true);
      await ssoService.redirectToLogin();
    } catch (e: any) {
      setIsMedianSsoLoading(false);
      setMedianSsoMessage({ text: e.message || "Gagal mengarahkan ke SSO Provider", isError: true });
    }
  };

  const handleDisconnectMedianSso = () => {
    ssoService.clearSession();
    medianOauthService.clearSession();
    setMedianSsoUser(null);
    setMedianSsoMessage({ text: "Sesi Median ID SSO telah terputus.", isError: false });
  };

  if (!isOpen) return null;

  // Production SaaS: identity may only come from the Django SSO gateway.
  // Local role switching, local NIP/password login, and direct Supabase Auth are deliberately unavailable.
  if (import.meta.env.PROD) {
    return (
      <div className="fixed inset-0 z-[100] bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4">
        <div className="w-full max-w-lg bg-slate-900 border border-sky-500/40 rounded-xl shadow-2xl overflow-hidden">
          <div className="p-5 border-b border-slate-700 flex items-center justify-between">
            <div>
              <div className="text-[10px] uppercase tracking-widest text-sky-400 font-black">Median Cloud Tenant Identity</div>
              <h2 className="text-lg font-black text-white">Session SSO Django</h2>
            </div>
            <button type="button" onClick={onClose} className="p-2 text-slate-400 hover:text-white"><X className="w-5 h-5" /></button>
          </div>
          <div className="p-5 space-y-4">
            <div className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-4">
              <div className="flex items-center gap-2 text-emerald-300 font-bold"><BadgeCheck className="w-5 h-5" /> Authenticated server-side session</div>
              <div className="mt-3 text-sm text-slate-200 font-semibold">{medianSsoUser?.name || currentUser.name}</div>
              <div className="text-xs text-slate-400">{medianSsoUser?.email || currentUser.email}</div>
              <div className="text-xs text-sky-300 mt-1">{medianSsoUser?.position || currentUser.position}</div>
            </div>
            <p className="text-xs text-slate-400 leading-relaxed">
              Pada mode SaaS production, user, tenant, membership, dan subscription dikunci oleh wildcard host dan control-plane Django. Browser tidak dapat mengganti role atau tenant secara lokal.
            </p>
            <div className="flex flex-col sm:flex-row gap-2">
              <button type="button" onClick={handleDirectRedirectSso} className="flex-1 py-2.5 px-4 rounded-lg bg-sky-500 hover:bg-sky-400 text-slate-950 font-black text-xs uppercase">Login Ulang SSO</button>
              <button type="button" onClick={() => { handleDisconnectMedianSso(); window.location.href = "/auth/login"; }} className="flex-1 py-2.5 px-4 rounded-lg bg-red-950/60 hover:bg-red-900 border border-red-700 text-red-200 font-bold text-xs uppercase">Keluar Session</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const handleRoleSelection = (emp: Employee) => {
    localStorage.setItem("current_user_id", emp.id);
    onSelectUser(emp);
    onClose();
  };

  const handleSupabaseAuth = async (e: React.FormEvent) => {
    e.preventDefault();
    setSupaMessage(null);

    if (!supaEmail || !supaPassword) {
      setSupaMessage({ text: "Silakan isi Email & Password Supabase.", isError: true });
      return;
    }

    setIsSupaAuthenticating(true);

    if (supaMode === "login") {
      const res = await supabaseService.signInWithAuth(supaEmail, supaPassword);
      setIsSupaAuthenticating(false);

      if (res.success) {
        setSupaMessage({ text: "Berhasil login dengan Supabase Auth! Token tersimpan.", isError: false });
        setActiveToken(res.token || localStorage.getItem("supabase_auth_token"));

        // Match employee by email or default to CEO
        const matched = employees.find(e => e.email.toLowerCase() === supaEmail.toLowerCase()) || currentUser;
        localStorage.setItem("current_user_id", matched.id);
        onSelectUser(matched);
        setTimeout(() => onClose(), 1000);
      } else {
        setSupaMessage({ text: res.error || "Gagal login ke Supabase Auth.", isError: true });
      }
    } else {
      const res = await supabaseService.signUpWithAuth(supaEmail, supaPassword);
      setIsSupaAuthenticating(false);

      if (res.success) {
        setSupaMessage({ text: "Pendaftaran akun Supabase Auth berhasil! Silakan login.", isError: false });
        setSupaMode("login");
      } else {
        setSupaMessage({ text: res.error || "Gagal mendaftar akun Supabase.", isError: true });
      }
    }
  };

  const handleSignOutSupabase = async () => {
    await supabaseService.signOutAuth();
    setActiveToken(null);
    setSupaMessage({ text: "Sesi Supabase Auth telah dicabut/logout.", isError: false });
  };

  // Filter preset executive profiles
  const presetRoles = [
    {
      id: "emp-ceo-01",
      roleLabel: "Direktur Utama (CEO)",
      badgeColor: "bg-[#facc15] text-black",
      icon: ShieldCheck,
      description: "Akses Super Admin Seluruh Modul & Menu Enterprise"
    },
    {
      id: "emp-cto-01",
      roleLabel: "Chief Technology Officer (CTO)",
      badgeColor: "bg-purple-500/20 text-purple-300 border border-purple-500/40",
      icon: Cpu,
      description: "Akses Modul Integrasi Database, REST API & Operational Workflows"
    },
    {
      id: "emp-cfo-01",
      roleLabel: "Chief Financial Officer (CFO)",
      badgeColor: "bg-green-500/20 text-green-300 border border-green-500/40",
      icon: DollarSign,
      description: "Akses Modul Draft RKAP, Konsolidasi Arus Kas & Otorisasi Budget"
    },
    {
      id: "emp-chr-01",
      roleLabel: "Chief Human Resources (CHR)",
      badgeColor: "bg-pink-500/20 text-pink-300 border border-pink-500/40",
      icon: Users,
      description: "Akses Modul Master SDM 360°, Struktur Org & Approval HR"
    }
  ];

  const filteredEmployees = employees.filter(e => 
    e.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    e.position.toLowerCase().includes(searchQuery.toLowerCase()) ||
    e.division.toLowerCase().includes(searchQuery.toLowerCase()) ||
    e.nip.includes(searchQuery)
  );

  const handleManualLogin = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage("");

    const term = inputNip.trim().toLowerCase();
    if (!term) {
      setErrorMessage("Silakan masukkan NIP, NIK, atau Email pegawai.");
      return;
    }

    const matched = employees.find(emp => 
      emp.nip.toLowerCase() === term || 
      emp.nik.toLowerCase() === term ||
      emp.email.toLowerCase() === term ||
      emp.name.toLowerCase() === term
    );

    if (matched) {
      handleRoleSelection(matched);
      setInputNip("");
      setInputPassword("");
    } else {
      setErrorMessage(`Kredensial '${inputNip}' tidak ditemukan. Silakan gunakan NIP (contoh: 196519920001) atau pilih dari daftar.`);
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-3 sm:p-4 font-sans">
      <div className="bg-[#0f172a] border border-[#1e3a8a]/60 w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col shadow-2xl rounded-xl">
        {/* Modal Header */}
        <div className="p-4 sm:p-5 bg-[#0b132b] border-b border-[#1e3a8a]/60 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 sm:w-10 sm:h-10 bg-gradient-to-br from-blue-600 to-sky-500 text-white font-black flex items-center justify-center rounded-lg shadow-md shadow-blue-500/30">
              <Key className="w-4 h-4 sm:w-5 sm:h-5 text-white" />
            </div>
            <div>
              <h2 className="text-sm sm:text-base font-extrabold uppercase text-white tracking-tight bg-gradient-to-r from-sky-400 via-blue-200 to-white bg-clip-text text-transparent">
                Sistem Login & Switch Role Direktorat
              </h2>
              <p className="text-[10px] sm:text-xs text-sky-200/70 font-mono">
                MEDIAN PT MEDIA EKOSISTEM DIGITAL APLIKASI NASIONAL
              </p>
            </div>
          </div>

          <button 
            onClick={onClose}
            className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 transition-colors rounded-lg"
          >
            <X className="w-4 h-4 sm:w-5 sm:h-5" />
          </button>
        </div>

        {/* Modal Content - Scrollable */}
        <div className="p-4 sm:p-6 overflow-y-auto space-y-4 sm:space-y-6">
          {/* Current Active User Status & Supabase Token Badge */}
          <div className="bg-[#1e293b]/70 border border-sky-500/30 p-3 sm:p-4 flex flex-col sm:flex-row items-center justify-between gap-3 rounded-lg">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-r from-blue-600 to-sky-500 rounded-lg flex items-center justify-center font-black text-lg text-white shadow-md shadow-blue-500/20 shrink-0">
                {currentUser.name.charAt(0)}
              </div>
              <div>
                <span className="text-[9px] uppercase font-mono text-sky-400 font-bold tracking-wider block">
                  USER SAAT INI TERHUBUNG:
                </span>
                <h4 className="text-xs sm:text-sm font-bold text-white">{currentUser.name}</h4>
                <p className="text-[10px] sm:text-xs text-slate-300 font-mono">
                  {currentUser.position} • {getDirectorateName(currentUser.position, currentUser.division)}
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2 flex-wrap">
              {medianSsoUser && (
                <div className="px-2.5 py-1 bg-sky-500/20 border border-sky-400/50 text-sky-200 text-[10px] font-mono flex items-center gap-1.5 rounded-md shadow-sm" title="Median ID SSO Verified">
                  <Globe className="w-3.5 h-3.5 text-sky-400" />
                  <span className="font-extrabold">MEDIAN SSO: {medianSsoUser.email}</span>
                  <button onClick={handleDisconnectMedianSso} className="ml-1 text-slate-400 hover:text-red-400 font-bold" title="Putuskan Sesi Median SSO">✕</button>
                </div>
              )}
              {activeToken && (
                <div className="px-2.5 py-1 bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-[10px] font-mono flex items-center gap-1.5 rounded" title="Sesi Supabase Auth Aktif">
                  <Database className="w-3 h-3 text-emerald-400" />
                  <span>SUPABASE AUTH TOKEN ACTIVE</span>
                  <button onClick={handleSignOutSupabase} className="ml-1 text-slate-400 hover:text-red-400 font-bold" title="Logout Supabase Auth">✕</button>
                </div>
              )}
              <span className="px-2.5 py-1 bg-sky-500/10 text-sky-300 border border-sky-500/30 text-[10px] sm:text-xs font-mono font-bold flex items-center gap-1.5 rounded">
                <BadgeCheck className="w-3.5 h-3.5 text-sky-400" />
                AUTHENTICATED
              </span>
            </div>
          </div>

          {/* PRIMARY OAUTH PROVIDER: MEDIAN CLOUD DJANGO SSO (https://auth.median-cloud.web.id) */}
          <div className="bg-gradient-to-r from-[#031525] via-[#062038] to-[#031525] border-2 border-sky-400 p-4 sm:p-5 rounded-xl shadow-xl shadow-sky-950/40 space-y-3.5 relative overflow-hidden">
            {/* Background Glow */}
            <div className="absolute -right-10 -top-10 w-40 h-40 bg-sky-500/10 rounded-full blur-2xl pointer-events-none"></div>

            <div className="flex items-start sm:items-center justify-between gap-3 border-b border-sky-800/40 pb-3">
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 sm:w-10 sm:h-10 bg-sky-500 text-slate-950 font-black flex items-center justify-center rounded-lg shadow-lg shadow-sky-500/30 shrink-0">
                  <Globe className="w-5 h-5 text-slate-950" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <span className="px-2 py-0.5 bg-sky-400/20 text-sky-300 border border-sky-400/40 text-[9px] font-mono font-black uppercase tracking-wider rounded">
                      PRIMARY LOGIN PROVIDER
                    </span>
                    <span className="text-[10px] text-slate-400 font-mono">Python Django OAuth2 + Supabase DB</span>
                  </div>
                  <h3 className="text-sm sm:text-base font-extrabold text-white tracking-tight flex items-center gap-1.5 mt-0.5">
                    Median Cloud SSO <span className="text-sky-400 text-xs font-mono font-normal">(https://auth.median-cloud.web.id)</span>
                  </h3>
                </div>
              </div>

              {medianSsoUser ? (
                <span className="px-3 py-1 bg-emerald-500/20 border border-emerald-500/40 text-emerald-300 text-xs font-mono font-bold flex items-center gap-1.5 rounded-lg shrink-0">
                  <BadgeCheck className="w-4 h-4 text-emerald-400" />
                  VERIFIED SSO SESSION
                </span>
              ) : (
                <span className="px-2.5 py-1 bg-amber-500/10 border border-amber-500/30 text-amber-300 text-[10px] font-mono font-bold flex items-center gap-1 rounded shrink-0">
                  <KeyRound className="w-3.5 h-3.5 text-amber-400" />
                  SIAP TERHUBUNG
                </span>
              )}
            </div>

            <p className="text-xs text-sky-100/80 leading-relaxed font-sans">
              Server Single Sign-On berbasis Python Django (auth.median-cloud.web.id) & Supabase PostgreSQL untuk seluruh pegawai & eksekutif MEDIAN CLOUD.
            </p>

            <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2.5 pt-1">
              <button
                type="button"
                onClick={handleTriggerMedianSso}
                disabled={isMedianSsoLoading}
                className="flex-1 py-3 px-4 bg-gradient-to-r from-sky-400 via-sky-500 to-blue-600 hover:from-sky-300 hover:to-blue-500 disabled:opacity-50 text-slate-950 font-black uppercase text-xs tracking-wider flex items-center justify-center gap-2 rounded-lg shadow-lg shadow-sky-500/25 transition-all cursor-pointer border border-sky-300"
              >
                {isMedianSsoLoading ? (
                  <>
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    Membuka Authorization...
                  </>
                ) : (
                  <>
                    <Globe className="w-4 h-4" />
                    Login SSO (Popup)
                    <ExternalLink className="w-3.5 h-3.5 opacity-80" />
                  </>
                )}
              </button>

              <button
                type="button"
                onClick={handleDirectRedirectSso}
                disabled={isMedianSsoLoading}
                title="Redirect langsung ke https://auth.median-cloud.web.id"
                className="py-3 px-4 bg-slate-900/90 hover:bg-slate-800 border border-sky-500/40 hover:border-sky-400 text-sky-300 text-xs font-mono font-bold rounded-lg transition-colors flex items-center justify-center gap-1.5 cursor-pointer"
              >
                <ArrowRight className="w-3.5 h-3.5 text-sky-400" />
                <span>Redirect Penuh</span>
              </button>

              {medianSsoUser && (
                <button
                  type="button"
                  onClick={handleDisconnectMedianSso}
                  className="py-2.5 px-3 bg-red-950/40 hover:bg-red-900/60 border border-red-800 text-red-300 text-xs font-mono font-bold rounded-lg transition-colors"
                >
                  Disconnect
                </button>
              )}
            </div>

            {medianSsoMessage && (
              <p className={`text-xs font-mono p-2.5 rounded border ${
                medianSsoMessage.isError 
                  ? "bg-red-950/40 border-red-500/40 text-red-300" 
                  : "bg-emerald-950/40 border-emerald-500/40 text-emerald-300"
              }`}>
                {medianSsoMessage.text}
              </p>
            )}
          </div>

          {/* Supabase Auth Form Section */}
          <div className="bg-[#0a0a0a] border border-emerald-500/30 p-4 space-y-3 font-mono">
            <div className="flex items-center justify-between border-b border-[#222] pb-2">
              <div className="flex items-center gap-2">
                <Database className="w-4 h-4 text-emerald-400" />
                <span className="text-xs font-black uppercase text-emerald-400 tracking-wider">
                  Autentikasi Akun Supabase Auth (Email & Password)
                </span>
              </div>
              <div className="flex items-center gap-1 text-[10px]">
                <button
                  type="button"
                  onClick={() => setSupaMode("login")}
                  className={`px-2 py-0.5 border ${supaMode === "login" ? "bg-emerald-600 text-white border-emerald-400" : "bg-[#111] text-slate-400 border-[#333]"}`}
                >
                  Sign In
                </button>
                <button
                  type="button"
                  onClick={() => setSupaMode("signup")}
                  className={`px-2 py-0.5 border ${supaMode === "signup" ? "bg-emerald-600 text-white border-emerald-400" : "bg-[#111] text-slate-400 border-[#333]"}`}
                >
                  Sign Up
                </button>
              </div>
            </div>

            <form onSubmit={handleSupabaseAuth} className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <div className="relative">
                <Mail className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
                <input
                  type="email"
                  placeholder="Email Supabase..."
                  value={supaEmail}
                  onChange={e => setSupaEmail(e.target.value)}
                  className="w-full bg-[#050505] border border-[#333] focus:border-emerald-500 text-white pl-8 pr-2 py-1.5 text-xs font-mono"
                />
              </div>

              <div className="relative">
                <Lock className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
                <input
                  type="password"
                  placeholder="Password..."
                  value={supaPassword}
                  onChange={e => setSupaPassword(e.target.value)}
                  className="w-full bg-[#050505] border border-[#333] focus:border-emerald-500 text-white pl-8 pr-2 py-1.5 text-xs font-mono"
                />
              </div>

              <button
                type="submit"
                disabled={isSupaAuthenticating}
                className="bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white font-black uppercase text-xs tracking-wider px-3 py-1.5 flex items-center justify-center gap-1.5 border border-emerald-400/40 transition-colors"
              >
                {isSupaAuthenticating ? (
                  <>
                    <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                    Proses...
                  </>
                ) : supaMode === "login" ? (
                  <>
                    <Key className="w-3.5 h-3.5" />
                    Login Supabase
                  </>
                ) : (
                  <>
                    <UserPlus className="w-3.5 h-3.5" />
                    Daftar Akun
                  </>
                )}
              </button>
            </form>

            {supaMessage && (
              <p className={`text-[11px] font-mono ${supaMessage.isError ? 'text-red-400' : 'text-emerald-400'}`}>
                {supaMessage.text}
              </p>
            )}
          </div>

          {/* Quick Preset Role Selection Cards */}
          <div className="space-y-3">
            <div className="flex items-center justify-between border-b border-[#222] pb-2">
              <span className="text-xs font-black uppercase text-[#facc15] tracking-wider flex items-center gap-2">
                <Sparkles className="w-4 h-4" />
                Quick Login Presets (Akses Direksi & Eksekutif)
              </span>
              <span className="text-[10px] font-mono text-slate-500">
                Ganti Role Instan
              </span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {presetRoles.map((preset) => {
                const emp = employees.find(e => e.id === preset.id);
                if (!emp) return null;
                const isSelected = currentUser.id === emp.id;
                const IconComp = preset.icon;

                return (
                  <button
                    key={preset.id}
                    onClick={() => handleRoleSelection(emp)}
                    className={`p-3.5 text-left border transition-all flex flex-col justify-between space-y-2 relative ${
                      isSelected 
                        ? "bg-[#141414] border-[#facc15] shadow-md" 
                        : "bg-[#050505] border-[#222] hover:border-[#444] hover:bg-[#0c0c0c]"
                    }`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-2">
                        <IconComp className="w-4 h-4 text-[#facc15]" />
                        <span className={`text-[10px] font-black font-mono uppercase px-2 py-0.5 ${preset.badgeColor}`}>
                          {preset.roleLabel}
                        </span>
                      </div>
                      {isSelected && (
                        <span className="text-xs text-[#facc15] font-black flex items-center gap-1">
                          <Check className="w-4 h-4" /> Active
                        </span>
                      )}
                    </div>

                    <div>
                      <strong className="text-xs font-black text-white block">{emp.name}</strong>
                      <span className="text-[10px] text-slate-400 font-mono block">NIP: {emp.nip}</span>
                      <p className="text-[10px] text-slate-500 font-mono mt-1 leading-tight">
                        {preset.description}
                      </p>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Manual Login or All Employees Search */}
          <div className="space-y-4 pt-2 border-t border-[#222]">
            <div className="flex items-center justify-between">
              <span className="text-xs font-black uppercase text-white tracking-wider flex items-center gap-2">
                <Search className="w-4 h-4 text-[#facc15]" />
                Cari & Switch Login Ke Seluruh Pegawai ({employees.length})
              </span>
            </div>

            {/* Search Input */}
            <div className="relative">
              <Search className="w-4 h-4 text-slate-500 absolute left-3 top-2.5" />
              <input
                type="text"
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                placeholder="Cari nama, jabatan, divisi, atau NIP..."
                className="w-full bg-[#050505] border border-[#222] text-white pl-9 pr-3 py-2 text-xs font-mono focus:border-[#facc15] rounded-none"
              />
            </div>

            {/* List of employees */}
            <div className="max-h-48 overflow-y-auto divide-y divide-[#181818] border border-[#222] bg-[#050505]">
              {filteredEmployees.map((emp) => {
                const isSelected = currentUser.id === emp.id;
                const dir = getDirectorateName(emp.position, emp.division);

                return (
                  <div 
                    key={emp.id} 
                    className={`p-3 flex items-center justify-between hover:bg-[#0f0f0f] transition-colors ${
                      isSelected ? "bg-[#111]" : ""
                    }`}
                  >
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="text-xs font-bold text-white">{emp.name}</span>
                        <span className="text-[10px] font-mono text-[#facc15] bg-[#1a1a1a] px-1.5 py-0.2 border border-[#222]">
                          NIP: {emp.nip}
                        </span>
                      </div>
                      <span className="text-[10px] text-slate-400 font-mono block mt-0.5">
                        {emp.position} • {emp.division} ({dir})
                      </span>
                    </div>

                    <button
                      onClick={() => handleRoleSelection(emp)}
                      className={`text-xs font-black uppercase tracking-wider px-3 py-1 transition-colors ${
                        isSelected 
                          ? "bg-green-600 text-white cursor-default" 
                          : "bg-[#222] hover:bg-[#facc15] hover:text-black text-slate-200"
                      }`}
                    >
                      {isSelected ? "Aktif" : "Pilih Login"}
                    </button>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Form Login NIP Simulasi */}
          <div className="bg-[#050505] border border-[#222] p-4 space-y-3">
            <span className="text-xs font-black uppercase text-slate-400 font-mono flex items-center gap-2">
              <Lock className="w-3.5 h-3.5 text-[#facc15]" />
              Form Simulasi Autentikasi NIP / Password
            </span>

            <form onSubmit={handleManualLogin} className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <input
                type="text"
                value={inputNip}
                onChange={e => setInputNip(e.target.value)}
                placeholder="Masukkan NIP (Contoh: 196519920001)"
                className="bg-black border border-[#222] text-white px-3 py-2 text-xs font-mono focus:border-[#facc15] rounded-none"
              />
              <input
                type="password"
                value={inputPassword}
                onChange={e => setInputPassword(e.target.value)}
                placeholder="Password (bebas untuk simulasi)"
                className="bg-black border border-[#222] text-white px-3 py-2 text-xs font-mono focus:border-[#facc15] rounded-none"
              />
              <button
                type="submit"
                className="bg-[#facc15] hover:bg-yellow-500 text-black font-black uppercase text-xs tracking-wider px-4 py-2 rounded-none transition-colors"
              >
                Login Sistem
              </button>
            </form>

            {errorMessage && (
              <p className="text-xs text-red-400 font-mono">{errorMessage}</p>
            )}
          </div>
        </div>

        {/* Modal Footer */}
        <div className="p-4 bg-[#0d0d0d] border-t border-[#222] flex justify-end">
          <button
            onClick={onClose}
            className="px-5 py-2 bg-[#222] hover:bg-[#333] text-white font-black text-xs uppercase tracking-wider rounded-none transition-colors"
          >
            Tutup Window
          </button>
        </div>
      </div>
    </div>
  );
}
