import React, { useState, useMemo } from "react";
import { 
  Employee, 
  FinancialTransaction, 
  CashBankAccount, 
  BudgetItem, 
  JournalEntry,
  MonthlyUnitReport
} from "../types";
import { 
  DollarSign, 
  Plus, 
  FileText, 
  CheckCircle2, 
  XCircle, 
  Clock, 
  Building2, 
  TrendingUp, 
  TrendingDown, 
  Scale, 
  PieChart, 
  BookOpen, 
  Layers, 
  Search, 
  Filter, 
  ArrowUpRight, 
  ArrowDownLeft, 
  AlertTriangle, 
  Sparkles, 
  Download, 
  Send, 
  ShieldCheck, 
  FileSpreadsheet, 
  Receipt, 
  Wallet, 
  Briefcase, 
  CheckSquare, 
  RefreshCw,
  Eye,
  Info,
  Calculator
} from "lucide-react";
import { BudgetDivisionModule } from "./BudgetDivisionModule";

interface FinanceSapModuleProps {
  currentUser: Employee;
  transactions: FinancialTransaction[];
  onUpdateTransactions: React.Dispatch<React.SetStateAction<FinancialTransaction[]>>;
  cashAccounts: CashBankAccount[];
  onUpdateCashAccounts: React.Dispatch<React.SetStateAction<CashBankAccount[]>>;
  budgetItems: BudgetItem[];
  onUpdateBudgetItems: React.Dispatch<React.SetStateAction<BudgetItem[]>>;
  journals: JournalEntry[];
  onUpdateJournals: React.Dispatch<React.SetStateAction<JournalEntry[]>>;
}

export default function FinanceSapModule({
  currentUser,
  transactions,
  onUpdateTransactions,
  cashAccounts,
  onUpdateCashAccounts,
  budgetItems,
  onUpdateBudgetItems,
  journals,
  onUpdateJournals
}: FinanceSapModuleProps) {
  // Main Sub-Tab State
  const [activeSubTab, setActiveSubTab] = useState<
    "transactions" | "cashbook" | "adjustments" | "ledger" | "balance_sheet" | "lra" | "management_report" | "budget_division"
  >("transactions");

  // Filter States
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("ALL");
  const [typeFilter, setTypeFilter] = useState<string>("ALL");
  const [divisionFilter, setDivisionFilter] = useState<string>("ALL");

  // Selected Cash/Bank Account for Cashbook
  const [selectedCashAccountId, setSelectedCashAccountId] = useState<string>("ALL");

  // Selected GL Account for Ledger
  const [selectedGlCode, setSelectedGlCode] = useState<string>("5101");

  // Selected Month/Year for Management Report
  const [reportMonth, setReportMonth] = useState<string>("2026-08");

  // New Transaction Voucher Modal State
  const [isVoucherModalOpen, setIsVoucherModalOpen] = useState(false);
  const [trxType, setTrxType] = useState<"Pengeluaran" | "Penerimaan">("Pengeluaran");
  const [trxDivision, setTrxDivision] = useState<string>(currentUser.division || "Developer");
  const [trxBudgetCode, setTrxBudgetCode] = useState<string>("5101");
  const [trxAmount, setTrxAmount] = useState<string>("");
  const [trxCashAccountId, setTrxCashAccountId] = useState<string>("1103");
  const [trxVendor, setTrxVendor] = useState<string>("");
  const [trxInvoiceRef, setTrxInvoiceRef] = useState<string>("");
  const [trxDate, setTrxDate] = useState<string>(new Date().toISOString().split("T")[0]);
  const [trxDueDate, setTrxDueDate] = useState<string>("");
  const [trxDescription, setTrxDescription] = useState<string>("");
  const [trxAttachmentName, setTrxAttachmentName] = useState<string>("");

  // Manual Adjustment Journal Modal State
  const [isAdjModalOpen, setIsAdjModalOpen] = useState(false);
  const [adjDescription, setAdjDescription] = useState("");
  const [adjLines, setAdjLines] = useState<Array<{ accountCode: string; accountName: string; debit: number; credit: number; memo: string }>>([
    { accountCode: "5201", accountName: "Beban Penyusutan IT", debit: 10000000, credit: 0, memo: "Penyusutan IT" },
    { accountCode: "1302", accountName: "Akumulasi Penyusutan IT", debit: 0, credit: 10000000, memo: "Akumulasi Penyusutan" }
  ]);

  // View Transaction Detail Modal State
  const [viewingTrx, setViewingTrx] = useState<FinancialTransaction | null>(null);

  // Notification Toast
  const [toastMsg, setToastMsg] = useState<string | null>(null);

  const showToast = (msg: string) => {
    setToastMsg(msg);
    setTimeout(() => setToastMsg(null), 4000);
  };

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

  // Helper: Selected Budget Item details
  const selectedBudgetItem = useMemo(() => {
    return budgetItems.find(b => b.code === trxBudgetCode) || budgetItems[0];
  }, [budgetItems, trxBudgetCode]);

  // Helper: Numeric amount from form input
  const numericTrxAmount = useMemo(() => {
    const clean = trxAmount.replace(/[^0-9]/g, "");
    return clean ? parseInt(clean, 10) : 0;
  }, [trxAmount]);

  // Handle New Transaction Submission
  const handleCreateVoucher = (e: React.FormEvent) => {
    e.preventDefault();
    if (numericTrxAmount <= 0) {
      alert("Masukkan nominal transaksi yang valid (> 0)!");
      return;
    }
    if (!trxVendor.trim()) {
      alert("Masukkan nama Vendor / Customer / Penerima Dana!");
      return;
    }

    const newVoucherNo = `VOUCHER-SAP-2026-${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(transactions.length + 1).padStart(3, "0")}`;
    const cashAcc = cashAccounts.find(c => c.id === trxCashAccountId);

    const newTrx: FinancialTransaction = {
      id: `trx-${Date.now()}`,
      voucherNo: newVoucherNo,
      transactionType: trxType,
      division: trxDivision,
      requesterId: currentUser.id,
      requesterName: currentUser.name,
      requesterPosition: currentUser.position,
      transactionDate: trxDate,
      dueDate: trxDueDate || undefined,
      budgetCode: selectedBudgetItem.code,
      budgetName: selectedBudgetItem.name,
      amount: numericTrxAmount,
      cashBankAccountId: trxCashAccountId,
      cashBankAccountName: `${cashAcc?.code || "1103"} - ${cashAcc?.name || "Bank BCA"}`,
      recipientVendor: trxVendor.trim(),
      invoiceRef: trxInvoiceRef.trim() || `INV-${Date.now().toString().substring(6)}`,
      description: trxDescription.trim() || `Pengajuan Transaksi ${trxType} untuk ${selectedBudgetItem.name}`,
      attachmentName: trxAttachmentName.trim() || "Lampiran_Invoice_Voucher.pdf",
      status: "Menunggu Verifikasi Anggaran",
      currentStage: "Divisi Anggaran",
      createdAt: new Date().toISOString()
    };

    onUpdateTransactions(prev => [newTrx, ...prev]);

    // Reset Form
    setIsVoucherModalOpen(false);
    setTrxAmount("");
    setTrxVendor("");
    setTrxInvoiceRef("");
    setTrxDescription("");
    setTrxAttachmentName("");

    showToast(`Berhasil mengajukan ${newVoucherNo}! Status: Menunggu Verifikasi Divisi Anggaran.`);
  };

  // Workflow Action: Approve by Budget Division
  const handleApproveBudgetStage = (trx: FinancialTransaction) => {
    const approverName = currentUser.name;
    const approverPos = `${currentUser.position} (${currentUser.division})`;

    onUpdateTransactions(prev => prev.map(t => {
      if (t.id !== trx.id) return t;
      return {
        ...t,
        status: "Menunggu Posting Akuntansi",
        currentStage: "Divisi Akuntansi",
        budgetApproval: {
          approverName,
          approverPosition: approverPos,
          date: new Date().toISOString().replace("T", " ").substring(0, 16),
          status: "Approved",
          notes: `Anggaran terverifikasi aman. Sisa Pagu mencukupi untuk dialokasikan.`
        }
      };
    }));

    showToast(`Voucher ${trx.voucherNo} berhasil disetujui Divisi Anggaran! Diteruskan ke Akuntansi.`);
  };

  // Workflow Action: Final Posting by Accounting Division
  const handlePostAccountingStage = (trx: FinancialTransaction) => {
    const approverName = currentUser.name;
    const approverPos = `${currentUser.position} (${currentUser.division})`;
    const journalNo = `JRN-SAP-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(journals.length + 1).padStart(3, "0")}`;

    // 1. Update Transaction Status
    onUpdateTransactions(prev => prev.map(t => {
      if (t.id !== trx.id) return t;
      return {
        ...t,
        status: "Diposting",
        currentStage: "Selesai",
        accountingApproval: {
          approverName,
          approverPosition: approverPos,
          date: new Date().toISOString().replace("T", " ").substring(0, 16),
          status: "Approved",
          journalNo,
          notes: `Diposting otomatis ke Jurnal SAP, Buku Besar, dan Buku Kas/Bank.`
        }
      };
    }));

    // 2. Update Cash/Bank Account Balance
    onUpdateCashAccounts(prev => prev.map(acc => {
      if (acc.id !== trx.cashBankAccountId) return acc;
      const delta = trx.transactionType === "Penerimaan" ? trx.amount : -trx.amount;
      return {
        ...acc,
        currentBalance: acc.currentBalance + delta
      };
    }));

    // 3. Update Budget Realization Amount
    onUpdateBudgetItems(prev => prev.map(b => {
      if (b.code !== trx.budgetCode) return b;
      return {
        ...b,
        realizedAmount: b.realizedAmount + trx.amount
      };
    }));

    // 4. Automatically Create Balanced Journal Entry
    const isIncome = trx.transactionType === "Penerimaan";
    const newJournal: JournalEntry = {
      id: `jrn-${Date.now()}`,
      journalNo,
      voucherNoRef: trx.voucherNo,
      date: trx.transactionDate,
      type: "Otomatis SAP",
      description: `Posting ${trx.transactionType}: ${trx.description} (${trx.recipientVendor})`,
      postedBy: `${approverName} (Akuntansi)`,
      postedByPosition: approverPos,
      isBalanced: true,
      lines: [
        {
          id: `jl-${Date.now()}-1`,
          accountCode: isIncome ? trx.cashBankAccountId : trx.budgetCode,
          accountName: isIncome ? trx.cashBankAccountName : trx.budgetName,
          debit: trx.amount,
          credit: 0,
          memo: isIncome ? `Debet Kas/Bank Penerimaan` : `Debet Beban ${trx.budgetName}`
        },
        {
          id: `jl-${Date.now()}-2`,
          accountCode: isIncome ? trx.budgetCode : trx.cashBankAccountId,
          accountName: isIncome ? trx.budgetName : trx.cashBankAccountName,
          debit: 0,
          credit: trx.amount,
          memo: isIncome ? `Kredit Pendapatan ${trx.budgetName}` : `Kredit Kas/Bank Pengeluaran`
        }
      ]
    };

    onUpdateJournals(prev => [newJournal, ...prev]);

    showToast(`Voucher ${trx.voucherNo} DIPOSTING! Jurnal ${journalNo} dibuat & Buku Kas/Bank ter-update.`);
  };

  // Workflow Action: Reject Transaction
  const handleRejectTrx = (trx: FinancialTransaction) => {
    const reason = prompt("Masukkan alasan penolakan transaksi ini:", "Budget tidak mencukupi / dokumen kurang lengkap");
    if (reason === null) return;

    onUpdateTransactions(prev => prev.map(t => {
      if (t.id !== trx.id) return t;
      return {
        ...t,
        status: "Ditolak",
        currentStage: "Selesai",
        budgetApproval: t.budgetApproval || {
          approverName: currentUser.name,
          approverPosition: currentUser.position,
          date: new Date().toISOString().replace("T", " ").substring(0, 16),
          status: "Rejected",
          notes: reason
        }
      };
    }));

    showToast(`Transaksi ${trx.voucherNo} ditolak.`);
  };

  // Handle Manual Adjustment Journal Entry Submission
  const handleCreateAdjustmentJournal = (e: React.FormEvent) => {
    e.preventDefault();
    const totalDebit = adjLines.reduce((sum, l) => sum + (l.debit || 0), 0);
    const totalCredit = adjLines.reduce((sum, l) => sum + (l.credit || 0), 0);

    if (totalDebit !== totalCredit) {
      alert(`Jurnal TIDAK BALANCE! Total Debet (${formatIDR(totalDebit)}) tidak sama dengan Total Kredit (${formatIDR(totalCredit)}).`);
      return;
    }
    if (totalDebit <= 0) {
      alert("Nominal jurnal harus lebih besar dari 0!");
      return;
    }

    const journalNo = `JRN-ADJ-2026-${String(journals.length + 1).padStart(3, "0")}`;
    const newAdjJournal: JournalEntry = {
      id: `adj-${Date.now()}`,
      journalNo,
      date: new Date().toISOString().split("T")[0],
      type: "Adjustment Manual",
      description: adjDescription.trim() || "Jurnal Penyesuaian Akuntansi",
      postedBy: currentUser.name,
      postedByPosition: currentUser.position,
      isBalanced: true,
      lines: adjLines.map((line, idx) => ({
        id: `line-${Date.now()}-${idx}`,
        accountCode: line.accountCode,
        accountName: line.accountName,
        debit: line.debit,
        credit: line.credit,
        memo: line.memo || adjDescription
      }))
    };

    onUpdateJournals(prev => [newAdjJournal, ...prev]);
    setIsAdjModalOpen(false);
    setAdjDescription("");
    showToast(`Berhasil menyimpan Jurnal Penyesuaian Manual ${journalNo}!`);
  };

  // Filtered Transactions
  const filteredTransactions = useMemo(() => {
    return transactions.filter(t => {
      const matchQuery = 
        t.voucherNo.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.recipientVendor.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.budgetName.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.requesterName.toLowerCase().includes(searchQuery.toLowerCase());
      const matchStatus = statusFilter === "ALL" || t.status === statusFilter;
      const matchType = typeFilter === "ALL" || t.transactionType === typeFilter;
      const matchDivision = divisionFilter === "ALL" || t.division === divisionFilter;
      return matchQuery && matchStatus && matchType && matchDivision;
    });
  }, [transactions, searchQuery, statusFilter, typeFilter, divisionFilter]);

  // Compute Financial Summary Statistics
  const financialStats = useMemo(() => {
    const totalCashBank = cashAccounts.reduce((sum, c) => sum + c.currentBalance, 0);
    const postedTrx = transactions.filter(t => t.status === "Diposting");
    const totalExpenses = postedTrx.filter(t => t.transactionType === "Pengeluaran").reduce((sum, t) => sum + t.amount, 0);
    const totalIncome = postedTrx.filter(t => t.transactionType === "Penerimaan").reduce((sum, t) => sum + t.amount, 0);
    const pendingCount = transactions.filter(t => t.status.startsWith("Menunggu")).length;

    return {
      totalCashBank,
      totalExpenses,
      totalIncome,
      netCashFlow: totalIncome - totalExpenses,
      pendingCount
    };
  }, [cashAccounts, transactions]);

  // Compute Cashbook Entries
  const cashbookEntries = useMemo(() => {
    const postedTrx = transactions.filter(t => t.status === "Diposting");
    let filtered = postedTrx;
    if (selectedCashAccountId !== "ALL") {
      filtered = filtered.filter(t => t.cashBankAccountId === selectedCashAccountId);
    }

    let runningBalance = cashAccounts
      .filter(a => selectedCashAccountId === "ALL" || a.id === selectedCashAccountId)
      .reduce((sum, a) => sum + a.openingBalance, 0);

    return filtered.map(t => {
      const isInflow = t.transactionType === "Penerimaan";
      const inflow = isInflow ? t.amount : 0;
      const outflow = !isInflow ? t.amount : 0;
      runningBalance += inflow - outflow;

      return {
        ...t,
        inflow,
        outflow,
        runningBalance
      };
    });
  }, [transactions, cashAccounts, selectedCashAccountId]);

  // Compute General Ledger Details for selected GL Code
  const selectedGlDetails = useMemo(() => {
    const glLines: Array<{
      date: string;
      journalNo: string;
      voucherRef?: string;
      description: string;
      debit: number;
      credit: number;
      postedBy: string;
    }> = [];

    journals.forEach(j => {
      j.lines.forEach(line => {
        if (line.accountCode === selectedGlCode) {
          glLines.push({
            date: j.date,
            journalNo: j.journalNo,
            voucherRef: j.voucherNoRef,
            description: line.memo || j.description,
            debit: line.debit,
            credit: line.credit,
            postedBy: j.postedBy
          });
        }
      });
    });

    const totalDebit = glLines.reduce((sum, l) => sum + l.debit, 0);
    const totalCredit = glLines.reduce((sum, l) => sum + l.credit, 0);
    const netBalance = totalDebit - totalCredit;

    return {
      glLines,
      totalDebit,
      totalCredit,
      netBalance
    };
  }, [journals, selectedGlCode]);

  // Balance Sheet Data Calculation
  const balanceSheetData = useMemo(() => {
    // Current Assets
    const cashTotal = cashAccounts.reduce((sum, c) => sum + c.currentBalance, 0);
    const piutangUsaha = 1450000000;
    const uangMukaOperasional = 320000000;
    const totalAsetLancar = cashTotal + piutangUsaha + uangMukaOperasional;

    // Fixed Assets
    const peralatanServer = 3800000000;
    const gedungFasilitas = 7500000000;
    const akumulasiPenyusutan = -1250000000;
    const totalAsetTetap = peralatanServer + gedungFasilitas + akumulasiPenyusutan;

    const totalAset = totalAsetLancar + totalAsetTetap;

    // Liabilities
    const utangUsaha = 850000000;
    const utangGaji = 420000000;
    const utangPajak = 180000000;
    const totalKewajibanLancar = utangUsaha + utangGaji + utangPajak;

    // Equity
    const modalDisetor = 8000000000;
    const labaDitahan = 2270000000;
    const labaTahunBerjalan = financialStats.netCashFlow; // Net Income from real transactions
    const totalEkuitas = modalDisetor + labaDitahan + labaTahunBerjalan;

    const totalPasiva = totalKewajibanLancar + totalEkuitas;
    const isBalanced = Math.abs(totalAset - totalPasiva) < 100;

    return {
      cashTotal,
      piutangUsaha,
      uangMukaOperasional,
      totalAsetLancar,
      peralatanServer,
      gedungFasilitas,
      akumulasiPenyusutan,
      totalAsetTetap,
      totalAset,
      utangUsaha,
      utangGaji,
      utangPajak,
      totalKewajibanLancar,
      modalDisetor,
      labaDitahan,
      labaTahunBerjalan,
      totalEkuitas,
      totalPasiva,
      isBalanced
    };
  }, [cashAccounts, financialStats.netCashFlow]);

  // Monthly Management Report per Unit Kerja
  const monthlyUnitReports: MonthlyUnitReport[] = useMemo(() => {
    const units = [
      { name: "Direktorat IT (CTO)", divisionKey: "Developer", monthlyBudget: 150000000 },
      { name: "Direktorat Operasional (COO)", divisionKey: "Operasional", monthlyBudget: 80000000 },
      { name: "Direktorat Pemasaran & Sales", divisionKey: "Pemasaran", monthlyBudget: 120000000 },
      { name: "Direktorat HR (CHR)", divisionKey: "Pengembangan SDM", monthlyBudget: 60000000 },
      { name: "Direktorat Keuangan (CFO)", divisionKey: "Bendahara", monthlyBudget: 50000000 },
      { name: "Executive Office (CEO)", divisionKey: "Executive Office", monthlyBudget: 100000000 }
    ];

    return units.map(unit => {
      const unitTrx = transactions.filter(t => 
        t.status === "Diposting" && 
        (t.division === unit.divisionKey || (unit.divisionKey === "Developer" && t.division.includes("IT")))
      );

      const count = unitTrx.length;
      const expense = unitTrx.filter(t => t.transactionType === "Pengeluaran").reduce((sum, t) => sum + t.amount, 0);
      const income = unitTrx.filter(t => t.transactionType === "Penerimaan").reduce((sum, t) => sum + t.amount, 0);
      const realizationPct = unit.monthlyBudget > 0 ? Math.round((expense / unit.monthlyBudget) * 100) : 0;
      const variancePct = 100 - realizationPct;

      let status: "Sangat Efisien" | "Normal" | "Mendekati Pagu" | "Overbudget" = "Normal";
      if (realizationPct < 50) status = "Sangat Efisien";
      else if (realizationPct <= 85) status = "Normal";
      else if (realizationPct <= 100) status = "Mendekati Pagu";
      else status = "Overbudget";

      let insight = "";
      if (status === "Sangat Efisien") {
        insight = `Unit kerja ${unit.name} beroperasi sangat hemat. Penyerapan anggaran baru ${realizationPct}% dari pagu bulanan.`;
      } else if (status === "Normal") {
        insight = `Realisasi anggaran ${unit.name} terkendali dengan baik pada tingkat ${realizationPct}%. Sesuai target RKAP.`;
      } else if (status === "Mendekati Pagu") {
        insight = `PERHATIAN: ${unit.name} telah menyerap ${realizationPct}% pagu bulanan. Perlu kontrol pengeluaran ketat akhir bulan.`;
      } else {
        insight = `PERINGATAN OVERBUDGET: Realisasi ${unit.name} melampaui pagu bulanan (${realizationPct}%). Diperlukan adendum otorisasi CFO.`;
      }

      return {
        unitName: unit.name,
        monthYear: reportMonth,
        transactionCount: count,
        monthlyBudget: unit.monthlyBudget,
        expenseAmount: expense,
        incomeAmount: income,
        budgetRealizationPct: realizationPct,
        variancePct,
        efficiencyStatus: status,
        aiExecutiveInsight: insight
      };
    });
  }, [transactions, reportMonth]);

  return (
    <div className="space-y-6 animate-in fade-in duration-300">
      
      {/* Toast Notification Alert */}
      {toastMsg && (
        <div className="fixed bottom-5 right-5 z-50 bg-[#0f172a] border-2 border-sky-400 text-sky-100 px-5 py-3 rounded-lg shadow-2xl flex items-center gap-3 font-mono text-xs animate-bounce">
          <CheckCircle2 className="w-5 h-5 text-sky-400 shrink-0" />
          <span>{toastMsg}</span>
        </div>
      )}

      {/* SAP FI/CO Executive Header Banner */}
      <div className="bg-gradient-to-r from-slate-900 via-[#0b1736] to-slate-900 border-2 border-sky-500/40 p-5 sm:p-6 rounded-xl shadow-2xl relative overflow-hidden">
        <div className="absolute top-0 right-0 w-96 h-96 bg-sky-500/10 rounded-full blur-3xl pointer-events-none"></div>
        <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 relative z-10">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="px-2.5 py-0.5 bg-sky-500/20 text-sky-300 border border-sky-400/40 text-[10px] font-mono font-bold rounded uppercase tracking-wider">
                SAP FI/CO INTEGRATED MODULE
              </span>
              <span className="px-2.5 py-0.5 bg-emerald-500/20 text-emerald-300 border border-emerald-400/40 text-[10px] font-mono font-bold rounded uppercase tracking-wider flex items-center gap-1">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-ping"></span>
                LIVE LEDGER CONNECTED
              </span>
            </div>
            <h2 className="text-xl sm:text-2xl font-black uppercase tracking-tight text-white flex items-center gap-2.5">
              <Building2 className="w-6 h-6 text-sky-400 shrink-0" />
              Sistem Keuangan & Workflow Permohonan Transaksi
            </h2>
            <p className="text-xs text-slate-300 max-w-3xl mt-1 leading-relaxed">
              Modul transaksi keuangan penerimaan dan pengeluaran SAP FI/CO terintegrasi. Pengajuan permohonan pembayaran lintas divisi berdasarkan Mata Anggaran (Cost Center) melalui mekanisme workflow berjenjang, pencatatan otomatis Buku Kas/Bank, Jurnal Penyesuaian, Buku Besar, Neraca, LRA, serta Laporan Manajemen Seluruh Unit Kerja.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2.5 w-full lg:w-auto shrink-0">
            <button
              onClick={() => setIsVoucherModalOpen(true)}
              className="flex-1 lg:flex-none px-4 py-2.5 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-white font-black text-xs uppercase tracking-wider rounded-lg shadow-lg shadow-sky-500/30 flex items-center justify-center gap-2 transition-all active:scale-95"
            >
              <Plus className="w-4 h-4" />
              Form Transaksi Baruu
            </button>
            <button
              onClick={() => setIsAdjModalOpen(true)}
              className="flex-1 lg:flex-none px-4 py-2.5 bg-[#1e293b] hover:bg-[#334155] border border-sky-500/40 text-sky-300 font-bold text-xs uppercase tracking-wider rounded-lg flex items-center justify-center gap-2 transition-all"
            >
              <FileSpreadsheet className="w-4 h-4 text-sky-400" />
              Jurnal Adjustment Manual
            </button>
          </div>
        </div>

        {/* Realtime KPI Financial Summary Bar */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-5 pt-4 border-t border-sky-500/20 font-mono">
          <div className="bg-[#081026]/80 p-3 rounded-lg border border-sky-500/30">
            <span className="text-[10px] uppercase text-slate-400 font-bold block">Total Kas & Bank Liquidity:</span>
            <span className="text-sm sm:text-base font-black text-sky-300 block mt-0.5">
              {formatIDR(financialStats.totalCashBank)}
            </span>
          </div>
          <div className="bg-[#081026]/80 p-3 rounded-lg border border-emerald-500/30">
            <span className="text-[10px] uppercase text-slate-400 font-bold block">Total Realisasi Penerimaan:</span>
            <span className="text-sm sm:text-base font-black text-emerald-400 block mt-0.5">
              {formatIDR(financialStats.totalIncome)}
            </span>
          </div>
          <div className="bg-[#081026]/80 p-3 rounded-lg border border-rose-500/30">
            <span className="text-[10px] uppercase text-slate-400 font-bold block">Total Realisasi Pengeluaran:</span>
            <span className="text-sm sm:text-base font-black text-rose-400 block mt-0.5">
              {formatIDR(financialStats.totalExpenses)}
            </span>
          </div>
          <div className="bg-[#081026]/80 p-3 rounded-lg border border-amber-500/30">
            <span className="text-[10px] uppercase text-slate-400 font-bold block">Voucher Menunggu Approval:</span>
            <span className="text-sm sm:text-base font-black text-amber-300 block mt-0.5 flex items-center gap-1.5">
              {financialStats.pendingCount} Permohonan
              {financialStats.pendingCount > 0 && <span className="w-2 h-2 rounded-full bg-amber-400 animate-ping"></span>}
            </span>
          </div>
        </div>
      </div>

      {/* SAP Accounting Sub-Module Navigation Tabs */}
      <div className="flex items-center gap-1.5 overflow-x-auto no-scrollbar border-b border-[#1e293b] pb-2">
        <button
          onClick={() => setActiveSubTab("transactions")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "transactions"
              ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
              : "bg-[#0f172a] text-slate-300 hover:bg-[#1e293b] border border-[#1e293b]"
          }`}
        >
          <Receipt className="w-4 h-4" />
          Workflow Permohonan Transaksi
          {financialStats.pendingCount > 0 && (
            <span className="bg-amber-400 text-black px-1.5 py-0.2 rounded-full text-[10px] font-black">
              {financialStats.pendingCount}
            </span>
          )}
        </button>

        <button
          onClick={() => setActiveSubTab("budget_division")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "budget_division"
              ? "bg-[#facc15] text-black shadow-md shadow-yellow-500/30"
              : "bg-[#0f172a] text-[#facc15] hover:bg-[#1e293b] border border-[#facc15]/30"
          }`}
        >
          <Calculator className="w-4 h-4" />
          Divisi Anggaran & Preset Bisnis
        </button>

        <button
          onClick={() => setActiveSubTab("cashbook")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "cashbook"
              ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
              : "bg-[#0f172a] text-slate-300 hover:bg-[#1e293b] border border-[#1e293b]"
          }`}
        >
          <Wallet className="w-4 h-4 text-emerald-400" />
          1. Buku Kas / Bank
        </button>

        <button
          onClick={() => setActiveSubTab("adjustments")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "adjustments"
              ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
              : "bg-[#0f172a] text-slate-300 hover:bg-[#1e293b] border border-[#1e293b]"
          }`}
        >
          <FileSpreadsheet className="w-4 h-4 text-amber-400" />
          2. Jurnal Adjustment
        </button>

        <button
          onClick={() => setActiveSubTab("ledger")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "ledger"
              ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
              : "bg-[#0f172a] text-slate-300 hover:bg-[#1e293b] border border-[#1e293b]"
          }`}
        >
          <BookOpen className="w-4 h-4 text-sky-400" />
          3. Buku Besar (GL)
        </button>

        <button
          onClick={() => setActiveSubTab("balance_sheet")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "balance_sheet"
              ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
              : "bg-[#0f172a] text-slate-300 hover:bg-[#1e293b] border border-[#1e293b]"
          }`}
        >
          <Scale className="w-4 h-4 text-indigo-400" />
          4. Neraca
        </button>

        <button
          onClick={() => setActiveSubTab("lra")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "lra"
              ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
              : "bg-[#0f172a] text-slate-300 hover:bg-[#1e293b] border border-[#1e293b]"
          }`}
        >
          <PieChart className="w-4 h-4 text-purple-400" />
          5. Laporan Realisasi Anggaran (LRA)
        </button>

        <button
          onClick={() => setActiveSubTab("management_report")}
          className={`px-3.5 py-2 rounded-lg text-xs font-bold uppercase tracking-wide transition-all whitespace-nowrap flex items-center gap-2 ${
            activeSubTab === "management_report"
              ? "bg-sky-500 text-white shadow-md shadow-sky-500/30"
              : "bg-[#0f172a] text-slate-300 hover:bg-[#1e293b] border border-[#1e293b]"
          }`}
        >
          <Briefcase className="w-4 h-4 text-yellow-400" />
          6. Laporan Manajemen Bulanan
        </button>
      </div>

      {/* ========================================================================= */}
      {/* SUB-TAB 0: WORKFLOW PERMOHONAN TRANSAKSI (ALL DIVISIONS & SAP POSTING)    */}
      {/* ========================================================================= */}
      {activeSubTab === "transactions" && (
        <div className="space-y-4">
          
          {/* Controls & Filter Bar */}
          <div className="bg-[#0f172a] border border-[#1e293b] p-4 rounded-xl flex flex-col md:flex-row items-center justify-between gap-3">
            <div className="relative w-full md:w-80">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
              <input
                type="text"
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                placeholder="Cari voucher, vendor, pemohon, mata anggaran..."
                className="w-full bg-[#081026] border border-[#1e293b] pl-9 pr-3 py-1.5 text-xs text-white placeholder-slate-500 rounded-lg focus:outline-none focus:border-sky-400"
              />
            </div>

            <div className="flex flex-wrap items-center gap-2 w-full md:w-auto">
              <select
                value={statusFilter}
                onChange={e => setStatusFilter(e.target.value)}
                className="bg-[#081026] border border-[#1e293b] px-3 py-1.5 text-xs text-slate-300 rounded-lg focus:outline-none focus:border-sky-400"
              >
                <option value="ALL">Semua Status Workflow</option>
                <option value="Menunggu Verifikasi Anggaran">Menunggu Verifikasi Anggaran</option>
                <option value="Menunggu Posting Akuntansi">Menunggu Posting Akuntansi</option>
                <option value="Diposting">Diposting (Approved & Posted)</option>
                <option value="Ditolak">Ditolak</option>
              </select>

              <select
                value={typeFilter}
                onChange={e => setTypeFilter(e.target.value)}
                className="bg-[#081026] border border-[#1e293b] px-3 py-1.5 text-xs text-slate-300 rounded-lg focus:outline-none focus:border-sky-400"
              >
                <option value="ALL">Semua Jenis Transaksi</option>
                <option value="Pengeluaran">Pengeluaran (Expense)</option>
                <option value="Penerimaan">Penerimaan (Income)</option>
              </select>

              <select
                value={divisionFilter}
                onChange={e => setDivisionFilter(e.target.value)}
                className="bg-[#081026] border border-[#1e293b] px-3 py-1.5 text-xs text-slate-300 rounded-lg focus:outline-none focus:border-sky-400"
              >
                <option value="ALL">Semua Divisi Pemohon</option>
                <option value="Developer">Developer / CTO</option>
                <option value="Operasional">Operasional / COO</option>
                <option value="Pemasaran">Pemasaran & Sales</option>
                <option value="Pengembangan SDM">Pengembangan SDM / HR</option>
                <option value="Bendahara">Bendahara & Keuangan</option>
                <option value="Executive Office">Executive Office / CEO</option>
              </select>
            </div>
          </div>

          {/* Transactions List Table */}
          <div className="bg-[#0f172a] border border-[#1e293b] rounded-xl overflow-hidden shadow-xl">
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-[#081026] text-slate-400 text-[10px] font-mono uppercase tracking-wider border-b border-[#1e293b]">
                    <th className="py-3 px-4">No. Voucher / Tanggal</th>
                    <th className="py-3 px-4">Jenis & Divisi</th>
                    <th className="py-3 px-4">Mata Anggaran (Cost Center)</th>
                    <th className="py-3 px-4">Vendor / Customer / Keperluan</th>
                    <th className="py-3 px-4 text-right">Nominal (Rp)</th>
                    <th className="py-3 px-4">Tahap Workflow & Approval</th>
                    <th className="py-3 px-4 text-center">Aksi / Otorisasi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1e293b] text-xs font-mono">
                  {filteredTransactions.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="py-8 text-center text-slate-500">
                        Tidak ada transaksi keuangan yang sesuai dengan filter.
                      </td>
                    </tr>
                  ) : (
                    filteredTransactions.map(trx => (
                      <tr key={trx.id} className="hover:bg-[#1e293b]/50 transition-colors">
                        <td className="py-3 px-4 whitespace-nowrap">
                          <span className="font-bold text-sky-300 block">{trx.voucherNo}</span>
                          <span className="text-[10px] text-slate-400 block mt-0.5">{trx.transactionDate}</span>
                        </td>

                        <td className="py-3 px-4 whitespace-nowrap">
                          <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-black uppercase mb-1 ${
                            trx.transactionType === "Penerimaan"
                              ? "bg-emerald-500/20 text-emerald-300 border border-emerald-500/40"
                              : "bg-rose-500/20 text-rose-300 border border-rose-500/40"
                          }`}>
                            {trx.transactionType === "Penerimaan" ? <ArrowDownLeft className="w-3 h-3" /> : <ArrowUpRight className="w-3 h-3" />}
                            {trx.transactionType}
                          </span>
                          <span className="text-[10px] text-slate-300 block">
                            {trx.division} ({trx.requesterName})
                          </span>
                        </td>

                        <td className="py-3 px-4">
                          <span className="font-bold text-slate-200 block">{trx.budgetCode}</span>
                          <span className="text-[10px] text-slate-400 block truncate max-w-xs">{trx.budgetName}</span>
                        </td>

                        <td className="py-3 px-4">
                          <span className="font-bold text-slate-100 block">{trx.recipientVendor}</span>
                          <span className="text-[10px] text-slate-400 block truncate max-w-xs">{trx.description}</span>
                          <span className="text-[9px] text-sky-400 block mt-0.5">Ref: {trx.invoiceRef}</span>
                        </td>

                        <td className="py-3 px-4 text-right whitespace-nowrap font-black">
                          <span className={trx.transactionType === "Penerimaan" ? "text-emerald-400" : "text-slate-100"}>
                            {formatIDR(trx.amount)}
                          </span>
                        </td>

                        <td className="py-3 px-4 whitespace-nowrap">
                          <div className="space-y-1">
                            <span className={`inline-block px-2 py-0.5 rounded text-[10px] font-bold ${
                              trx.status === "Diposting" 
                                ? "bg-emerald-500/20 text-emerald-300 border border-emerald-500/40" 
                                : trx.status === "Ditolak" 
                                ? "bg-rose-500/20 text-rose-300 border border-rose-500/40"
                                : "bg-amber-500/20 text-amber-300 border border-amber-500/40"
                            }`}>
                              {trx.status}
                            </span>
                            <span className="text-[9px] text-slate-400 block">
                              Tahap: <strong className="text-sky-300">{trx.currentStage}</strong>
                            </span>
                          </div>
                        </td>

                        <td className="py-3 px-4 text-center whitespace-nowrap">
                          <div className="flex items-center justify-center gap-1.5">
                            <button
                              onClick={() => setViewingTrx(trx)}
                              className="p-1.5 bg-[#1e293b] hover:bg-sky-500 hover:text-white text-sky-300 rounded transition-colors border border-sky-500/30"
                              title="Lihat Detail Voucher & Audit Log SAP"
                            >
                              <Eye className="w-3.5 h-3.5" />
                            </button>

                            {trx.status === "Menunggu Verifikasi Anggaran" && (
                              <button
                                onClick={() => handleApproveBudgetStage(trx)}
                                className="px-2.5 py-1 bg-amber-500 hover:bg-amber-400 text-black font-black text-[10px] uppercase rounded transition-colors flex items-center gap-1"
                                title="Setujui Alokasi Anggaran (Divisi Anggaran)"
                              >
                                <CheckCircle2 className="w-3 h-3" />
                                Approve Anggaran
                              </button>
                            )}

                            {trx.status === "Menunggu Posting Akuntansi" && (
                              <button
                                onClick={() => handlePostAccountingStage(trx)}
                                className="px-2.5 py-1 bg-emerald-500 hover:bg-emerald-400 text-black font-black text-[10px] uppercase rounded transition-colors flex items-center gap-1 shadow-md shadow-emerald-500/20"
                                title="Post ke Buku Besar, Jurnal, dan Buku Kas/Bank (Divisi Akuntansi)"
                              >
                                <Send className="w-3 h-3" />
                                Post SAP Ledger
                              </button>
                            )}

                            {trx.status.startsWith("Menunggu") && (
                              <button
                                onClick={() => handleRejectTrx(trx)}
                                className="p-1.5 bg-rose-950/60 hover:bg-rose-600 text-rose-300 hover:text-white rounded transition-colors border border-rose-500/40"
                                title="Tolak Transaksi"
                              >
                                <XCircle className="w-3.5 h-3.5" />
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* SUB-TAB 1: BUKU KAS / BANK (CASH & BANK BOOK)                            */}
      {/* ========================================================================= */}
      {activeSubTab === "cashbook" && (
        <div className="space-y-4">
          
          {/* Account Selector Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3 font-mono">
            <button
              onClick={() => setSelectedCashAccountId("ALL")}
              className={`p-3.5 rounded-xl text-left border transition-all ${
                selectedCashAccountId === "ALL"
                  ? "bg-sky-500/20 border-sky-400 text-white shadow-lg shadow-sky-500/20"
                  : "bg-[#0f172a] border-[#1e293b] text-slate-300 hover:bg-[#1e293b]"
              }`}
            >
              <span className="text-[10px] uppercase font-bold text-slate-400 block">SEMUA AKUN KAS/BANK</span>
              <span className="text-base font-black text-sky-300 block mt-1">
                {formatIDR(financialStats.totalCashBank)}
              </span>
              <span className="text-[9px] text-slate-400 block mt-1">Konsolidasi Likuiditas HQ</span>
            </button>

            {cashAccounts.map(acc => (
              <button
                key={acc.id}
                onClick={() => setSelectedCashAccountId(acc.id)}
                className={`p-3.5 rounded-xl text-left border transition-all ${
                  selectedCashAccountId === acc.id
                    ? "bg-sky-500/20 border-sky-400 text-white shadow-lg shadow-sky-500/20"
                    : "bg-[#0f172a] border-[#1e293b] text-slate-300 hover:bg-[#1e293b]"
                }`}
              >
                <div className="flex items-center justify-between mb-1">
                  <span className="text-[10px] uppercase font-bold text-sky-400">{acc.code}</span>
                  <span className="text-[9px] font-bold px-1.5 py-0.2 rounded bg-slate-800 text-slate-300">
                    {acc.type}
                  </span>
                </div>
                <span className="text-xs font-bold text-slate-200 block truncate">{acc.name}</span>
                <span className="text-sm font-black text-emerald-400 block mt-1">
                  {formatIDR(acc.currentBalance)}
                </span>
                <span className="text-[9px] text-slate-400 block mt-0.5 truncate">
                  {acc.accountNumber || "Saldo Kas Fisik"}
                </span>
              </button>
            ))}
          </div>

          {/* Cash & Bank Mutasi Table */}
          <div className="bg-[#0f172a] border border-[#1e293b] rounded-xl overflow-hidden shadow-xl">
            <div className="p-4 bg-[#081026] border-b border-[#1e293b] flex items-center justify-between">
              <h3 className="text-sm font-black uppercase text-white tracking-wide flex items-center gap-2">
                <Wallet className="w-4 h-4 text-emerald-400" />
                Rincian Mutasi Buku Kas & Bank ({selectedCashAccountId === "ALL" ? "Konsolidasi Semua Akun" : cashAccounts.find(a => a.id === selectedCashAccountId)?.name})
              </h3>
              <span className="text-xs font-mono text-slate-400">
                Total Transaksi Terposting: {cashbookEntries.length} Records
              </span>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-[#081026] text-slate-400 text-[10px] font-mono uppercase tracking-wider border-b border-[#1e293b]">
                    <th className="py-3 px-4">Tanggal / No. Voucher</th>
                    <th className="py-3 px-4">Akun Kas / Bank</th>
                    <th className="py-3 px-4">Uraian / Keterangan Transaksi</th>
                    <th className="py-3 px-4">Divisi Pemohon</th>
                    <th className="py-3 px-4 text-right">Penerimaan (Debet)</th>
                    <th className="py-3 px-4 text-right">Pengeluaran (Kredit)</th>
                    <th className="py-3 px-4 text-right">Saldo Berjalan (Rp)</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1e293b] text-xs font-mono">
                  {cashbookEntries.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="py-8 text-center text-slate-500">
                        Belum ada mutasi transaksi terposting pada akun kas/bank ini.
                      </td>
                    </tr>
                  ) : (
                    cashbookEntries.map(e => (
                      <tr key={e.id} className="hover:bg-[#1e293b]/50 transition-colors">
                        <td className="py-3 px-4 whitespace-nowrap">
                          <span className="font-bold text-sky-300 block">{e.voucherNo}</span>
                          <span className="text-[10px] text-slate-400 block">{e.transactionDate}</span>
                        </td>
                        <td className="py-3 px-4 whitespace-nowrap text-slate-300">
                          {e.cashBankAccountName}
                        </td>
                        <td className="py-3 px-4">
                          <span className="font-bold text-slate-100 block">{e.recipientVendor}</span>
                          <span className="text-[10px] text-slate-400 block truncate max-w-sm">{e.description}</span>
                        </td>
                        <td className="py-3 px-4 whitespace-nowrap text-slate-300">
                          {e.division}
                        </td>
                        <td className="py-3 px-4 text-right whitespace-nowrap font-bold text-emerald-400">
                          {e.inflow > 0 ? formatIDR(e.inflow) : "-"}
                        </td>
                        <td className="py-3 px-4 text-right whitespace-nowrap font-bold text-rose-400">
                          {e.outflow > 0 ? formatIDR(e.outflow) : "-"}
                        </td>
                        <td className="py-3 px-4 text-right whitespace-nowrap font-black text-sky-300">
                          {formatIDR(e.runningBalance)}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* SUB-TAB 2: JURNAL ADJUSTMENT & GENERAL JOURNALS                          */}
      {/* ========================================================================= */}
      {activeSubTab === "adjustments" && (
        <div className="space-y-4">
          
          <div className="bg-[#0f172a] border border-[#1e293b] p-4 rounded-xl flex items-center justify-between">
            <div>
              <h3 className="text-sm font-black uppercase text-white tracking-wide flex items-center gap-2">
                <FileSpreadsheet className="w-4 h-4 text-amber-400" />
                Daftar Jurnal Umum & Penyesuaian (Adjustment Journal SAP)
              </h3>
              <p className="text-xs text-slate-400 mt-0.5">
                Pencatatan berpasangan Debit & Kredit otomatis dari transaksi SAP dan jurnal penyesuaian manual.
              </p>
            </div>
            <button
              onClick={() => setIsAdjModalOpen(true)}
              className="px-4 py-2 bg-amber-500 hover:bg-amber-400 text-black font-black text-xs uppercase tracking-wider rounded-lg flex items-center gap-1.5 shadow-lg shadow-amber-500/20"
            >
              <Plus className="w-4 h-4" />
              Buat Jurnal Adjustment Manual
            </button>
          </div>

          <div className="space-y-3">
            {journals.map(j => (
              <div key={j.id} className="bg-[#0f172a] border border-[#1e293b] rounded-xl p-4 space-y-3 shadow-lg">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[#1e293b] pb-2 font-mono">
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-black text-amber-300 text-sm">{j.journalNo}</span>
                      <span className="text-[10px] font-bold px-2 py-0.5 bg-slate-800 text-slate-300 rounded border border-slate-700">
                        {j.type}
                      </span>
                      {j.voucherNoRef && (
                        <span className="text-[10px] text-sky-400 font-bold">
                          Ref: {j.voucherNoRef}
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-slate-200 mt-1 font-bold">{j.description}</p>
                  </div>
                  <div className="text-right text-[11px] text-slate-400">
                    <div>Tanggal: <strong className="text-slate-200">{j.date}</strong></div>
                    <div>User Posting: <strong className="text-sky-300">{j.postedBy}</strong></div>
                  </div>
                </div>

                {/* Journal Lines Table */}
                <div className="overflow-x-auto font-mono text-xs">
                  <table className="w-full text-left">
                    <thead>
                      <tr className="text-[10px] uppercase text-slate-400 border-b border-[#1e293b]">
                        <th className="py-1.5 px-3">Kode & Nama Akun (GL)</th>
                        <th className="py-1.5 px-3">Keterangan Line</th>
                        <th className="py-1.5 px-3 text-right">Debet (Rp)</th>
                        <th className="py-1.5 px-3 text-right">Kredit (Rp)</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[#1e293b]/50">
                      {j.lines.map(line => (
                        <tr key={line.id} className="hover:bg-[#1e293b]/30">
                          <td className="py-2 px-3 font-bold text-slate-200">
                            {line.accountCode} - {line.accountName}
                          </td>
                          <td className="py-2 px-3 text-slate-400 text-[11px]">
                            {line.memo || "-"}
                          </td>
                          <td className="py-2 px-3 text-right font-bold text-emerald-400">
                            {line.debit > 0 ? formatIDR(line.debit) : "-"}
                          </td>
                          <td className="py-2 px-3 text-right font-bold text-sky-300">
                            {line.credit > 0 ? formatIDR(line.credit) : "-"}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                    <tfoot>
                      <tr className="border-t border-[#1e293b] font-black text-slate-200 bg-[#081026]">
                        <td colSpan={2} className="py-2 px-3 text-right text-[10px] uppercase">
                          TOTAL BALANCE JURNAL:
                        </td>
                        <td className="py-2 px-3 text-right text-emerald-400">
                          {formatIDR(j.lines.reduce((s, l) => s + l.debit, 0))}
                        </td>
                        <td className="py-2 px-3 text-right text-sky-300">
                          {formatIDR(j.lines.reduce((s, l) => s + l.credit, 0))}
                        </td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* SUB-TAB 3: BUKU BESAR (GENERAL LEDGER / GL ACCOUNTS)                      */}
      {/* ========================================================================= */}
      {activeSubTab === "ledger" && (
        <div className="space-y-4 font-mono">
          
          {/* Select GL Account Bar */}
          <div className="bg-[#0f172a] border border-[#1e293b] p-4 rounded-xl flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
            <div>
              <label className="block text-[10px] uppercase font-bold text-slate-400 mb-1">
                Pilih Kode Akun Buku Besar (GL Account):
              </label>
              <select
                value={selectedGlCode}
                onChange={e => setSelectedGlCode(e.target.value)}
                className="bg-[#081026] border border-[#1e293b] text-sky-300 font-black text-sm px-3 py-2 rounded-lg focus:outline-none focus:border-sky-400 min-w-[300px]"
              >
                {budgetItems.map(b => (
                  <option key={b.code} value={b.code}>
                    {b.code} - {b.name} ({b.type})
                  </option>
                ))}
                {cashAccounts.map(c => (
                  <option key={c.code} value={c.code}>
                    {c.code} - {c.name} (Kas/Bank)
                  </option>
                ))}
                <option value="5201">5201 - Beban Penyusutan Perangkat IT & Server</option>
                <option value="1302">1302 - Akumulasi Penyusutan Peralatan IT</option>
              </select>
            </div>

            <div className="flex items-center gap-3 bg-[#081026] p-3 rounded-lg border border-[#1e293b]">
              <div>
                <span className="text-[10px] uppercase text-slate-400 font-bold block">Total Debet GL:</span>
                <span className="text-sm font-black text-emerald-400">{formatIDR(selectedGlDetails.totalDebit)}</span>
              </div>
              <div className="w-px h-8 bg-[#1e293b]"></div>
              <div>
                <span className="text-[10px] uppercase text-slate-400 font-bold block">Total Kredit GL:</span>
                <span className="text-sm font-black text-sky-300">{formatIDR(selectedGlDetails.totalCredit)}</span>
              </div>
              <div className="w-px h-8 bg-[#1e293b]"></div>
              <div>
                <span className="text-[10px] uppercase text-slate-400 font-bold block">Saldo Mutasi Net:</span>
                <span className="text-sm font-black text-amber-300">{formatIDR(selectedGlDetails.netBalance)}</span>
              </div>
            </div>
          </div>

          {/* GL Transactions Table */}
          <div className="bg-[#0f172a] border border-[#1e293b] rounded-xl overflow-hidden shadow-xl">
            <div className="p-4 bg-[#081026] border-b border-[#1e293b]">
              <h3 className="text-sm font-black uppercase text-white tracking-wide flex items-center gap-2">
                <BookOpen className="w-4 h-4 text-sky-400" />
                Posting Rincian Buku Besar Akun Kode: {selectedGlCode}
              </h3>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left">
                <thead>
                  <tr className="bg-[#081026] text-slate-400 text-[10px] uppercase tracking-wider border-b border-[#1e293b]">
                    <th className="py-3 px-4">Tanggal / No. Jurnal</th>
                    <th className="py-3 px-4">Voucher Ref</th>
                    <th className="py-3 px-4">Uraian Transaksi Buku Besar</th>
                    <th className="py-3 px-4 text-right">Debet (Rp)</th>
                    <th className="py-3 px-4 text-right">Kredit (Rp)</th>
                    <th className="py-3 px-4">User Posting</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1e293b] text-xs">
                  {selectedGlDetails.glLines.length === 0 ? (
                    <tr>
                      <td colSpan={6} className="py-8 text-center text-slate-500">
                        Belum ada posting transaksi pada kode akun buku besar ini.
                      </td>
                    </tr>
                  ) : (
                    selectedGlDetails.glLines.map((line, idx) => (
                      <tr key={idx} className="hover:bg-[#1e293b]/50">
                        <td className="py-3 px-4 whitespace-nowrap">
                          <span className="font-bold text-amber-300 block">{line.journalNo}</span>
                          <span className="text-[10px] text-slate-400 block">{line.date}</span>
                        </td>
                        <td className="py-3 px-4 whitespace-nowrap text-sky-300 font-bold">
                          {line.voucherRef || "-"}
                        </td>
                        <td className="py-3 px-4 text-slate-200">
                          {line.description}
                        </td>
                        <td className="py-3 px-4 text-right font-bold text-emerald-400 whitespace-nowrap">
                          {line.debit > 0 ? formatIDR(line.debit) : "-"}
                        </td>
                        <td className="py-3 px-4 text-right font-bold text-sky-300 whitespace-nowrap">
                          {line.credit > 0 ? formatIDR(line.credit) : "-"}
                        </td>
                        <td className="py-3 px-4 text-slate-400 whitespace-nowrap">
                          {line.postedBy}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* SUB-TAB 4: NERACA (BALANCE SHEET)                                         */}
      {/* ========================================================================= */}
      {activeSubTab === "balance_sheet" && (
        <div className="space-y-4 font-mono">
          
          <div className="bg-[#0f172a] border border-[#1e293b] p-4 rounded-xl flex items-center justify-between">
            <div>
              <h3 className="text-sm font-black uppercase text-white tracking-wide flex items-center gap-2">
                <Scale className="w-4 h-4 text-indigo-400" />
                Laporan Neraca Keuangan (Balance Sheet Statement PT Median)
              </h3>
              <p className="text-xs text-slate-400 mt-0.5">
                Laporan Posisi Keuangan resmi mengonsolidasikan Total Aktiva (Aset) vs Total Pasiva (Kewajiban & Ekuitas).
              </p>
            </div>

            <div className={`px-3 py-1.5 rounded-lg border text-xs font-black uppercase flex items-center gap-1.5 ${
              balanceSheetData.isBalanced 
                ? "bg-emerald-500/20 border-emerald-400 text-emerald-300"
                : "bg-rose-500/20 border-rose-400 text-rose-300"
            }`}>
              <CheckCircle2 className="w-4 h-4" />
              STATUS: {balanceSheetData.isBalanced ? "BALANCE OK (AKTIVA = PASIVA)" : "UNBALANCED WARNING"}
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            
            {/* AKTIVA / ASET */}
            <div className="bg-[#0f172a] border-2 border-sky-500/30 rounded-xl p-5 space-y-4 shadow-xl">
              <div className="border-b border-sky-500/30 pb-3 flex items-center justify-between">
                <h4 className="text-base font-black uppercase text-sky-300 flex items-center gap-2">
                  <ArrowDownLeft className="w-5 h-5 text-sky-400" />
                  AKTIVA / ASET PERUSAHAAN
                </h4>
                <span className="text-xs font-bold text-slate-400">PT Median HQ</span>
              </div>

              {/* Aset Lancar */}
              <div className="space-y-2">
                <h5 className="text-xs font-bold uppercase text-slate-400 border-b border-[#1e293b] pb-1">
                  1. ASET LANCAR (CURRENT ASSETS)
                </h5>
                <div className="space-y-1.5 text-xs">
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Kas & Bank Likuid (BCA, Mandiri, Kas Office)</span>
                    <span className="font-bold text-emerald-400">{formatIDR(balanceSheetData.cashTotal)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Piutang Usaha Enterprise (Accounts Receivable)</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.piutangUsaha)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Uang Muka Operasional & Vendor Prepayments</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.uangMukaOperasional)}</span>
                  </div>
                  <div className="flex justify-between py-1.5 font-bold text-sky-300 bg-[#081026] px-2 rounded">
                    <span>Subtotal Aset Lancar:</span>
                    <span>{formatIDR(balanceSheetData.totalAsetLancar)}</span>
                  </div>
                </div>
              </div>

              {/* Aset Tetap */}
              <div className="space-y-2 pt-2">
                <h5 className="text-xs font-bold uppercase text-slate-400 border-b border-[#1e293b] pb-1">
                  2. ASET TETAP (NON-CURRENT ASSETS)
                </h5>
                <div className="space-y-1.5 text-xs">
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Perangkat IT, Server & Network Hardware</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.peralatanServer)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Gedung & Fasilitas Kantor HQ</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.gedungFasilitas)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-rose-400">Akumulasi Penyusutan Aset Tetap</span>
                    <span className="font-bold text-rose-400">{formatIDR(balanceSheetData.akumulasiPenyusutan)}</span>
                  </div>
                  <div className="flex justify-between py-1.5 font-bold text-sky-300 bg-[#081026] px-2 rounded">
                    <span>Subtotal Aset Tetap:</span>
                    <span>{formatIDR(balanceSheetData.totalAsetTetap)}</span>
                  </div>
                </div>
              </div>

              {/* Grand Total Aset */}
              <div className="p-3 bg-gradient-to-r from-blue-900/60 to-sky-900/60 border border-sky-400 rounded-lg flex justify-between items-center font-black text-sm text-white">
                <span>GRAND TOTAL AKTIVA / ASET:</span>
                <span className="text-sky-300 text-base">{formatIDR(balanceSheetData.totalAset)}</span>
              </div>
            </div>

            {/* PASIVA / KEWAJIBAN & EKUITAS */}
            <div className="bg-[#0f172a] border-2 border-indigo-500/30 rounded-xl p-5 space-y-4 shadow-xl">
              <div className="border-b border-indigo-500/30 pb-3 flex items-center justify-between">
                <h4 className="text-base font-black uppercase text-indigo-300 flex items-center gap-2">
                  <ArrowUpRight className="w-5 h-5 text-indigo-400" />
                  PASIVA / KEWAJIBAN & EKUITAS
                </h4>
                <span className="text-xs font-bold text-slate-400">PT Median HQ</span>
              </div>

              {/* Kewajiban Lancar */}
              <div className="space-y-2">
                <h5 className="text-xs font-bold uppercase text-slate-400 border-b border-[#1e293b] pb-1">
                  1. KEWAJIBAN LANCAR (LIABILITIES)
                </h5>
                <div className="space-y-1.5 text-xs">
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Utang Usaha Vendor (Accounts Payable)</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.utangUsaha)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Utang Gaji & Tunjangan Pegawai</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.utangGaji)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Utang Pajak PPh & PPN Terutang</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.utangPajak)}</span>
                  </div>
                  <div className="flex justify-between py-1.5 font-bold text-indigo-300 bg-[#081026] px-2 rounded">
                    <span>Subtotal Kewajiban:</span>
                    <span>{formatIDR(balanceSheetData.totalKewajibanLancar)}</span>
                  </div>
                </div>
              </div>

              {/* Ekuitas / Modal */}
              <div className="space-y-2 pt-2">
                <h5 className="text-xs font-bold uppercase text-slate-400 border-b border-[#1e293b] pb-1">
                  2. EKUITAS & MODAL PERUSAHAAN (EQUITY)
                </h5>
                <div className="space-y-1.5 text-xs">
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Modal Disetor Pemegang Saham</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.modalDisetor)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-slate-300">Laba Ditahan Tahun Lalu (Retained Earnings)</span>
                    <span className="font-bold text-slate-200">{formatIDR(balanceSheetData.labaDitahan)}</span>
                  </div>
                  <div className="flex justify-between py-1 border-b border-[#1e293b]/40">
                    <span className="text-emerald-400">Laba Bersih Tahun Berjalan (Net Profit)</span>
                    <span className="font-bold text-emerald-400">{formatIDR(balanceSheetData.labaTahunBerjalan)}</span>
                  </div>
                  <div className="flex justify-between py-1.5 font-bold text-indigo-300 bg-[#081026] px-2 rounded">
                    <span>Subtotal Ekuitas:</span>
                    <span>{formatIDR(balanceSheetData.totalEkuitas)}</span>
                  </div>
                </div>
              </div>

              {/* Grand Total Pasiva */}
              <div className="p-3 bg-gradient-to-r from-indigo-900/60 to-purple-900/60 border border-indigo-400 rounded-lg flex justify-between items-center font-black text-sm text-white">
                <span>GRAND TOTAL PASIVA (KEWAJIBAN + EKUITAS):</span>
                <span className="text-indigo-300 text-base">{formatIDR(balanceSheetData.totalPasiva)}</span>
              </div>
            </div>

          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* SUB-TAB 5: LAPORAN REALISASI ANGGARAN (LRA)                               */}
      {/* ========================================================================= */}
      {activeSubTab === "lra" && (
        <div className="space-y-4 font-mono">
          
          <div className="bg-[#0f172a] border border-[#1e293b] p-4 rounded-xl flex items-center justify-between">
            <div>
              <h3 className="text-sm font-black uppercase text-white tracking-wide flex items-center gap-2">
                <PieChart className="w-4 h-4 text-purple-400" />
                Laporan Realisasi Anggaran (LRA) per Mata Anggaran & Divisi
              </h3>
              <p className="text-xs text-slate-400 mt-0.5">
                Perbandingan Pagu Anggaran RKAP vs Realisasi Transaksi Keuangan yang telah diposting secara real-time.
              </p>
            </div>
            <button
              onClick={() => showToast("Laporan Realisasi Anggaran berhasil di-export ke Excel / PDF.")}
              className="px-3.5 py-1.5 bg-[#1e293b] hover:bg-slate-800 border border-slate-700 text-slate-200 font-bold text-xs uppercase rounded flex items-center gap-1.5"
            >
              <Download className="w-4 h-4" />
              Export LRA (PDF)
            </button>
          </div>

          <div className="bg-[#0f172a] border border-[#1e293b] rounded-xl overflow-hidden shadow-xl">
            <div className="overflow-x-auto">
              <table className="w-full text-left">
                <thead>
                  <tr className="bg-[#081026] text-slate-400 text-[10px] uppercase tracking-wider border-b border-[#1e293b]">
                    <th className="py-3 px-4">Kode & Mata Anggaran (Cost Center)</th>
                    <th className="py-3 px-4">Jenis & Divisi</th>
                    <th className="py-3 px-4 text-right">Pagu Anggaran (Budget)</th>
                    <th className="py-3 px-4 text-right">Realisasi (Actual)</th>
                    <th className="py-3 px-4 text-right">Sisa Anggaran (Variance)</th>
                    <th className="py-3 px-4 text-center">% Realisasi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1e293b] text-xs">
                  {budgetItems.map(item => {
                    const remaining = item.type === "Beban" 
                      ? item.annualBudget - item.realizedAmount 
                      : item.realizedAmount - item.annualBudget;
                    const pct = item.annualBudget > 0 ? Math.round((item.realizedAmount / item.annualBudget) * 100) : 0;

                    return (
                      <tr key={item.code} className="hover:bg-[#1e293b]/50">
                        <td className="py-3 px-4">
                          <span className="font-bold text-sky-300 block">{item.code}</span>
                          <span className="text-[11px] text-slate-200 block font-bold">{item.name}</span>
                        </td>
                        <td className="py-3 px-4 whitespace-nowrap">
                          <span className={`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase mb-0.5 ${
                            item.type === "Pendapatan" ? "bg-emerald-500/20 text-emerald-300" : "bg-rose-500/20 text-rose-300"
                          }`}>
                            {item.type}
                          </span>
                          <span className="text-[10px] text-slate-400 block">{item.division}</span>
                        </td>
                        <td className="py-3 px-4 text-right font-bold text-slate-200 whitespace-nowrap">
                          {formatIDR(item.annualBudget)}
                        </td>
                        <td className="py-3 px-4 text-right font-bold text-amber-300 whitespace-nowrap">
                          {formatIDR(item.realizedAmount)}
                        </td>
                        <td className="py-3 px-4 text-right font-bold text-sky-300 whitespace-nowrap">
                          {formatIDR(remaining)}
                        </td>
                        <td className="py-3 px-4 text-center whitespace-nowrap">
                          <div className="w-28 mx-auto space-y-1">
                            <div className="flex justify-between text-[10px]">
                              <span className="font-bold text-slate-300">{pct}%</span>
                              <span className={`font-bold ${
                                pct > 100 ? "text-rose-400" : pct > 80 ? "text-amber-400" : "text-emerald-400"
                              }`}>
                                {pct > 100 ? "OVER" : pct > 80 ? "WASPADA" : "NORMAL"}
                              </span>
                            </div>
                            <div className="w-full bg-slate-800 h-2 rounded-full overflow-hidden">
                              <div
                                className={`h-full transition-all duration-500 ${
                                  pct > 100 ? "bg-rose-500" : pct > 80 ? "bg-amber-400" : "bg-emerald-400"
                                }`}
                                style={{ width: `${Math.min(pct, 100)}%` }}
                              ></div>
                            </div>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* SUB-TAB 6: LAPORAN MANAJEMEN SELURUH UNIT KERJA SETIAP BULAN               */}
      {/* ========================================================================= */}
      {activeSubTab === "management_report" && (
        <div className="space-y-4">
          
          <div className="bg-[#0f172a] border border-[#1e293b] p-4 rounded-xl flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 font-mono">
            <div>
              <h3 className="text-sm font-black uppercase text-white tracking-wide flex items-center gap-2">
                <Briefcase className="w-4 h-4 text-yellow-400" />
                Laporan Manajemen Keuangan Seluruh Unit Kerja Bulanan
              </h3>
              <p className="text-xs text-slate-400 mt-0.5">
                Rekapitulasi performa alokasi budget, realisasi pengeluaran, penerimaan, dan analisa efisiensi per unit kerja.
              </p>
            </div>

            <div className="flex items-center gap-2">
              <label className="text-xs text-slate-400 font-bold uppercase">Periode Bulan:</label>
              <select
                value={reportMonth}
                onChange={e => setReportMonth(e.target.value)}
                className="bg-[#081026] border border-[#1e293b] text-sky-300 font-black text-xs px-3 py-1.5 rounded-lg focus:outline-none focus:border-sky-400"
              >
                <option value="2026-08">Agustus 2026</option>
                <option value="2026-07">Juli 2026</option>
                <option value="2026-06">Juni 2026</option>
              </select>
            </div>
          </div>

          {/* Unit Work Cards Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {monthlyUnitReports.map((report, idx) => (
              <div key={idx} className="bg-[#0f172a] border border-[#1e293b] rounded-xl p-4 space-y-3 shadow-lg font-mono">
                <div className="flex items-center justify-between border-b border-[#1e293b] pb-2">
                  <h4 className="text-sm font-black text-white">{report.unitName}</h4>
                  <span className={`px-2 py-0.5 rounded text-[10px] font-black uppercase ${
                    report.efficiencyStatus === "Sangat Efisien" 
                      ? "bg-emerald-500/20 text-emerald-300 border border-emerald-500/40"
                      : report.efficiencyStatus === "Normal"
                      ? "bg-sky-500/20 text-sky-300 border border-sky-500/40"
                      : report.efficiencyStatus === "Mendekati Pagu"
                      ? "bg-amber-500/20 text-amber-300 border border-amber-500/40"
                      : "bg-rose-500/20 text-rose-300 border border-rose-500/40"
                  }`}>
                    {report.efficiencyStatus}
                  </span>
                </div>

                <div className="grid grid-cols-2 gap-2 text-xs">
                  <div className="bg-[#081026] p-2 rounded border border-[#1e293b]">
                    <span className="text-[9px] uppercase text-slate-400 font-bold block">Pagu Bulanan:</span>
                    <span className="font-bold text-slate-200">{formatIDR(report.monthlyBudget)}</span>
                  </div>
                  <div className="bg-[#081026] p-2 rounded border border-[#1e293b]">
                    <span className="text-[9px] uppercase text-slate-400 font-bold block">Realisasi Pengeluaran:</span>
                    <span className="font-bold text-rose-400">{formatIDR(report.expenseAmount)}</span>
                  </div>
                </div>

                <div className="space-y-1">
                  <div className="flex justify-between text-[10px] font-bold">
                    <span className="text-slate-400">Penyerapan Budget Bulanan:</span>
                    <span className="text-sky-300">{report.budgetRealizationPct}%</span>
                  </div>
                  <div className="w-full bg-slate-800 h-2 rounded-full overflow-hidden">
                    <div 
                      className="bg-gradient-to-r from-sky-400 to-blue-500 h-full transition-all"
                      style={{ width: `${Math.min(report.budgetRealizationPct, 100)}%` }}
                    ></div>
                  </div>
                </div>

                <div className="bg-sky-950/30 border border-sky-500/20 p-2.5 rounded text-[11px] text-sky-200 font-sans flex items-start gap-2">
                  <Sparkles className="w-4 h-4 text-sky-400 shrink-0 mt-0.5" />
                  <span>{report.aiExecutiveInsight}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* SUB-TAB: DIVISI ANGGARAN (MATA ANGGARAN & AUTO PRESETS CLIENT)            */}
      {/* ========================================================================= */}
      {activeSubTab === "budget_division" && (
        <BudgetDivisionModule
          currentUser={currentUser}
          budgetItems={budgetItems}
          onUpdateBudgetItems={onUpdateBudgetItems}
        />
      )}

      {/* ========================================================================= */}
      {/* MODAL: FORM TRANSAKSI BARU (VOUCHER PERMOHONAN PEMBAYARAN)               */}
      {/* ========================================================================= */}
      {isVoucherModalOpen && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-[#0f172a] border-2 border-sky-500 max-w-2xl w-full p-6 rounded-2xl text-white space-y-4 shadow-2xl relative max-h-[90vh] overflow-y-auto">
            
            <div className="flex items-center justify-between border-b border-[#1e293b] pb-3">
              <h3 className="text-base font-black uppercase text-sky-300 flex items-center gap-2">
                <Receipt className="w-5 h-5 text-sky-400" />
                Form Permohonan Transaksi Keuangan (Voucher SAP)
              </h3>
              <button
                onClick={() => setIsVoucherModalOpen(false)}
                className="text-slate-400 hover:text-white p-1 rounded"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleCreateVoucher} className="space-y-4 font-mono text-xs">
              
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                    Jenis Transaksi Keuangan: *
                  </label>
                  <select
                    value={trxType}
                    onChange={e => setTrxType(e.target.value as any)}
                    className="w-full bg-[#081026] border border-[#1e293b] p-2 text-sky-300 font-bold rounded focus:outline-none focus:border-sky-400"
                  >
                    <option value="Pengeluaran">Pengeluaran (Payment / Expense Voucher)</option>
                    <option value="Penerimaan">Penerimaan (Receipt / Income Voucher)</option>
                  </select>
                </div>

                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                    Divisi / Unit Kerja Pemohon: *
                  </label>
                  <select
                    value={trxDivision}
                    onChange={e => setTrxDivision(e.target.value)}
                    className="w-full bg-[#081026] border border-[#1e293b] p-2 text-slate-200 font-bold rounded focus:outline-none focus:border-sky-400"
                  >
                    <option value="Developer">Developer / CTO</option>
                    <option value="Operasional">Operasional / COO</option>
                    <option value="Pemasaran">Pemasaran & Sales</option>
                    <option value="Pengembangan SDM">Pengembangan SDM / HR</option>
                    <option value="Bendahara">Bendahara & Keuangan</option>
                    <option value="Executive Office">Executive Office / CEO</option>
                  </select>
                </div>
              </div>

              {/* Mata Anggaran Selection */}
              <div className="p-3 bg-[#081026] border border-sky-500/30 rounded-lg space-y-2">
                <label className="block text-[10px] uppercase font-bold text-sky-300">
                  Mata Anggaran / Cost Center (SAP Budget Line): *
                </label>
                <select
                  value={trxBudgetCode}
                  onChange={e => setTrxBudgetCode(e.target.value)}
                  className="w-full bg-[#0f172a] border border-[#1e293b] p-2 text-slate-100 font-bold rounded focus:outline-none focus:border-sky-400"
                >
                  {budgetItems.map(b => (
                    <option key={b.code} value={b.code}>
                      {b.code} - {b.name} ({b.division})
                    </option>
                  ))}
                </select>

                <div className="flex justify-between items-center text-[10px] pt-1 text-slate-300">
                  <span>Pagu Anggaran Tahunan: <strong>{formatIDR(selectedBudgetItem.annualBudget)}</strong></span>
                  <span>Sisa Pagu: <strong className="text-emerald-400">{formatIDR(selectedBudgetItem.annualBudget - selectedBudgetItem.realizedAmount)}</strong></span>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                    Nominal Transaksi (Rp): *
                  </label>
                  <input
                    type="text"
                    value={trxAmount}
                    onChange={e => setTrxAmount(e.target.value)}
                    placeholder="Contoh: 25000000"
                    required
                    className="w-full bg-[#081026] border border-[#1e293b] p-2 text-emerald-400 font-black text-sm rounded focus:outline-none focus:border-sky-400"
                  />
                  {numericTrxAmount > 0 && (
                    <span className="text-[10px] text-emerald-400 font-bold block mt-1">
                      Terbilang: {formatIDR(numericTrxAmount)}
                    </span>
                  )}
                </div>

                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                    Akun Kas / Bank Tujuan: *
                  </label>
                  <select
                    value={trxCashAccountId}
                    onChange={e => setTrxCashAccountId(e.target.value)}
                    className="w-full bg-[#081026] border border-[#1e293b] p-2 text-slate-200 font-bold rounded focus:outline-none focus:border-sky-400"
                  >
                    {cashAccounts.map(c => (
                      <option key={c.id} value={c.id}>
                        {c.code} - {c.name} ({formatIDR(c.currentBalance)})
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                    Vendor / Customer / Penerima Dana: *
                  </label>
                  <input
                    type="text"
                    value={trxVendor}
                    onChange={e => setTrxVendor(e.target.value)}
                    placeholder="Contoh: PT Telkom Akses / AWS SG"
                    required
                    className="w-full bg-[#081026] border border-[#1e293b] p-2 text-slate-100 rounded focus:outline-none focus:border-sky-400"
                  />
                </div>

                <div>
                  <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                    No. Invoice / Kuitansi Referensi:
                  </label>
                  <input
                    type="text"
                    value={trxInvoiceRef}
                    onChange={e => setTrxInvoiceRef(e.target.value)}
                    placeholder="Contoh: INV-2026-9921"
                    className="w-full bg-[#081026] border border-[#1e293b] p-2 text-slate-100 rounded focus:outline-none focus:border-sky-400"
                  />
                </div>
              </div>

              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                  Keterangan & Rincian Pengajuan: *
                </label>
                <textarea
                  value={trxDescription}
                  onChange={e => setTrxDescription(e.target.value)}
                  rows={2}
                  placeholder="Jelaskan keperluan pembayaran / penerimaan ini secara mendetail..."
                  className="w-full bg-[#081026] border border-[#1e293b] p-2 text-slate-100 rounded focus:outline-none focus:border-sky-400"
                ></textarea>
              </div>

              <div className="flex justify-end gap-2 pt-3 border-t border-[#1e293b]">
                <button
                  type="button"
                  onClick={() => setIsVoucherModalOpen(false)}
                  className="px-4 py-2 bg-[#1e293b] text-slate-300 font-bold uppercase text-xs rounded hover:bg-slate-700"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-6 py-2 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-white font-black uppercase text-xs rounded flex items-center gap-1.5 shadow-lg shadow-sky-500/20"
                >
                  <Send className="w-4 h-4" />
                  Kirim Permohonan Transaksi
                </button>
              </div>

            </form>

          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* MODAL: MANUAL ADJUSTMENT JOURNAL                                          */}
      {/* ========================================================================= */}
      {isAdjModalOpen && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-[#0f172a] border-2 border-amber-500 max-w-2xl w-full p-6 rounded-2xl text-white space-y-4 shadow-2xl relative">
            
            <div className="flex items-center justify-between border-b border-[#1e293b] pb-3">
              <h3 className="text-base font-black uppercase text-amber-300 flex items-center gap-2">
                <FileSpreadsheet className="w-5 h-5 text-amber-400" />
                Form Input Jurnal Penyesuaian Manual (Adjustment Journal)
              </h3>
              <button
                onClick={() => setIsAdjModalOpen(false)}
                className="text-slate-400 hover:text-white p-1 rounded"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleCreateAdjustmentJournal} className="space-y-4 font-mono text-xs">
              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-300 mb-1">
                  Keterangan Jurnal Penyesuaian: *
                </label>
                <input
                  type="text"
                  value={adjDescription}
                  onChange={e => setAdjDescription(e.target.value)}
                  placeholder="Contoh: Jurnal penyesuaian penyusutan server & akrual beban listrik"
                  required
                  className="w-full bg-[#081026] border border-[#1e293b] p-2 text-slate-100 rounded focus:outline-none focus:border-amber-400"
                />
              </div>

              {/* Dynamic Journal Lines */}
              <div className="space-y-2 bg-[#081026] p-3 rounded-lg border border-[#1e293b]">
                <div className="flex items-center justify-between">
                  <span className="text-[10px] font-bold uppercase text-amber-300">Rincian Baris Debit & Kredit:</span>
                </div>

                {adjLines.map((line, idx) => (
                  <div key={idx} className="grid grid-cols-12 gap-2 items-center bg-[#0f172a] p-2 rounded border border-[#1e293b]">
                    <div className="col-span-5">
                      <input
                        type="text"
                        value={`${line.accountCode} - ${line.accountName}`}
                        onChange={e => {
                          const val = e.target.value;
                          const copy = [...adjLines];
                          copy[idx].accountName = val;
                          setAdjLines(copy);
                        }}
                        className="w-full bg-[#081026] border border-[#1e293b] p-1 text-[11px] text-slate-200 rounded"
                      />
                    </div>
                    <div className="col-span-3">
                      <input
                        type="number"
                        placeholder="Debet"
                        value={line.debit || ""}
                        onChange={e => {
                          const copy = [...adjLines];
                          copy[idx].debit = parseInt(e.target.value, 10) || 0;
                          setAdjLines(copy);
                        }}
                        className="w-full bg-[#081026] border border-[#1e293b] p-1 text-[11px] text-emerald-400 font-bold rounded text-right"
                      />
                    </div>
                    <div className="col-span-3">
                      <input
                        type="number"
                        placeholder="Kredit"
                        value={line.credit || ""}
                        onChange={e => {
                          const copy = [...adjLines];
                          copy[idx].credit = parseInt(e.target.value, 10) || 0;
                          setAdjLines(copy);
                        }}
                        className="w-full bg-[#081026] border border-[#1e293b] p-1 text-[11px] text-sky-300 font-bold rounded text-right"
                      />
                    </div>
                  </div>
                ))}
              </div>

              <div className="flex justify-end gap-2 pt-3 border-t border-[#1e293b]">
                <button
                  type="button"
                  onClick={() => setIsAdjModalOpen(false)}
                  className="px-4 py-2 bg-[#1e293b] text-slate-300 font-bold uppercase text-xs rounded hover:bg-slate-700"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-6 py-2 bg-amber-500 hover:bg-amber-400 text-black font-black uppercase text-xs rounded flex items-center gap-1.5 shadow-lg shadow-amber-500/20"
                >
                  <CheckCircle2 className="w-4 h-4" />
                  Simpan Jurnal Adjustment
                </button>
              </div>

            </form>

          </div>
        </div>
      )}

      {/* ========================================================================= */}
      {/* MODAL: VIEW TRANSACTION DETAIL & AUDIT LOG                                */}
      {/* ========================================================================= */}
      {viewingTrx && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-[#0f172a] border-2 border-sky-500 max-w-xl w-full p-6 rounded-2xl text-white space-y-4 shadow-2xl relative font-mono text-xs">
            
            <div className="flex items-center justify-between border-b border-[#1e293b] pb-3">
              <div>
                <h3 className="text-base font-black uppercase text-sky-300">{viewingTrx.voucherNo}</h3>
                <span className="text-[10px] text-slate-400">Dibuat tanggal: {viewingTrx.transactionDate}</span>
              </div>
              <button
                onClick={() => setViewingTrx(null)}
                className="text-slate-400 hover:text-white p-1 rounded"
              >
                ✕
              </button>
            </div>

            <div className="space-y-2 bg-[#081026] p-4 rounded-lg border border-[#1e293b]">
              <div className="flex justify-between border-b border-[#1e293b] pb-1.5">
                <span className="text-slate-400">Jenis Transaksi:</span>
                <span className="font-bold text-emerald-400">{viewingTrx.transactionType}</span>
              </div>
              <div className="flex justify-between border-b border-[#1e293b] pb-1.5">
                <span className="text-slate-400">Pemohon / Divisi:</span>
                <span className="font-bold text-slate-200">{viewingTrx.requesterName} ({viewingTrx.division})</span>
              </div>
              <div className="flex justify-between border-b border-[#1e293b] pb-1.5">
                <span className="text-slate-400">Mata Anggaran:</span>
                <span className="font-bold text-sky-300">{viewingTrx.budgetCode} - {viewingTrx.budgetName}</span>
              </div>
              <div className="flex justify-between border-b border-[#1e293b] pb-1.5">
                <span className="text-slate-400">Vendor / Penerima:</span>
                <span className="font-bold text-slate-100">{viewingTrx.recipientVendor}</span>
              </div>
              <div className="flex justify-between border-b border-[#1e293b] pb-1.5">
                <span className="text-slate-400">Nominal Rp:</span>
                <span className="font-black text-emerald-400 text-sm">{formatIDR(viewingTrx.amount)}</span>
              </div>
            </div>

            <div className="space-y-1">
              <label className="text-[10px] uppercase font-bold text-slate-400">Deskripsi & Keterangan:</label>
              <p className="bg-[#081026] p-3 rounded border border-[#1e293b] text-slate-200">{viewingTrx.description}</p>
            </div>

            {/* Approval History Logs */}
            <div className="space-y-2 border-t border-[#1e293b] pt-3">
              <h4 className="text-[10px] font-bold uppercase text-slate-400">Riwayat Workflow & Approval SAP:</h4>
              
              {viewingTrx.budgetApproval && (
                <div className="bg-[#081026] p-2.5 rounded border border-emerald-500/30 text-[11px] space-y-1">
                  <span className="font-bold text-emerald-400 block">✓ Approval Divisi Anggaran</span>
                  <p className="text-slate-300">Oleh: {viewingTrx.budgetApproval.approverName} ({viewingTrx.budgetApproval.date})</p>
                  <p className="text-slate-400 text-[10px]">Catatan: {viewingTrx.budgetApproval.notes}</p>
                </div>
              )}

              {viewingTrx.accountingApproval && (
                <div className="bg-[#081026] p-2.5 rounded border border-sky-500/30 text-[11px] space-y-1">
                  <span className="font-bold text-sky-300 block">✓ Posting Divisi Akuntansi</span>
                  <p className="text-slate-300">Oleh: {viewingTrx.accountingApproval.approverName} ({viewingTrx.accountingApproval.date})</p>
                  <p className="text-sky-400 text-[10px]">No. Jurnal SAP: {viewingTrx.accountingApproval.journalNo}</p>
                </div>
              )}
            </div>

            <div className="flex justify-end pt-2">
              <button
                onClick={() => setViewingTrx(null)}
                className="px-4 py-2 bg-[#1e293b] text-slate-300 font-bold uppercase text-xs rounded hover:bg-slate-700"
              >
                Tutup
              </button>
            </div>

          </div>
        </div>
      )}

    </div>
  );
}
