/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useMemo, useEffect } from "react";
import { 
  GOVERNANCE_DATA, 
  DirectorateGovernance, 
  DivisionGovernance, 
  CompanySop, 
  AuthorityMatrixItem, 
  FinancialLimitItem 
} from "../data/governanceData";
import { Employee } from "../types";
import { 
  ShieldCheck, 
  DollarSign, 
  Cpu, 
  Users, 
  Network, 
  FileText, 
  CheckCircle2, 
  AlertCircle, 
  Search, 
  Filter, 
  Calculator, 
  ChevronRight, 
  ArrowRight, 
  Printer, 
  Download, 
  Plus, 
  Building2, 
  Layers, 
  Clock, 
  HelpCircle, 
  FileCheck, 
  Lock,
  Sparkles,
  Info,
  Eye,
  History,
  Trash2,
  UserCheck,
  FileDown
} from "lucide-react";

export interface DocAccessLog {
  id: string;
  docCode: string;
  docTitle: string;
  userName: string;
  userPosition: string;
  action: "VIEW" | "DOWNLOAD" | "PRINT";
  timestamp: string;
}

interface GovernancePolicyModuleProps {
  currentUser?: Employee;
}

export default function GovernancePolicyModule({ currentUser }: GovernancePolicyModuleProps) {
  // Selected Directorate & Division state
  const [selectedDirId, setSelectedDirId] = useState<string>("dir-ceo");
  const [selectedDivName, setSelectedDivName] = useState<string>("Executive Office");

  // Active Policy View Sub-tab
  const [activeSubTab, setActiveSubTab] = useState<"matrix" | "financial" | "sop">("matrix");

  // Search & Filters
  const [searchQuery, setSearchQuery] = useState<string>("");

  // Financial Limit Interactive Calculator state
  const [calcAmount, setCalcAmount] = useState<number>(75000000);
  const [calcPosition, setCalcPosition] = useState<'Staf / Specialist' | 'Supervisor / Team Lead' | 'Manager Divisi' | 'Direktur (C-Suite)' | 'CEO / Board of Directors'>("Manager Divisi");

  // SOP Modal / Viewer State
  const [activeSopModal, setActiveSopModal] = useState<CompanySop | null>(null);
  const [isAddingSop, setIsAddingSop] = useState<boolean>(false);

  // Document Access Logs & Sidebar Tracking state
  const [accessLogs, setAccessLogs] = useState<DocAccessLog[]>(() => {
    const cached = localStorage.getItem("gov_doc_access_logs");
    if (cached) {
      try { return JSON.parse(cached); } catch (e) { /* fallback */ }
    }
    return [
      {
        id: "log-init-1",
        docCode: "SOP-EXEC-001",
        docTitle: "Prosedur Pengesahan Keputusan Strategis Board",
        userName: currentUser?.name || "Budi Santoso",
        userPosition: currentUser?.position || "CEO / Board of Directors",
        action: "VIEW",
        timestamp: new Date(Date.now() - 6 * 60000).toISOString()
      },
      {
        id: "log-init-2",
        docCode: "SOP-FIN-001",
        docTitle: "Prosedur Pengajuan Petty Cash & Reimbursable",
        userName: "Siti Rahmawati",
        userPosition: "Manager Finance",
        action: "DOWNLOAD",
        timestamp: new Date(Date.now() - 28 * 60000).toISOString()
      },
      {
        id: "log-init-3",
        docCode: "SOP-IT-001",
        docTitle: "Prosedur Pengajuan Perubahan Akses Server",
        userName: "Ahmad Subagyo",
        userPosition: "Head of Infrastructure",
        action: "PRINT",
        timestamp: new Date(Date.now() - 2 * 3600000).toISOString()
      },
      {
        id: "log-init-4",
        docCode: "SOP-HR-001",
        docTitle: "SOP Rekrutmen & Onboarding Karyawan Baru",
        userName: "Dewi Lestari",
        userPosition: "HR Business Partner",
        action: "VIEW",
        timestamp: new Date(Date.now() - 4 * 3600000).toISOString()
      }
    ];
  });

  const [logFilter, setLogFilter] = useState<"ALL" | "VIEW" | "DOWNLOAD" | "PRINT">("ALL");

  useEffect(() => {
    localStorage.setItem("gov_doc_access_logs", JSON.stringify(accessLogs));
  }, [accessLogs]);

  // Record document access action
  const logDocAccess = (docCode: string, docTitle: string, action: "VIEW" | "DOWNLOAD" | "PRINT") => {
    const uName = currentUser?.name || "Dian Ermawan";
    const uPos = currentUser?.position || "System Admin (COO)";

    const newLog: DocAccessLog = {
      id: `log-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
      docCode,
      docTitle,
      userName: uName,
      userPosition: uPos,
      action,
      timestamp: new Date().toISOString()
    };

    setAccessLogs(prev => [newLog, ...prev.slice(0, 49)]); // Keep latest 50 logs
  };

  // Helper to get last access log for a specific document
  const getLastAccessForDoc = (docCode: string) => {
    return accessLogs.find(log => log.docCode === docCode);
  };

  // Helper to format log time relative or date
  const formatLogTime = (isoString: string) => {
    try {
      const date = new Date(isoString);
      const now = new Date();
      const diffMs = now.getTime() - date.getTime();
      const diffMins = Math.floor(diffMs / 60000);
      if (diffMins < 1) return "Baru saja";
      if (diffMins < 60) return `${diffMins} mnt lalu`;
      const diffHours = Math.floor(diffMins / 60);
      if (diffHours < 24) return `${diffHours} jam lalu`;
      return date.toLocaleDateString("id-ID", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
    } catch (e) {
      return isoString;
    }
  };

  // Filtered Access Logs for Sidebar
  const filteredAccessLogs = useMemo(() => {
    if (logFilter === "ALL") return accessLogs;
    return accessLogs.filter(log => log.action === logFilter);
  }, [accessLogs, logFilter]);

  // Open SOP and record VIEW
  const handleOpenSop = (sop: CompanySop) => {
    setActiveSopModal(sop);
    logDocAccess(sop.sopCode, sop.title, "VIEW");
  };

  // Download SOP as file and record DOWNLOAD
  const handleDownloadSop = (sop: CompanySop) => {
    logDocAccess(sop.sopCode, sop.title, "DOWNLOAD");

    const textContent = `========================================================
STANDARD OPERATING PROCEDURE (SOP) RESMI
PT MEDIA EKOSISTEM DIGITAL APLIKASI NASIONAL
========================================================

Kode SOP       : ${sop.sopCode}
Judul SOP      : ${sop.title}
Direktorat     : ${sop.directorate}
Divisi         : ${sop.division}
Kategori       : ${sop.category}
Versi Dokumen  : ${sop.version}
Tanggal Efektif: ${sop.effectiveDate}
Status Dokumen : ${sop.docStatus}

1. TUJUAN (OBJECTIVE):
${sop.objective}

2. RUANG LINGKUP (SCOPE):
${sop.scope}

3. PROSEDUR LANGKAH OPERASIONAL:
${sop.steps.map(s => `Step ${s.stepNumber}. [Pelaksana: ${s.actor}]
   Tindakan: ${s.action}
   Output  : ${s.systemOutput}`).join("\n\n")}

4. CHECKLIST KEPATUHAN & AUDIT:
${sop.complianceChecklist.map((c, i) => `${i + 1}. [ ] ${c}`).join("\n")}

========================================================
Diunduh Oleh   : ${currentUser?.name || "Dian Ermawan"} (${currentUser?.position || "System Admin"})
Waktu Diunduh  : ${new Date().toLocaleString("id-ID")}
Sistem         : EMS Corporate Governance Engine ISO 9001:2026
========================================================`;

    const blob = new Blob([textContent], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `${sop.sopCode}_${sop.title.replace(/[^a-zA-Z0-9]/g, "_")}.txt`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  // Print SOP and record PRINT
  const handlePrintSop = (sop: CompanySop) => {
    logDocAccess(sop.sopCode, sop.title, "PRINT");
    window.print();
  };

  // Print full Governance policy and record PRINT
  const handlePrintPolicy = () => {
    logDocAccess("GOV-POLICY-ALL", `Kebijakan Governance ${currentDivision.divisionName}`, "PRINT");
    window.print();
  };

  // Reset access logs
  const handleClearLogs = () => {
    if (window.confirm("Apakah Anda yakin ingin mengosongkan riwayat log akses dokumen?")) {
      setAccessLogs([]);
    }
  };

  // Custom added SOPs state (persisted in local state)
  const [customSops, setCustomSops] = useState<CompanySop[]>([]);

  // New SOP Form state
  const [newSopCode, setNewSopCode] = useState("");
  const [newSopTitle, setNewSopTitle] = useState("");
  const [newSopObjective, setNewSopObjective] = useState("");
  const [newSopScope, setNewSopScope] = useState("");

  // Selected Directorate Object
  const currentDirectorate = useMemo(() => {
    return GOVERNANCE_DATA.find(d => d.directorateId === selectedDirId) || GOVERNANCE_DATA[0];
  }, [selectedDirId]);

  // Handle directorate change
  const handleSelectDirectorate = (dirId: string) => {
    setSelectedDirId(dirId);
    const dir = GOVERNANCE_DATA.find(d => d.directorateId === dirId);
    if (dir && dir.divisions.length > 0) {
      setSelectedDivName(dir.divisions[0].divisionName);
    }
  };

  // Selected Division Object
  const currentDivision = useMemo(() => {
    const div = currentDirectorate.divisions.find(d => d.divisionName === selectedDivName);
    return div || currentDirectorate.divisions[0];
  }, [currentDirectorate, selectedDivName]);

  // Combined SOPs (Base + Custom)
  const allDivisionSops = useMemo(() => {
    const base = currentDivision.sops || [];
    const added = customSops.filter(s => s.directorate === currentDirectorate.directorateName && s.division === currentDivision.divisionName);
    return [...base, ...added];
  }, [currentDivision, customSops, currentDirectorate]);

  // Filtered Authority Matrix items
  const filteredMatrix = useMemo(() => {
    if (!searchQuery.trim()) return currentDivision.authorityMatrix;
    const q = searchQuery.toLowerCase();
    return currentDivision.authorityMatrix.filter(item => 
      item.decisionType.toLowerCase().includes(q) ||
      item.category.toLowerCase().includes(q)
    );
  }, [currentDivision, searchQuery]);

  // Filtered Financial Limits
  const filteredLimits = useMemo(() => {
    return currentDivision.financialLimits;
  }, [currentDivision]);

  // Filtered SOPs
  const filteredSops = useMemo(() => {
    if (!searchQuery.trim()) return allDivisionSops;
    const q = searchQuery.toLowerCase();
    return allDivisionSops.filter(sop =>
      sop.sopCode.toLowerCase().includes(q) ||
      sop.title.toLowerCase().includes(q) ||
      sop.category.toLowerCase().includes(q)
    );
  }, [allDivisionSops, searchQuery]);

  // Format IDR Helper
  const formatIDR = (num: number) => {
    return new Intl.NumberFormat("id-ID", {
      style: "currency",
      currency: "IDR",
      maximumFractionDigits: 0
    }).format(num);
  };

  // Icon selector helper
  const getDirIcon = (iconName: string) => {
    switch (iconName) {
      case "ShieldCheck": return <ShieldCheck className="w-4 h-4" />;
      case "DollarSign": return <DollarSign className="w-4 h-4" />;
      case "Cpu": return <Cpu className="w-4 h-4" />;
      case "Users": return <Users className="w-4 h-4" />;
      case "Network": return <Network className="w-4 h-4" />;
      default: return <Building2 className="w-4 h-4" />;
    }
  };

  // Calculation evaluation for interactive limit checker
  const calcEvaluation = useMemo(() => {
    const limits = currentDivision.financialLimits;
    const userLimitItem = limits.find(l => l.positionLevel === calcPosition);
    if (!userLimitItem) return null;

    const isWithinSingleLimit = calcAmount <= userLimitItem.singleTransactionLimit;
    
    // Find required approver tier
    let requiredApproverTier = "Staf / Specialist";
    for (const l of limits) {
      if (calcAmount <= l.singleTransactionLimit) {
        requiredApproverTier = l.positionLevel;
        break;
      }
      requiredApproverTier = "CEO / Board of Directors (> Limits)";
    }

    return {
      isWithinSingleLimit,
      userLimit: userLimitItem.singleTransactionLimit,
      requiredApproverTier,
      note: isWithinSingleLimit 
        ? `Nominal ${formatIDR(calcAmount)} berada dalam limit wewenang ${calcPosition}.`
        : `Nominal ${formatIDR(calcAmount)} melebihi limit ${calcPosition} (${formatIDR(userLimitItem.singleTransactionLimit)}). Diperlukan otorisasi tingkat ${requiredApproverTier}.`
    };
  }, [calcAmount, calcPosition, currentDivision]);

  // Handle Create SOP
  const handleSaveNewSop = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newSopCode || !newSopTitle) return;

    const newSop: CompanySop = {
      id: `sop-custom-${Date.now()}`,
      sopCode: newSopCode.toUpperCase(),
      title: newSopTitle,
      category: "SOP Tambahan",
      directorate: currentDirectorate.directorateName,
      division: currentDivision.divisionName,
      effectiveDate: new Date().toISOString().split("T")[0],
      version: "v1.0",
      objective: newSopObjective || "Memastikan operasional berjalan terstandarisasi.",
      scope: newSopScope || `Seluruh staf dan manajemen di ${currentDivision.divisionName}.`,
      steps: [
        { stepNumber: 1, actor: "Inisiator", action: "Mengajukan draft permohonan via sistem EMS", systemOutput: "Tiket Request Created" },
        { stepNumber: 2, actor: "Supervisor / Lead", action: "Melakukan verifikasi kelengkapan berkas", systemOutput: "Verifikasi OK" },
        { stepNumber: 3, actor: "Manager Divisi", action: "Persetujuan akhir dan pengesahan hasil", systemOutput: "SOP Execution Approved" }
      ],
      complianceChecklist: [
        "Verifikasi kelengkapan dokumen pendukung",
        "Kepatuhan terhadap SLA response time",
        "Persetujuan dari atasan langsung"
      ],
      docStatus: "Efektif / Berlaku"
    };

    setCustomSops(prev => [newSop, ...prev]);
    setIsAddingSop(false);
    setNewSopCode("");
    setNewSopTitle("");
    setNewSopObjective("");
    setNewSopScope("");
  };

  return (
    <div className="space-y-6" id="governance-policy-master-container">
      {/* Header Banner */}
      <div className="bg-gradient-to-r from-slate-900 via-blue-950 to-slate-900 border border-sky-500/30 rounded-xl p-5 shadow-xl relative overflow-hidden">
        <div className="absolute top-0 right-0 transform translate-x-8 -translate-y-8 w-64 h-64 bg-sky-500/10 rounded-full blur-3xl pointer-events-none"></div>
        <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4 relative z-10">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="text-[10px] font-mono font-bold bg-sky-500/20 text-sky-300 border border-sky-500/30 px-2.5 py-0.5 rounded uppercase tracking-wider">
                CORPORATE GOVERNANCE & COMPLIANCE
              </span>
              <span className="text-[10px] font-mono text-emerald-400 flex items-center gap-1">
                <CheckCircle2 className="w-3 h-3 text-emerald-400" />
                ISO 9001:2026 Ready
              </span>
            </div>
            <h2 className="text-xl sm:text-2xl font-black uppercase text-white tracking-tight flex items-center gap-2">
              <ShieldCheck className="w-6 h-6 text-sky-400" />
              TATA KELOLA, MATRIKS WEWENANG & SOP DIVISI
            </h2>
            <p className="text-xs text-slate-300 max-w-3xl mt-1 leading-relaxed">
              Panduan otorisasi resmi perusahaan, batas limit transaksi keuangan, dan Standard Operating Procedure (SOP) terintegrasi untuk seluruh divisi pada tiap direktorat PT Media Ekosistem Digital Aplikasi Nasional.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2 self-stretch md:self-auto justify-end">
            <button
              type="button"
              onClick={handlePrintPolicy}
              className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-sky-300 border border-sky-500/30 rounded text-xs font-bold uppercase tracking-wide transition-all flex items-center gap-1.5 shadow-sm cursor-pointer"
            >
              <Printer className="w-3.5 h-3.5 text-sky-400" />
              Cetak Kebijakan
            </button>
            <button
              type="button"
              onClick={() => setIsAddingSop(true)}
              className="px-3 py-1.5 bg-gradient-to-r from-blue-600 to-sky-500 hover:from-blue-500 hover:to-sky-400 text-white rounded text-xs font-bold uppercase tracking-wide transition-all flex items-center gap-1.5 shadow-md shadow-blue-600/30 cursor-pointer"
            >
              <Plus className="w-3.5 h-3.5" />
              Tambah SOP Baru
            </button>
          </div>
        </div>
      </div>

      {/* Main Grid: Content (3 Cols) + Sidebar Log Tracking (1 Col) */}
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 items-start">
        {/* LEFT / MAIN COLUMN */}
        <div className="lg:col-span-3 space-y-6">

      {/* 1. DIRECTORATE SELECTOR TABS */}
      <div className="space-y-2">
        <label className="text-[11px] font-bold text-sky-300 uppercase tracking-wider flex items-center gap-1.5">
          <Building2 className="w-3.5 h-3.5 text-sky-400" />
          PILIH DIREKTORAT PERUSAHAAN:
        </label>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
          {GOVERNANCE_DATA.map((dir) => {
            const isSelected = dir.directorateId === selectedDirId;
            return (
              <button
                key={dir.directorateId}
                onClick={() => handleSelectDirectorate(dir.directorateId)}
                className={`p-3 rounded-lg border text-left transition-all flex flex-col justify-between ${
                  isSelected 
                    ? "bg-gradient-to-b from-blue-900/80 to-slate-900 border-sky-400 text-white shadow-lg shadow-blue-950/50 ring-1 ring-sky-400/50" 
                    : "bg-[#0f172a]/80 border-slate-800 text-slate-400 hover:bg-slate-800/60 hover:text-slate-200"
                }`}
              >
                <div className="flex items-center justify-between mb-2">
                  <div className={`p-1.5 rounded ${isSelected ? "bg-sky-500 text-white" : "bg-slate-800 text-slate-400"}`}>
                    {getDirIcon(dir.iconName)}
                  </div>
                  <span className="text-[9px] font-mono font-bold px-1.5 py-0.5 rounded bg-slate-900 border border-slate-700 text-slate-300">
                    {dir.divisions.length} Divisi
                  </span>
                </div>
                <div className="text-xs font-black uppercase tracking-tight line-clamp-2">
                  {dir.directorateName}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* 2. DIVISION SELECTOR & SUB-TAB NAVIGATION */}
      <div className="bg-[#0f172a] border border-slate-800 rounded-xl p-4 space-y-4 shadow-md">
        <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 border-b border-slate-800 pb-4">
          {/* Divisions Pill Selector */}
          <div className="space-y-1.5 w-full lg:w-auto">
            <span className="text-[10px] font-bold uppercase text-slate-400 tracking-wider block">
              DIVISI PADA {currentDirectorate.directorateName.toUpperCase()}:
            </span>
            <div className="flex flex-wrap items-center gap-1.5">
              {currentDirectorate.divisions.map((div) => {
                const isSelected = div.divisionName === selectedDivName;
                return (
                  <button
                    key={div.divisionName}
                    onClick={() => setSelectedDivName(div.divisionName)}
                    className={`px-3 py-1.5 rounded-md text-xs font-bold uppercase tracking-wide transition-all ${
                      isSelected
                        ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
                        : "bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-white border border-slate-700/50"
                    }`}
                  >
                    {div.divisionName}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Sub-Tab Module Controls */}
          <div className="flex items-center bg-slate-900 border border-slate-800 rounded-lg p-1 w-full lg:w-auto justify-center">
            <button
              onClick={() => setActiveSubTab("matrix")}
              className={`flex-1 lg:flex-initial px-3.5 py-1.5 rounded text-xs font-extrabold uppercase tracking-wider transition-all flex items-center justify-center gap-1.5 ${
                activeSubTab === "matrix"
                  ? "bg-gradient-to-r from-blue-600 to-sky-500 text-white shadow-sm"
                  : "text-slate-400 hover:text-slate-200"
              }`}
            >
              <FileCheck className="w-3.5 h-3.5" />
              1. Matriks Wewenang & Approval
            </button>

            <button
              onClick={() => setActiveSubTab("financial")}
              className={`flex-1 lg:flex-initial px-3.5 py-1.5 rounded text-xs font-extrabold uppercase tracking-wider transition-all flex items-center justify-center gap-1.5 ${
                activeSubTab === "financial"
                  ? "bg-gradient-to-r from-blue-600 to-sky-500 text-white shadow-sm"
                  : "text-slate-400 hover:text-slate-200"
              }`}
            >
              <DollarSign className="w-3.5 h-3.5" />
              2. Limit Otorisasi Keuangan
            </button>

            <button
              onClick={() => setActiveSubTab("sop")}
              className={`flex-1 lg:flex-initial px-3.5 py-1.5 rounded text-xs font-extrabold uppercase tracking-wider transition-all flex items-center justify-center gap-1.5 relative ${
                activeSubTab === "sop"
                  ? "bg-gradient-to-r from-blue-600 to-sky-500 text-white shadow-sm"
                  : "text-slate-400 hover:text-slate-200"
              }`}
            >
              <FileText className="w-3.5 h-3.5" />
              3. SOP Perusahaan ({allDivisionSops.length})
            </button>
          </div>
        </div>

        {/* Filter & Search Bar */}
        <div className="flex items-center justify-between gap-3">
          <div className="relative flex-1">
            <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder={`Cari dalam ${currentDivision.divisionName}... (contoh: "PO", "Petty Cash", "Release")`}
              className="w-full bg-slate-900 border border-slate-700/80 rounded-lg pl-9 pr-4 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-sky-500 transition-colors font-mono"
            />
          </div>
          <div className="text-xs font-mono text-slate-400 hidden sm:block">
            Divisi Terpilih: <strong className="text-sky-400 font-sans uppercase">{currentDivision.divisionName}</strong>
          </div>
        </div>
      </div>

      {/* 3. SUB-TAB VIEW CONTENT */}

      {/* TAB 1: MATRIKS WEWENANG DAN APPROVAL */}
      {activeSubTab === "matrix" && (
        <div className="space-y-6">
          <div className="bg-[#0f172a] border border-slate-800 rounded-xl overflow-hidden shadow-lg">
            <div className="bg-slate-900/90 px-4 py-3 border-b border-slate-800 flex items-center justify-between">
              <h3 className="text-xs font-black uppercase tracking-wider text-sky-400 flex items-center gap-2">
                <FileCheck className="w-4 h-4 text-sky-400" />
                TABEL MATRIKS WEWENANG KEPUTUSAN & APPROVAL FLOW — {currentDivision.divisionName.toUpperCase()}
              </h3>
              <span className="text-[10px] font-mono text-slate-400">
                {filteredMatrix.length} Kategori Keputusan Terdaftar
              </span>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-slate-900/60 text-[10px] font-mono uppercase text-slate-400 border-b border-slate-800">
                    <th className="py-3 px-4 font-bold">Kategori & Jenis Keputusan</th>
                    <th className="py-3 px-3 font-bold text-slate-300">Level Staf</th>
                    <th className="py-3 px-3 font-bold text-sky-300">Level Supervisor</th>
                    <th className="py-3 px-3 font-bold text-blue-300">Level Manager</th>
                    <th className="py-3 px-3 font-bold text-indigo-300">Level Direktur</th>
                    <th className="py-3 px-3 font-bold text-purple-300">Level CEO / Board</th>
                    <th className="py-3 px-4 font-bold">Dokumen Pendukung & SLA</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/60 text-xs">
                  {filteredMatrix.map((item) => (
                    <tr key={item.id} className="hover:bg-slate-800/40 transition-colors">
                      <td className="py-3.5 px-4">
                        <span className="text-[9px] font-mono font-bold bg-sky-950 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded uppercase block w-fit mb-1">
                          {item.category}
                        </span>
                        <div className="font-extrabold text-white text-xs leading-snug">
                          {item.decisionType}
                        </div>
                      </td>

                      <td className="py-3.5 px-3">
                        <span className={`inline-block px-2 py-1 rounded text-[10px] font-bold ${
                          item.staffAuthority.includes("Tidak") ? "bg-slate-800 text-slate-500" :
                          item.staffAuthority.includes("Inisiasi") ? "bg-cyan-950 text-cyan-300 border border-cyan-500/30" : "bg-emerald-950 text-emerald-300"
                        }`}>
                          {item.staffAuthority}
                        </span>
                      </td>

                      <td className="py-3.5 px-3">
                        <span className={`inline-block px-2 py-1 rounded text-[10px] font-bold ${
                          item.supervisorAuthority.includes("Tidak") ? "bg-slate-800 text-slate-500" :
                          item.supervisorAuthority.includes("Verifikasi") ? "bg-sky-950 text-sky-300 border border-sky-500/30" : "bg-emerald-950 text-emerald-300"
                        }`}>
                          {item.supervisorAuthority}
                        </span>
                      </td>

                      <td className="py-3.5 px-3">
                        <span className={`inline-block px-2 py-1 rounded text-[10px] font-bold ${
                          item.managerAuthority.includes("Tidak") ? "bg-slate-800 text-slate-500" :
                          item.managerAuthority.includes("Persetujuan Mutlak") ? "bg-emerald-950 text-emerald-300 border border-emerald-500/30 font-extrabold" : "bg-blue-950 text-blue-300 border border-blue-500/30"
                        }`}>
                          {item.managerAuthority}
                        </span>
                      </td>

                      <td className="py-3.5 px-3">
                        <span className={`inline-block px-2 py-1 rounded text-[10px] font-bold ${
                          item.directorAuthority.includes("Tidak") ? "bg-slate-800 text-slate-500" :
                          item.directorAuthority.includes("Utama") || item.directorAuthority.includes("Mutlak") ? "bg-indigo-950 text-indigo-300 border border-indigo-500/30 font-extrabold" : "bg-slate-800 text-slate-300"
                        }`}>
                          {item.directorAuthority}
                        </span>
                      </td>

                      <td className="py-3.5 px-3">
                        <span className={`inline-block px-2 py-1 rounded text-[10px] font-bold ${
                          item.ceoAuthority.includes("Tidak Perlu") ? "bg-slate-800 text-slate-500" : "bg-purple-950 text-purple-300 border border-purple-500/30 font-extrabold"
                        }`}>
                          {item.ceoAuthority}
                        </span>
                      </td>

                      <td className="py-3.5 px-4 space-y-1">
                        <div className="flex flex-wrap gap-1">
                          {item.requiredDocs.map((doc, idx) => (
                            <span key={idx} className="text-[9px] bg-slate-800 text-slate-300 px-1.5 py-0.5 rounded font-mono border border-slate-700">
                              • {doc}
                            </span>
                          ))}
                        </div>
                        <div className="text-[10px] font-mono text-sky-400 flex items-center gap-1 pt-0.5">
                          <Clock className="w-3 h-3 text-sky-400" />
                          SLA Approval: max {item.slaHours} Jam Kerja
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Visual Step-by-Step Approval Flow Chart */}
          <div className="bg-[#0f172a] border border-slate-800 rounded-xl p-5 space-y-4">
            <h4 className="text-xs font-black uppercase tracking-wider text-sky-400 flex items-center gap-2">
              <Network className="w-4 h-4 text-sky-400" />
              ALUR BERJENJANG APPROVAL WORKFLOW KANBAN SYSTEM ({currentDivision.divisionName.toUpperCase()})
            </h4>

            <div className="grid grid-cols-1 md:grid-cols-5 gap-3 relative">
              {[
                { step: "Stage 1", title: "Staf / Specialist", desc: "Input permohonan & unggah dokumen pendukung", color: "border-slate-700 bg-slate-900" },
                { step: "Stage 2", title: "Supervisor / Lead", desc: "Verifikasi kelengkapan administrasi & teknis", color: "border-sky-500/40 bg-sky-950/30" },
                { step: "Stage 3", title: "Manager Divisi", desc: "Persetujuan otorisasi s/d limit anggaran divisi", color: "border-blue-500/40 bg-blue-950/30" },
                { step: "Stage 4", title: "Direktur (C-Suite)", desc: "Approval pengeluaran skala besar & strategi", color: "border-indigo-500/40 bg-indigo-950/30" },
                { step: "Stage 5", title: "CEO / Board", desc: "Persetujuan final / investasi korporasi", color: "border-purple-500/40 bg-purple-950/30" }
              ].map((s, i) => (
                <div key={i} className={`p-3.5 rounded-lg border ${s.color} space-y-1.5 relative group`}>
                  <div className="flex items-center justify-between">
                    <span className="text-[9px] font-mono font-bold text-sky-400 bg-slate-800 px-1.5 py-0.5 rounded">
                      {s.step}
                    </span>
                    <ChevronRight className="w-4 h-4 text-slate-600 group-hover:text-sky-400 transition-colors hidden md:block" />
                  </div>
                  <h5 className="text-xs font-extrabold text-white uppercase">{s.title}</h5>
                  <p className="text-[10px] text-slate-400 leading-normal">{s.desc}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* TAB 2: LIMIT OTORISASI KEUANGAN */}
      {activeSubTab === "financial" && (
        <div className="space-y-6">
          
          {/* Interactive Amount Calculator & Approval Checker */}
          <div className="bg-gradient-to-r from-slate-900 via-blue-950 to-slate-900 border border-sky-500/40 rounded-xl p-5 shadow-xl space-y-4">
            <div className="flex items-center justify-between border-b border-sky-500/20 pb-3">
              <h3 className="text-sm font-black uppercase text-white flex items-center gap-2">
                <Calculator className="w-4.5 h-4.5 text-sky-400" />
                SIMULASI INTERAKTIF WEWENANG OTORISASI NOMINAL TRANSAKSI
              </h3>
              <span className="text-[10px] font-mono bg-sky-950 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded">
                Real-time Limits Engine
              </span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-1.5">
                <label className="text-[10px] font-bold text-slate-300 uppercase tracking-wider block">
                  NOMINAL PERMOHONAN (IDR):
                </label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-xs font-bold text-sky-400 font-mono">Rp</span>
                  <input
                    type="number"
                    value={calcAmount}
                    onChange={(e) => setCalcAmount(Math.max(0, Number(e.target.value)))}
                    className="w-full bg-slate-900 border border-slate-700 rounded-lg pl-9 pr-3 py-2 text-sm text-white font-mono font-bold focus:outline-none focus:border-sky-400"
                  />
                </div>
                <div className="text-[10px] text-slate-400 font-mono">
                  {formatIDR(calcAmount)}
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[10px] font-bold text-slate-300 uppercase tracking-wider block">
                  POSISI JABATAN PENGATUR:
                </label>
                <select
                  value={calcPosition}
                  onChange={(e) => setCalcPosition(e.target.value as any)}
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-xs text-white font-semibold focus:outline-none focus:border-sky-400"
                >
                  <option value="Staf / Specialist">Staf / Specialist</option>
                  <option value="Supervisor / Team Lead">Supervisor / Team Lead</option>
                  <option value="Manager Divisi">Manager Divisi</option>
                  <option value="Direktur (C-Suite)">Direktur (C-Suite)</option>
                  <option value="CEO / Board of Directors">CEO / Board of Directors</option>
                </select>
                <div className="text-[10px] text-slate-400 font-mono">
                  Divisi: <span className="text-white uppercase">{currentDivision.divisionName}</span>
                </div>
              </div>

              {/* Evaluation Output Result */}
              {calcEvaluation && (
                <div className={`p-3.5 rounded-lg border flex flex-col justify-between ${
                  calcEvaluation.isWithinSingleLimit
                    ? "bg-emerald-950/40 border-emerald-500/40 text-emerald-200"
                    : "bg-amber-950/40 border-amber-500/40 text-amber-200"
                }`}>
                  <div>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[10px] font-bold uppercase tracking-wider">HASIL VERIFIKASI:</span>
                      {calcEvaluation.isWithinSingleLimit ? (
                        <span className="text-[9px] bg-emerald-500 text-black font-black px-1.5 py-0.5 rounded">TERVERIFIKASI WAKTU SINGKAT</span>
                      ) : (
                        <span className="text-[9px] bg-amber-500 text-black font-black px-1.5 py-0.5 rounded">PERLU ESCALATION</span>
                      )}
                    </div>
                    <p className="text-xs leading-snug font-medium">{calcEvaluation.note}</p>
                  </div>
                  <div className="text-[10px] font-mono mt-2 pt-1 border-t border-current/20 flex items-center justify-between">
                    <span>Approver Diperlukan:</span>
                    <strong className="uppercase">{calcEvaluation.requiredApproverTier}</strong>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Cards for each Level Financial Limit */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredLimits.map((limit, idx) => (
              <div key={idx} className="bg-[#0f172a] border border-slate-800 rounded-xl p-4 space-y-3 hover:border-sky-500/50 transition-all shadow-md">
                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                  <span className="text-xs font-black uppercase text-white flex items-center gap-1.5">
                    <DollarSign className="w-4 h-4 text-sky-400" />
                    {limit.positionLevel}
                  </span>
                  <span className="text-[9px] font-mono bg-sky-950 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded">
                    Tier {idx + 1}
                  </span>
                </div>

                <div className="space-y-2">
                  <div>
                    <span className="text-[10px] font-mono text-slate-400 uppercase">Limit Per Transaksi Tunggal:</span>
                    <div className="text-lg font-black font-mono text-emerald-400">
                      {formatIDR(limit.singleTransactionLimit)}
                    </div>
                  </div>

                  <div>
                    <span className="text-[10px] font-mono text-slate-400 uppercase">Limit Harian (Daily Cap):</span>
                    <div className="text-sm font-bold font-mono text-sky-300">
                      {formatIDR(limit.dailyTransactionLimit)}
                    </div>
                  </div>

                  <div className="pt-2 border-t border-slate-800 space-y-1">
                    <span className="text-[10px] font-bold text-slate-300 uppercase block">Syarat Persetujuan:</span>
                    <p className="text-xs text-slate-300 font-medium leading-relaxed bg-slate-900 p-2 rounded border border-slate-800">
                      {limit.approvalRequirement}
                    </p>
                  </div>

                  <p className="text-[11px] text-slate-400 italic">
                    {limit.description}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* TAB 3: SOP PERUSAHAAN (STANDARD OPERATING PROCEDURES) */}
      {activeSubTab === "sop" && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredSops.map((sop) => {
              const lastAccess = getLastAccessForDoc(sop.sopCode);

              return (
                <div key={sop.id} className="bg-[#0f172a] border border-slate-800 rounded-xl p-5 space-y-4 hover:border-sky-400 transition-all shadow-lg flex flex-col justify-between group">
                  <div className="space-y-3">
                    <div className="flex items-start justify-between gap-2">
                      <span className="text-xs font-mono font-black text-sky-400 bg-sky-950 border border-sky-500/30 px-2.5 py-1 rounded">
                        {sop.sopCode}
                      </span>
                      <span className="text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-500/30 px-2 py-0.5 rounded font-mono font-bold">
                        {sop.docStatus}
                      </span>
                    </div>

                    <div>
                      <h4 className="text-sm font-black text-white group-hover:text-sky-300 transition-colors leading-snug">
                        {sop.title}
                      </h4>
                      <p className="text-[10px] font-mono text-slate-400 mt-1 uppercase">
                        Kategori: {sop.category} • Versi: {sop.version}
                      </p>
                    </div>

                    <p className="text-xs text-slate-300 line-clamp-2 leading-relaxed">
                      {sop.objective}
                    </p>

                    {/* Last Viewed / Downloaded Badge */}
                    {lastAccess ? (
                      <div className="bg-slate-900/90 border border-slate-800 rounded px-2.5 py-1.5 text-[10px] text-slate-300 font-mono flex items-center justify-between gap-2">
                        <span className="flex items-center gap-1 text-sky-400 truncate">
                          <Eye className="w-3 h-3 text-sky-400 shrink-0" />
                          Terakhir: <strong className="text-slate-100 font-sans truncate">{lastAccess.userName}</strong>
                        </span>
                        <span className="text-slate-500 text-[9px] shrink-0">{formatLogTime(lastAccess.timestamp)}</span>
                      </div>
                    ) : (
                      <div className="bg-slate-900/50 border border-slate-800/60 rounded px-2.5 py-1 text-[10px] text-slate-500 font-mono italic">
                        Belum ada catatan pembacaan.
                      </div>
                    )}
                  </div>

                  <div className="pt-3 border-t border-slate-800 space-y-2">
                    <div className="flex items-center justify-between text-[10px] font-mono text-slate-400">
                      <span>TMT: {sop.effectiveDate}</span>
                      <span>EMS Verified</span>
                    </div>

                    <div className="flex items-center gap-2">
                      <button
                        type="button"
                        onClick={() => handleOpenSop(sop)}
                        className="flex-1 px-3 py-1.5 bg-slate-800 hover:bg-sky-600 text-slate-200 hover:text-white rounded text-xs font-bold uppercase transition-all flex items-center justify-center gap-1 cursor-pointer"
                      >
                        <Eye className="w-3.5 h-3.5 text-sky-400" />
                        Buka SOP
                      </button>

                      <button
                        type="button"
                        onClick={() => handleDownloadSop(sop)}
                        className="px-3 py-1.5 bg-sky-950 hover:bg-emerald-600 text-sky-300 hover:text-white border border-sky-500/30 hover:border-emerald-500 rounded text-xs font-bold uppercase transition-all flex items-center justify-center gap-1 cursor-pointer"
                        title="Unduh Salinan Dokumen SOP"
                      >
                        <Download className="w-3.5 h-3.5" />
                        Unduh
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

        </div>
        {/* END LEFT / MAIN COLUMN */}

        {/* RIGHT SIDEBAR COLUMN: TERAKHIR DILIHAT & DIUNDUH */}
        <div className="lg:col-span-1 space-y-4">
          <div className="bg-[#0f172a] border border-slate-800 rounded-xl p-4 space-y-4 shadow-xl sticky top-4">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <div className="flex items-center gap-2">
                <div className="p-2 bg-sky-500/10 border border-sky-500/30 text-sky-400 rounded-lg">
                  <History className="w-4.5 h-4.5" />
                </div>
                <div>
                  <h3 className="text-xs font-black uppercase text-white tracking-wider">
                    TERAKHIR DILIHAT
                  </h3>
                  <p className="text-[10px] text-slate-400 font-mono">
                    Aktivitas Akses Dokumen
                  </p>
                </div>
              </div>
              <span className="text-[10px] font-mono bg-sky-950 text-sky-300 border border-sky-500/30 px-2 py-0.5 rounded font-bold">
                {accessLogs.length} Log
              </span>
            </div>

            {/* Log Filter Pills */}
            <div className="grid grid-cols-4 gap-1 bg-slate-900 p-1 rounded-lg border border-slate-800 text-[10px] font-mono font-bold">
              <button
                type="button"
                onClick={() => setLogFilter("ALL")}
                className={`py-1 rounded text-center transition-colors cursor-pointer ${
                  logFilter === "ALL" ? "bg-sky-500 text-white shadow-sm" : "text-slate-400 hover:text-white"
                }`}
              >
                Semua
              </button>
              <button
                type="button"
                onClick={() => setLogFilter("VIEW")}
                className={`py-1 rounded text-center transition-colors cursor-pointer ${
                  logFilter === "VIEW" ? "bg-sky-500 text-white shadow-sm" : "text-slate-400 hover:text-white"
                }`}
              >
                Lihat
              </button>
              <button
                type="button"
                onClick={() => setLogFilter("DOWNLOAD")}
                className={`py-1 rounded text-center transition-colors cursor-pointer ${
                  logFilter === "DOWNLOAD" ? "bg-sky-500 text-white shadow-sm" : "text-slate-400 hover:text-white"
                }`}
              >
                Unduh
              </button>
              <button
                type="button"
                onClick={() => setLogFilter("PRINT")}
                className={`py-1 rounded text-center transition-colors cursor-pointer ${
                  logFilter === "PRINT" ? "bg-sky-500 text-white shadow-sm" : "text-slate-400 hover:text-white"
                }`}
              >
                Cetak
              </button>
            </div>

            {/* Access Logs List */}
            <div className="space-y-2 max-h-[520px] overflow-y-auto pr-1">
              {filteredAccessLogs.length === 0 ? (
                <div className="text-center py-8 text-slate-500 text-xs font-mono">
                  Belum ada log aktivitas dokumen.
                </div>
              ) : (
                filteredAccessLogs.map((log) => (
                  <div key={log.id} className="p-3 rounded-lg bg-slate-900/90 border border-slate-800 hover:border-sky-500/40 transition-all space-y-1.5 shadow-sm">
                    <div className="flex items-center justify-between">
                      <span className={`text-[9px] font-mono font-bold px-2 py-0.5 rounded uppercase flex items-center gap-1 ${
                        log.action === "VIEW" ? "bg-sky-950 text-sky-300 border border-sky-500/30" :
                        log.action === "DOWNLOAD" ? "bg-emerald-950 text-emerald-300 border border-emerald-500/30" :
                        "bg-amber-950 text-amber-300 border border-amber-500/30"
                      }`}>
                        {log.action === "VIEW" && <Eye className="w-3 h-3" />}
                        {log.action === "DOWNLOAD" && <FileDown className="w-3 h-3" />}
                        {log.action === "PRINT" && <Printer className="w-3 h-3" />}
                        {log.action === "VIEW" ? "Membuka" : log.action === "DOWNLOAD" ? "Mengunduh" : "Mencetak"}
                      </span>
                      <span className="text-[9px] text-slate-400 font-mono">
                        {formatLogTime(log.timestamp)}
                      </span>
                    </div>

                    <div>
                      <span className="text-[9px] font-mono font-bold text-sky-400 block">{log.docCode}</span>
                      <div className="text-xs font-bold text-white leading-snug line-clamp-2" title={log.docTitle}>
                        {log.docTitle}
                      </div>
                    </div>

                    <div className="text-[10px] text-slate-400 flex items-center justify-between pt-1 border-t border-slate-800/80 font-mono">
                      <span className="text-slate-300 font-semibold truncate max-w-[130px]" title={log.userName}>
                        👤 {log.userName}
                      </span>
                      <span className="text-slate-500 text-[9px] truncate max-w-[90px]" title={log.userPosition}>
                        {log.userPosition}
                      </span>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Footer of Sidebar */}
            <div className="pt-2 border-t border-slate-800 flex items-center justify-between text-[10px] font-mono text-slate-400">
              <span>EMS Audit Engine</span>
              <button
                type="button"
                onClick={handleClearLogs}
                className="text-slate-400 hover:text-red-400 flex items-center gap-1 transition-colors cursor-pointer"
              >
                <Trash2 className="w-3 h-3" />
                Reset Log
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 4. SOP DETAIL VIEWER MODAL */}
      {activeSopModal && (
        <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto">
          <div className="bg-[#0f172a] border border-sky-500/40 rounded-2xl max-w-4xl w-full p-6 space-y-6 max-h-[90vh] overflow-y-auto shadow-2xl relative text-slate-100">
            
            {/* Modal Header */}
            <div className="flex flex-col md:flex-row items-start md:items-center justify-between border-b border-slate-800 pb-4 gap-4">
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-xs font-mono font-black text-sky-400 bg-sky-950 border border-sky-500/30 px-2.5 py-0.5 rounded">
                    {activeSopModal.sopCode}
                  </span>
                  <span className="text-[10px] font-mono bg-emerald-950 text-emerald-300 border border-emerald-500/30 px-2 py-0.5 rounded">
                    {activeSopModal.docStatus}
                  </span>
                </div>
                <h3 className="text-xl font-black text-white">{activeSopModal.title}</h3>
                <p className="text-xs text-slate-400 font-mono mt-0.5">
                  {activeSopModal.directorate} • {activeSopModal.division} • Effective Date: {activeSopModal.effectiveDate} (Version {activeSopModal.version})
                </p>

                {/* Last Access Audit Bar */}
                {(() => {
                  const modalLastAccess = getLastAccessForDoc(activeSopModal.sopCode);
                  if (!modalLastAccess) return null;
                  return (
                    <div className="mt-2.5 bg-sky-950/50 border border-sky-500/30 rounded-lg px-3 py-1.5 text-[11px] font-mono text-sky-200 flex items-center gap-2">
                      <Eye className="w-3.5 h-3.5 text-sky-400 shrink-0" />
                      <span>
                        Terakhir Diakui: <strong className="text-white font-sans">{modalLastAccess.userName}</strong> ({modalLastAccess.userPosition}) — <span className="uppercase text-sky-300">{modalLastAccess.action}</span> ({formatLogTime(modalLastAccess.timestamp)})
                      </span>
                    </div>
                  );
                })()}
              </div>

              <div className="flex items-center gap-2 self-stretch md:self-auto justify-end shrink-0">
                <button
                  type="button"
                  onClick={() => handleDownloadSop(activeSopModal)}
                  className="px-3 py-1.5 bg-emerald-950 hover:bg-emerald-600 text-emerald-300 hover:text-white border border-emerald-500/40 rounded text-xs font-bold uppercase transition-all flex items-center gap-1.5 cursor-pointer shadow-sm"
                >
                  <Download className="w-3.5 h-3.5" />
                  Unduh Dokumen
                </button>
                <button
                  type="button"
                  onClick={() => handlePrintSop(activeSopModal)}
                  className="p-2 bg-slate-800 hover:bg-slate-700 text-sky-300 rounded border border-slate-700 cursor-pointer"
                  title="Cetak SOP"
                >
                  <Printer className="w-4 h-4" />
                </button>
                <button
                  type="button"
                  onClick={() => setActiveSopModal(null)}
                  className="p-2 bg-slate-800 hover:bg-red-600 text-white rounded border border-slate-700 transition-colors font-bold text-xs cursor-pointer"
                >
                  [X] Tutup
                </button>
              </div>
            </div>

            {/* Document Metadata Table */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-slate-900 p-4 rounded-xl border border-slate-800 text-xs">
              <div>
                <span className="text-[10px] font-mono text-slate-400 uppercase block font-bold">1. TUJUAN (OBJECTIVE):</span>
                <p className="text-slate-200 leading-relaxed font-medium mt-0.5">{activeSopModal.objective}</p>
              </div>
              <div>
                <span className="text-[10px] font-mono text-slate-400 uppercase block font-bold">2. RUANG LINGKUP (SCOPE):</span>
                <p className="text-slate-200 leading-relaxed font-medium mt-0.5">{activeSopModal.scope}</p>
              </div>
            </div>

            {/* Operational Steps Timeline */}
            <div className="space-y-3">
              <h4 className="text-xs font-black uppercase text-sky-400 tracking-wider flex items-center gap-2">
                <Layers className="w-4 h-4 text-sky-400" />
                3. PROSEDUR LANGKAH OPERASIONAL (STEP-BY-STEP WORKFLOW):
              </h4>

              <div className="space-y-3">
                {activeSopModal.steps.map((step) => (
                  <div key={step.stepNumber} className="bg-slate-900/90 border border-slate-800 rounded-lg p-3.5 flex items-start gap-3">
                    <div className="w-7 h-7 rounded-full bg-sky-500 text-white font-black font-mono text-xs flex items-center justify-center shrink-0">
                      {step.stepNumber}
                    </div>
                    <div className="flex-1 space-y-1">
                      <div className="flex items-center justify-between">
                        <span className="text-xs font-extrabold text-white uppercase">Pelaksana: {step.actor}</span>
                        <span className="text-[9px] font-mono bg-slate-800 text-sky-300 px-2 py-0.5 rounded">
                          Step {step.stepNumber}
                        </span>
                      </div>
                      <p className="text-xs text-slate-300">{step.action}</p>
                      <div className="text-[10px] font-mono text-emerald-400 pt-1 flex items-center gap-1">
                        <Sparkles className="w-3 h-3 text-emerald-400" />
                        Output Sistem / Artefak: {step.systemOutput}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Compliance Checklist */}
            <div className="space-y-2 pt-2 border-t border-slate-800">
              <h4 className="text-xs font-black uppercase text-sky-400 tracking-wider flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                4. CHECKLIST KEPATUHAN & KONTROL AUDIT:
              </h4>
              <ul className="space-y-1.5">
                {activeSopModal.complianceChecklist.map((item, idx) => (
                  <li key={idx} className="flex items-center gap-2 text-xs text-slate-300 bg-slate-900 px-3 py-2 rounded border border-slate-800">
                    <input type="checkbox" defaultChecked readOnly className="rounded text-sky-500 focus:ring-0" />
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
            </div>

          </div>
        </div>
      )}

      {/* 5. ADD NEW SOP MODAL */}
      {isAddingSop && (
        <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4">
          <form onSubmit={handleSaveNewSop} className="bg-[#0f172a] border border-sky-500/40 rounded-xl max-w-xl w-full p-6 space-y-4 shadow-2xl">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <h3 className="text-sm font-black uppercase text-white flex items-center gap-2">
                <Plus className="w-4 h-4 text-sky-400" />
                TAMBAH SOP PERUSAHAAN BARU ({currentDivision.divisionName.toUpperCase()})
              </h3>
              <button
                type="button"
                onClick={() => setIsAddingSop(false)}
                className="text-slate-400 hover:text-white font-bold text-xs"
              >
                [X]
              </button>
            </div>

            <div className="space-y-3 text-xs">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-[10px] font-bold text-slate-300 uppercase block mb-1">Kode SOP:</label>
                  <input
                    type="text"
                    required
                    placeholder="Contoh: SOP-IT-005"
                    value={newSopCode}
                    onChange={(e) => setNewSopCode(e.target.value)}
                    className="w-full bg-slate-900 border border-slate-700 rounded px-3 py-1.5 text-white font-mono focus:outline-none focus:border-sky-400"
                  />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-slate-300 uppercase block mb-1">Versi Dokumen:</label>
                  <input
                    type="text"
                    defaultValue="v1.0"
                    readOnly
                    className="w-full bg-slate-900 border border-slate-700 rounded px-3 py-1.5 text-slate-400 font-mono"
                  />
                </div>
              </div>

              <div>
                <label className="text-[10px] font-bold text-slate-300 uppercase block mb-1">Judul SOP Resmi:</label>
                <input
                  type="text"
                  required
                  placeholder="Contoh: Prosedur Pengujian Keamanan Aplikasi Pre-Release"
                  value={newSopTitle}
                  onChange={(e) => setNewSopTitle(e.target.value)}
                  className="w-full bg-slate-900 border border-slate-700 rounded px-3 py-1.5 text-white focus:outline-none focus:border-sky-400"
                />
              </div>

              <div>
                <label className="text-[10px] font-bold text-slate-300 uppercase block mb-1">Tujuan SOP (Objective):</label>
                <textarea
                  rows={2}
                  placeholder="Jelaskan tujuan utama SOP ini dipublikasikan..."
                  value={newSopObjective}
                  onChange={(e) => setNewSopObjective(e.target.value)}
                  className="w-full bg-slate-900 border border-slate-700 rounded px-3 py-1.5 text-white focus:outline-none focus:border-sky-400"
                />
              </div>

              <div>
                <label className="text-[10px] font-bold text-slate-300 uppercase block mb-1">Ruang Lingkup (Scope):</label>
                <input
                  type="text"
                  placeholder="Pengaplikasian SOP pada staf / divisi..."
                  value={newSopScope}
                  onChange={(e) => setNewSopScope(e.target.value)}
                  className="w-full bg-slate-900 border border-slate-700 rounded px-3 py-1.5 text-white focus:outline-none focus:border-sky-400"
                />
              </div>
            </div>

            <div className="pt-3 border-t border-slate-800 flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setIsAddingSop(false)}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded text-xs font-bold uppercase"
              >
                Batal
              </button>
              <button
                type="submit"
                className="px-4 py-2 bg-sky-500 hover:bg-sky-400 text-white rounded text-xs font-bold uppercase shadow-md shadow-sky-500/30"
              >
                Simpan & Terbitkan SOP
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}
