import React, { useState, useEffect } from 'react';
import { 
  Tag, 
  Megaphone, 
  Receipt, 
  RefreshCw, 
  Calendar, 
  ArrowLeftRight, 
  Building, 
  Dumbbell, 
  ShieldAlert, 
  FileText, 
  ClipboardList, 
  Wrench, 
  Clock, 
  CheckCircle2, 
  AlertTriangle, 
  Plus, 
  User, 
  Trash2,
  DollarSign,
  Briefcase,
  Layers,
  HelpCircle,
  Bell,
  Mail,
  Smartphone,
  Send,
  MessageSquare,
  CheckCircle,
  Printer,
  Upload,
  Search
} from 'lucide-react';
import { Property, Transaction } from '../types';

interface OperationsHubProps {
  properties: Property[];
  transactions: Transaction[];
  currentUser: any;
  onRefreshAll: () => void;
  notifications?: any[];
  onRefreshNotifications?: () => void;
}

export default function OperationsHub({ 
  properties, 
  transactions, 
  currentUser, 
  onRefreshAll,
  notifications = [],
  onRefreshNotifications
}: OperationsHubProps) {
  const myProperties = properties.filter((p) => {
    if (currentUser?.role === 'superadmin') return true;
    if (currentUser?.role === 'admin') return p.id === currentUser.propertyId;
    if (currentUser?.role === 'owner') return p.ownerId === currentUser.id;
    return false;
  });

  const [activeSubTab, setActiveSubTab] = useState<'promos-ads' | 'billing' | 'guest-cycle' | 'fm' | 'complaints' | 'maintenance' | 'logs' | 'notifications'>('promos-ads');

  // Loading States
  const [loading, setLoading] = useState(false);
  const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);

  // Entities State
  const [promos, setPromos] = useState<any[]>([]);
  const [ads, setAds] = useState<any[]>([]);
  const [buildings, setBuildings] = useState<any[]>([]);
  const [facilities, setFacilities] = useState<any[]>([]);
  const [payments, setPayments] = useState<any[]>([]);
  const [guestCycles, setGuestCycles] = useState<any[]>([]);
  const [complaints, setComplaints] = useState<any[]>([]);
  const [logs, setLogs] = useState<any[]>([]);
  const [maintenances, setMaintenances] = useState<any[]>([]);

  // Filter States
  const [logFilter, setLogFilter] = useState<'all' | 'user' | 'system' | 'app'>('all');
  const [maintFilter, setMaintFilter] = useState<'all' | 'preventive' | 'corrective' | 'predictive'>('all');

  // Operational Search & Sort States
  const [paymentSearchQuery, setPaymentSearchQuery] = useState('');
  const [paymentSortField, setPaymentSortField] = useState<'id' | 'propertyName' | 'totalAmount' | 'amountPaid' | 'dueDate'>('propertyName');
  const [paymentSortOrder, setPaymentSortOrder] = useState<'asc' | 'desc'>('asc');

  const [guestSearchQuery, setGuestSearchQuery] = useState('');
  const [guestSortField, setGuestSortField] = useState<'guestName' | 'propertyName' | 'roomNumber' | 'status'>('guestName');
  const [guestSortOrder, setGuestSortOrder] = useState<'asc' | 'desc'>('asc');

  const [logSearchQuery, setLogSearchQuery] = useState('');
  const [logSortField, setLogSortField] = useState<'timestamp' | 'type' | 'user' | 'message'>('timestamp');
  const [logSortOrder, setLogSortOrder] = useState<'desc' | 'asc'>('desc');

  // Form States
  const [newPromo, setNewPromo] = useState({ code: '', discount: '', type: 'coupon', maxUse: '50', description: '' });
  const [newAd, setNewAd] = useState({ title: '', imageUrl: '', link: '#', section: 'banner' });
  const [adDragActive, setAdDragActive] = useState(false);
  const [uploadedAdFile, setUploadedAdFile] = useState<{ name: string, size: string } | null>(null);
  const [newBuilding, setNewBuilding] = useState({ name: '', floors: '1', address: '', unitCount: '10' });
  const [newFacility, setNewFacility] = useState({ name: '', type: 'Umum', status: 'Aktif', location: '' });
  const [newComplaint, setNewComplaint] = useState({ guestName: '', propertyName: '', title: '', description: '', category: 'Fasilitas', priority: 'Medium' });
  const [newMaint, setNewMaint] = useState({ propertyId: '', assetName: '', issue: '', type: 'preventive', cost: '' });
  const [newPayment, setNewPayment] = useState({ transactionId: '', propertyName: '', totalAmount: '', amountPaid: '', paymentMethod: 'Bank Transfer - Mandiri', type: 'DP', dueDate: '', notes: '' });

  // Move booking form state
  const [selectedTxId, setSelectedTxId] = useState('');
  const [moveTargetPropId, setMoveTargetPropId] = useState('');
  const [moveStartDate, setMoveStartDate] = useState('');
  const [moveEndDate, setMoveEndDate] = useState('');

  // User and Notification Simulator states
  const [users, setUsers] = useState<any[]>([]);
  const [notifSim, setNotifSim] = useState({ userId: '', title: '', message: '', type: 'system' });
  const [simulatedWA, setSimulatedWA] = useState<any>(null);
  const [simulatedEmail, setSimulatedEmail] = useState<any>(null);

  // Toast Trigger
  const showLocalToast = (message: string, type: 'success' | 'error' = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  // Fetch all Operational Data
  const fetchOperationalData = async (showLoading: any = false) => {
    if (showLoading === true || promos.length === 0) {
      setLoading(true);
    }
    try {
      const [
        promosRes, adsRes, buildingsRes, facilitiesRes, 
        paymentsRes, cyclesRes, complaintsRes, logsRes, maintRes,
        usersRes
      ] = await Promise.all([
        fetch('/api/promos'),
        fetch('/api/advertisements'),
        fetch('/api/buildings'),
        fetch('/api/facilities'),
        fetch('/api/payments'),
        fetch('/api/guest-cycles'),
        fetch('/api/complaints'),
        fetch('/api/logs'),
        fetch('/api/maintenances'),
        fetch('/api/users')
      ]);

      if (promosRes.ok) setPromos(await promosRes.json());
      if (adsRes.ok) setAds(await adsRes.json());
      if (buildingsRes.ok) setBuildings(await buildingsRes.json());
      if (facilitiesRes.ok) setFacilities(await facilitiesRes.json());
      if (paymentsRes.ok) setPayments(await paymentsRes.json());
      if (cyclesRes.ok) setGuestCycles(await cyclesRes.json());
      if (complaintsRes.ok) setComplaints(await complaintsRes.json());
      if (logsRes.ok) setLogs(await logsRes.json());
      if (maintRes.ok) setMaintenances(await maintRes.json());
      if (usersRes && usersRes.ok) setUsers(await usersRes.json());
    } catch (err) {
      console.error("Gagal memuat data operasional", err);
      showLocalToast("Gagal menyinkronkan data dengan server", "error");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOperationalData();
  }, []);

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

  // Helper to export any operational table into an elegant CSV spreadsheet download
  const handleExportCSV = (dataType: 'promos' | 'ads' | 'billing' | 'guest-cycle' | 'fm' | 'complaints' | 'maintenance' | 'logs' | 'promos-ads' | 'notifications') => {
    let csvContent = "data:text/csv;charset=utf-8,";
    let fileName = `Laporan_${dataType}_SewaBeliPro_${new Date().toISOString().substring(0, 10)}.csv`;

    if (dataType === 'promos') {
      csvContent += "ID,Kode Kupon,Potongan Harga (IDR),Tipe,Maksimal Penggunaan,Sudah Digunakan,Deskripsi\n";
      promos.forEach(p => {
        csvContent += `"${p.id}","${p.code}",${p.discount},"${p.type}",${p.maxUse},${p.used},"${p.description}"\n`;
      });
    } else if (dataType === 'promos-ads') {
      csvContent += "--- KUPON PROMO SEWABELIPRO ---\n";
      csvContent += "ID,Kode Kupon,Potongan Harga (IDR),Tipe,Maksimal Penggunaan,Sudah Digunakan,Deskripsi\n";
      promos.forEach(p => {
        csvContent += `"${p.id}","${p.code}",${p.discount},"${p.type}",${p.maxUse},${p.used},"${p.description}"\n`;
      });
      csvContent += "\n--- IKLAN SEWABELIPRO ---\n";
      csvContent += "ID,Judul Iklan,Section,Status,Tautan\n";
      ads.forEach(ad => {
        csvContent += `"${ad.id}","${ad.title}","${ad.section}","${ad.status}","${ad.link}"\n`;
      });
    } else if (dataType === 'notifications') {
      csvContent += "ID Notifikasi,ID User,Judul Notifikasi,Pesan,Tipe Notifikasi,Status Baca,Saluran Email,Saluran WA,Tanggal Dibuat\n";
      notifications.forEach(n => {
        const emailSent = n.channels?.email?.sent ? `Sent (${n.channels.email.address})` : 'None';
        const waSent = n.channels?.whatsapp?.sent ? `Sent (${n.channels.whatsapp.phone})` : 'None';
        csvContent += `"${n.id}","${n.userId}","${n.title}","${n.message}","${n.type}","${n.read ? 'Selesai Dibaca' : 'Belum Dibaca'}","${emailSent}","${waSent}","${n.createdAt}"\n`;
      });
    } else if (dataType === 'ads') {
      csvContent += "ID,Judul Iklan,Section,Status,Tautan\n";
      ads.forEach(ad => {
        csvContent += `"${ad.id}","${ad.title}","${ad.section}","${ad.status}","${ad.link}"\n`;
      });
    } else if (dataType === 'billing') {
      csvContent += "ID Tagihan,ID Transaksi,Nama Properti,Tipe Tagihan (DP/Lunas),Total Tagihan,Terbayar,Sisa Tagihan,Jatuh Tempo,Metode,Status,Catatan\n";
      payments.forEach(p => {
        const sisa = p.totalAmount - p.amountPaid;
        csvContent += `"${p.id}","${p.transactionId}","${p.propertyName}","${p.type}",${p.totalAmount},${p.amountPaid},${sisa},"${p.dueDate}","${p.paymentMethod}","${p.status}","${p.notes || ''}"\n`;
      });
    } else if (dataType === 'guest-cycle') {
      csvContent += "ID Siklus,Nama Tamu,Properti,Unit/Kamar,Status Alur,Waktu Check-In,Waktu Check-Out\n";
      guestCycles.forEach(g => {
        csvContent += `"${g.id}","${g.guestName}","${g.propertyName}","${g.roomNumber}","${g.status}","${g.checkInTime}","${g.checkOutTime}"\n`;
      });
    } else if (dataType === 'fm') {
      csvContent += "ID,Nama Fasilitas,Kategori,Status Kondisi,Lokasi/Sektor\n";
      facilities.forEach(f => {
        csvContent += `"${f.id}","${f.name}","${f.type}","${f.status}","${f.location}"\n`;
      });
    } else if (dataType === 'complaints') {
      csvContent += "ID Komplain,Nama Tamu,Nama Properti,Kategori,Subjek Keluhan,Prioritas,Status Penanganan,Solusi Penyelesaian,Tanggal Dilaporkan\n";
      complaints.forEach(c => {
        csvContent += `"${c.id}","${c.guestName}","${c.propertyName}","${c.category}","${c.title}","${c.priority}","${c.status}","${c.resolution || ''}","${c.createdAt}"\n`;
      });
    } else if (dataType === 'maintenance') {
      csvContent += "ID Tiket,Nama Properti,Nama Aset,Detail Kerusakan,Jenis Pemeliharaan,Estimasi Biaya,Status Pekerjaan,Tanggal Masuk\n";
      maintenances.forEach(m => {
        csvContent += `"${m.id}","${m.propertyName}","${m.assetName}","${m.issue}","${m.type}",${m.cost},"${m.status}","${m.createdAt}"\n`;
      });
    } else if (dataType === 'logs') {
      csvContent += "ID Log,Timestamp,Kategori,Aktor/User,Pesan Aktivitas\n";
      logs.forEach(l => {
        csvContent += `"${l.id}","${l.timestamp}","${l.type}","${l.user}","${l.message}"\n`;
      });
    }

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    showLocalToast(`Laporan ${dataType} berhasil diunduh sebagai spreadsheet CSV!`);
  };

  // Helper to generate a beautifully formatted, official printable PDF or sheet layout
  const handlePrintReport = (dataType: string) => {
    const printWindow = window.open('', '_blank');
    if (!printWindow) {
      showLocalToast("Gagal membuka jendela cetak. Pastikan pop-up diizinkan!", "error");
      return;
    }

    let title = `Laporan Operasional - ${dataType.toUpperCase()}`;
    let tableHeader = '';
    let tableRows = '';

    if (dataType === 'promos' || dataType === 'promos-ads') {
      title = "Laporan Kupon Promosi & Iklan Aktif";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Kode Kupon</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Potongan Harga</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Tipe</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Maks Penggunaan</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Sudah Digunakan</th>
        </tr>
      `;
      promos.forEach(p => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${p.code}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${formatIDR(p.discount)}</td>
            <td style="border: 1px solid #ddd; padding: 10px; text-transform: uppercase;">${p.type}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${p.maxUse}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${p.used}</td>
          </tr>
        `;
      });
    } else if (dataType === 'billing') {
      title = "Laporan Rincian & Status Tagihan Keuangan";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">ID Tagihan</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Properti</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Tipe</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Total Tagihan</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Terbayar</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Sisa Tagihan</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Jatuh Tempo</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Status</th>
        </tr>
      `;
      payments.forEach(p => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px; font-family: monospace;">${p.id}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${p.propertyName}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${p.type}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${formatIDR(p.totalAmount)}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${formatIDR(p.amountPaid)}</td>
            <td style="border: 1px solid #ddd; padding: 10px; color: #dc2626;">${formatIDR(p.totalAmount - p.amountPaid)}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${p.dueDate}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold; color: ${p.status === 'Lunas' ? '#16a34a' : '#d97706'}">${p.status}</td>
          </tr>
        `;
      });
    } else if (dataType === 'guest-cycle') {
      title = "Laporan Siklus & Check-In Alur Tamu";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">ID Siklus</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Nama Tamu</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Nama Properti</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Kamar/Unit</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Alur Status</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Check-In</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Check-Out</th>
        </tr>
      `;
      guestCycles.forEach(g => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px; font-family: monospace;">${g.id}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${g.guestName}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${g.propertyName}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${g.roomNumber}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold; text-transform: uppercase;">${g.status}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${g.checkInTime}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${g.checkOutTime}</td>
          </tr>
        `;
      });
    } else if (dataType === 'fm') {
      title = "Laporan Fasilitas & Kondisi Fisik Gedung";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Fasilitas</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Kategori</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Kondisi Fisik</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Lokasi Sektor</th>
        </tr>
      `;
      facilities.forEach(f => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${f.name}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${f.type}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold; color: ${f.status === 'Sangat Baik' || f.status === 'Normal' ? '#16a34a' : '#dc2626'}">${f.status}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${f.location}</td>
          </tr>
        `;
      });
    } else if (dataType === 'complaints') {
      title = "Laporan Rekapitulasi Keluhan & Komplain Tamu";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Tamu</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Properti</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Kategori</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Detail Keluhan</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Prioritas</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Status</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Resolusi</th>
        </tr>
      `;
      complaints.forEach(c => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${c.guestName}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${c.propertyName}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${c.category}</td>
            <td style="border: 1px solid #ddd; padding: 10px;"><strong>${c.title}</strong><br/>${c.description || ''}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold; color: ${c.priority === 'Tinggi' ? '#dc2626' : '#2563eb'}">${c.priority}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${c.status}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-style: italic;">${c.resolution || '-'}</td>
          </tr>
        `;
      });
    } else if (dataType === 'maintenance') {
      title = "Laporan Tiket Pemeliharaan & Kerusakan Aset";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Properti</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Nama Aset</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Permasalahan</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Jenis</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Biaya Perbaikan</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Status Pekerjaan</th>
        </tr>
      `;
      maintenances.forEach(m => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px;">${m.propertyName}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${m.assetName}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${m.issue}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${m.type}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${formatIDR(m.cost)}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold; text-transform: uppercase;">${m.status}</td>
          </tr>
        `;
      });
    } else if (dataType === 'logs') {
      title = "Laporan Jejak Audit (Audit Logs System)";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9; width: 150px;">Waktu (Timestamp)</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9; width: 100px;">Kategori</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9; width: 150px;">Aktor (Pengguna)</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Pesan Log Aktivitas</th>
        </tr>
      `;
      logs.forEach(l => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px; font-family: monospace;">${l.timestamp}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold; text-transform: uppercase;">${l.type}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${l.user}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${l.message}</td>
          </tr>
        `;
      });
    } else if (dataType === 'notifications') {
      title = "Laporan Notifikasi, Email & Saluran WhatsApp";
      tableHeader = `
        <tr>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9; width: 140px;">Waktu</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9; width: 180px;">Judul Notifikasi</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9;">Isi Pesan Notifikasi</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9; width: 140px;">Saluran Email</th>
          <th style="border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f1f5f9; width: 140px;">Saluran WA</th>
        </tr>
      `;
      notifications.forEach(n => {
        tableRows += `
          <tr>
            <td style="border: 1px solid #ddd; padding: 10px; font-family: monospace;">${n.createdAt}</td>
            <td style="border: 1px solid #ddd; padding: 10px; font-weight: bold;">${n.title}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${n.message}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${n.channels?.email?.sent ? `SMTP Sent (${n.channels.email.address})` : 'Off'}</td>
            <td style="border: 1px solid #ddd; padding: 10px;">${n.channels?.whatsapp?.sent ? `WA Gateway (${n.channels.whatsapp.phone})` : 'Off'}</td>
          </tr>
        `;
      });
    }

    printWindow.document.write(`
      <html>
        <head>
          <title>${title}</title>
          <style>
            body {
              font-family: Arial, sans-serif;
              color: #333;
              margin: 35px;
              line-height: 1.4;
            }
            .header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              border-bottom: 2px solid #2563eb;
              padding-bottom: 15px;
              margin-bottom: 25px;
            }
            .brand {
              font-size: 22px;
              font-weight: bold;
              color: #2563eb;
            }
            .meta {
              text-align: right;
              font-size: 11px;
              color: #666;
            }
            h1 {
              font-size: 18px;
              color: #1e3a8a;
              margin: 0 0 10px 0;
            }
            table {
              width: 100%;
              border-collapse: collapse;
              font-size: 11px;
              margin-bottom: 30px;
            }
            tr:nth-child(even) {
              background-color: #f8fafc;
            }
            .signatures {
              margin-top: 50px;
              display: flex;
              justify-content: space-between;
            }
            .sig-line {
              border-top: 1px solid #444;
              width: 180px;
              text-align: center;
              padding-top: 6px;
              font-size: 11px;
              margin-top: 45px;
            }
          </style>
        </head>
        <body>
          <div class="header">
            <div>
              <div class="brand">SewaBeliPro</div>
              <div style="font-size: 11px; color: #555;">Integrated Smart Property Management Platform</div>
            </div>
            <div class="meta">
              <div><strong>Tanggal Cetak:</strong> ${new Date().toLocaleString('id-ID')}</div>
              <div><strong>Petugas:</strong> ${currentUser ? currentUser.fullName : 'Sistem Admin'}</div>
              <div><strong>Status:</strong> RESMI / TERVALIDASI</div>
            </div>
          </div>

          <h1>${title}</h1>
          <p style="font-size: 11px; color: #666; margin-bottom: 20px;">Laporan operasional resmi ditarik secara real-time dari basis data manajemen internal SewaBeliPro.</p>

          <table>
            <thead>
              ${tableHeader}
            </thead>
            <tbody>
              ${tableRows || '<tr><td colspan="10" style="text-align: center; padding: 20px; color: #999;">Tidak ada data operasional yang tercatat.</td></tr>'}
            </tbody>
          </table>

          <div class="signatures">
            <div>
              <p style="font-size: 11px; margin: 0;">Disiapkan oleh,</p>
              <div class="sig-line">${currentUser ? currentUser.fullName : 'System Manager'}</div>
            </div>
            <div>
              <p style="font-size: 11px; margin: 0;">Disetujui oleh,</p>
              <div class="sig-line">Direktur Operasional</div>
            </div>
          </div>

          <script>
            window.onload = function() {
              window.print();
              setTimeout(function() { window.close(); }, 500);
            };
          </script>
        </body>
      </html>
    `);
    printWindow.document.close();
  };

  // Submit functions
  const handleAddPromo = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newPromo.code || !newPromo.discount) return;
    try {
      const res = await fetch('/api/promos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newPromo)
      });
      if (res.ok) {
        setNewPromo({ code: '', discount: '', type: 'coupon', maxUse: '50', description: '' });
        fetchOperationalData();
        showLocalToast("Promo / kupon berhasil ditambahkan!");
      }
    } catch (err) {
      showLocalToast("Gagal menambah promo", "error");
    }
  };

  const handleAdFile = (file: File) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      const dataUrl = e.target?.result as string;
      setNewAd({ ...newAd, imageUrl: dataUrl });
      setUploadedAdFile({
        name: file.name,
        size: (file.size / (1024 * 1024)).toFixed(2) + ' MB'
      });
    };
    reader.readAsDataURL(file);
  };

  const handleAdDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setAdDragActive(true);
    } else if (e.type === "dragleave") {
      setAdDragActive(false);
    }
  };

  const handleAdDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setAdDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleAdFile(e.dataTransfer.files[0]);
    }
  };

  const handleAdFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleAdFile(e.target.files[0]);
    }
  };

  const handleAddAd = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newAd.title || !newAd.imageUrl) return;
    try {
      const res = await fetch('/api/advertisements', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newAd)
      });
      if (res.ok) {
        setNewAd({ title: '', imageUrl: '', link: '#', section: 'banner' });
        setUploadedAdFile(null);
        fetchOperationalData();
        showLocalToast("Iklan / banner berhasil dipasang!");
      }
    } catch (err) {
      showLocalToast("Gagal menambah iklan", "error");
    }
  };

  const handleAddBuilding = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newBuilding.name || !newBuilding.address) return;
    try {
      const res = await fetch('/api/buildings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newBuilding)
      });
      if (res.ok) {
        setNewBuilding({ name: '', floors: '1', address: '', unitCount: '10' });
        fetchOperationalData();
        showLocalToast("Gedung baru berhasil ditambahkan ke portofolio!");
      }
    } catch (err) {
      showLocalToast("Gagal menambah gedung", "error");
    }
  };

  const handleAddFacility = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newFacility.name) return;
    try {
      const res = await fetch('/api/facilities', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newFacility)
      });
      if (res.ok) {
        setNewFacility({ name: '', type: 'Umum', status: 'Aktif', location: '' });
        fetchOperationalData();
        showLocalToast("Fasilitas gedung berhasil terdaftar!");
      }
    } catch (err) {
      showLocalToast("Gagal menambah fasilitas", "error");
    }
  };

  const handleAddComplaint = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newComplaint.guestName || !newComplaint.propertyName || !newComplaint.title) return;
    try {
      const res = await fetch('/api/complaints', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newComplaint)
      });
      if (res.ok) {
        setNewComplaint({ guestName: '', propertyName: '', title: '', description: '', category: 'Fasilitas', priority: 'Medium' });
        fetchOperationalData();
        showLocalToast("Komplain tamu berhasil dicatat!");
      }
    } catch (err) {
      showLocalToast("Gagal mengirim komplain", "error");
    }
  };

  const handleAddMaint = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newMaint.propertyName && !newMaint.propertyId) return;
    const selectedProp = myProperties.find(p => p.id === newMaint.propertyId);
    try {
      const res = await fetch('/api/maintenances', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...newMaint,
          propertyName: selectedProp ? selectedProp.name : 'Unknown Property'
        })
      });
      if (res.ok) {
        setNewMaint({ propertyId: '', assetName: '', issue: '', type: 'preventive', cost: '' });
        fetchOperationalData();
        showLocalToast("Tiket pemeliharaan berhasil diterbitkan!");
      }
    } catch (err) {
      showLocalToast("Gagal mendaftarkan maintenance", "error");
    }
  };

  const handleAddPayment = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newPayment.propertyName || !newPayment.totalAmount) return;
    try {
      const res = await fetch('/api/payments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newPayment)
      });
      if (res.ok) {
        setNewPayment({ transactionId: '', propertyName: '', totalAmount: '', amountPaid: '', paymentMethod: 'Bank Transfer - Mandiri', type: 'DP', dueDate: '', notes: '' });
        fetchOperationalData();
        showLocalToast("Laporan tagihan manual berhasil dibuat!");
      }
    } catch (err) {
      showLocalToast("Gagal membuat tagihan", "error");
    }
  };

  // Put / Update actions
  const handleUpdatePaymentStatus = async (id: string, updates: any) => {
    try {
      const res = await fetch(`/api/payments/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updates)
      });
      if (res.ok) {
        fetchOperationalData();
        showLocalToast("Laporan tagihan berhasil diperbarui.");
      }
    } catch (err) {
      showLocalToast("Gagal memperbarui tagihan", "error");
    }
  };

  const handleUpdateGuestStatus = async (id: string, status: string) => {
    try {
      const res = await fetch(`/api/guest-cycles/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status })
      });
      if (res.ok) {
        fetchOperationalData();
        showLocalToast(`Siklus tamu diubah menjadi ${status}`);
      }
    } catch (err) {
      showLocalToast("Gagal mengubah siklus tamu", "error");
    }
  };

  const handleUpdateComplaint = async (id: string, status: string, resolution: string) => {
    try {
      const res = await fetch(`/api/complaints/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status, resolution })
      });
      if (res.ok) {
        fetchOperationalData();
        showLocalToast("Status penyelesaian komplain telah diperbarui!");
      }
    } catch (err) {
      showLocalToast("Gagal mengupdate komplain", "error");
    }
  };

  const handleUpdateMaint = async (id: string, status: string, cost?: number) => {
    try {
      const res = await fetch(`/api/maintenances/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status, cost })
      });
      if (res.ok) {
        fetchOperationalData();
        showLocalToast(`Status pemeliharaan diubah ke ${status}`);
      }
    } catch (err) {
      showLocalToast("Gagal memperbarui maintenance", "error");
    }
  };

  const handleUpdatePropertyStatus = async (id: string, status: string) => {
    try {
      const res = await fetch(`/api/properties/${id}/status`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status })
      });
      if (res.ok) {
        onRefreshAll();
        fetchOperationalData();
        showLocalToast(`Status properti/kamar diperbarui ke: ${status}`);
      }
    } catch (err) {
      showLocalToast("Gagal memperbarui status properti", "error");
    }
  };

  const handleUpdateFacilityStatus = async (id: string, status: string) => {
    try {
      const res = await fetch(`/api/facilities/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status })
      });
      if (res.ok) {
        fetchOperationalData();
        showLocalToast(`Status fasilitas diperbarui ke: ${status}`);
      }
    } catch (err) {
      showLocalToast("Gagal memperbarui fasilitas", "error");
    }
  };

  // Move Booking Action
  const handleMoveBooking = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedTxId || !moveTargetPropId) {
      showLocalToast("Pilih booking dan properti tujuan!", "error");
      return;
    }

    try {
      const res = await fetch(`/api/transactions/${selectedTxId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          propertyId: moveTargetPropId,
          startDate: moveStartDate || undefined,
          endDate: moveEndDate || undefined
        })
      });

      if (res.ok) {
        onRefreshAll();
        fetchOperationalData();
        setSelectedTxId('');
        setMoveTargetPropId('');
        setMoveStartDate('');
        setMoveEndDate('');
        showLocalToast("Pemesanan berhasil dipindahkan ke properti baru!");
      } else {
        const errJson = await res.json();
        showLocalToast(errJson.error || "Gagal memindahkan pesanan", "error");
      }
    } catch (err) {
      showLocalToast("Gagal memproses pemindahan pesanan", "error");
    }
  };

  const handleSimulateNotif = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!notifSim.userId || !notifSim.title || !notifSim.message) {
      showLocalToast("Harap isi seluruh field simulasi!", "error");
      return;
    }
    try {
      const res = await fetch('/api/notifications/simulate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(notifSim)
      });
      if (res.ok) {
        const result = await res.json();
        const createdNotif = result.notification;
        
        // Setup live preview bubbles
        setSimulatedWA({
          phone: createdNotif.channels.whatsapp.phone,
          message: createdNotif.channels.whatsapp.message,
          time: createdNotif.createdAt
        });

        setSimulatedEmail({
          address: createdNotif.channels.email.address,
          subject: createdNotif.channels.email.subject,
          body: createdNotif.message,
          time: createdNotif.createdAt
        });

        setNotifSim({ userId: '', title: '', message: '', type: 'system' });
        showLocalToast("Notifikasi disimulasikan & dikirim!");
        
        // Refresh notifications
        if (onRefreshNotifications) {
          onRefreshNotifications();
        }
        fetchOperationalData(); // Refresh logs to see System Notifier log!
      }
    } catch (err) {
      showLocalToast("Gagal melakukan simulasi notifikasi", "error");
    }
  };

  // Filtering & Sorting Logic for operational entities

  // Payments / Bills
  let displayedPayments = payments;
  if (paymentSearchQuery.trim() !== '') {
    const q = paymentSearchQuery.toLowerCase();
    displayedPayments = displayedPayments.filter(p => 
      String(p.id).toLowerCase().includes(q) ||
      p.propertyName.toLowerCase().includes(q) ||
      (p.dueDate && p.dueDate.toLowerCase().includes(q)) ||
      (p.paymentMethod && p.paymentMethod.toLowerCase().includes(q)) ||
      (p.notes && p.notes.toLowerCase().includes(q)) ||
      (p.type && p.type.toLowerCase().includes(q))
    );
  }

  displayedPayments = [...displayedPayments].sort((a, b) => {
    let comparison = 0;
    if (paymentSortField === 'propertyName') {
      comparison = a.propertyName.localeCompare(b.propertyName);
    } else if (paymentSortField === 'id') {
      comparison = String(a.id).localeCompare(String(b.id));
    } else if (paymentSortField === 'totalAmount') {
      comparison = (a.totalAmount || 0) - (b.totalAmount || 0);
    } else if (paymentSortField === 'amountPaid') {
      comparison = (a.amountPaid || 0) - (b.amountPaid || 0);
    } else if (paymentSortField === 'dueDate') {
      comparison = (a.dueDate || '').localeCompare(b.dueDate || '');
    }
    return paymentSortOrder === 'asc' ? comparison : -comparison;
  });

  const handleTogglePaymentSort = (field: 'id' | 'propertyName' | 'totalAmount' | 'amountPaid' | 'dueDate') => {
    if (paymentSortField === field) {
      setPaymentSortOrder(paymentSortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setPaymentSortField(field);
      setPaymentSortOrder('asc');
    }
  };

  // Guest Cycles
  let displayedGuestCycles = guestCycles;
  if (guestSearchQuery.trim() !== '') {
    const q = guestSearchQuery.toLowerCase();
    displayedGuestCycles = displayedGuestCycles.filter(gc => 
      gc.guestName.toLowerCase().includes(q) ||
      gc.propertyName.toLowerCase().includes(q) ||
      String(gc.roomNumber).toLowerCase().includes(q) ||
      gc.status.toLowerCase().includes(q) ||
      (gc.checkInTime && gc.checkInTime.toLowerCase().includes(q)) ||
      (gc.checkOutTime && gc.checkOutTime.toLowerCase().includes(q))
    );
  }

  displayedGuestCycles = [...displayedGuestCycles].sort((a, b) => {
    let comparison = 0;
    if (guestSortField === 'guestName') {
      comparison = a.guestName.localeCompare(b.guestName);
    } else if (guestSortField === 'propertyName') {
      comparison = a.propertyName.localeCompare(b.propertyName);
    } else if (guestSortField === 'roomNumber') {
      comparison = String(a.roomNumber).localeCompare(String(b.roomNumber), undefined, { numeric: true });
    } else if (guestSortField === 'status') {
      comparison = a.status.localeCompare(b.status);
    }
    return guestSortOrder === 'asc' ? comparison : -comparison;
  });

  const handleToggleGuestSort = (field: 'guestName' | 'propertyName' | 'roomNumber' | 'status') => {
    if (guestSortField === field) {
      setGuestSortOrder(guestSortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setGuestSortField(field);
      setGuestSortOrder('asc');
    }
  };

  // Logs
  let displayedLogs = logs.filter(l => logFilter === 'all' || l.type === logFilter);
  if (logSearchQuery.trim() !== '') {
    const q = logSearchQuery.toLowerCase();
    displayedLogs = displayedLogs.filter(l => 
      l.message.toLowerCase().includes(q) ||
      l.user.toLowerCase().includes(q) ||
      l.timestamp.toLowerCase().includes(q) ||
      l.type.toLowerCase().includes(q)
    );
  }

  displayedLogs = [...displayedLogs].sort((a, b) => {
    let comparison = 0;
    if (logSortField === 'timestamp') {
      comparison = a.timestamp.localeCompare(b.timestamp);
    } else if (logSortField === 'type') {
      comparison = a.type.localeCompare(b.type);
    } else if (logSortField === 'user') {
      comparison = a.user.localeCompare(b.user);
    } else if (logSortField === 'message') {
      comparison = a.message.localeCompare(b.message);
    }
    return logSortOrder === 'asc' ? comparison : -comparison;
  });

  const handleToggleLogSort = (field: 'timestamp' | 'type' | 'user' | 'message') => {
    if (logSortField === field) {
      setLogSortOrder(logSortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setLogSortField(field);
      setLogSortOrder('asc');
    }
  };

  const filteredMaint = maintenances.filter(m => maintFilter === 'all' || m.type === maintFilter);

  // Status Style Maps
  const propertyStatusStyles: Record<string, string> = {
    available: 'bg-emerald-100 text-emerald-800 border-emerald-200',
    rented: 'bg-rose-100 text-rose-800 border-rose-200',
    sold: 'bg-gray-100 text-gray-800 border-gray-200',
    maintenance: 'bg-amber-100 text-amber-800 border-amber-200',
    dirty: 'bg-purple-100 text-purple-800 border-purple-200',
    reserved: 'bg-sky-100 text-sky-800 border-sky-200',
  };

  const propertyStatusLabels: Record<string, string> = {
    available: 'Tersedia',
    rented: 'Disewa',
    sold: 'Terjual',
    maintenance: 'Pemeliharaan',
    dirty: 'Kotor / Pembersihan',
    reserved: 'Dipesan',
  };

  const maintenanceTypeStyles: Record<string, string> = {
    preventive: 'bg-blue-50 text-blue-700 border-blue-200',
    corrective: 'bg-red-50 text-red-700 border-red-200',
    predictive: 'bg-purple-50 text-purple-700 border-purple-200',
  };

  return (
    <div className="space-y-6" id="operations-hub-root">
      {/* Toast Alert */}
      {toast && (
        <div className="fixed bottom-5 right-5 z-50">
          <div className={`px-4 py-3 rounded-xl shadow-lg border text-xs font-semibold flex items-center space-x-2 ${
            toast.type === 'success' ? 'bg-emerald-50 text-emerald-800 border-emerald-100' : 'bg-red-50 text-red-800 border-red-100'
          }`}>
            <span>{toast.message}</span>
          </div>
        </div>
      )}

      {/* Hero Banner Header */}
      <div className="bg-gradient-to-r from-blue-900 to-indigo-950 p-6 rounded-2xl text-white shadow-md flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <div className="flex items-center space-x-2">
            <ClipboardList className="h-6 w-6 text-blue-400" />
            <h1 className="font-sans font-bold text-xl">Operational & Hotel Operations Hub</h1>
          </div>
          <p className="text-xs text-blue-200 mt-1 max-w-xl">
            Pusat kendali operasional SewaBeliPro: manajemen promo/iklan, siklus hidup tamu, 
            DP/Lunas tagihan, re-booking kamar, fasilitas gedung, komplain layanan, serta jadwal preventive & predictive maintenance.
          </p>
        </div>
        <button 
          onClick={() => fetchOperationalData(false)}
          disabled={loading}
          className="bg-white/10 hover:bg-white/20 px-4 py-2 rounded-xl text-xs font-semibold flex items-center gap-1.5 transition-all self-start md:self-auto cursor-pointer"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />
          Sinkronkan Data
        </button>
      </div>

      {/* Sub Tabs Navigation */}
      <div className="flex flex-wrap gap-2 border-b border-gray-100 pb-2">
        <button
          onClick={() => setActiveSubTab('promos-ads')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'promos-ads' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <Tag className="h-3.5 w-3.5" />
          <span>Promo, Kupon & Iklan</span>
        </button>

        <button
          onClick={() => setActiveSubTab('billing')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'billing' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <Receipt className="h-3.5 w-3.5" />
          <span>DP, Tagihan & Pembayaran</span>
        </button>

        <button
          onClick={() => setActiveSubTab('guest-cycle')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'guest-cycle' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <Calendar className="h-3.5 w-3.5" />
          <span>Siklus Tamu & Pindah Booking</span>
        </button>

        <button
          onClick={() => setActiveSubTab('fm')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'fm' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <Building className="h-3.5 w-3.5" />
          <span>Gedung & Status Properti</span>
        </button>

        <button
          onClick={() => setActiveSubTab('complaints')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'complaints' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <ShieldAlert className="h-3.5 w-3.5" />
          <span>Services & Komplain</span>
        </button>

        <button
          onClick={() => setActiveSubTab('maintenance')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'maintenance' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <Wrench className="h-3.5 w-3.5" />
          <span>Maintenance (P, C, Pd)</span>
        </button>

        <button
          onClick={() => setActiveSubTab('logs')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'logs' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <FileText className="h-3.5 w-3.5" />
          <span>Auditing Logs (User/System)</span>
        </button>

        <button
          onClick={() => setActiveSubTab('notifications')}
          className={`px-4 py-2 rounded-lg text-xs font-medium transition flex items-center space-x-1.5 cursor-pointer ${
            activeSubTab === 'notifications' ? 'bg-blue-600 text-white shadow-xs' : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-100'
          }`}
        >
          <Bell className="h-3.5 w-3.5" />
          <span>Simulasi & Logs Notifikasi (Email/WA)</span>
        </button>
      </div>

      {/* Contextual Action & Report Generation Bar */}
      <div className="bg-blue-50 border border-blue-100 rounded-xl p-4 my-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4" id="operations-reporting-banner">
        <div className="space-y-0.5">
          <p className="text-xs font-bold text-blue-900 flex items-center gap-1.5">
            <ClipboardList className="h-4 w-4 text-blue-600" />
            <span>Pusat Pelaporan Operasional Terintegrasi ({activeSubTab.toUpperCase()})</span>
          </p>
          <p className="text-[11px] text-blue-700 font-medium">Unduh rincian data tabular real-time untuk pembukuan keuangan, analisis keluhan, pemeliharaan aset, dan logs.</p>
        </div>
        <div className="flex gap-2 shrink-0">
          <button
            onClick={() => handleExportCSV(activeSubTab)}
            className="bg-blue-600 hover:bg-blue-700 text-white text-[11px] font-bold px-3.5 py-1.5 rounded-lg shadow-xs flex items-center gap-1.5 cursor-pointer transition-colors"
          >
            <FileText className="h-3.5 w-3.5" />
            <span>Ekspor Laporan CSV (Spreadsheet)</span>
          </button>
          <button
            onClick={() => handlePrintReport(activeSubTab)}
            className="bg-white hover:bg-gray-50 text-gray-700 text-[11px] font-bold px-3.5 py-1.5 rounded-lg border border-gray-200 shadow-xs flex items-center gap-1.5 cursor-pointer transition-colors"
          >
            <Printer className="h-3.5 w-3.5 text-gray-500" />
            <span>Cetak Laporan Resmi (PDF)</span>
          </button>
        </div>
      </div>

      {/* Grid Content / Selected Area */}
      <div className="bg-gray-50/30 p-2 rounded-xl">

        {/* SUB TAB 1: PROMOS, COUPONS, AND ADVERTISEMENTS */}
        {activeSubTab === 'promos-ads' && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
            {/* Left Column: Coupon / Promo Add & List */}
            <div className="lg:col-span-7 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-6">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <Tag className="h-4 w-4 text-emerald-600" />
                  <span>Manajemen Kupon & Promosi</span>
                </h3>
                <p className="text-[11px] text-gray-400">Buat kupon potongan langsung untuk pemesanan tamu harian atau sewa bulanan.</p>
              </div>

              <form onSubmit={handleAddPromo} className="grid grid-cols-1 md:grid-cols-2 gap-3 p-4 bg-gray-50/50 rounded-xl border border-gray-100">
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Kode Kupon/Promo</label>
                  <input 
                    type="text" 
                    value={newPromo.code} 
                    onChange={e => setNewPromo({...newPromo, code: e.target.value})} 
                    placeholder="Contoh: HEMATBANYAK" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs focus:ring-1 focus:ring-blue-500"
                    required
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Diskon Potongan (IDR)</label>
                  <input 
                    type="number" 
                    value={newPromo.discount} 
                    onChange={e => setNewPromo({...newPromo, discount: e.target.value})} 
                    placeholder="Contoh: 150000" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs focus:ring-1 focus:ring-blue-500"
                    required
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Tipe</label>
                  <select 
                    value={newPromo.type} 
                    onChange={e => setNewPromo({...newPromo, type: e.target.value})} 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                  >
                    <option value="coupon">Kupon Pengguna Baru</option>
                    <option value="promo">Promo Musiman</option>
                  </select>
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Kuota Pemakaian</label>
                  <input 
                    type="number" 
                    value={newPromo.maxUse} 
                    onChange={e => setNewPromo({...newPromo, maxUse: e.target.value})} 
                    placeholder="100" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Deskripsi Promosi</label>
                  <input 
                    type="text" 
                    value={newPromo.description} 
                    onChange={e => setNewPromo({...newPromo, description: e.target.value})} 
                    placeholder="Masukkan deskripsi penawaran..." 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                  />
                </div>
                <div className="md:col-span-2 flex justify-end">
                  <button type="submit" className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-1.5 rounded-lg text-xs font-bold shadow-xs flex items-center gap-1 cursor-pointer">
                    <Plus className="h-3.5 w-3.5" />
                    Simpan Promo
                  </button>
                </div>
              </form>

              <div className="space-y-2">
                <p className="text-xs font-bold text-gray-700">Daftar Kode Promo Aktif ({promos.length})</p>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {promos.map((p) => (
                    <div key={p.id} className="p-3 bg-white border border-gray-150 rounded-xl hover:shadow-xs transition-shadow flex items-start justify-between">
                      <div className="space-y-1">
                        <div className="flex items-center space-x-2">
                          <span className="font-mono bg-emerald-50 text-emerald-800 text-[10px] font-bold px-2 py-0.5 rounded border border-emerald-100 uppercase tracking-wide">
                            {p.code}
                          </span>
                          <span className="text-[10px] text-gray-400 capitalize">({p.type})</span>
                        </div>
                        <p className="text-xs font-extrabold text-gray-800">Potongan {formatIDR(p.discount)}</p>
                        <p className="text-[10px] text-gray-500 line-clamp-1">{p.description || 'Tidak ada deskripsi'}</p>
                        <p className="text-[9px] text-gray-400">Terpakai: {p.used || 0} / {p.maxUse || 100} kuota</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Right Column: Advertisements Placement */}
            <div className="lg:col-span-5 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-6">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <Megaphone className="h-4 w-4 text-orange-500" />
                  <span>Penempatan Banner & Iklan</span>
                </h3>
                <p className="text-[11px] text-gray-400">Atur penayangan baliho iklan marketing di halaman pencarian properti.</p>
              </div>

              <form onSubmit={handleAddAd} className="space-y-3 p-4 bg-gray-50/50 rounded-xl border border-gray-100">
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Judul / Kampanye Iklan</label>
                  <input 
                    type="text" 
                    value={newAd.title} 
                    onChange={e => setNewAd({...newAd, title: e.target.value})} 
                    placeholder="Contoh: Staycation Mewah Diskon 20%" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase mb-1">Upload Gambar Banner (Iklan) *</label>
                  
                  {/* Drag and Drop Zone */}
                  <div 
                    onDragEnter={handleAdDrag}
                    onDragOver={handleAdDrag}
                    onDragLeave={handleAdDrag}
                    onDrop={handleAdDrop}
                    onClick={() => {
                      const input = document.createElement('input');
                      input.type = 'file';
                      input.accept = 'image/*';
                      input.onchange = (e: any) => {
                        if (e.target.files && e.target.files[0]) {
                          handleAdFile(e.target.files[0]);
                        }
                      };
                      input.click();
                    }}
                    className={`border-2 border-dashed rounded-lg p-3 text-center cursor-pointer transition-all flex flex-col items-center justify-center space-y-1 min-h-[90px] ${
                      adDragActive 
                        ? 'border-blue-600 bg-blue-50/50' 
                        : 'border-gray-200 hover:border-blue-500 hover:bg-gray-50/40 bg-white'
                    }`}
                  >
                    {newAd.imageUrl && newAd.imageUrl.startsWith('data:') ? (
                      <div className="flex items-center gap-2">
                        <img src={newAd.imageUrl} alt="Uploaded" className="h-10 w-16 object-cover rounded border border-gray-100" />
                        <div className="text-left">
                          <p className="text-[10px] font-bold text-gray-800 line-clamp-1">
                            {uploadedAdFile ? uploadedAdFile.name : "Foto Terunggah"}
                          </p>
                          <p className="text-[9px] text-gray-400">
                            {uploadedAdFile ? uploadedAdFile.size : "Berhasil dikonversi"} • Siap Tayang
                          </p>
                        </div>
                      </div>
                    ) : (
                      <>
                        <Upload className="h-4 w-4 text-blue-500" />
                        <p className="text-[11px] font-bold text-gray-700">Seret & Lepas Gambar Iklan</p>
                        <p className="text-[9px] text-gray-400">atau klik untuk telusuri berkas</p>
                      </>
                    )}
                  </div>

                  {/* Alternative URL Input */}
                  <div className="mt-2">
                    <span className="text-[9px] text-gray-400 font-semibold block mb-0.5">Atau masukkan URL gambar langsung:</span>
                    <input 
                      type="text" 
                      value={newAd.imageUrl && !newAd.imageUrl.startsWith('data:') ? newAd.imageUrl : ''} 
                      onChange={e => {
                        setNewAd({...newAd, imageUrl: e.target.value});
                        setUploadedAdFile(null);
                      }} 
                      placeholder="https://images.unsplash.com/..." 
                      className="w-full px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                    />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Tautan Kampanye</label>
                    <input 
                      type="text" 
                      value={newAd.link} 
                      onChange={e => setNewAd({...newAd, link: e.target.value})} 
                      placeholder="#" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Posisi Tayang</label>
                    <select 
                      value={newAd.section} 
                      onChange={e => setNewAd({...newAd, section: e.target.value})} 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                    >
                      <option value="banner">Banner Atas</option>
                      <option value="sidebar">Sidebar Kanan</option>
                    </select>
                  </div>
                </div>
                <button type="submit" className="w-full bg-blue-600 hover:bg-blue-700 text-white py-1.5 rounded-lg text-xs font-bold cursor-pointer transition">
                  Tayangkan Iklan Sekarang
                </button>
              </form>

              <div className="space-y-3">
                <p className="text-xs font-bold text-gray-700">Iklan yang Sedang Tayang ({ads.length})</p>
                <div className="space-y-2">
                  {ads.map((ad) => (
                    <div key={ad.id} className="p-2 border border-gray-100 rounded-xl flex items-center space-x-3 bg-white">
                      <img src={ad.imageUrl} alt={ad.title} className="h-12 w-16 object-cover rounded-md bg-gray-50 shrink-0" />
                      <div className="min-w-0 flex-1">
                        <p className="text-xs font-bold text-gray-800 truncate">{ad.title}</p>
                        <div className="flex items-center space-x-1.5 mt-0.5">
                          <span className="text-[9px] bg-blue-50 text-blue-700 px-1.5 py-0.2 rounded font-semibold capitalize">{ad.section}</span>
                          <span className="text-[9px] text-green-600 font-bold">● Aktif</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* SUB TAB 2: BILLING, PAYMENTS, DP, AND LUNAS */}
        {activeSubTab === 'billing' && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
              {/* Manual Invoice Creation */}
              <div className="lg:col-span-4 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
                <div>
                  <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                    <Receipt className="h-4 w-4 text-indigo-600" />
                    <span>Buat Laporan Tagihan Baru</span>
                  </h3>
                  <p className="text-[11px] text-gray-400">Terbitkan tagihan baru dengan metode bayar, DP, atau pelunasan.</p>
                </div>

                <form onSubmit={handleAddPayment} className="space-y-3">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Pilih Transaksi (Opsional)</label>
                    <select 
                      value={newPayment.transactionId} 
                      onChange={e => {
                        const tx = transactions.find(t => t.id === e.target.value);
                        setNewPayment({
                          ...newPayment, 
                          transactionId: e.target.value,
                          propertyName: tx ? tx.propertyName : '',
                          totalAmount: tx ? String(tx.totalPrice) : ''
                        });
                      }} 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                    >
                      <option value="">-- Manual Tanpa Booking --</option>
                      {transactions.map(t => (
                        <option key={t.id} value={t.id}>#{t.id} - {t.buyerName} ({t.propertyName})</option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Nama Properti / Tagihan</label>
                    <input 
                      type="text" 
                      value={newPayment.propertyName} 
                      onChange={e => setNewPayment({...newPayment, propertyName: e.target.value})} 
                      placeholder="Contoh: Sewa Kamar Grand Melia" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      required
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase">Total Tagihan (Rp)</label>
                      <input 
                        type="number" 
                        value={newPayment.totalAmount} 
                        onChange={e => setNewPayment({...newPayment, totalAmount: e.target.value})} 
                        placeholder="1500000" 
                        className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase">DP / Terbayar (Rp)</label>
                      <input 
                        type="number" 
                        value={newPayment.amountPaid} 
                        onChange={e => setNewPayment({...newPayment, amountPaid: e.target.value})} 
                        placeholder="500000" 
                        className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase">Status Siklus Tagihan</label>
                      <select 
                        value={newPayment.type} 
                        onChange={e => setNewPayment({...newPayment, type: e.target.value})} 
                        className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                      >
                        <option value="DP">Uang Muka / DP</option>
                        <option value="lunas">Lunas / Pembayaran Penuh</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase">Metode Pembayaran</label>
                      <select 
                        value={newPayment.paymentMethod} 
                        onChange={e => setNewPayment({...newPayment, paymentMethod: e.target.value})} 
                        className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                      >
                        <option value="Bank Transfer - Mandiri">Mandiri Transfer</option>
                        <option value="Bank Transfer - BCA">BCA Transfer</option>
                        <option value="Credit Card">Kartu Kredit</option>
                        <option value="E-Wallet (OVO/Gopay)">E-Wallet</option>
                        <option value="Tunai / Cash">Tunai / Cash</option>
                      </select>
                    </div>
                  </div>

                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Catatan Pembayaran & Konfirmasi</label>
                    <input 
                      type="text" 
                      value={newPayment.notes} 
                      onChange={e => setNewPayment({...newPayment, notes: e.target.value})} 
                      placeholder="Contoh: DP 30% sisa dilunasi saat check-in" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    />
                  </div>

                  <button type="submit" className="w-full bg-indigo-600 hover:bg-indigo-700 text-white py-1.5 rounded-lg text-xs font-bold transition cursor-pointer">
                    Buat Tagihan Baru
                  </button>
                </form>
              </div>

              {/* Tagihan / Billing Reports */}
              <div className="lg:col-span-8 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
                <div>
                  <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                    <FileText className="h-4 w-4 text-indigo-600" />
                    <span>Laporan Rincian & Status Tagihan</span>
                  </h3>
                  <p className="text-[11px] text-gray-400">Daftar rekonsiliasi tagihan pembayaran lunas, cicilan, dan deposit (DP) dari seluruh aktivitas.</p>
                </div>

                {/* SEARCH BAR FOR PAYMENTS */}
                <div className="relative w-full">
                  <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Cari tagihan berdasarkan properti, catatan, metode, status..."
                    value={paymentSearchQuery}
                    onChange={(e) => setPaymentSearchQuery(e.target.value)}
                    className="w-full bg-gray-50 border border-gray-200 rounded-lg pl-9 pr-4 py-2 text-xs focus:outline-hidden focus:ring-2 focus:ring-blue-100 focus:bg-white focus:border-blue-500 transition-all text-gray-800"
                  />
                </div>

                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse text-xs">
                    <thead>
                      <tr className="border-b border-gray-100 text-gray-400 font-bold uppercase bg-gray-50/50">
                        <th className="py-2.5 px-4 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleTogglePaymentSort('id')}>
                          <div className="flex items-center space-x-1">
                            <span>ID Tagihan</span>
                            {paymentSortField === 'id' ? (paymentSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                          </div>
                        </th>
                        <th className="py-2.5 px-4 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleTogglePaymentSort('propertyName')}>
                          <div className="flex items-center space-x-1">
                            <span>Properti</span>
                            {paymentSortField === 'propertyName' ? (paymentSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                          </div>
                        </th>
                        <th className="py-2.5 px-4">Siklus</th>
                        <th className="py-2.5 px-4 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleTogglePaymentSort('totalAmount')}>
                          <div className="flex items-center space-x-1">
                            <span>Total Biaya</span>
                            {paymentSortField === 'totalAmount' ? (paymentSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                          </div>
                        </th>
                        <th className="py-2.5 px-4 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleTogglePaymentSort('amountPaid')}>
                          <div className="flex items-center space-x-1">
                            <span>Telah Dibayar</span>
                            {paymentSortField === 'amountPaid' ? (paymentSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                          </div>
                        </th>
                        <th className="py-2.5 px-4">Metode / Catatan</th>
                        <th className="py-2.5 px-4 text-center">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-50">
                      {displayedPayments.length === 0 ? (
                        <tr>
                          <td colSpan={7} className="text-center py-8 text-gray-400 italic">
                            Tidak ada data tagihan yang sesuai pencarian.
                          </td>
                        </tr>
                      ) : (
                        displayedPayments.map(p => {
                        const unpaidAmount = p.totalAmount - p.amountPaid;
                        return (
                          <tr key={p.id} className="hover:bg-gray-50/10 text-gray-700">
                            <td className="py-3 px-4 font-mono font-semibold text-gray-400">#{p.id.substring(4, 9)}</td>
                            <td className="py-3 px-4">
                              <span className="font-bold text-gray-900 block">{p.propertyName}</span>
                              <span className="text-[10px] text-gray-400 font-medium">Batas: {p.dueDate}</span>
                            </td>
                            <td className="py-3 px-4">
                              <span className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                                p.type === 'DP' ? 'bg-amber-50 text-amber-700 border border-amber-200' : 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                              }`}>
                                {p.type === 'DP' ? 'DP (Muka)' : 'Lunas'}
                              </span>
                            </td>
                            <td className="py-3 px-4 font-bold text-gray-900">{formatIDR(p.totalAmount)}</td>
                            <td className="py-3 px-4">
                              <span className="font-semibold text-emerald-600 block">{formatIDR(p.amountPaid)}</span>
                              {unpaidAmount > 0 && (
                                <span className="text-[9px] text-red-500 block">Kurang: {formatIDR(unpaidAmount)}</span>
                              )}
                            </td>
                            <td className="py-3 px-4">
                              <p className="text-[10px] font-medium text-gray-600">{p.paymentMethod}</p>
                              <p className="text-[9px] text-gray-400 italic line-clamp-1">{p.notes || '-'}</p>
                            </td>
                            <td className="py-3 px-4 text-center">
                              {p.status === 'paid' ? (
                                <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-700 bg-emerald-50 px-2.5 py-0.5 rounded-full border border-emerald-100">
                                  ✓ Selesai
                                </span>
                              ) : (
                                <div className="space-y-1">
                                  <span className="inline-block text-[10px] font-bold text-amber-700 bg-amber-50 px-2 py-0.5 rounded border border-amber-100">
                                    Belum Lunas
                                  </span>
                                  <button
                                    onClick={() => handleUpdatePaymentStatus(p.id, { amountPaid: p.totalAmount, status: 'paid' })}
                                    className="block mx-auto text-[9px] font-bold text-indigo-600 hover:underline cursor-pointer"
                                  >
                                    Konfirmasi Lunas
                                  </button>
                                </div>
                              )}
                            </td>
                          </tr>
                        );
                      }))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* SUB TAB 3: GUEST LIFECYCLE & MOVE BOOKING (Pindah Kamar) */}
        {activeSubTab === 'guest-cycle' && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
            {/* Left Column: Guest Lifecycle Monitor */}
            <div className="lg:col-span-8 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <Clock className="h-4 w-4 text-blue-600" />
                  <span>Siklus Hidup Tamu (Guest Life-Cycle)</span>
                </h3>
                <p className="text-[11px] text-gray-400">Pantau dan kelola proses kedatangan, menginap (check-in), hingga kepulangan (check-out) tamu.</p>
              </div>

              {/* SEARCH BAR FOR GUESTS */}
              <div className="relative w-full">
                <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="Cari tamu berdasarkan nama, properti, nomor kamar, status..."
                  value={guestSearchQuery}
                  onChange={(e) => setGuestSearchQuery(e.target.value)}
                  className="w-full bg-gray-50 border border-gray-200 rounded-lg pl-9 pr-4 py-2 text-xs focus:outline-hidden focus:ring-2 focus:ring-blue-100 focus:bg-white focus:border-blue-500 transition-all text-gray-800"
                />
              </div>

              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse text-xs">
                  <thead>
                    <tr className="border-b border-gray-100 text-gray-400 font-bold uppercase bg-gray-50/50">
                      <th className="py-2.5 px-4 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleToggleGuestSort('guestName')}>
                        <div className="flex items-center space-x-1">
                          <span>Nama Tamu</span>
                          {guestSortField === 'guestName' ? (guestSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                        </div>
                      </th>
                      <th className="py-2.5 px-4 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleToggleGuestSort('propertyName')}>
                        <div className="flex items-center space-x-1">
                          <span>Akomodasi & Unit</span>
                          {guestSortField === 'propertyName' ? (guestSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                        </div>
                      </th>
                      <th className="py-2.5 px-4">Check-In</th>
                      <th className="py-2.5 px-4">Check-Out</th>
                      <th className="py-2.5 px-4 text-center cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleToggleGuestSort('status')}>
                        <div className="flex items-center justify-center space-x-1">
                          <span>Status Alur</span>
                          {guestSortField === 'status' ? (guestSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                        </div>
                      </th>
                      <th className="py-2.5 px-4 text-center">Aksi Cepat</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-50 text-gray-700">
                    {displayedGuestCycles.length === 0 ? (
                      <tr>
                        <td colSpan={6} className="text-center py-8 text-gray-400 italic">
                          Tidak ada data tamu yang sesuai pencarian.
                        </td>
                      </tr>
                    ) : (
                      displayedGuestCycles.map(gc => (
                      <tr key={gc.id} className="hover:bg-gray-50/10">
                        <td className="py-3 px-4 font-bold text-gray-900">{gc.guestName}</td>
                        <td className="py-3 px-4">
                          <span className="block font-semibold">{gc.propertyName}</span>
                          <span className="text-[10px] text-gray-400">No. Ruangan: {gc.roomNumber}</span>
                        </td>
                        <td className="py-3 px-4 font-mono text-gray-500">{gc.checkInTime}</td>
                        <td className="py-3 px-4 font-mono text-gray-500">{gc.checkOutTime}</td>
                        <td className="py-3 px-4 text-center">
                          <span className={`inline-block px-2.5 py-0.5 text-[10px] font-bold rounded-full ${
                            gc.status === 'Checked In' ? 'bg-emerald-50 text-emerald-800 border border-emerald-100' :
                            gc.status === 'Reserved' ? 'bg-blue-50 text-blue-800 border border-blue-100' :
                            gc.status === 'Checked Out' ? 'bg-gray-100 text-gray-700 border border-gray-200' :
                            'bg-red-50 text-red-800 border border-red-150'
                          }`}>
                            {gc.status}
                          </span>
                        </td>
                        <td className="py-3 px-4 text-center">
                          <div className="flex justify-center gap-1.5">
                            {gc.status === 'Reserved' && (
                              <button 
                                onClick={() => handleUpdateGuestStatus(gc.id, 'Checked In')}
                                className="bg-emerald-600 hover:bg-emerald-700 text-white px-2 py-0.8 rounded text-[9px] font-bold cursor-pointer"
                              >
                                Check In
                              </button>
                            )}
                            {gc.status === 'Checked In' && (
                              <button 
                                onClick={() => handleUpdateGuestStatus(gc.id, 'Checked Out')}
                                className="bg-gray-600 hover:bg-gray-700 text-white px-2 py-0.8 rounded text-[9px] font-bold cursor-pointer"
                              >
                                Check Out
                              </button>
                            )}
                            <button 
                              onClick={() => handleUpdateGuestStatus(gc.id, 'Cancelled')}
                              className="text-red-500 hover:text-red-700 text-[9px] font-bold px-1 py-0.8"
                            >
                              Batalkan
                            </button>
                          </div>
                        </td>
                      </tr>
                    )))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Right Column: Move Booking (Ganti Kamar) */}
            <div className="lg:col-span-4 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <ArrowLeftRight className="h-4 w-4 text-blue-600 animate-pulse" />
                  <span>Pindah Unit / Ganti Pemesanan</span>
                </h3>
                <p className="text-[11px] text-gray-400">Modifikasi pesanan yang sudah dibuat, seperti ganti properti/kamar atau penyesuaian tanggal.</p>
              </div>

              <form onSubmit={handleMoveBooking} className="space-y-3 bg-blue-50/40 p-4 rounded-xl border border-blue-100">
                <div>
                  <label className="block text-[10px] font-bold text-blue-900 uppercase">Pilih Pemesanan Tamu</label>
                  <select 
                    value={selectedTxId} 
                    onChange={e => {
                      setSelectedTxId(e.target.value);
                      const tx = transactions.find(t => t.id === e.target.value);
                      if (tx) {
                        setMoveStartDate(tx.startDate || '');
                        setMoveEndDate(tx.endDate || '');
                      }
                    }}
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white text-gray-700"
                    required
                  >
                    <option value="">-- Pilih Booking Tamu --</option>
                    {transactions.map(t => (
                      <option key={t.id} value={t.id}>#{t.id} - {t.buyerName} ({t.propertyName})</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-blue-900 uppercase">Pindahkan Ke Properti / Kamar Baru</label>
                  <select 
                    value={moveTargetPropId} 
                    onChange={e => setMoveTargetPropId(e.target.value)}
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white text-gray-700"
                    required
                  >
                    <option value="">-- Pilih Properti Tujuan --</option>
                    {myProperties.map(p => (
                      <option key={p.id} value={p.id}>{p.name} ({p.type} - {p.status})</option>
                    ))}
                  </select>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label className="block text-[10px] font-bold text-blue-900 uppercase">Tanggal Mulai Baru</label>
                    <input 
                      type="date" 
                      value={moveStartDate} 
                      onChange={e => setMoveStartDate(e.target.value)}
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs text-gray-700"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-blue-900 uppercase">Tanggal Selesai Baru</label>
                    <input 
                      type="date" 
                      value={moveEndDate} 
                      onChange={e => setMoveEndDate(e.target.value)}
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs text-gray-700"
                    />
                  </div>
                </div>

                <div className="pt-2">
                  <button type="submit" className="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg text-xs font-bold transition flex items-center justify-center gap-1 cursor-pointer">
                    <ArrowLeftRight className="h-3.5 w-3.5" />
                    Simpan & Pindahkan Booking
                  </button>
                  <p className="text-[10px] text-gray-400 mt-2 text-center">Tindakan ini akan mengosongkan status unit lama dan memperbarui unit tujuan otomatis.</p>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* SUB TAB 4: BUILDING, FACILITIES & ROOM STATUS (FM) */}
        {activeSubTab === 'fm' && (
          <div className="space-y-6">
            {/* Color Legend explanation */}
            <div className="bg-white p-4 rounded-xl border border-gray-150 flex flex-wrap gap-4 items-center">
              <span className="text-xs font-bold text-gray-600">Panduan Warna Status Unit:</span>
              <div className="flex items-center space-x-1.5">
                <span className="h-3.5 w-3.5 rounded-full bg-emerald-500"></span>
                <span className="text-[10px] text-gray-600 font-semibold">Tersedia (Available)</span>
              </div>
              <div className="flex items-center space-x-1.5">
                <span className="h-3.5 w-3.5 rounded-full bg-rose-500"></span>
                <span className="text-[10px] text-gray-600 font-semibold">Disewa / Terjual (Occupied / Sold)</span>
              </div>
              <div className="flex items-center space-x-1.5">
                <span className="h-3.5 w-3.5 rounded-full bg-sky-500"></span>
                <span className="text-[10px] text-gray-600 font-semibold">Dipesan (Reserved)</span>
              </div>
              <div className="flex items-center space-x-1.5">
                <span className="h-3.5 w-3.5 rounded-full bg-amber-500"></span>
                <span className="text-[10px] text-gray-600 font-semibold">Pemeliharaan (Maintenance)</span>
              </div>
              <div className="flex items-center space-x-1.5">
                <span className="h-3.5 w-3.5 rounded-full bg-purple-500"></span>
                <span className="text-[10px] text-gray-600 font-semibold">Kotor / Dirty</span>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
              {/* Left Side: Gedung & Fasilitas */}
              <div className="lg:col-span-5 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-6">
                <div>
                  <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                    <Building className="h-4 w-4 text-slate-700" />
                    <span>Manajemen Gedung (Building Portfolio)</span>
                  </h3>
                  <p className="text-[11px] text-gray-400">Tambahkan daftar gedung / menara yang dikelola dalam naungan sistem.</p>
                </div>

                <form onSubmit={handleAddBuilding} className="space-y-3 bg-gray-50/50 p-4 rounded-xl border border-gray-100">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Nama Gedung / Menara</label>
                    <input 
                      type="text" 
                      value={newBuilding.name} 
                      onChange={e => setNewBuilding({...newBuilding, name: e.target.value})} 
                      placeholder="Contoh: Tower B - Sudirman Residence" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Alamat Lokasi</label>
                    <input 
                      type="text" 
                      value={newBuilding.address} 
                      onChange={e => setNewBuilding({...newBuilding, address: e.target.value})} 
                      placeholder="Contoh: Jl. Sudirman Kav 22, Jakarta" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase">Jumlah Lantai</label>
                      <input 
                        type="number" 
                        value={newBuilding.floors} 
                        onChange={e => setNewBuilding({...newBuilding, floors: e.target.value})} 
                        className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase">Total Unit</label>
                      <input 
                        type="number" 
                        value={newBuilding.unitCount} 
                        onChange={e => setNewBuilding({...newBuilding, unitCount: e.target.value})} 
                        className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      />
                    </div>
                  </div>
                  <button type="submit" className="w-full bg-slate-700 hover:bg-slate-800 text-white py-1.5 rounded-lg text-xs font-bold cursor-pointer">
                    Daftarkan Gedung Baru
                  </button>
                </form>

                <div className="space-y-3">
                  <p className="text-xs font-bold text-gray-700">Gedung / Properti Terdaftar ({buildings.length})</p>
                  <div className="grid grid-cols-1 gap-2">
                    {buildings.map((b) => (
                      <div key={b.id} className="p-3 border border-gray-100 rounded-xl bg-white flex items-center justify-between">
                        <div>
                          <p className="text-xs font-bold text-gray-800">{b.name}</p>
                          <p className="text-[10px] text-gray-400 truncate max-w-xs">{b.address}</p>
                        </div>
                        <div className="text-right">
                          <span className="text-[10px] font-mono font-bold bg-slate-100 px-2 py-0.5 rounded text-slate-700">{b.floors} Lantai</span>
                          <p className="text-[9px] text-gray-400 mt-0.5">{b.unitCount} Unit Kamar</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Right Side: Kelola Status Properti Langsung & Fasilitas */}
              <div className="lg:col-span-7 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-6">
                <div>
                  <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                    <Dumbbell className="h-4 w-4 text-emerald-600" />
                    <span>Layanan Fasilitas Gedung (Facilities Management)</span>
                  </h3>
                  <p className="text-[11px] text-gray-400">Pantau status fungsionalitas dan kondisi fasilitas umum gedung.</p>
                </div>

                <form onSubmit={handleAddFacility} className="grid grid-cols-1 md:grid-cols-3 gap-3 p-4 bg-gray-50/50 rounded-xl border border-gray-100">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Nama Fasilitas</label>
                    <input 
                      type="text" 
                      value={newFacility.name} 
                      onChange={e => setNewFacility({...newFacility, name: e.target.value})} 
                      placeholder="Contoh: Sauna & Spa" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Kategori / Tipe</label>
                    <input 
                      type="text" 
                      value={newFacility.type} 
                      onChange={e => setNewFacility({...newFacility, type: e.target.value})} 
                      placeholder="Rekreasi / Olahraga" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Lokasi Penempatan</label>
                    <input 
                      type="text" 
                      value={newFacility.location} 
                      onChange={e => setNewFacility({...newFacility, location: e.target.value})} 
                      placeholder="Lantai 5 Tower Utama" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    />
                  </div>
                  <div className="md:col-span-3 flex justify-end">
                    <button type="submit" className="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-1.5 rounded-lg text-xs font-bold cursor-pointer">
                      Simpan Fasilitas
                    </button>
                  </div>
                </form>

                <div className="space-y-3">
                  <p className="text-xs font-bold text-gray-700">Status Operasional Fasilitas ({facilities.length})</p>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                    {facilities.map((f) => (
                      <div key={f.id} className="p-3 border border-gray-100 rounded-xl bg-white flex items-center justify-between">
                        <div>
                          <p className="text-xs font-bold text-gray-800">{f.name}</p>
                          <p className="text-[10px] text-gray-400">{f.type} • {f.location}</p>
                        </div>
                        <div>
                          <select 
                            value={f.status} 
                            onChange={e => handleUpdateFacilityStatus(f.id, e.target.value)}
                            className={`px-2 py-0.5 rounded text-[10px] font-bold bg-white border cursor-pointer ${
                              f.status === 'Aktif' ? 'text-green-700 border-green-200 bg-green-50' :
                              f.status === 'Maintenance' ? 'text-amber-700 border-amber-200 bg-amber-50' :
                              'text-red-700 border-red-200 bg-red-50'
                            }`}
                          >
                            <option value="Aktif">Aktif</option>
                            <option value="Maintenance">Maintenance</option>
                            <option value="Rusak">Rusak / Mati</option>
                          </select>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="pt-4 border-t border-gray-100 space-y-3">
                  <p className="text-xs font-bold text-gray-700">Ubah Status Ruangan / Properti Langsung</p>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2 max-h-[220px] overflow-y-auto pr-1">
                    {myProperties.map((p) => (
                      <div key={p.id} className="p-2 border border-gray-100 rounded-lg flex items-center justify-between bg-white hover:bg-gray-50/50">
                        <span className="text-xs font-bold text-gray-800 truncate max-w-[150px]">{p.name}</span>
                        <select 
                          value={p.status} 
                          onChange={e => handleUpdatePropertyStatus(p.id, e.target.value)}
                          className={`px-2 py-0.5 rounded text-[10px] font-bold border cursor-pointer ${propertyStatusStyles[p.status]}`}
                        >
                          <option value="available">Tersedia</option>
                          <option value="rented">Rented (Sewa)</option>
                          <option value="sold">Sold (Terjual)</option>
                          <option value="maintenance">Maintenance</option>
                          <option value="dirty">Kotor</option>
                          <option value="reserved">Direservasi</option>
                        </select>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* SUB TAB 5: COMPLAINTS & SERVICES */}
        {activeSubTab === 'complaints' && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
            {/* Left Column: Complaint Logger Form */}
            <div className="lg:col-span-4 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <ShieldAlert className="h-4 w-4 text-red-600" />
                  <span>Laporkan Komplain & Masalah</span>
                </h3>
                <p className="text-[11px] text-gray-400">Laporkan keluhan pelayanan atau kerusakan infrastruktur dari unit sewa.</p>
              </div>

              <form onSubmit={handleAddComplaint} className="space-y-3">
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Nama Tamu Pelapor</label>
                  <input 
                    type="text" 
                    value={newComplaint.guestName} 
                    onChange={e => setNewComplaint({...newComplaint, guestName: e.target.value})} 
                    placeholder="Contoh: Ani Wijaya" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Pilih Akomodasi Bermasalah</label>
                  <select 
                    value={newComplaint.propertyName} 
                    onChange={e => setNewComplaint({...newComplaint, propertyName: e.target.value})} 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white text-gray-700"
                    required
                  >
                    <option value="">-- Pilih Properti --</option>
                    {myProperties.map(p => (
                      <option key={p.id} value={p.name}>{p.name}</option>
                    ))}
                  </select>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Kategori</label>
                    <select 
                      value={newComplaint.category} 
                      onChange={e => setNewComplaint({...newComplaint, category: e.target.value})} 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                    >
                      <option value="Fasilitas">Infrastruktur/Fasilitas</option>
                      <option value="Layanan">Pelayanan Staff</option>
                      <option value="Kebersihan">Kebersihan Unit</option>
                      <option value="Lainnya">Lainnya</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Prioritas Penanganan</label>
                    <select 
                      value={newComplaint.priority} 
                      onChange={e => setNewComplaint({...newComplaint, priority: e.target.value})} 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white"
                    >
                      <option value="High">Tinggi (High)</option>
                      <option value="Medium">Sedang (Medium)</option>
                      <option value="Low">Rendah (Low)</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Subjek Keluhan</label>
                  <input 
                    type="text" 
                    value={newComplaint.title} 
                    onChange={e => setNewComplaint({...newComplaint, title: e.target.value})} 
                    placeholder="Contoh: Kebocoran Pipa Wastafel" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Rincian Deskripsi Masalah</label>
                  <textarea 
                    value={newComplaint.description} 
                    onChange={e => setNewComplaint({...newComplaint, description: e.target.value})} 
                    placeholder="Deskripsikan dengan detail..." 
                    rows={3}
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs focus:ring-1 focus:ring-blue-500"
                    required
                  ></textarea>
                </div>

                <button type="submit" className="w-full bg-red-600 hover:bg-red-700 text-white py-1.5 rounded-lg text-xs font-bold cursor-pointer transition">
                  Kirim Pengaduan Tamu
                </button>
              </form>
            </div>

            {/* Right Column: Complaints List & Resolution Panel */}
            <div className="lg:col-span-8 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <ClipboardList className="h-4 w-4 text-red-600" />
                  <span>Daftar & Penanganan Komplain</span>
                </h3>
                <p className="text-[11px] text-gray-400">Pantau proses tindak lanjut penyelesaian komplain pelayanan tamu.</p>
              </div>

              <div className="space-y-3">
                {complaints.map(c => (
                  <div key={c.id} className="p-4 border border-gray-150 rounded-xl bg-gray-50/20 space-y-3 hover:shadow-xs transition">
                    <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
                      <div>
                        <div className="flex items-center space-x-2">
                          <span className={`px-2 py-0.2 rounded text-[9px] font-bold ${
                            c.priority === 'High' ? 'bg-red-100 text-red-850' : 
                            c.priority === 'Medium' ? 'bg-amber-100 text-amber-800' : 
                            'bg-blue-100 text-blue-800'
                          }`}>
                            Prioritas: {c.priority}
                          </span>
                          <span className="text-[10px] text-gray-400">{c.category}</span>
                        </div>
                        <h4 className="font-sans font-bold text-xs text-gray-900 mt-1">{c.title}</h4>
                        <p className="text-[10px] text-gray-500">Oleh: <strong>{c.guestName}</strong> di {c.propertyName} • {c.createdAt}</p>
                      </div>
                      <div className="flex items-center space-x-1">
                        <span className={`px-2.5 py-1 text-[10px] font-bold rounded-full ${
                          c.status === 'resolved' ? 'bg-emerald-100 text-emerald-800' :
                          c.status === 'in_progress' ? 'bg-amber-100 text-amber-800 animate-pulse' :
                          'bg-red-100 text-red-800'
                        }`}>
                          {c.status === 'resolved' ? '✓ Selesai' : c.status === 'in_progress' ? 'Diproses' : 'Pending'}
                        </span>
                      </div>
                    </div>

                    <p className="text-xs text-gray-600 bg-white p-2.5 rounded-lg border border-gray-100 leading-relaxed font-mono">
                      {c.description}
                    </p>

                    {c.resolution && (
                      <div className="bg-emerald-50/50 p-2.5 rounded-lg border border-emerald-100 space-y-0.5">
                        <p className="text-[10px] font-bold text-emerald-900">Solusi Penyelesaian:</p>
                        <p className="text-xs text-emerald-800">{c.resolution}</p>
                      </div>
                    )}

                    {c.status !== 'resolved' && (
                      <div className="flex flex-wrap items-center gap-2 pt-2 border-t border-gray-100">
                        <input 
                          type="text" 
                          id={`res-${c.id}`} 
                          placeholder="Ketik tindakan / solusi perbaikan..." 
                          className="flex-1 px-3 py-1 border border-gray-200 rounded-lg text-xs"
                        />
                        <button 
                          onClick={() => {
                            const val = (document.getElementById(`res-${c.id}`) as HTMLInputElement)?.value;
                            handleUpdateComplaint(c.id, 'in_progress', val || 'Sedang dicek oleh teknisi.');
                          }}
                          className="bg-amber-500 hover:bg-amber-600 text-white px-3 py-1 rounded-lg text-[10px] font-bold cursor-pointer"
                        >
                          Tindak Lanjut
                        </button>
                        <button 
                          onClick={() => {
                            const val = (document.getElementById(`res-${c.id}`) as HTMLInputElement)?.value;
                            handleUpdateComplaint(c.id, 'resolved', val || 'Masalah telah diselesaikan sepenuhnya.');
                          }}
                          className="bg-emerald-600 hover:bg-emerald-700 text-white px-3 py-1 rounded-lg text-[10px] font-bold cursor-pointer"
                        >
                          Selesaikan
                        </button>
                      </div>
                    )}
                  </div>
                ))}
                {complaints.length === 0 && (
                  <p className="text-center py-8 text-gray-400 italic text-xs">Semua aman! Belum ada komplain atau keluhan masuk.</p>
                )}
              </div>
            </div>
          </div>
        )}

        {/* SUB TAB 6: MAINTENANCE (PREVENTIVE, CORRECTIVE, PREDICTIVE) */}
        {activeSubTab === 'maintenance' && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
            {/* Left Column: Maintenance Ticket Form */}
            <div className="lg:col-span-4 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <Wrench className="h-4 w-4 text-blue-600" />
                  <span>Daftar Pemeliharaan & Kerusakan</span>
                </h3>
                <p className="text-[11px] text-gray-400">Jadwalkan pemeliharaan aset preventif, perbaikan kerusakan korektif, atau analisis prediktif.</p>
              </div>

              <form onSubmit={handleAddMaint} className="space-y-3">
                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Pilih Properti / Unit</label>
                  <select 
                    value={newMaint.propertyId} 
                    onChange={e => setNewMaint({...newMaint, propertyId: e.target.value})} 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white text-gray-700"
                    required
                  >
                    <option value="">-- Pilih Properti --</option>
                    {myProperties.map(p => (
                      <option key={p.id} value={p.id}>{p.name}</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Nama Aset / Mesin</label>
                  <input 
                    type="text" 
                    value={newMaint.assetName} 
                    onChange={e => setNewMaint({...newMaint, assetName: e.target.value})} 
                    placeholder="Contoh: Genset Utama, Pompa Lantai 3" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-500 uppercase">Detail Kerusakan / Masalah</label>
                  <input 
                    type="text" 
                    value={newMaint.issue} 
                    onChange={e => setNewMaint({...newMaint, issue: e.target.value})} 
                    placeholder="Contoh: Penggantian oli bulanan" 
                    className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    required
                  />
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Jenis Maintenance</label>
                    <select 
                      value={newMaint.type} 
                      onChange={e => setNewMaint({...newMaint, type: e.target.value})} 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs bg-white text-gray-700"
                    >
                      <option value="preventive">Preventive (Pencegahan)</option>
                      <option value="corrective">Corrective (Perbaikan)</option>
                      <option value="predictive">Predictive (Prediktif)</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-500 uppercase">Estimasi Biaya (Rp)</label>
                    <input 
                      type="number" 
                      value={newMaint.cost} 
                      onChange={e => setNewMaint({...newMaint, cost: e.target.value})} 
                      placeholder="1200000" 
                      className="w-full mt-1 px-3 py-1.5 border border-gray-200 rounded-lg text-xs"
                    />
                  </div>
                </div>

                <button type="submit" className="w-full bg-blue-600 hover:bg-blue-700 text-white py-1.5 rounded-lg text-xs font-bold transition cursor-pointer">
                  Terbitkan Tiket Maintenance
                </button>
              </form>
            </div>

            {/* Right Column: Maintenance Tasks List with color status */}
            <div className="lg:col-span-8 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
              <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
                <div>
                  <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                    <Wrench className="h-4 w-4 text-blue-600" />
                    <span>Daftar Pemeliharaan Aset</span>
                  </h3>
                  <p className="text-[11px] text-gray-400">Manajemen jenis preventive, corrective (perbaikan kerusakan), dan predictive maintenance.</p>
                </div>

                <div className="flex space-x-1 shrink-0">
                  <button 
                    onClick={() => setMaintFilter('all')} 
                    className={`px-2 py-1 rounded text-[10px] font-semibold border ${maintFilter === 'all' ? 'bg-blue-600 text-white border-blue-600' : 'bg-white text-gray-600 border-gray-100'}`}
                  >
                    Semua
                  </button>
                  <button 
                    onClick={() => setMaintFilter('preventive')} 
                    className={`px-2 py-1 rounded text-[10px] font-semibold border ${maintFilter === 'preventive' ? 'bg-blue-50 text-blue-700 border-blue-200' : 'bg-white text-gray-600 border-gray-100'}`}
                  >
                    Preventive
                  </button>
                  <button 
                    onClick={() => setMaintFilter('corrective')} 
                    className={`px-2 py-1 rounded text-[10px] font-semibold border ${maintFilter === 'corrective' ? 'bg-red-50 text-red-700 border-red-200' : 'bg-white text-gray-600 border-gray-100'}`}
                  >
                    Corrective
                  </button>
                  <button 
                    onClick={() => setMaintFilter('predictive')} 
                    className={`px-2 py-1 rounded text-[10px] font-semibold border ${maintFilter === 'predictive' ? 'bg-purple-50 text-purple-700 border-purple-200' : 'bg-white text-gray-600 border-gray-100'}`}
                  >
                    Predictive
                  </button>
                </div>
              </div>

              <div className="space-y-3">
                {filteredMaint.map(m => (
                  <div key={m.id} className="p-4 border border-gray-150 rounded-xl bg-white space-y-3 hover:shadow-xs transition">
                    <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
                      <div>
                        <div className="flex items-center space-x-2">
                          <span className={`px-2.5 py-0.5 rounded text-[10px] font-bold border ${maintenanceTypeStyles[m.type]}`}>
                            {m.type === 'preventive' ? 'Pencegahan (Preventive)' : m.type === 'corrective' ? 'Kerusakan (Corrective)' : 'Prediktif (Predictive)'}
                          </span>
                          <span className="text-[10px] text-gray-400">ID: #{m.id.substring(2, 7)}</span>
                        </div>
                        <h4 className="font-sans font-bold text-xs text-gray-900 mt-1">{m.assetName}</h4>
                        <p className="text-[10px] text-gray-500">Properti: <strong>{m.propertyName}</strong> • Masalah: {m.issue}</p>
                      </div>

                      <div className="text-right">
                        <p className="text-xs font-extrabold text-gray-900">{formatIDR(m.cost)}</p>
                        <p className="text-[9px] text-gray-400">Diajukan: {m.createdAt}</p>
                      </div>
                    </div>

                    <div className="flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-gray-100">
                      <div className="flex items-center space-x-1">
                        <span className="text-[10px] text-gray-400">Status Tindakan:</span>
                        <span className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                          m.status === 'completed' ? 'bg-emerald-100 text-emerald-800' :
                          m.status === 'in_progress' ? 'bg-indigo-100 text-indigo-800 animate-pulse' :
                          m.status === 'scheduled' ? 'bg-sky-100 text-sky-800' :
                          'bg-amber-100 text-amber-800'
                        }`}>
                          {m.status === 'completed' ? 'Selesai' : m.status === 'in_progress' ? 'Dalam Perbaikan' : m.status === 'scheduled' ? 'Dijadwalkan' : 'Pending'}
                        </span>
                      </div>

                      {m.status !== 'completed' && (
                        <div className="flex gap-1">
                          {m.status === 'pending' && (
                            <button 
                              onClick={() => handleUpdateMaint(m.id, 'scheduled')}
                              className="bg-sky-600 hover:bg-sky-700 text-white px-2.5 py-1 rounded text-[10px] font-semibold cursor-pointer"
                            >
                              Jadwalkan
                            </button>
                          )}
                          {(m.status === 'pending' || m.status === 'scheduled') && (
                            <button 
                              onClick={() => handleUpdateMaint(m.id, 'in_progress')}
                              className="bg-indigo-600 hover:bg-indigo-700 text-white px-2.5 py-1 rounded text-[10px] font-semibold cursor-pointer"
                            >
                              Kerjakan (Mulai)
                            </button>
                          )}
                          {m.status === 'in_progress' && (
                            <button 
                              onClick={() => handleUpdateMaint(m.id, 'completed')}
                              className="bg-emerald-600 hover:bg-emerald-700 text-white px-2.5 py-1 rounded text-[10px] font-bold cursor-pointer"
                            >
                              Selesai (Completed)
                            </button>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
                {filteredMaint.length === 0 && (
                  <p className="text-center py-8 text-gray-400 italic text-xs">Belum ada jadwal pemeliharaan terdaftar untuk kategori ini.</p>
                )}
              </div>
            </div>
          </div>
        )}

        {/* SUB TAB 7: AUDITING & LOGS */}
        {activeSubTab === 'logs' && (
          <div className="bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
            <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <FileText className="h-4 w-4 text-indigo-600" />
                  <span>Audit Log Aplikasi & System Logs</span>
                </h3>
                <p className="text-[11px] text-gray-400">Log pencatatan transaksi aplikasi, tindakan user admin/owner, dan log aktivitas sistem otomatis.</p>
              </div>

              {/* SEARCH INPUT FOR LOGS */}
              <div className="relative min-w-[200px] flex-1 lg:max-w-xs">
                <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="Cari log..."
                  value={logSearchQuery}
                  onChange={(e) => setLogSearchQuery(e.target.value)}
                  className="w-full bg-gray-50 border border-gray-200 rounded-lg pl-9 pr-4 py-2 text-xs focus:outline-hidden focus:ring-2 focus:ring-blue-100 focus:bg-white focus:border-blue-500 transition-all text-gray-800"
                />
              </div>

              {/* Filtering Controls */}
              <div className="flex flex-wrap gap-1">
                <button 
                  onClick={() => setLogFilter('all')} 
                  className={`px-3 py-1 rounded-lg text-xs font-semibold border cursor-pointer transition ${
                    logFilter === 'all' ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-100'
                  }`}
                >
                  Semua Log
                </button>
                <button 
                  onClick={() => setLogFilter('user')} 
                  className={`px-3 py-1 rounded-lg text-xs font-semibold border cursor-pointer transition ${
                    logFilter === 'user' ? 'bg-indigo-50 text-indigo-700 border-indigo-200' : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-100'
                  }`}
                >
                  User Logs
                </button>
                <button 
                  onClick={() => setLogFilter('system')} 
                  className={`px-3 py-1 rounded-lg text-xs font-semibold border cursor-pointer transition ${
                    logFilter === 'system' ? 'bg-amber-50 text-amber-700 border-amber-200' : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-100'
                  }`}
                >
                  System Logs
                </button>
                <button 
                  onClick={() => setLogFilter('app')} 
                  className={`px-3 py-1 rounded-lg text-xs font-semibold border cursor-pointer transition ${
                    logFilter === 'app' ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-100'
                  }`}
                >
                  App Logs
                </button>
              </div>
            </div>

            {/* Audit Logs Table */}
            <div className="border border-gray-150 rounded-xl overflow-hidden">
              <div className="max-h-[500px] overflow-y-auto">
                <table className="w-full text-left border-collapse text-xs font-mono">
                  <thead>
                    <tr className="border-b border-gray-150 text-gray-400 font-bold bg-gray-50/50 uppercase">
                      <th className="py-2.5 px-4 w-32 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleToggleLogSort('timestamp')}>
                        <div className="flex items-center space-x-1">
                          <span>Timestamp</span>
                          {logSortField === 'timestamp' ? (logSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                        </div>
                      </th>
                      <th className="py-2.5 px-4 w-28 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleToggleLogSort('type')}>
                        <div className="flex items-center space-x-1">
                          <span>Kategori</span>
                          {logSortField === 'type' ? (logSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                        </div>
                      </th>
                      <th className="py-2.5 px-4 w-32 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleToggleLogSort('user')}>
                        <div className="flex items-center space-x-1">
                          <span>Aktor</span>
                          {logSortField === 'user' ? (logSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                        </div>
                      </th>
                      <th className="py-2.5 px-4 cursor-pointer hover:bg-gray-100 select-none transition-colors" onClick={() => handleToggleLogSort('message')}>
                        <div className="flex items-center space-x-1">
                          <span>Deskripsi Aktivitas</span>
                          {logSortField === 'message' ? (logSortOrder === 'asc' ? '▲' : '▼') : '↕'}
                        </div>
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 text-gray-700">
                    {displayedLogs.map(l => (
                      <tr key={l.id} className="hover:bg-gray-50/20">
                        <td className="py-2.5 px-4 text-gray-400 font-medium whitespace-nowrap">{l.timestamp}</td>
                        <td className="py-2.5 px-4">
                          <span className={`px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-wide inline-block ${
                            l.type === 'user' ? 'bg-indigo-50 text-indigo-700 border border-indigo-100' :
                            l.type === 'system' ? 'bg-amber-50 text-amber-700 border border-amber-100' :
                            'bg-emerald-50 text-emerald-700 border border-emerald-100'
                          }`}>
                            {l.type}
                          </span>
                        </td>
                        <td className="py-2.5 px-4 font-bold text-gray-600 whitespace-nowrap">@{l.user}</td>
                        <td className="py-2.5 px-4 text-gray-900 leading-normal">{l.message}</td>
                      </tr>
                    ))}
                    {displayedLogs.length === 0 && (
                      <tr>
                        <td colSpan={4} className="text-center py-8 text-gray-400 italic">Tidak ada rekaman log pada filter ini yang sesuai pencarian.</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* SUB TAB 8: SIMULASI & LOGS NOTIFIKASI */}
        {activeSubTab === 'notifications' && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            {/* Left: Manual Simulator Form */}
            <div className="bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4 lg:col-span-1">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <Bell className="h-4 w-4 text-blue-600" />
                  <span>Manual Notification Simulator</span>
                </h3>
                <p className="text-[11px] text-gray-400">Gunakan form ini untuk menyimulasikan dan memicu pengiriman notifikasi instan (Email & WhatsApp) ke pengguna terdaftar.</p>
              </div>

              <form onSubmit={handleSimulateNotif} className="space-y-3 text-xs">
                <div>
                  <label className="block text-[10px] font-bold text-gray-400 uppercase mb-1">Pilih Pengguna Tujuan</label>
                  <select
                    value={notifSim.userId}
                    onChange={(e) => setNotifSim({ ...notifSim, userId: e.target.value })}
                    className="w-full bg-gray-50 border border-gray-200 rounded-lg p-2.5 outline-hidden text-xs focus:border-blue-500 font-medium"
                    required
                  >
                    <option value="">-- Pilih Pengguna Terdaftar --</option>
                    {users.map((u) => (
                      <option key={u.id} value={u.id}>
                        {u.fullName} ({u.role.toUpperCase()}) - {u.email}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label className="block text-[10px] font-bold text-gray-400 uppercase mb-1">Jenis Notifikasi</label>
                    <select
                      value={notifSim.type}
                      onChange={(e) => setNotifSim({ ...notifSim, type: e.target.value })}
                      className="w-full bg-gray-50 border border-gray-200 rounded-lg p-2.5 outline-hidden text-xs focus:border-blue-500 font-medium"
                    >
                      <option value="system">Sistem / Info</option>
                      <option value="booking">Booking / Transaksi</option>
                      <option value="maint">Maintenance / Aset</option>
                      <option value="complaint">Keluhan / Service</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-gray-400 uppercase mb-1">Judul Notif</label>
                    <input
                      type="text"
                      placeholder="Judul pemberitahuan..."
                      value={notifSim.title}
                      onChange={(e) => setNotifSim({ ...notifSim, title: e.target.value })}
                      className="w-full bg-gray-50 border border-gray-200 rounded-lg p-2.5 outline-hidden text-xs focus:border-blue-500 font-medium"
                      required
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-400 uppercase mb-1">Isi Pesan Notifikasi</label>
                  <textarea
                    rows={4}
                    placeholder="Tulis pesan lengkap yang ingin dikirimkan via email dan WA..."
                    value={notifSim.message}
                    onChange={(e) => setNotifSim({ ...notifSim, message: e.target.value })}
                    className="w-full bg-gray-50 border border-gray-200 rounded-lg p-2.5 outline-hidden text-xs focus:border-blue-500 font-medium resize-none"
                    required
                  />
                </div>

                <button
                  type="submit"
                  className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold p-2.5 rounded-lg flex items-center justify-center space-x-1.5 shadow-sm transition-colors cursor-pointer text-xs"
                >
                  <Send className="h-3.5 w-3.5" />
                  <span>Kirim & Simulasikan Dispas</span>
                </button>
              </form>
            </div>

            {/* Middle & Right: Live Dispatched Preview */}
            <div className="lg:col-span-2 flex flex-col gap-4">
              
              {/* Simulator Screens */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                
                {/* Mock Phone - WhatsApp Screen */}
                <div className="bg-slate-900 rounded-2xl p-4 border border-slate-800 shadow-lg flex flex-col h-[350px]">
                  {/* Phone Header */}
                  <div className="flex items-center justify-between border-b border-slate-800 pb-2.5 mb-2.5">
                    <div className="flex items-center space-x-2">
                      <div className="bg-teal-700 text-white font-bold h-7 w-7 rounded-full flex items-center justify-center text-xs">
                        SP
                      </div>
                      <div className="flex flex-col text-left">
                        <span className="text-xs font-bold text-slate-100 flex items-center gap-1">
                          <span>SewaBeliPro</span>
                          <span className="bg-teal-500 text-white text-[8px] h-3.5 w-3.5 rounded-full flex items-center justify-center font-bold">✓</span>
                        </span>
                        <span className="text-[9px] text-teal-400 font-semibold">Official Business Account</span>
                      </div>
                    </div>
                    <div className="text-[10px] text-slate-400 font-mono">12:00 PM</div>
                  </div>

                  {/* Phone Screen Body (WhatsApp wallpaper style backgound) */}
                  <div className="flex-grow rounded-xl bg-slate-950 p-3 overflow-y-auto relative flex flex-col justify-end space-y-3" style={{ backgroundImage: "radial-gradient(#1e293b 1px, transparent 0)", backgroundSize: "16px 16px" }}>
                    
                    {simulatedWA ? (
                      <div className="self-start max-w-[85%] bg-teal-900 border border-teal-800 rounded-2xl rounded-tl-none p-3 shadow-md text-left text-slate-100 space-y-2 animate-fade-in">
                        <p className="text-[11px] leading-relaxed whitespace-pre-line font-medium">
                          {simulatedWA.message}
                        </p>
                        <div className="flex items-center justify-between text-[8px] text-teal-400 font-semibold">
                          <span>{simulatedWA.time}</span>
                          <span className="flex items-center gap-0.5">
                            <span>Delivered</span>
                            <span>✓✓</span>
                          </span>
                        </div>
                      </div>
                    ) : (
                      <div className="self-center my-auto text-center text-slate-500 text-xs p-6 italic space-y-1">
                        <Smartphone className="h-8 w-8 mx-auto text-slate-600 mb-1" />
                        <p>Simulasi Layar WhatsApp Aktif</p>
                        <p className="text-[10px] text-slate-600">Dispas notifikasi untuk melihat gelembung pesan masuk</p>
                      </div>
                    )}
                    
                  </div>
                </div>

                {/* Mock Browser - Email Client */}
                <div className="bg-slate-900 rounded-2xl p-4 border border-slate-800 shadow-lg flex flex-col h-[350px]">
                  {/* Browser Window Header */}
                  <div className="flex items-center space-x-1.5 border-b border-slate-800 pb-2.5 mb-2.5">
                    <span className="h-2 w-2 rounded-full bg-red-500"></span>
                    <span className="h-2 w-2 rounded-full bg-yellow-500"></span>
                    <span className="h-2 w-2 rounded-full bg-green-500"></span>
                    <span className="text-[10px] text-slate-400 font-semibold pl-2 font-mono">SewaBeliPro Webmail Client</span>
                  </div>

                  {/* Mail Body */}
                  <div className="flex-grow rounded-xl bg-white p-3 overflow-y-auto text-left text-gray-800 flex flex-col">
                    {simulatedEmail ? (
                      <div className="space-y-3 flex-grow flex flex-col text-xs animate-fade-in">
                        <div className="border-b border-gray-100 pb-2 space-y-1">
                          <p className="text-gray-400">From: <span className="text-gray-900 font-semibold">SewaBeliPro &lt;info@sewabelipro.com&gt;</span></p>
                          <p className="text-gray-400">To: <span className="text-gray-900 font-semibold">{simulatedEmail.address}</span></p>
                          <p className="text-gray-900 font-bold text-sm">Subject: {simulatedEmail.subject}</p>
                          <p className="text-gray-400 text-[10px]">Date: {simulatedEmail.time}</p>
                        </div>
                        <div className="flex-grow p-2.5 bg-gray-50 rounded-xl font-medium border border-gray-100 leading-relaxed text-gray-700 whitespace-pre-line">
                          {simulatedEmail.body}
                        </div>
                        <div className="pt-2 border-t border-gray-100 flex justify-between items-center text-[10px] text-gray-400">
                          <span>SewaBeliPro Dispatcher Engine</span>
                          <span className="text-emerald-600 font-bold flex items-center gap-0.5">
                            <CheckCircle className="h-3 w-3" />
                            <span>SMTP Sent (SSL/TLS)</span>
                          </span>
                        </div>
                      </div>
                    ) : (
                      <div className="my-auto text-center text-gray-400 text-xs p-6 italic space-y-1">
                        <Mail className="h-8 w-8 mx-auto text-gray-300 mb-1" />
                        <p>Simulasi Inbox Email Aktif</p>
                        <p className="text-[10px] text-gray-400">Notifikasi yang dikirimkan juga akan diantarkan ke inbox email di sini</p>
                      </div>
                    )}
                  </div>
                </div>

              </div>

              {/* System Logs Notification Indicator */}
              <div className="bg-slate-900 p-4 rounded-xl border border-slate-800 flex items-center justify-between text-xs text-slate-300">
                <div className="flex items-center space-x-2">
                  <span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse"></span>
                  <span className="font-semibold text-slate-100">Live Simulation Status: Active</span>
                </div>
                <div className="text-[10px] text-slate-400 font-mono">
                  SMTP Host: mail.sewabelipro.com:465 | WA Gateway: wa-api.sewabelipro.com
                </div>
              </div>

            </div>

            {/* Bottom: History Log Table */}
            <div className="bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4 lg:col-span-3 text-left">
              <div>
                <h3 className="font-sans font-bold text-sm text-gray-900 flex items-center gap-1.5">
                  <ClipboardList className="h-4 w-4 text-emerald-600" />
                  <span>Riwayat Pengiriman Notifikasi Sistem & Simpangan Saluran</span>
                </h3>
                <p className="text-[11px] text-gray-400">Berikut adalah daftar seluruh notifikasi yang terdaftar di dalam sistem, beserta detail saluran pengiriman (Email SMTP dan WhatsApp gateway dispatch).</p>
              </div>

              <div className="border border-gray-150 rounded-xl overflow-hidden">
                <table className="w-full text-xs text-left border-collapse">
                  <thead>
                    <tr className="border-b border-gray-150 text-gray-400 font-bold bg-gray-50/50 uppercase text-[10px] tracking-wider">
                      <th className="py-2.5 px-4 w-36">Tanggal</th>
                      <th className="py-2.5 px-4 w-32">Penerima (ID)</th>
                      <th className="py-2.5 px-4 w-44">Judul Notifikasi</th>
                      <th className="py-2.5 px-4">Pesan Pemberitahuan</th>
                      <th className="py-2.5 px-4 w-52">Saluran Terkirim (SMTP & WA Gateway)</th>
                      <th className="py-2.5 px-4 w-20">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 text-gray-700">
                    {notifications.slice().reverse().map((notif) => {
                      const recipient = users.find(u => String(u.id) === String(notif.userId));
                      const recipientLabel = recipient ? recipient.fullName : `User #${notif.userId}`;
                      return (
                        <tr key={notif.id} className="hover:bg-gray-50/40 transition">
                          <td className="py-2.5 px-4 text-gray-400 font-medium font-mono">{notif.createdAt}</td>
                          <td className="py-2.5 px-4 font-bold text-gray-800 whitespace-nowrap">{recipientLabel}</td>
                          <td className="py-2.5 px-4 font-semibold text-gray-900">{notif.title}</td>
                          <td className="py-2.5 px-4 text-gray-500 font-normal leading-relaxed">{notif.message}</td>
                          <td className="py-2.5 px-4 whitespace-nowrap">
                            <div className="flex items-center gap-1.5">
                              {notif.channels?.email?.sent ? (
                                <span className="inline-flex items-center gap-1 bg-emerald-50 text-emerald-700 border border-emerald-100 text-[9px] px-1.5 py-0.5 rounded font-bold" title={notif.channels.email.address}>
                                  <Mail className="h-2.5 w-2.5" />
                                  <span>Email</span>
                                </span>
                              ) : (
                                <span className="bg-gray-50 text-gray-400 text-[9px] px-1.5 py-0.5 rounded border border-gray-100">Email Off</span>
                              )}
                              
                              {notif.channels?.whatsapp?.sent ? (
                                <span className="inline-flex items-center gap-1 bg-teal-50 text-teal-700 border border-teal-100 text-[9px] px-1.5 py-0.5 rounded font-bold" title={notif.channels.whatsapp.phone}>
                                  <MessageSquare className="h-2.5 w-2.5" />
                                  <span>WhatsApp</span>
                                </span>
                              ) : (
                                <span className="bg-gray-50 text-gray-400 text-[9px] px-1.5 py-0.5 rounded border border-gray-100">WA Off</span>
                              )}
                            </div>
                          </td>
                          <td className="py-2.5 px-4">
                            <span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider inline-block ${
                              notif.read ? 'bg-gray-100 text-gray-500' : 'bg-blue-100 text-blue-700 font-bold'
                            }`}>
                              {notif.read ? 'Read' : 'Unread'}
                            </span>
                          </td>
                        </tr>
                      );
                    })}
                    {notifications.length === 0 && (
                      <tr>
                        <td colSpan={6} className="text-center py-8 text-gray-400 italic">Belum ada riwayat notifikasi terkirim.</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>

          </div>
        )}
      </div>
    </div>
  );
}
