import React, { useState, useMemo } from "react";
import { 
  Calculator, 
  Plus, 
  Trash2, 
  TrendingUp, 
  Building2, 
  FileSpreadsheet, 
  DollarSign, 
  PieChart, 
  Send, 
  CheckCircle2, 
  Sparkles,
  Layers,
  ArrowDownRight,
  ArrowUpRight,
  Calendar,
  AlertCircle,
  Users,
  Sliders,
  Check,
  RefreshCw
} from "lucide-react";
import { WorkflowRequest, BudgetItem, Employee } from "../types";
import { INITIAL_BUDGET_ITEMS, INITIAL_EMPLOYEES } from "../data";
import { BudgetDivisionModule } from "./BudgetDivisionModule";

interface RkapModuleProps {
  onCreateWorkflow?: (request: Partial<WorkflowRequest>) => void;
}

export interface CoaAccount {
  code: string;
  name: string;
  category: "Pendapatan" | "Beban Operasional" | "Belanja Modal (CAPEX)";
}

export interface ActionPlanItem {
  id: string;
  directorate: "Direktorat Operasional (COO)" | "Direktorat Keuangan (CFO)" | "Direktorat IT (CTO)" | "Direktorat Human Resources (CHR)" | "Executive Office (CEO)";
  programName: string;
  kpiTarget: string;
  timeline: "Q1" | "Q2" | "Q3" | "Q4" | "Sepanjang Tahun (Q1-Q4)";
  coaCode: string;
  q1Amount: number;
  q2Amount: number;
  q3Amount: number;
  q4Amount: number;
  notes: string;
}

export interface SalaryGradeDivision {
  id: string;
  divisionName: string;
  directorate: string;
  headcount: number;
  currentBaseSalary: number; // per month per employee
  proposedRaisePercent: number; // % adjustment
  allowanceMultiplierPercent: number; // BPJS + Tunjangan %
  thrBonusMultiplier: number; // Months of salary for THR/Bonus
}

export const COA_LIST: CoaAccount[] = [
  // Pendapatan
  { code: "4-1001", name: "Pendapatan Sewa Aplikasi Web & Cloud ERP", category: "Pendapatan" },
  { code: "4-1002", name: "Pendapatan Jasa Custom Development & Integrasi API", category: "Pendapatan" },
  { code: "4-1003", name: "Pendapatan SLA Maintenance & Support System", category: "Pendapatan" },
  
  // Beban Operasional (OPEX)
  { code: "5-1001", name: "Beban Gaji, Tunjangan & Kesejahteraan Pegawai", category: "Beban Operasional" },
  { code: "5-1002", name: "Beban Server Cloud AWS/GCP & Infrastructure Web", category: "Beban Operasional" },
  { code: "5-1003", name: "Beban Lisensi Software, API Services & Network", category: "Beban Operasional" },
  { code: "5-1004", name: "Beban Marketing, Ads Digital & PR Corporate", category: "Beban Operasional" },
  { code: "5-1005", name: "Beban Legal, Perizinan & Hukum Perseroan", category: "Beban Operasional" },
  { code: "5-1006", name: "Beban General Affair (GA), Listrik, Air & Operasional", category: "Beban Operasional" },
  { code: "5-1007", name: "Beban Pelatihan, Rekrutmen & Sertifikasi SDM", category: "Beban Operasional" },
  { code: "5-1008", name: "Beban Perjalanan Dinas & Transportasi Direksi/Staff", category: "Beban Operasional" },
  { code: "5-1009", name: "Beban Jasa Profesional, Audit & Pajak Perusahaan", category: "Beban Operasional" },

  // Belanja Modal (CAPEX)
  { code: "1-2001", name: "CAPEX: Pengadaan Hardware Server & Network Gear", category: "Belanja Modal (CAPEX)" },
  { code: "1-2002", name: "CAPEX: Pengembangan Asset Intangible (R&D System)", category: "Belanja Modal (CAPEX)" },
  { code: "1-2003", name: "CAPEX: Inventaris Kantor, Komputer & Fasilitas GA", category: "Belanja Modal (CAPEX)" },
];

export const INITIAL_ACTION_PLANS: ActionPlanItem[] = [
  {
    id: "ap-01",
    directorate: "Direktorat Operasional (COO)",
    programName: "Ekspansi Pemasaran & Penjualan Sewa Aplikasi Web Cloud",
    kpiTarget: "Penambahan 15 Klien Perusahaan Baru",
    timeline: "Sepanjang Tahun (Q1-Q4)",
    coaCode: "4-1001",
    q1Amount: 150000000,
    q2Amount: 200000000,
    q3Amount: 250000000,
    q4Amount: 300000000,
    notes: "Target arus kas masuk utama dari core bisnis sewa aplikasi web EMD."
  },
  {
    id: "ap-02",
    directorate: "Direktorat IT (CTO)",
    programName: "Upgrade Infrastruktur Cloud Server High-Availability & Security Load Balancer",
    kpiTarget: "System Uptime 99.95% & zero downtime",
    timeline: "Q1",
    coaCode: "5-1002",
    q1Amount: 35000000,
    q2Amount: 35000000,
    q3Amount: 35000000,
    q4Amount: 35000000,
    notes: "Beban operasional server bulanan untuk menjaga stabilitas aplikasi sewa."
  },
  {
    id: "ap-03",
    directorate: "Direktorat IT (CTO)",
    programName: "CAPEX Pengadaan Server Bare-metal Dedicated & Network Switch",
    kpiTarget: "Kapasitas server meningkat 3x lipat",
    timeline: "Q2",
    coaCode: "1-2001",
    q1Amount: 0,
    q2Amount: 85000000,
    q3Amount: 0,
    q4Amount: 0,
    notes: "Pengeluaran belanja modal IT untuk pengadaan perangkat fisik."
  },
  {
    id: "ap-04",
    directorate: "Direktorat Human Resources (CHR)",
    programName: "Penggajian, BPJS, Tunjangan & Program Retensi Karyawan All Directorate",
    kpiTarget: "Tingkat Retensi Pegawai > 95%",
    timeline: "Sepanjang Tahun (Q1-Q4)",
    coaCode: "5-1001",
    q1Amount: 120000000,
    q2Amount: 125000000,
    q3Amount: 125000000,
    q4Amount: 130000000,
    notes: "Termasuk estimasi THR di Q2 dan bonus akhir tahun di Q4."
  },
  {
    id: "ap-05",
    directorate: "Direktorat Operasional (COO)",
    programName: "Kampanye Marketing Digital & Legal Corporate Perizinan App",
    kpiTarget: "Brand awareness & kepatuhan regulasi 100%",
    timeline: "Q1",
    coaCode: "5-1004",
    q1Amount: 20000000,
    q2Amount: 15000000,
    q3Amount: 15000000,
    q4Amount: 25000000,
    notes: "Beban iklan Meta/Google Ads dan konsultan hukum."
  },
  {
    id: "ap-06",
    directorate: "Direktorat Keuangan (CFO)",
    programName: "Audit Laporan Keuangan Independen & Konsultasi Perpajakan",
    kpiTarget: "Laporan Keuangan WTP (Wajar Tanpa Pengecualian)",
    timeline: "Q4",
    coaCode: "5-1009",
    q1Amount: 10000000,
    q2Amount: 10000000,
    q3Amount: 10000000,
    q4Amount: 30000000,
    notes: "Beban jasa KAP dan konsultan pajak tahunan."
  }
];

export const INITIAL_SALARY_DIVISIONS: SalaryGradeDivision[] = [
  {
    id: "sal-1",
    divisionName: "Executive Office (Bambang Hartono, Hendra, Maya)",
    directorate: "Executive Office (CEO)",
    headcount: 3,
    currentBaseSalary: 22000000,
    proposedRaisePercent: 5,
    allowanceMultiplierPercent: 20,
    thrBonusMultiplier: 2
  },
  {
    id: "sal-2",
    divisionName: "Developer & Maintenance (Budi, Eko, Rina, Sigit, Wisnu)",
    directorate: "Direktorat IT (CTO)",
    headcount: 5,
    currentBaseSalary: 12500000,
    proposedRaisePercent: 8,
    allowanceMultiplierPercent: 15,
    thrBonusMultiplier: 1.5
  },
  {
    id: "sal-3",
    divisionName: "Core Bisnis (Sewa Web & Dev Custom - Dewi, Farhan)",
    directorate: "Direktorat Operasional (COO)",
    headcount: 4,
    currentBaseSalary: 10000000,
    proposedRaisePercent: 5,
    allowanceMultiplierPercent: 15,
    thrBonusMultiplier: 1.5
  },
  {
    id: "sal-4",
    divisionName: "Bendahara, Akuntansi & Perpajakan (Siti, Agus)",
    directorate: "Direktorat Keuangan (CFO)",
    headcount: 3,
    currentBaseSalary: 9000000,
    proposedRaisePercent: 5,
    allowanceMultiplierPercent: 15,
    thrBonusMultiplier: 1.25
  },
  {
    id: "sal-5",
    divisionName: "Payroll, Rekrutmen & HR (Nita, Gilang)",
    directorate: "Direktorat Human Resources (CHR)",
    headcount: 2,
    currentBaseSalary: 8500000,
    proposedRaisePercent: 6,
    allowanceMultiplierPercent: 15,
    thrBonusMultiplier: 1.25
  },
  {
    id: "sal-6",
    divisionName: "Marketing & Legal Corporate (Diana, Tari)",
    directorate: "Direktorat Operasional (COO)",
    headcount: 2,
    currentBaseSalary: 8000000,
    proposedRaisePercent: 5,
    allowanceMultiplierPercent: 12,
    thrBonusMultiplier: 1.0
  },
  {
    id: "sal-7",
    divisionName: "General Affair (GA) & Sarpras (Joko, Rudi)",
    directorate: "Direktorat Operasional (COO)",
    headcount: 2,
    currentBaseSalary: 6500000,
    proposedRaisePercent: 5,
    allowanceMultiplierPercent: 12,
    thrBonusMultiplier: 1.0
  }
];

export default function RkapModule({ onCreateWorkflow }: RkapModuleProps) {
  const [fiscalYear, setFiscalYear] = useState(2027);
  const [initialCashBalance, setInitialCashBalance] = useState(150000000); // Initial Cash Rp 150 jt
  const [actionPlans, setActionPlans] = useState<ActionPlanItem[]>(INITIAL_ACTION_PLANS);
  const [activeTab, setActiveTab] = useState<"plans" | "matrix" | "salary_sim" | "cashflow" | "budget_division">("plans");
  const [submittedToWorkflow, setSubmittedToWorkflow] = useState(false);
  const [salaryAppliedNotif, setSalaryAppliedNotif] = useState(false);

  // Budget Division Items State
  const [budgetItems, setBudgetItems] = useState<BudgetItem[]>(INITIAL_BUDGET_ITEMS);

  // Salary Simulation Divisions State
  const [salaryDivisions, setSalaryDivisions] = useState<SalaryGradeDivision[]>(INITIAL_SALARY_DIVISIONS);

  // Form State for Adding New Action Plan
  const [newDir, setNewDir] = useState<ActionPlanItem["directorate"]>("Direktorat Operasional (COO)");
  const [newProgram, setNewProgram] = useState("");
  const [newKpi, setNewKpi] = useState("");
  const [newTimeline, setNewTimeline] = useState<ActionPlanItem["timeline"]>("Sepanjang Tahun (Q1-Q4)");
  const [newCoa, setNewCoa] = useState("5-1002");
  const [newQ1, setNewQ1] = useState("");
  const [newQ2, setNewQ2] = useState("");
  const [newQ3, setNewQ3] = useState("");
  const [newQ4, setNewQ4] = useState("");
  const [newNotes, setNewNotes] = useState("");

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

  // Add Action Plan Handler
  const handleAddPlan = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newProgram || !newCoa) return;

    const item: ActionPlanItem = {
      id: `ap-${Date.now()}`,
      directorate: newDir,
      programName: newProgram,
      kpiTarget: newKpi || "Target KPI Kinerja",
      timeline: newTimeline,
      coaCode: newCoa,
      q1Amount: parseFloat(newQ1) || 0,
      q2Amount: parseFloat(newQ2) || 0,
      q3Amount: parseFloat(newQ3) || 0,
      q4Amount: parseFloat(newQ4) || 0,
      notes: newNotes || "-"
    };

    setActionPlans(prev => [...prev, item]);
    setNewProgram("");
    setNewKpi("");
    setNewQ1("");
    setNewQ2("");
    setNewQ3("");
    setNewQ4("");
    setNewNotes("");
  };

  // Delete Action Plan
  const handleDeletePlan = (id: string) => {
    setActionPlans(prev => prev.filter(p => p.id !== id));
  };

  // Salary Simulation Calculations
  const salarySimSummary = useMemo(() => {
    let baselineMonthlyTotal = 0;
    let baselineYearlyTotal = 0;
    let simMonthlyTotal = 0;
    let simYearlyTotal = 0;
    let totalHeadcount = 0;

    salaryDivisions.forEach(div => {
      totalHeadcount += div.headcount;

      // Baseline Calculation
      const baseMonthlyPerPerson = div.currentBaseSalary * (1 + div.allowanceMultiplierPercent / 100);
      const baseMonthlyDiv = baseMonthlyPerPerson * div.headcount;
      const baseYearlyDiv = (baseMonthlyDiv * 12) + (div.headcount * div.currentBaseSalary * div.thrBonusMultiplier);

      baselineMonthlyTotal += baseMonthlyDiv;
      baselineYearlyTotal += baseYearlyDiv;

      // Simulated Calculation with raise
      const simBaseSalary = div.currentBaseSalary * (1 + div.proposedRaisePercent / 100);
      const simMonthlyPerPerson = simBaseSalary * (1 + div.allowanceMultiplierPercent / 100);
      const simMonthlyDiv = simMonthlyPerPerson * div.headcount;
      const simYearlyDiv = (simMonthlyDiv * 12) + (div.headcount * simBaseSalary * div.thrBonusMultiplier);

      simMonthlyTotal += simMonthlyDiv;
      simYearlyTotal += simYearlyDiv;
    });

    const yearlyImpact = simYearlyTotal - baselineYearlyTotal;
    const monthlyImpact = simMonthlyTotal - baselineMonthlyTotal;
    const percentageChange = baselineYearlyTotal > 0 ? (yearlyImpact / baselineYearlyTotal) * 100 : 0;

    return {
      baselineMonthlyTotal,
      baselineYearlyTotal,
      simMonthlyTotal,
      simYearlyTotal,
      yearlyImpact,
      monthlyImpact,
      percentageChange,
      totalHeadcount
    };
  }, [salaryDivisions]);

  // Update Salary Division
  const handleUpdateSalaryDivision = (id: string, field: keyof SalaryGradeDivision, value: number) => {
    setSalaryDivisions(prev => prev.map(item => {
      if (item.id === id) {
        return { ...item, [field]: value };
      }
      return item;
    }));
  };

  // Apply Simulation to Action Plan 5-1001 (Beban Gaji & Tunjangan)
  const handleApplySalaryToRkap = () => {
    const totalSimulatedYearly = salarySimSummary.simYearlyTotal;
    // Distribute across Q1, Q2 (with THR), Q3, Q4 (with bonus)
    // Q1: 3 months salary
    // Q2: 3 months salary + 50% THR
    // Q3: 3 months salary
    // Q4: 3 months salary + 50% THR/Bonus
    const q1Amount = Math.round(salarySimSummary.simMonthlyTotal * 3);
    const q2Amount = Math.round(salarySimSummary.simMonthlyTotal * 3 + (totalSimulatedYearly - salarySimSummary.simMonthlyTotal * 12) * 0.5);
    const q3Amount = Math.round(salarySimSummary.simMonthlyTotal * 3);
    const q4Amount = Math.round(salarySimSummary.simMonthlyTotal * 3 + (totalSimulatedYearly - salarySimSummary.simMonthlyTotal * 12) * 0.5);

    setActionPlans(prev => {
      const existing = prev.find(p => p.coaCode === "5-1001");
      if (existing) {
        return prev.map(p => p.coaCode === "5-1001" ? {
          ...p,
          q1Amount,
          q2Amount,
          q3Amount,
          q4Amount,
          notes: `Anggaran Gaji Terkalkulasi Hasil Simulasi HR Pay Grade (${salarySimSummary.totalHeadcount} Pegawai, Kenaikan Rata-rata ${salarySimSummary.percentageChange.toFixed(1)}%)`
        } : p);
      } else {
        return [
          ...prev,
          {
            id: `ap-sal-${Date.now()}`,
            directorate: "Direktorat Human Resources (CHR)",
            programName: "Penggajian, BPJS, Tunjangan & Program Retensi Karyawan All Directorate (Simulasi HR)",
            kpiTarget: "Tingkat Retensi Pegawai > 95%",
            timeline: "Sepanjang Tahun (Q1-Q4)",
            coaCode: "5-1001",
            q1Amount,
            q2Amount,
            q3Amount,
            q4Amount,
            notes: `Anggaran Gaji Terkalkulasi Hasil Simulasi HR Pay Grade (${salarySimSummary.totalHeadcount} Pegawai)`
          }
        ];
      }
    });

    setSalaryAppliedNotif(true);
    setTimeout(() => setSalaryAppliedNotif(false), 4000);
  };

  // Calculate Cash Flow Aggregation
  const cashFlowSummary = useMemo(() => {
    let q1In = 0, q2In = 0, q3In = 0, q4In = 0;
    let q1Opex = 0, q2Opex = 0, q3Opex = 0, q4Opex = 0;
    let q1Capex = 0, q2Capex = 0, q3Capex = 0, q4Capex = 0;

    actionPlans.forEach(plan => {
      const coaMeta = COA_LIST.find(c => c.code === plan.coaCode);
      const cat = coaMeta?.category || "Beban Operasional";

      if (cat === "Pendapatan") {
        q1In += plan.q1Amount;
        q2In += plan.q2Amount;
        q3In += plan.q3Amount;
        q4In += plan.q4Amount;
      } else if (cat === "Belanja Modal (CAPEX)") {
        q1Capex += plan.q1Amount;
        q2Capex += plan.q2Amount;
        q3Capex += plan.q3Amount;
        q4Capex += plan.q4Amount;
      } else {
        // Beban Operasional
        q1Opex += plan.q1Amount;
        q2Opex += plan.q2Amount;
        q3Opex += plan.q3Amount;
        q4Opex += plan.q4Amount;
      }
    });

    const totalIn = q1In + q2In + q3In + q4In;
    const totalOpex = q1Opex + q2Opex + q3Opex + q4Opex;
    const totalCapex = q1Capex + q2Capex + q3Capex + q4Capex;
    const totalOut = totalOpex + totalCapex;
    const netCashFlow = totalIn - totalOut;
    const endingCash = initialCashBalance + netCashFlow;

    // Per quarter net
    const q1Net = q1In - (q1Opex + q1Capex);
    const q1End = initialCashBalance + q1Net;

    const q2Net = q2In - (q2Opex + q2Capex);
    const q2End = q1End + q2Net;

    const q3Net = q3In - (q3Opex + q3Capex);
    const q3End = q2End + q3Net;

    const q4Net = q4In - (q4Opex + q4Capex);
    const q4End = q3End + q4Net;

    return {
      q1In, q2In, q3In, q4In, totalIn,
      q1Opex, q2Opex, q3Opex, q4Opex, totalOpex,
      q1Capex, q2Capex, q3Capex, q4Capex, totalCapex,
      totalOut, netCashFlow, endingCash,
      q1Net, q1End,
      q2Net, q2End,
      q3Net, q3End,
      q4Net, q4End
    };
  }, [actionPlans, initialCashBalance]);

  // Submit Draft to Workflow Engine
  const handleSubmitToWorkflow = () => {
    if (onCreateWorkflow) {
      onCreateWorkflow({
        title: `Draft RKAP Tahun ${fiscalYear} - Pengesahan Cash Flow & Budget Direktorat`,
        type: "Kegiatan Direktorat",
        description: `Draft Rencana Kerja & Anggaran Perusahaan (RKAP) Tahun ${fiscalYear}.\nTotal Target Pendapatan: ${formatIdr(cashFlowSummary.totalIn)}\nTotal Outflow (OPEX+CAPEX): ${formatIdr(cashFlowSummary.totalOut)}\nProyeksi Net Cash Flow: ${formatIdr(cashFlowSummary.netCashFlow)}\nEstimasi Saldo Kas Akhir: ${formatIdr(cashFlowSummary.endingCash)}`,
        amount: formatIdr(cashFlowSummary.totalOut),
        budgetAmount: formatIdr(cashFlowSummary.totalOut),
        directorate: "Direktorat Keuangan (CFO)",
        hrServiceType: "N/A",
        hrServiceStatus: "Tidak Perlu",
        budgetStatus: "Perlu Otorisasi CFO",
        financeAuthStatus: "Verifikasi Budget OK",
        financeNotes: `Draft RKAP dikalkulasi berdasarkan ${actionPlans.length} Action Plan direktorat & simulasi gaji HR.`
      });
    }
    setSubmittedToWorkflow(true);
  };

  return (
    <div className="space-y-4 sm:space-y-6 animate-fadeIn">
      {/* Module Banner */}
      <div className="flex flex-col md:flex-row md:items-end justify-between border-b border-[#1e3a8a]/60 pb-4 sm:pb-6 gap-3">
        <div>
          <div className="flex items-center gap-2 mb-1 flex-wrap">
            <span className="text-[9px] sm:text-[10px] uppercase tracking-wider text-sky-300 font-bold bg-sky-950/80 px-2 py-0.5 border border-sky-500/30 rounded">
              Perencanaan Anggaran Tahun {fiscalYear}
            </span>
            <span className="text-[9px] sm:text-[10px] uppercase tracking-wider text-slate-400 font-mono">
              Consolidated Cash Flow & Payroll Engine
            </span>
          </div>
          <h2 className="text-xl sm:text-2xl md:text-3xl font-extrabold text-white uppercase tracking-tight leading-tight bg-gradient-to-r from-sky-400 via-blue-200 to-white bg-clip-text text-transparent">
            Draft Penyusunan RKAP & Cash Flow
          </h2>
          <p className="text-[10px] sm:text-xs text-slate-400 font-mono mt-1">
            MEDIAN PT MEDIA EKOSISTEM DIGITAL APLIKASI NASIONAL • Action Plan, Matriks COA, Simulasi Gaji HR & Arus Kas Konsolidasi
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-2 sm:gap-3">
          <div className="flex items-center gap-1.5 bg-[#0f172a] border border-[#1e3a8a]/60 px-2.5 py-1 sm:px-3 sm:py-1.5 rounded-lg text-[10px] sm:text-xs font-mono">
            <Calendar className="w-3.5 h-3.5 text-sky-400" />
            <span className="text-slate-300 uppercase font-bold">Tahun RKAP:</span>
            <select 
              value={fiscalYear} 
              onChange={e => setFiscalYear(Number(e.target.value))}
              className="bg-[#0b132b] text-white font-bold focus:outline-none cursor-pointer rounded px-1"
            >
              <option value={2026}>2026</option>
              <option value={2027}>2027</option>
              <option value={2028}>2028</option>
            </select>
          </div>

          <div className="flex items-center gap-1.5 bg-[#0f172a] border border-[#1e3a8a]/60 px-2.5 py-1 sm:px-3 sm:py-1.5 rounded-lg text-[10px] sm:text-xs font-mono">
            <DollarSign className="w-3.5 h-3.5 text-emerald-400" />
            <span className="text-slate-300 uppercase font-bold">Kas Awal:</span>
            <input 
              type="number" 
              value={initialCashBalance}
              onChange={e => setInitialCashBalance(Number(e.target.value) || 0)}
              className="w-24 sm:w-28 bg-[#0b132b] text-emerald-400 font-bold focus:outline-none rounded px-1"
            />
          </div>

          <button
            onClick={handleSubmitToWorkflow}
            disabled={submittedToWorkflow}
            className={`text-[10px] sm:text-xs font-bold uppercase tracking-wider px-3.5 py-1.5 sm:px-4 sm:py-2 rounded-lg flex items-center gap-1.5 transition-all shadow-md ${
              submittedToWorkflow 
                ? "bg-emerald-600 text-white cursor-default" 
                : "bg-gradient-to-r from-blue-600 to-sky-500 hover:from-blue-500 hover:to-sky-400 text-white shadow-blue-500/20"
            }`}
          >
            {submittedToWorkflow ? (
              <>
                <CheckCircle2 className="w-3.5 h-3.5 text-white" />
                <span>RKAP Terkirim Ke Workflow</span>
              </>
            ) : (
              <>
                <Send className="w-3.5 h-3.5 text-sky-200" />
                <span>Ajukan RKAP Ke CEO</span>
              </>
            )}
          </button>
        </div>
      </div>

      {/* RKAP Executive KPI Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-4">
        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3 sm:p-4 space-y-1">
          <div className="flex items-center justify-between text-[10px] sm:text-xs text-slate-400 font-mono uppercase">
            <span>Cash Inflow</span>
            <ArrowUpRight className="w-3.5 h-3.5 text-emerald-400" />
          </div>
          <p className="text-base sm:text-lg font-bold text-emerald-400 font-mono tracking-tight">
            {formatIdr(cashFlowSummary.totalIn)}
          </p>
          <p className="text-[9px] sm:text-[10px] text-slate-400 font-mono">Pendapatan Sewa & Custom Dev</p>
        </div>

        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3 sm:p-4 space-y-1">
          <div className="flex items-center justify-between text-[10px] sm:text-xs text-slate-400 font-mono uppercase">
            <span>Total Outflow</span>
            <ArrowDownRight className="w-3.5 h-3.5 text-rose-400" />
          </div>
          <p className="text-base sm:text-lg font-bold text-rose-400 font-mono tracking-tight">
            {formatIdr(cashFlowSummary.totalOut)}
          </p>
          <p className="text-[9px] sm:text-[10px] text-slate-400 font-mono">OPEX: {formatIdr(cashFlowSummary.totalOpex)} | CAPEX: {formatIdr(cashFlowSummary.totalCapex)}</p>
        </div>

        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3 sm:p-4 space-y-1">
          <div className="flex items-center justify-between text-[10px] sm:text-xs text-slate-400 font-mono uppercase">
            <span>Net Cash Flow</span>
            <TrendingUp className="w-3.5 h-3.5 text-sky-400" />
          </div>
          <p className={`text-base sm:text-lg font-bold font-mono tracking-tight ${cashFlowSummary.netCashFlow >= 0 ? 'text-sky-300' : 'text-rose-400'}`}>
            {formatIdr(cashFlowSummary.netCashFlow)}
          </p>
          <p className="text-[9px] sm:text-[10px] text-slate-400 font-mono">Arus Kas Bersih 1 Tahun</p>
        </div>

        <div className="bg-[#0f172a]/90 border border-[#1e3a8a]/60 rounded-xl p-3 sm:p-4 space-y-1">
          <div className="flex items-center justify-between text-[10px] sm:text-xs text-slate-400 font-mono uppercase">
            <span>Saldo Kas Akhir</span>
            <Building2 className="w-3.5 h-3.5 text-indigo-400" />
          </div>
          <p className="text-base sm:text-lg font-bold text-indigo-300 font-mono tracking-tight">
            {formatIdr(cashFlowSummary.endingCash)}
          </p>
          <p className="text-[9px] sm:text-[10px] text-slate-400 font-mono">Proyeksi Ending Cash {fiscalYear}</p>
        </div>
      </div>

      {/* Mode Sub-Navigation Tabs - Scrollable on mobile */}
      <div className="flex border-b border-[#1e3a8a]/60 bg-[#0f172a] rounded-xl overflow-x-auto no-scrollbar p-1 gap-1">
        <button
          onClick={() => setActiveTab("plans")}
          className={`px-3 py-2 sm:px-4 sm:py-2.5 text-[11px] sm:text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 rounded-lg transition-all whitespace-nowrap ${
            activeTab === "plans" 
              ? "bg-gradient-to-r from-blue-600 to-sky-500 text-white shadow-md shadow-blue-500/20" 
              : "text-slate-300 hover:text-white hover:bg-slate-800/50"
          }`}
        >
          <Layers className="w-3.5 h-3.5" />
          <span>1. Action Plan Direktorat ({actionPlans.length})</span>
        </button>

        <button
          onClick={() => setActiveTab("matrix")}
          className={`px-3 py-2 sm:px-4 sm:py-2.5 text-[11px] sm:text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 rounded-lg transition-all whitespace-nowrap ${
            activeTab === "matrix" 
              ? "bg-gradient-to-r from-blue-600 to-sky-500 text-white shadow-md shadow-blue-500/20" 
              : "text-slate-300 hover:text-white hover:bg-slate-800/50"
          }`}
        >
          <FileSpreadsheet className="w-3.5 h-3.5" />
          <span>2. Matriks Kode Akuntansi (COA)</span>
        </button>

        <button
          onClick={() => setActiveTab("salary_sim")}
          className={`px-3 py-2 sm:px-4 sm:py-2.5 text-[11px] sm:text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 rounded-lg transition-all whitespace-nowrap relative ${
            activeTab === "salary_sim" 
              ? "bg-gradient-to-r from-blue-600 to-sky-500 text-white shadow-md shadow-blue-500/20" 
              : "text-slate-300 hover:text-white hover:bg-slate-800/50"
          }`}
        >
          <Sliders className="w-3.5 h-3.5 text-sky-300" />
          <span>3. Simulasi Gaji & Pay Grade HR</span>
          <span className="w-2 h-2 rounded-full bg-sky-400 animate-pulse"></span>
        </button>

        <button
          onClick={() => setActiveTab("cashflow")}
          className={`px-3 py-2 sm:px-4 sm:py-2.5 text-[11px] sm:text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 rounded-lg transition-all whitespace-nowrap ${
            activeTab === "cashflow" 
              ? "bg-gradient-to-r from-blue-600 to-sky-500 text-white shadow-md shadow-blue-500/20" 
              : "text-slate-300 hover:text-white hover:bg-slate-800/50"
          }`}
        >
          <PieChart className="w-3.5 h-3.5" />
          <span>4. Rangkuman Cash Flow Perusahaan</span>
        </button>

        <button
          onClick={() => setActiveTab("budget_division")}
          className={`px-3 py-2 sm:px-4 sm:py-2.5 text-[11px] sm:text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 rounded-lg transition-all whitespace-nowrap ${
            activeTab === "budget_division" 
              ? "bg-[#facc15] text-black font-extrabold shadow-md shadow-yellow-500/20" 
              : "text-[#facc15] hover:bg-yellow-500/10 border border-[#facc15]/30"
          }`}
        >
          <Calculator className="w-3.5 h-3.5" />
          <span>5. Divisi Anggaran & Presets Bisnis Client</span>
        </button>
      </div>

      {/* TAB 5: DIVISI ANGGARAN & PRESETS INDUSTRI BISNIS */}
      {activeTab === "budget_division" && (
        <BudgetDivisionModule
          currentUser={INITIAL_EMPLOYEES[0]}
          budgetItems={budgetItems}
          onUpdateBudgetItems={setBudgetItems}
        />
      )}

      {/* TAB 1: ACTION PLAN & BUDGET INPUT FORM & TABLE */}
      {activeTab === "plans" && (
        <div className="space-y-4 sm:space-y-6">
          {/* Action Plan Composer Form */}
          <div className="bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-4 sm:p-5 space-y-4">
            <div className="flex items-center justify-between border-b border-[#1e3a8a]/60 pb-3">
              <div className="flex items-center gap-2">
                <Calculator className="w-4 h-4 text-sky-400" />
                <h3 className="text-xs sm:text-sm font-bold text-white uppercase tracking-wider">
                  Form Tambah Action Plan & Anggaran Direktorat
                </h3>
              </div>
              <span className="text-[10px] font-mono text-slate-400 hidden sm:inline">
                Pilih Kode Akuntansi (COA) & Distribusi Triwulan (Q1-Q4)
              </span>
            </div>

            <form onSubmit={handleAddPlan} className="space-y-3 sm:space-y-4 text-xs font-mono">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4">
                {/* Direktorat Selector */}
                <div>
                  <label className="block font-bold uppercase text-slate-300 mb-1 text-[10px] sm:text-[11px]">
                    Direktorat Pengampu <span className="text-rose-400">*</span>
                  </label>
                  <select 
                    value={newDir} 
                    onChange={e => setNewDir(e.target.value as any)}
                    className="w-full bg-[#0b132b] border border-[#1e3a8a] text-white focus:border-sky-400 rounded-lg px-3 py-2 text-xs"
                  >
                    <option value="Direktorat Operasional (COO)">Direktorat Operasional (COO)</option>
                    <option value="Direktorat Keuangan (CFO)">Direktorat Keuangan (CFO)</option>
                    <option value="Direktorat IT (CTO)">Direktorat IT (CTO)</option>
                    <option value="Direktorat Human Resources (CHR)">Direktorat Human Resources (CHR)</option>
                    <option value="Executive Office (CEO)">Executive Office (CEO)</option>
                  </select>
                </div>

                {/* Mata Anggaran / COA Dropdown */}
                <div>
                  <label className="block font-bold uppercase text-slate-300 mb-1 text-[10px] sm:text-[11px]">
                    Mata Anggaran / Kode Akuntansi (COA) <span className="text-rose-400">*</span>
                  </label>
                  <select 
                    value={newCoa} 
                    onChange={e => setNewCoa(e.target.value)}
                    className="w-full bg-[#0b132b] border border-[#1e3a8a] text-sky-300 font-bold focus:border-sky-400 rounded-lg px-3 py-2 text-xs"
                  >
                    {COA_LIST.map(c => (
                      <option key={c.code} value={c.code}>
                        [{c.code}] {c.name} ({c.category})
                      </option>
                    ))}
                  </select>
                </div>

                {/* Timeline Option */}
                <div>
                  <label className="block font-bold uppercase text-slate-300 mb-1 text-[10px] sm:text-[11px]">
                    Timeline Eksekusi
                  </label>
                  <select 
                    value={newTimeline} 
                    onChange={e => setNewTimeline(e.target.value as any)}
                    className="w-full bg-[#0b132b] border border-[#1e3a8a] text-white focus:border-sky-400 rounded-lg px-3 py-2 text-xs"
                  >
                    <option value="Sepanjang Tahun (Q1-Q4)">Sepanjang Tahun (Q1-Q4)</option>
                    <option value="Q1">Triwulan 1 (Q1)</option>
                    <option value="Q2">Triwulan 2 (Q2)</option>
                    <option value="Q3">Triwulan 3 (Q3)</option>
                    <option value="Q4">Triwulan 4 (Q4)</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4">
                <div>
                  <label className="block font-bold uppercase text-slate-300 mb-1 text-[10px] sm:text-[11px]">
                    Nama Program / Program Action Plan <span className="text-rose-400">*</span>
                  </label>
                  <input 
                    type="text" 
                    placeholder="Contoh: Pengadaan License Cloud AWS & Cloudflare Enterprise" 
                    value={newProgram} 
                    onChange={e => setNewProgram(e.target.value)}
                    className="w-full bg-[#0b132b] border border-[#1e3a8a] text-white placeholder-slate-500 focus:border-sky-400 rounded-lg px-3 py-2 text-xs"
                  />
                </div>

                <div>
                  <label className="block font-bold uppercase text-slate-300 mb-1 text-[10px] sm:text-[11px]">
                    Target KPI / Hasil Sasaran Operasional
                  </label>
                  <input 
                    type="text" 
                    placeholder="Contoh: Uptime 99.9% & Zero Downtime Server Web" 
                    value={newKpi} 
                    onChange={e => setNewKpi(e.target.value)}
                    className="w-full bg-[#0b132b] border border-[#1e3a8a] text-white placeholder-slate-500 focus:border-sky-400 rounded-lg px-3 py-2 text-xs"
                  />
                </div>
              </div>

              {/* Quarterly Amounts (IDR) */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 sm:gap-3 bg-[#0b132b] p-3 rounded-lg border border-[#1e3a8a]/40">
                <div>
                  <label className="block font-bold text-sky-300 mb-1 text-[10px]">Pagu Q1 (IDR)</label>
                  <input 
                    type="number" 
                    placeholder="0" 
                    value={newQ1} 
                    onChange={e => setNewQ1(e.target.value)}
                    className="w-full bg-[#0f172a] border border-[#1e3a8a] text-white text-right px-2.5 py-1.5 rounded text-xs font-mono"
                  />
                </div>
                <div>
                  <label className="block font-bold text-sky-300 mb-1 text-[10px]">Pagu Q2 (IDR)</label>
                  <input 
                    type="number" 
                    placeholder="0" 
                    value={newQ2} 
                    onChange={e => setNewQ2(e.target.value)}
                    className="w-full bg-[#0f172a] border border-[#1e3a8a] text-white text-right px-2.5 py-1.5 rounded text-xs font-mono"
                  />
                </div>
                <div>
                  <label className="block font-bold text-sky-300 mb-1 text-[10px]">Pagu Q3 (IDR)</label>
                  <input 
                    type="number" 
                    placeholder="0" 
                    value={newQ3} 
                    onChange={e => setNewQ3(e.target.value)}
                    className="w-full bg-[#0f172a] border border-[#1e3a8a] text-white text-right px-2.5 py-1.5 rounded text-xs font-mono"
                  />
                </div>
                <div>
                  <label className="block font-bold text-sky-300 mb-1 text-[10px]">Pagu Q4 (IDR)</label>
                  <input 
                    type="number" 
                    placeholder="0" 
                    value={newQ4} 
                    onChange={e => setNewQ4(e.target.value)}
                    className="w-full bg-[#0f172a] border border-[#1e3a8a] text-white text-right px-2.5 py-1.5 rounded text-xs font-mono"
                  />
                </div>
              </div>

              <div className="flex items-center justify-between gap-4 pt-2">
                <input 
                  type="text" 
                  placeholder="Catatan penjelas pendukung rincian kegiatan..." 
                  value={newNotes} 
                  onChange={e => setNewNotes(e.target.value)}
                  className="w-full bg-[#0b132b] border border-[#1e3a8a] text-slate-300 placeholder-slate-500 rounded-lg px-3 py-2 text-xs"
                />

                <button 
                  type="submit"
                  className="bg-gradient-to-r from-blue-600 to-sky-500 hover:from-blue-500 hover:to-sky-400 text-white font-bold uppercase text-xs px-5 py-2 rounded-lg flex items-center gap-1.5 whitespace-nowrap shadow-md shadow-blue-500/20"
                >
                  <Plus className="w-4 h-4" />
                  <span>Simpan Action Plan</span>
                </button>
              </div>
            </form>
          </div>

          {/* Action Plans Table */}
          <div className="bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl overflow-hidden shadow-lg">
            <div className="p-3 sm:p-4 bg-[#0b132b] border-b border-[#1e3a8a]/60 flex items-center justify-between">
              <h3 className="text-xs sm:text-sm font-bold text-white uppercase tracking-wider flex items-center gap-2">
                <Sparkles className="w-4 h-4 text-sky-400" />
                Daftar Action Plan Perencanaan RKAP Per Perusahaan ({actionPlans.length})
              </h3>
              <span className="text-[10px] text-sky-300 font-mono bg-sky-950/80 px-2 py-0.5 rounded border border-sky-500/30">
                Konsolidasi Aktif
              </span>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left text-[10px] sm:text-xs font-mono">
                <thead>
                  <tr className="bg-[#0b132b] text-sky-300 uppercase text-[9px] sm:text-[10px] border-b border-[#1e3a8a]/60">
                    <th className="p-3">Direktorat & Program</th>
                    <th className="p-3">Kode COA & Kategori</th>
                    <th className="p-3 text-right">Q1 (IDR)</th>
                    <th className="p-3 text-right">Q2 (IDR)</th>
                    <th className="p-3 text-right">Q3 (IDR)</th>
                    <th className="p-3 text-right">Q4 (IDR)</th>
                    <th className="p-3 text-right font-bold text-white bg-[#0f172a]">Total RKAP</th>
                    <th className="p-3 text-center">Aksi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1e3a8a]/40">
                  {actionPlans.map(plan => {
                    const coaMeta = COA_LIST.find(c => c.code === plan.coaCode);
                    const rowTotal = plan.q1Amount + plan.q2Amount + plan.q3Amount + plan.q4Amount;
                    const isIncome = coaMeta?.category === "Pendapatan";
                    const isCapex = coaMeta?.category === "Belanja Modal (CAPEX)";

                    return (
                      <tr key={plan.id} className="hover:bg-slate-800/40 transition-colors">
                        <td className="p-3 space-y-0.5 max-w-xs">
                          <span className="text-[9px] font-bold text-sky-400 uppercase block">
                            {plan.directorate}
                          </span>
                          <span className="font-bold text-white block text-xs">
                            {plan.programName}
                          </span>
                          <span className="text-[10px] text-slate-400 block italic">
                            KPI: {plan.kpiTarget}
                          </span>
                        </td>

                        <td className="p-3 space-y-0.5">
                          <span className="font-bold text-sky-300 block">
                            [{plan.coaCode}]
                          </span>
                          <span className="text-[10px] text-slate-300 block">
                            {coaMeta?.name}
                          </span>
                          <span className={`text-[9px] font-bold uppercase px-1.5 py-0.2 rounded inline-block ${
                            isIncome ? 'bg-emerald-500/20 text-emerald-300' : isCapex ? 'bg-blue-500/20 text-blue-300' : 'bg-amber-500/20 text-amber-300'
                          }`}>
                            {coaMeta?.category}
                          </span>
                        </td>

                        <td className="p-3 text-right font-mono text-slate-200">{formatIdr(plan.q1Amount)}</td>
                        <td className="p-3 text-right font-mono text-slate-200">{formatIdr(plan.q2Amount)}</td>
                        <td className="p-3 text-right font-mono text-slate-200">{formatIdr(plan.q3Amount)}</td>
                        <td className="p-3 text-right font-mono text-slate-200">{formatIdr(plan.q4Amount)}</td>

                        <td className={`p-3 text-right font-bold font-mono bg-[#0b132b]/50 ${
                          isIncome ? 'text-emerald-400' : isCapex ? 'text-sky-300' : 'text-slate-100'
                        }`}>
                          {formatIdr(rowTotal)}
                        </td>

                        <td className="p-3 text-center">
                          <button 
                            onClick={() => handleDeletePlan(plan.id)}
                            className="p-1.5 text-slate-400 hover:text-rose-400 hover:bg-rose-500/10 rounded transition-colors"
                            title="Hapus Action Plan"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* TAB 2: MATRIKS COA ACCOUNTS */}
      {activeTab === "matrix" && (
        <div className="space-y-4 bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-4 sm:p-5">
          <div className="flex items-center justify-between border-b border-[#1e3a8a]/60 pb-3">
            <div>
              <h3 className="text-xs sm:text-sm font-bold text-white uppercase tracking-wider flex items-center gap-2">
                <FileSpreadsheet className="w-4 h-4 text-sky-400" />
                Matriks Chart of Accounts (COA) Standar PT MEDIAN
              </h3>
              <p className="text-[10px] sm:text-xs text-slate-400 font-mono mt-0.5">
                Pengelompokan Akun Pendapatan, OPEX, dan CAPEX Perseroan
              </p>
            </div>
            <span className="text-[10px] text-sky-300 font-mono bg-sky-950/80 px-2 py-0.5 rounded border border-sky-500/30">
              COA MASTER v2026
            </span>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Pendapatan */}
            <div className="space-y-2 border border-emerald-500/30 bg-[#0b132b]/80 p-3 sm:p-4 rounded-xl">
              <h4 className="font-bold text-emerald-400 uppercase text-xs flex items-center gap-1.5 border-b border-emerald-500/30 pb-2">
                <ArrowUpRight className="w-4 h-4" />
                1. Kategori Pendapatan (Inflow)
              </h4>
              <ul className="space-y-2 text-[10px] sm:text-xs font-mono">
                {COA_LIST.filter(c => c.category === "Pendapatan").map(c => (
                  <li key={c.code} className="bg-[#0f172a] p-2 rounded border border-emerald-500/20">
                    <span className="font-bold text-emerald-300 block">[{c.code}]</span>
                    <span className="text-slate-200 block">{c.name}</span>
                  </li>
                ))}
              </ul>
            </div>

            {/* OPEX */}
            <div className="space-y-2 border border-amber-500/30 bg-[#0b132b]/80 p-3 sm:p-4 rounded-xl">
              <h4 className="font-bold text-amber-400 uppercase text-xs flex items-center gap-1.5 border-b border-amber-500/30 pb-2">
                <ArrowDownRight className="w-4 h-4" />
                2. Kategori Beban Operasional (OPEX)
              </h4>
              <ul className="space-y-2 text-[10px] sm:text-xs font-mono max-h-96 overflow-y-auto pr-1">
                {COA_LIST.filter(c => c.category === "Beban Operasional").map(c => (
                  <li key={c.code} className="bg-[#0f172a] p-2 rounded border border-amber-500/20">
                    <span className="font-bold text-amber-300 block">[{c.code}]</span>
                    <span className="text-slate-200 block">{c.name}</span>
                  </li>
                ))}
              </ul>
            </div>

            {/* CAPEX */}
            <div className="space-y-2 border border-blue-500/30 bg-[#0b132b]/80 p-3 sm:p-4 rounded-xl">
              <h4 className="font-bold text-blue-400 uppercase text-xs flex items-center gap-1.5 border-b border-blue-500/30 pb-2">
                <Building2 className="w-4 h-4" />
                3. Belanja Modal (CAPEX)
              </h4>
              <ul className="space-y-2 text-[10px] sm:text-xs font-mono">
                {COA_LIST.filter(c => c.category === "Belanja Modal (CAPEX)").map(c => (
                  <li key={c.code} className="bg-[#0f172a] p-2 rounded border border-blue-500/20">
                    <span className="font-bold text-blue-300 block">[{c.code}]</span>
                    <span className="text-slate-200 block">{c.name}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      )}

      {/* TAB 3: SALARY SIMULATION MODULE FOR HR */}
      {activeTab === "salary_sim" && (
        <div className="space-y-4 sm:space-y-6">
          {/* Module Header Notification */}
          {salaryAppliedNotif && (
            <div className="bg-emerald-500/10 border border-emerald-500/40 p-3 rounded-lg text-emerald-300 text-xs font-mono flex items-center justify-between gap-3 animate-fadeIn">
              <div className="flex items-center gap-2">
                <Check className="w-4 h-4 text-emerald-400" />
                <span>
                  <strong>Simulasi Berhasil Diterapkan!</strong> Anggaran Gaji pada Action Plan RKAP (Mata Anggaran 5-1001) telah diperbarui secara otomatis.
                </span>
              </div>
            </div>
          )}

          {/* Simulation Summary KPI Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
            <div className="bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-4 space-y-1">
              <p className="text-[10px] text-slate-400 font-mono uppercase font-semibold">Total Pegawai Simulasi</p>
              <div className="flex items-center justify-between">
                <p className="text-2xl font-extrabold text-white font-mono">{salarySimSummary.totalHeadcount} SDM</p>
                <Users className="w-5 h-5 text-sky-400" />
              </div>
              <p className="text-[9px] text-sky-300 font-mono">Lintas 7 Divisi Perusahaan</p>
            </div>

            <div className="bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-4 space-y-1">
              <p className="text-[10px] text-slate-400 font-mono uppercase font-semibold">Beban Gaji Bulanan Simulasi</p>
              <p className="text-xl font-extrabold text-sky-300 font-mono">
                {formatIdr(salarySimSummary.simMonthlyTotal)}
              </p>
              <p className="text-[9px] text-slate-400 font-mono">
                Awal: {formatIdr(salarySimSummary.baselineMonthlyTotal)} / bln
              </p>
            </div>

            <div className="bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-4 space-y-1">
              <p className="text-[10px] text-slate-400 font-mono uppercase font-semibold">Total Anggaran Gaji 1 Tahun (RKAP)</p>
              <p className="text-xl font-extrabold text-emerald-400 font-mono">
                {formatIdr(salarySimSummary.simYearlyTotal)}
              </p>
              <p className="text-[9px] text-slate-400 font-mono">12 Bulan + THR + Bonus Kinerja</p>
            </div>

            <div className="bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-3.5 sm:p-4 space-y-1">
              <p className="text-[10px] text-slate-400 font-mono uppercase font-semibold">Dampak Selisih Anggaran Tahun</p>
              <p className={`text-xl font-extrabold font-mono ${salarySimSummary.yearlyImpact >= 0 ? 'text-amber-400' : 'text-emerald-400'}`}>
                {salarySimSummary.yearlyImpact >= 0 ? `+${formatIdr(salarySimSummary.yearlyImpact)}` : formatIdr(salarySimSummary.yearlyImpact)}
              </p>
              <p className="text-[9px] font-mono text-slate-300">
                Variasi: {salarySimSummary.percentageChange >= 0 ? `+${salarySimSummary.percentageChange.toFixed(2)}%` : `${salarySimSummary.percentageChange.toFixed(2)}%`}
              </p>
            </div>
          </div>

          {/* Interactive Pay Grade Adjustment Panel */}
          <div className="bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-4 sm:p-5 space-y-4 shadow-lg">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between border-b border-[#1e3a8a]/60 pb-3 gap-3">
              <div>
                <h3 className="text-xs sm:text-sm font-bold text-white uppercase tracking-wider flex items-center gap-2">
                  <Sliders className="w-4 h-4 text-sky-400" />
                  Modul Simulasi Penyesuaian Pay Grade & Tunjangan HR
                </h3>
                <p className="text-[10px] sm:text-xs text-slate-400 font-mono mt-0.5">
                  Sesuaikan persentase kenaikan gaji pokok, tunjangan BPJS, dan THR per divisi untuk mengukur dampak total terhadap anggaran perusahaan.
                </p>
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={() => setSalaryDivisions(INITIAL_SALARY_DIVISIONS)}
                  className="px-3 py-1.5 bg-[#0b132b] hover:bg-slate-800 text-slate-300 font-bold uppercase text-[10px] rounded border border-[#1e3a8a] transition-all flex items-center gap-1"
                  title="Reset Ke Default"
                >
                  <RefreshCw className="w-3 h-3" />
                  <span>Reset Default</span>
                </button>

                <button
                  onClick={handleApplySalaryToRkap}
                  className="px-4 py-1.5 bg-gradient-to-r from-blue-600 to-sky-500 hover:from-blue-500 hover:to-sky-400 text-white font-bold uppercase text-[10px] sm:text-xs tracking-wider transition-all flex items-center gap-1.5 rounded-lg shadow-md shadow-blue-500/20"
                >
                  <Check className="w-3.5 h-3.5" />
                  <span>Terapkan Ke Action Plan RKAP (5-1001)</span>
                </button>
              </div>
            </div>

            {/* Division Salary Sliders & Table */}
            <div className="overflow-x-auto">
              <table className="w-full text-left text-[10px] sm:text-xs font-mono">
                <thead>
                  <tr className="bg-[#0b132b] text-sky-300 uppercase text-[9px] sm:text-[10px] border-b border-[#1e3a8a]/60">
                    <th className="p-3">Divisi / Unit Kerja</th>
                    <th className="p-3 text-center">Jumlah SDM</th>
                    <th className="p-3 text-right">Gaji Pokok Awal / SDM</th>
                    <th className="p-3 text-center">Kenaikan Pay Grade (%)</th>
                    <th className="p-3 text-center">Tunjangan & BPJS (%)</th>
                    <th className="p-3 text-center">Faktor THR / Bonus (x Bln)</th>
                    <th className="p-3 text-right font-bold text-white bg-[#0b132b]">Proyeksi Beban 1 Tahun</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1e3a8a]/40">
                  {salaryDivisions.map(div => {
                    const simBase = div.currentBaseSalary * (1 + div.proposedRaisePercent / 100);
                    const simMonthlyDiv = simBase * (1 + div.allowanceMultiplierPercent / 100) * div.headcount;
                    const simYearlyDiv = (simMonthlyDiv * 12) + (div.headcount * simBase * div.thrBonusMultiplier);

                    return (
                      <tr key={div.id} className="hover:bg-slate-800/40 transition-colors">
                        <td className="p-3">
                          <span className="font-bold text-white block text-xs">{div.divisionName}</span>
                          <span className="text-[9px] text-sky-400 block uppercase">{div.directorate}</span>
                        </td>

                        <td className="p-3 text-center">
                          <input 
                            type="number" 
                            min={1} 
                            max={50} 
                            value={div.headcount} 
                            onChange={e => handleUpdateSalaryDivision(div.id, "headcount", Math.max(1, parseInt(e.target.value) || 1))}
                            className="w-12 bg-[#0b132b] border border-[#1e3a8a] text-white text-center py-1 rounded text-xs"
                          />
                        </td>

                        <td className="p-3 text-right font-mono">
                          <input 
                            type="number" 
                            step={500000} 
                            value={div.currentBaseSalary} 
                            onChange={e => handleUpdateSalaryDivision(div.id, "currentBaseSalary", Math.max(0, parseFloat(e.target.value) || 0))}
                            className="w-28 bg-[#0b132b] border border-[#1e3a8a] text-emerald-400 text-right px-2 py-1 rounded text-xs font-bold"
                          />
                        </td>

                        <td className="p-3 text-center">
                          <div className="flex items-center justify-center gap-1.5">
                            <input 
                              type="range" 
                              min={0} 
                              max={30} 
                              value={div.proposedRaisePercent} 
                              onChange={e => handleUpdateSalaryDivision(div.id, "proposedRaisePercent", parseFloat(e.target.value))}
                              className="w-16 accent-sky-400 cursor-pointer"
                            />
                            <span className="font-bold text-sky-300 w-8 text-right">{div.proposedRaisePercent}%</span>
                          </div>
                        </td>

                        <td className="p-3 text-center">
                          <select 
                            value={div.allowanceMultiplierPercent} 
                            onChange={e => handleUpdateSalaryDivision(div.id, "allowanceMultiplierPercent", parseFloat(e.target.value))}
                            className="bg-[#0b132b] border border-[#1e3a8a] text-slate-200 px-2 py-1 rounded text-xs"
                          >
                            <option value={10}>10% (Standar)</option>
                            <option value={12}>12% (+BPJS Kes)</option>
                            <option value={15}>15% (+BPJS Ketenagakerjaan)</option>
                            <option value={20}>20% (+Tunjangan Direksi)</option>
                          </select>
                        </td>

                        <td className="p-3 text-center">
                          <select 
                            value={div.thrBonusMultiplier} 
                            onChange={e => handleUpdateSalaryDivision(div.id, "thrBonusMultiplier", parseFloat(e.target.value))}
                            className="bg-[#0b132b] border border-[#1e3a8a] text-slate-200 px-2 py-1 rounded text-xs"
                          >
                            <option value={1.0}>1.0x (1 Bulan Gaji THR)</option>
                            <option value={1.25}>1.25x (+Bonus Kinerja Small)</option>
                            <option value={1.5}>1.5x (+Bonus Kinerja Med)</option>
                            <option value={2.0}>2.0x (2 Bulan Gaji Direksi)</option>
                          </select>
                        </td>

                        <td className="p-3 text-right font-bold font-mono text-emerald-300 bg-[#0b132b]/50">
                          {formatIdr(simYearlyDiv)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* TAB 4: CASH FLOW SUMMARY */}
      {activeTab === "cashflow" && (
        <div className="space-y-4 bg-[#0f172a] border border-[#1e3a8a]/60 rounded-xl p-4 sm:p-5 shadow-xl">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between border-b border-[#1e3a8a]/60 pb-3 gap-2">
            <div>
              <h3 className="text-xs sm:text-sm font-bold text-white uppercase tracking-wider flex items-center gap-2">
                <PieChart className="w-4 h-4 text-sky-400" />
                Laporan Proyeksi Arus Kas Konsolidasi (Consolidated Cash Flow Statement)
              </h3>
              <p className="text-[10px] sm:text-xs text-slate-400 font-mono mt-0.5">
                Konsolidasi Arus Kas Masuk & Keluar Berdasarkan Action Plan & Simulasi Gaji HR
              </p>
            </div>
            <span className="text-[10px] font-bold text-sky-300 bg-sky-950/80 px-2.5 py-1 rounded border border-sky-500/30 font-mono">
              Status: DRAFT KONSOLIDASI
            </span>
          </div>

          {/* Detailed Statement Table */}
          <div className="overflow-x-auto">
            <table className="w-full text-left text-[10px] sm:text-xs font-mono border-collapse border border-[#1e3a8a]/60 rounded-lg overflow-hidden">
              <thead>
                <tr className="bg-[#0b132b] text-sky-300 uppercase text-[9px] sm:text-[10px] border-b border-[#1e3a8a]/60">
                  <th className="p-3">Uraian Arus Kas (Cash Flow Items)</th>
                  <th className="p-3 text-right">Q1 (Triwulan 1)</th>
                  <th className="p-3 text-right">Q2 (Triwulan 2)</th>
                  <th className="p-3 text-right">Q3 (Triwulan 3)</th>
                  <th className="p-3 text-right">Q4 (Triwulan 4)</th>
                  <th className="p-3 text-right font-bold text-white bg-[#0f172a]">Total RKAP {fiscalYear}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#1e3a8a]/30">
                {/* SALDO KAS AWAL */}
                <tr className="bg-[#0b132b] font-bold">
                  <td className="p-3 text-slate-300 uppercase">1. SALDO KAS AWAL PERIODE</td>
                  <td className="p-3 text-right text-slate-300">{formatIdr(initialCashBalance)}</td>
                  <td className="p-3 text-right text-slate-300">{formatIdr(cashFlowSummary.q1End)}</td>
                  <td className="p-3 text-right text-slate-300">{formatIdr(cashFlowSummary.q2End)}</td>
                  <td className="p-3 text-right text-slate-300">{formatIdr(cashFlowSummary.q3End)}</td>
                  <td className="p-3 text-right text-slate-400 bg-[#0f172a]">{formatIdr(initialCashBalance)}</td>
                </tr>

                {/* ARUS KAS MASUK OPERASIONAL */}
                <tr className="bg-[#0f172a]">
                  <td className="p-3 font-bold text-emerald-400 uppercase">2. ARUS KAS MASUK OPERASIONAL (CASH INFLOW)</td>
                  <td className="p-3 text-right text-emerald-400">{formatIdr(cashFlowSummary.q1In)}</td>
                  <td className="p-3 text-right text-emerald-400">{formatIdr(cashFlowSummary.q2In)}</td>
                  <td className="p-3 text-right text-emerald-400">{formatIdr(cashFlowSummary.q3In)}</td>
                  <td className="p-3 text-right text-emerald-400">{formatIdr(cashFlowSummary.q4In)}</td>
                  <td className="p-3 text-right text-emerald-400 font-bold bg-[#0b132b]">{formatIdr(cashFlowSummary.totalIn)}</td>
                </tr>

                {/* ARUS KAS KELUAR OPERASIONAL */}
                <tr className="bg-[#0f172a]">
                  <td className="p-3 font-bold text-rose-400 uppercase">3. ARUS KAS KELUAR OPERASIONAL (OPEX)</td>
                  <td className="p-3 text-right text-rose-400">({formatIdr(cashFlowSummary.q1Opex)})</td>
                  <td className="p-3 text-right text-rose-400">({formatIdr(cashFlowSummary.q2Opex)})</td>
                  <td className="p-3 text-right text-rose-400">({formatIdr(cashFlowSummary.q3Opex)})</td>
                  <td className="p-3 text-right text-rose-400">({formatIdr(cashFlowSummary.q4Opex)})</td>
                  <td className="p-3 text-right text-rose-400 font-bold bg-[#0b132b]">({formatIdr(cashFlowSummary.totalOpex)})</td>
                </tr>

                {/* ARUS KAS INVESTASI (CAPEX) */}
                <tr className="bg-[#0f172a]">
                  <td className="p-3 font-bold text-sky-400 uppercase">4. ARUS KAS INVESTASI / BELANJA MODAL (CAPEX)</td>
                  <td className="p-3 text-right text-sky-400">({formatIdr(cashFlowSummary.q1Capex)})</td>
                  <td className="p-3 text-right text-sky-400">({formatIdr(cashFlowSummary.q2Capex)})</td>
                  <td className="p-3 text-right text-sky-400">({formatIdr(cashFlowSummary.q3Capex)})</td>
                  <td className="p-3 text-right text-sky-400">({formatIdr(cashFlowSummary.q4Capex)})</td>
                  <td className="p-3 text-right text-sky-400 font-bold bg-[#0b132b]">({formatIdr(cashFlowSummary.totalCapex)})</td>
                </tr>

                {/* SURPLUS / DEFISIT ARUS KAS BERSIH */}
                <tr className="bg-[#0b132b] font-bold border-t-2 border-[#1e3a8a]/80">
                  <td className="p-3 text-sky-300 uppercase">5. NET CASH FLOW (SURPLUS / DEFISIT)</td>
                  <td className="p-3 text-right text-sky-300">{formatIdr(cashFlowSummary.q1Net)}</td>
                  <td className="p-3 text-right text-sky-300">{formatIdr(cashFlowSummary.q2Net)}</td>
                  <td className="p-3 text-right text-sky-300">{formatIdr(cashFlowSummary.q3Net)}</td>
                  <td className="p-3 text-right text-sky-300">{formatIdr(cashFlowSummary.q4Net)}</td>
                  <td className="p-3 text-right text-sky-300 bg-[#0f172a] text-xs font-bold">{formatIdr(cashFlowSummary.netCashFlow)}</td>
                </tr>

                {/* SALDO KAS AKHIR PERIODE */}
                <tr className="bg-[#0f172a] font-bold text-xs border-t-2 border-sky-400">
                  <td className="p-3 text-white uppercase">6. SALDO KAS AKHIR PERIODE (ENDING CASH)</td>
                  <td className="p-3 text-right text-indigo-300">{formatIdr(cashFlowSummary.q1End)}</td>
                  <td className="p-3 text-right text-indigo-300">{formatIdr(cashFlowSummary.q2End)}</td>
                  <td className="p-3 text-right text-indigo-300">{formatIdr(cashFlowSummary.q3End)}</td>
                  <td className="p-3 text-right text-indigo-300">{formatIdr(cashFlowSummary.q4End)}</td>
                  <td className="p-3 text-right text-indigo-300 bg-[#0b132b] font-bold">{formatIdr(cashFlowSummary.endingCash)}</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* Executive Authorization Note */}
          <div className="bg-[#0b132b] border border-[#1e3a8a] p-3.5 sm:p-4 rounded-xl flex flex-col md:flex-row items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <AlertCircle className="w-5 h-5 text-sky-400 shrink-0" />
              <p className="text-[10px] sm:text-xs text-slate-300 font-mono">
                Draft RKAP ini siap diajukan ke Direktur Utama (CEO) Bambang Hartono dan CFO Hendra Wijaya untuk disahkan dalam Rapat Direksi & Dewan Komisaris.
              </p>
            </div>
            <button
              onClick={handleSubmitToWorkflow}
              disabled={submittedToWorkflow}
              className={`text-[10px] sm:text-xs font-bold uppercase tracking-wider px-5 py-2.5 rounded-lg flex items-center gap-2 whitespace-nowrap transition-all shadow-md ${
                submittedToWorkflow 
                  ? "bg-emerald-600 text-white cursor-default" 
                  : "bg-gradient-to-r from-blue-600 to-sky-500 hover:from-blue-500 hover:to-sky-400 text-white"
              }`}
            >
              {submittedToWorkflow ? "Sudah Diajukan Ke CEO" : "Kirimkan Ke Workflow Engine"}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
