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

import { useState, useEffect, useRef, useCallback } from 'react';
import { Property, User, Transaction, DashboardStats, PropertyType, AppNotification, Room } from './types';
import Navbar from './components/Navbar';
import Sidebar from './components/Sidebar';
import PropertyCard from './components/PropertyCard';
import PropertyDetailsModal from './components/PropertyDetailsModal';
import AddPropertyModal from './components/AddPropertyModal';
import DashboardView from './components/DashboardView';
import AuthModal from './components/AuthModal';
import ChangePasswordModal from './components/ChangePasswordModal';
import SqlSchemaViewer from './components/SqlSchemaViewer';
import UserManagementPanel from './components/UserManagementPanel';
import ProfilingHub from './components/ProfilingHub';
import Ci3TemplateExplorer from './components/Ci3TemplateExplorer';
import OperationsHub from './components/OperationsHub';
import AiPredictionHub from './components/AiPredictionHub';
import SuperadminConsole from './components/SuperadminConsole';
import CloudStoragePanel from './components/CloudStoragePanel';
import MenuGuidePanel from './components/MenuGuidePanel';
import { Search, SlidersHorizontal, BookOpen, Clock, Tag, CreditCard, Filter, RefreshCw, Sparkles, Building2, Megaphone, Cloud } from 'lucide-react';

export default function App() {
  // Navigation
  const [activeTab, setActiveTab] = useState<'explore' | 'dashboard' | 'schema' | 'my-bookings' | 'users' | 'permissions' | 'profiling' | 'ci3-template' | 'operations' | 'ai-prediction' | 'superadmin' | 'cloud-storage' | 'menu-guide'>('explore');
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [devMode, setDevMode] = useState<boolean>(() => {
    const saved = localStorage.getItem('devMode');
    return saved === 'true'; // Default to false (hidden) by default
  });

  // Core App State
  const [appData, setAppData] = useState<{
    properties: Property[];
    transactions: Transaction[];
    stats: DashboardStats | null;
    promos: any[];
    advertisements: any[];
    rooms: Room[];
  }>({
    properties: [],
    transactions: [],
    stats: null,
    promos: [],
    advertisements: [],
    rooms: []
  });
  const { properties, transactions, stats, promos, advertisements, rooms } = appData;
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  // Filter States
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedType, setSelectedType] = useState<PropertyType | 'all'>('all');
  const [priceRange, setPriceRange] = useState<'all' | 'under1m' | '1m5m' | 'over5m' | 'over100m'>('all');
  const [sortOrder, setSortOrder] = useState<'latest' | 'priceLow' | 'priceHigh'>('latest');

  // Modal States
  const [selectedProperty, setSelectedProperty] = useState<Property | null>(null);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authModalInitialRegister, setAuthModalInitialRegister] = useState(false);
  const [pendingBooking, setPendingBooking] = useState<any | null>(null);
  const [showAddPropertyModal, setShowAddPropertyModal] = useState(false);
  const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);

  // Loading indicator
  const [loading, setLoading] = useState(true);
  const fetchDataRef = useRef(false);
  const initialLoadCompleteRef = useRef(false);

  // Toast notification state
  const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' | 'info' } | null>(null);

  // Notifications State & Actions
  const [notifications, setNotifications] = useState<AppNotification[]>([]);

  const fetchNotifications = useCallback(async () => {
    if (!currentUser) {
      setNotifications([]);
      return;
    }
    try {
      const res = await fetch(`/api/notifications?userId=${currentUser.id}`);
      if (res.ok) {
        const data = await res.json();
        setNotifications(data);
      }
    } catch (e) {
      console.error("Gagal memuat notifikasi:", e);
    }
  }, [currentUser?.id]);

  // Custom confirmation modal state
  const [confirmModal, setConfirmModal] = useState<{
    isOpen: boolean;
    title: string;
    message: string;
    onConfirm: () => void;
  } | null>(null);

  const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
    setToast({ message, type });
    setTimeout(() => {
      setToast(null);
    }, 4000);
  };

  // Load initial data
  const fetchData = async (showLoading: any = false) => {
    if (fetchDataRef.current) return; // Prevent duplicate requests
    
    const shouldShowLoading = showLoading === true && !initialLoadCompleteRef.current;
    if (shouldShowLoading) {
      setLoading(true);
    }
    
    fetchDataRef.current = true;
    try {
      const [propsRes, txsRes, statsRes, promosRes, adsRes, roomsRes] = await Promise.all([
        fetch('/api/properties'),
        fetch('/api/transactions'),
        fetch('/api/stats'),
        fetch('/api/promos'),
        fetch('/api/advertisements'),
        fetch('/api/rooms')
      ]);

      const [
        propsData,
        txsData,
        statsData,
        promosData,
        adsData,
        roomsData
      ] = await Promise.all([
        propsRes.ok ? propsRes.json() : Promise.resolve([]),
        txsRes.ok ? txsRes.json() : Promise.resolve([]),
        statsRes.ok ? statsRes.json() : Promise.resolve(null),
        promosRes.ok ? promosRes.json() : Promise.resolve([]),
        adsRes.ok ? adsRes.json() : Promise.resolve([]),
        roomsRes.ok ? roomsRes.json() : Promise.resolve([])
      ]);

      setAppData({
        properties: propsData,
        transactions: txsData,
        stats: statsData,
        promos: promosData,
        advertisements: adsData,
        rooms: roomsData
      });
    } catch (e) {
      console.error("Gagal memuat data dari API", e);
    } finally {
      fetchDataRef.current = false;
      if (shouldShowLoading) {
        setLoading(false);
        initialLoadCompleteRef.current = true;
      }
    }
  };

  useEffect(() => {
    fetchData(true);
  }, []);

  // Handle Login success
  const handleLoginSuccess = async (user: User) => {
    setCurrentUser(user);
    if (pendingBooking) {
      const bookingToProcess = pendingBooking;
      setPendingBooking(null); // Clear first
      try {
        const response = await fetch('/api/transactions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            ...bookingToProcess,
            buyerId: user.id,
            buyerName: user.fullName
          })
        });

        if (response.ok) {
          showToast('Akun Anda berhasil didaftarkan dan pemesanan otomatis berhasil diproses!', 'success');
          setSelectedProperty(null);
          fetchData();
          fetchNotifications();
          setActiveTab('my-bookings');
        } else {
          const data = await response.json();
          showToast(data.error || 'Akun terdaftar, tetapi pemesanan gagal diproses.', 'error');
        }
      } catch (e) {
        showToast('Koneksi ke server gagal untuk memproses transaksi otomatis.', 'error');
      }
    } else {
      if (['owner', 'superadmin', 'admin'].includes(user.role)) {
        setActiveTab('dashboard');
      } else {
        setActiveTab('explore');
      }
    }
  };

  // Handle Logout
  const handleLogout = () => {
    setCurrentUser(null);
    setPendingBooking(null);
    setActiveTab('explore');
  };

  // Memoized callbacks for Navbar/Sidebar
  const handleOpenAuth = useCallback(() => setShowAuthModal(true), []);
  const handleOpenAddProperty = useCallback(() => setShowAddPropertyModal(true), []);
  const handleToggleSidebar = useCallback(() => setIsSidebarOpen(prev => !prev), []);
  const handleChangePassword = useCallback(() => setShowChangePasswordModal(true), []);
  const handleDevModeToggle = useCallback((val: boolean) => setDevMode(val), []);

  // Delete property (Owner action)
  const handleDeleteProperty = async (id: string) => {
    setConfirmModal({
      isOpen: true,
      title: 'Hapus Listing Properti',
      message: 'Apakah Anda yakin ingin menghapus listing properti ini? Tindakan ini tidak dapat dibatalkan.',
      onConfirm: async () => {
        try {
          const response = await fetch(`/api/properties/${id}`, {
            method: 'DELETE'
          });
          if (response.ok) {
            showToast('Properti berhasil dihapus!', 'success');
            fetchData();
          } else {
            const data = await response.json();
            showToast(data.error || 'Gagal menghapus properti.', 'error');
          }
        } catch (e) {
          showToast('Koneksi ke server gagal.', 'error');
        } finally {
          setConfirmModal(null);
        }
      }
    });
  };

  // Create new transaction (Stay, Rent, Buy)
  const handleTransaction = async (txData: {
    propertyId: string;
    type: 'stay' | 'rent' | 'buy';
    startDate?: string;
    endDate?: string;
    totalPrice: number;
    [key: string]: any;
  }) => {
    if (!currentUser) {
      setPendingBooking(txData);
      setAuthModalInitialRegister(true);
      setShowAuthModal(true);
      showToast('Silakan lengkapi pendaftaran akun Anda untuk menyelesaikan pemesanan ini.', 'info');
      return;
    }

    try {
      const response = await fetch('/api/transactions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...txData,
          buyerId: currentUser.id,
          buyerName: currentUser.fullName
        })
      });

      if (response.ok) {
        showToast('Transaksi berhasil diproses! Unit properti berhasil dibooking.', 'success');
        setSelectedProperty(null);
        fetchData();
        fetchNotifications();
        setActiveTab('my-bookings');
      } else {
        const data = await response.json();
        showToast(data.error || 'Transaksi gagal.', 'error');
      }
    } catch (e) {
      showToast('Koneksi ke server gagal.', 'error');
    }
  };

  // Register new property (Host/Owner action)
  const handleAddProperty = async (propertyData: {
    name: string;
    type: PropertyType;
    address: string;
    description: string;
    priceDay?: number;
    priceMonth?: number;
    priceBuy?: number;
    imageUrl?: string;
    contactPhone?: string;
    contactEmail?: string;
    mapEmbedUrl?: string;
  }) => {
    if (!currentUser || !['owner', 'superadmin', 'admin'].includes(currentUser.role)) {
      showToast('Hanya pengelola atau pemilik properti yang dapat melakukan tindakan ini!', 'error');
      return;
    }

    try {
      const response = await fetch('/api/properties', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...propertyData,
          ownerId: currentUser.id,
          ownerName: currentUser.fullName
        })
      });

      if (response.ok) {
        showToast('Properti berhasil didaftarkan!', 'success');
        setShowAddPropertyModal(false);
        fetchData();
        setActiveTab('dashboard');
      } else {
        const data = await response.json();
        showToast(data.error || 'Gagal mendaftarkan properti.', 'error');
      }
    } catch (e) {
      showToast('Koneksi ke server gagal.', 'error');
    }
  };

  // Filter & Search Logics
  const getPropertyBasePrice = (prop: Property) => {
    return prop.priceDay || prop.priceMonth || prop.priceBuy || 0;
  };

  const filteredProperties = properties.filter((prop) => {
    // Search
    const matchesSearch = prop.name.toLowerCase().includes(searchQuery.toLowerCase()) || 
                          prop.address.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          prop.description.toLowerCase().includes(searchQuery.toLowerCase());
    
    // Type
    const matchesType = selectedType === 'all' || prop.type === selectedType;

    // Price Filter
    const basePrice = getPropertyBasePrice(prop);
    let matchesPrice = true;
    if (priceRange === 'under1m') {
      matchesPrice = basePrice <= 1000000;
    } else if (priceRange === '1m5m') {
      matchesPrice = basePrice > 1000000 && basePrice <= 5000000;
    } else if (priceRange === 'over5m') {
      matchesPrice = basePrice > 5000000 && basePrice <= 50000000;
    } else if (priceRange === 'over100m') {
      matchesPrice = basePrice > 100000000;
    }

    return matchesSearch && matchesType && matchesPrice;
  }).sort((a, b) => {
    if (sortOrder === 'priceLow') {
      return getPropertyBasePrice(a) - getPropertyBasePrice(b);
    } else if (sortOrder === 'priceHigh') {
      return getPropertyBasePrice(b) - getPropertyBasePrice(a);
    }
    // Default: latest (reverse chronological)
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
  });

  // User transactions filter
  const userTransactions = currentUser 
    ? transactions.filter((t) => t.buyerId === currentUser.id)
    : [];

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

  return (
    <div className="min-h-screen bg-[#f4f6f9] flex font-sans text-gray-800 antialiased selection:bg-blue-100 selection:text-blue-900">
      
      {/* AdminLTE Left Sidebar - only show if user is logged in */}
      {currentUser && (
        <Sidebar
          currentUser={currentUser}
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          devMode={devMode}
          setDevMode={handleDevModeToggle}
          onLogout={handleLogout}
          onOpenAuth={handleOpenAuth}
          isOpen={isSidebarOpen}
          setIsOpen={setIsSidebarOpen}
          onChangePassword={handleChangePassword}
        />
      )}

      {/* Backdrop overlay for mobile sidebar */}
      {currentUser && isSidebarOpen && (
        <div 
          onClick={() => setIsSidebarOpen(false)}
          className="fixed inset-0 bg-black/50 z-30 md:hidden transition-opacity duration-300"
        />
      )}

      {/* Main Right Content Section */}
      <div className="flex-1 flex flex-col min-w-0 min-h-screen">
        
        {/* Top Navbar */}
        <Navbar
          currentUser={currentUser}
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          onOpenAuth={handleOpenAuth}
          onOpenAddProperty={handleOpenAddProperty}
          onLogout={handleLogout}
          devMode={devMode}
          setDevMode={handleDevModeToggle}
          notifications={notifications}
          onRefreshNotifications={fetchNotifications}
          onToggleSidebar={handleToggleSidebar}
          onChangePassword={handleChangePassword}
        />

        {/* Content Wrapper */}
        <main className="flex-grow w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        
        {activeTab === 'explore' && (
          <div className="space-y-6">
            {/* Header Jumbotron */}
            <div className="bg-white rounded-2xl border border-gray-100 p-6 md:p-8 shadow-xs relative overflow-hidden flex flex-col md:flex-row md:items-center justify-between gap-6">
              <div className="space-y-2 z-10 max-w-xl">
                <span className="text-xs font-bold text-blue-600 bg-blue-50 px-2.5 py-1 rounded-full uppercase tracking-wider">Multi-Hotel & Property Hub</span>
                <h1 className="text-2xl md:text-4xl font-sans font-extrabold text-gray-900 tracking-tight leading-none mt-1">
                  Temukan Akomodasi & Properti Impian
                </h1>
                <p className="text-gray-500 text-xs md:text-sm leading-relaxed">
                  Layanan terpadu penyewaan kamar hotel, villa wisata harian, sewa bulanan apartemen/kos-kosan, hingga pembelian properti modern siap huni.
                </p>
              </div>
              <div className="shrink-0 flex space-x-2 md:self-end">
                <button 
                  onClick={() => fetchData(false)} 
                  className="bg-gray-100 hover:bg-gray-200 text-gray-600 p-2.5 rounded-xl border border-gray-200 transition-all flex items-center space-x-1 cursor-pointer text-xs font-semibold"
                  title="Refresh Data"
                >
                  <RefreshCw className="h-4 w-4" />
                  <span>Refresh</span>
                </button>
              </div>
            </div>

            {/* Main Content Layout Grid */}
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
              
              {/* Left Column (3/4 width): Filters Bar & Properties Grid */}
              <div className="lg:col-span-3 space-y-6">
                
                {/* Filters Bar */}
                <div className="bg-white rounded-xl border border-gray-100 p-4 shadow-xs grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                  {/* Search */}
                  <div className="space-y-1.5">
                    <label className="block text-xs font-semibold text-gray-500">Cari Properti</label>
                    <div className="relative">
                      <input
                        type="text"
                        placeholder="Nama hotel, kota, alamat..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full pl-9 pr-3 py-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                      />
                      <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
                    </div>
                  </div>

                  {/* Property Type Filter */}
                  <div className="space-y-1.5">
                    <label className="block text-xs font-semibold text-gray-500">Tipe Akomodasi</label>
                    <div className="relative">
                      <select
                        value={selectedType}
                        onChange={(e) => setSelectedType(e.target.value as PropertyType | 'all')}
                        className="w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-xs bg-white appearance-none focus:outline-hidden focus:border-blue-500"
                      >
                        <option value="all">Semua Tipe Properti</option>
                        <option value="hotel">Hotel (Harian)</option>
                        <option value="villa">Villa (Harian)</option>
                        <option value="apartment">Apartemen (Bulanan/Jual)</option>
                        <option value="house">Rumah (Jual)</option>
                        <option value="kos">Kos-Kosan (Bulanan)</option>
                      </select>
                      <Building2 className="absolute right-3 top-2.5 h-4 w-4 text-gray-400 pointer-events-none" />
                    </div>
                  </div>

                  {/* Price Range Filter */}
                  <div className="space-y-1.5">
                    <label className="block text-xs font-semibold text-gray-500">Kisaran Tarif / Harga</label>
                    <div className="relative">
                      <select
                        value={priceRange}
                        onChange={(e) => setPriceRange(e.target.value as any)}
                        className="w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-xs bg-white appearance-none focus:outline-hidden focus:border-blue-500"
                      >
                        <option value="all">Semua Kisaran Harga</option>
                        <option value="under1m">Di bawah Rp 1 Juta (Hotel/Kos/Stay)</option>
                        <option value="1m5m">Rp 1 Juta - Rp 5 Juta (Stay/Sewa)</option>
                        <option value="over5m">Rp 5 Juta - Rp 50 Juta (Sewa Bulanan)</option>
                        <option value="over100m">Di atas Rp 100 Juta (Beli Properti)</option>
                      </select>
                      <Filter className="absolute right-3 top-2.5 h-4 w-4 text-gray-400 pointer-events-none" />
                    </div>
                  </div>

                  {/* Sort Filter */}
                  <div className="space-y-1.5">
                    <label className="block text-xs font-semibold text-gray-500">Urutkan Berdasarkan</label>
                    <div className="relative">
                      <select
                        value={sortOrder}
                        onChange={(e) => setSortOrder(e.target.value as any)}
                        className="w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-xs bg-white appearance-none focus:outline-hidden focus:border-blue-500"
                      >
                        <option value="latest">Rekomendasi / Terbaru</option>
                        <option value="priceLow">Harga Terendah</option>
                        <option value="priceHigh">Harga Tertinggi</option>
                      </select>
                      <SlidersHorizontal className="absolute right-3 top-2.5 h-4 w-4 text-gray-400 pointer-events-none" />
                    </div>
                  </div>
                </div>

                {/* Properties Grid */}
                {loading && properties.length === 0 ? (
                  <div className="py-20 text-center text-gray-500 flex flex-col items-center justify-center space-y-2">
                    <RefreshCw className="h-8 w-8 text-blue-600" />
                    <span className="text-xs font-semibold">Memuat daftar properti untuk Anda...</span>
                  </div>
                ) : (
                  <>
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                      {filteredProperties.map((prop) => (
                        <PropertyCard
                          key={prop.id}
                          property={prop}
                          currentUser={currentUser}
                          onSelect={(p) => setSelectedProperty(p)}
                          onDelete={handleDeleteProperty}
                          rooms={rooms}
                        />
                      ))}
                    </div>

                    {filteredProperties.length === 0 && (
                      <div className="bg-white p-16 text-center rounded-2xl border border-gray-100">
                        <Building2 className="h-12 w-12 text-gray-300 mx-auto" />
                        <h3 className="font-bold text-gray-800 mt-3 text-sm">Tidak Ada Properti Ditemukan</h3>
                        <p className="text-xs text-gray-400 mt-1 max-w-sm mx-auto">Coba sesuaikan kata kunci pencarian, tipe akomodasi, atau filter kisaran harga Anda.</p>
                      </div>
                    )}
                  </>
                )}
              </div>

              {/* Right Column (1/4 width): Promos, Coupons & Sponsored Ads */}
              <div className="lg:col-span-1 space-y-6">
                
                {/* Promo & Kupon Hemat */}
                <div className="bg-white rounded-2xl border border-gray-100 p-5 shadow-xs space-y-4">
                  <div className="flex items-center space-x-2 pb-2 border-b border-gray-100">
                    <div className="bg-blue-50 p-1.5 rounded-lg">
                      <Tag className="h-4 w-4 text-blue-600" />
                    </div>
                    <h3 className="font-sans font-bold text-gray-900 text-sm">Kupon & Promo Hemat</h3>
                  </div>
                  
                  {promos.length === 0 ? (
                    <div className="text-center py-6">
                      <p className="text-xs text-gray-400">Tidak ada kupon diskon aktif saat ini.</p>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {promos.map((promo) => (
                        <div 
                          key={promo.id} 
                          className="p-3 bg-blue-50/40 rounded-xl border border-blue-100/30 flex flex-col space-y-1 relative overflow-hidden group hover:bg-blue-50 transition-colors"
                        >
                          <div className="absolute top-0 right-0 h-8 w-8 bg-blue-100/20 rounded-full -mr-2 -mt-2"></div>
                          <div className="flex items-center justify-between">
                            <span className="font-mono text-[10px] font-bold text-blue-700 bg-blue-100/60 px-2 py-0.5 rounded-md uppercase tracking-wider">
                              {promo.code}
                            </span>
                            <span className="text-xs font-extrabold text-blue-700">
                              -{new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(promo.discount)}
                            </span>
                          </div>
                          <p className="text-[10px] text-gray-500 font-medium pt-1">
                            {promo.description || `Potongan langsung ${promo.type === 'coupon' ? 'Kupon' : 'Promo'}`}
                          </p>
                          <div className="text-[9px] text-gray-400 flex justify-between pt-1 border-t border-blue-100/10 mt-1">
                            <span>Maks guna: {promo.maxUse}</span>
                            <span>Digunakan: {promo.used}x</span>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* Iklan Sponsor */}
                <div className="bg-white rounded-2xl border border-gray-100 p-5 shadow-xs space-y-4">
                  <div className="flex items-center space-x-2 pb-2 border-b border-gray-100">
                    <div className="bg-emerald-50 p-1.5 rounded-lg">
                      <Megaphone className="h-4 w-4 text-emerald-600" />
                    </div>
                    <h3 className="font-sans font-bold text-gray-900 text-sm">Iklan & Promo Sponsor</h3>
                  </div>

                  {advertisements.length === 0 ? (
                    <div className="p-5 bg-gray-50 rounded-xl border border-dashed border-gray-200 text-center text-xs text-gray-400">
                      Iklan partner belum terbit harian.
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {advertisements.filter(ad => ad.status === 'active').map((ad) => (
                        <div key={ad.id} className="rounded-xl overflow-hidden border border-gray-100 bg-gray-50/40 hover:shadow-xs transition-all duration-200 group">
                          <div className="h-28 overflow-hidden bg-gray-100 relative">
                            <img 
                              src={ad.imageUrl} 
                              alt={ad.title} 
                              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                              referrerPolicy="no-referrer"
                            />
                            <span className="absolute top-2 left-2 bg-black/50 text-[8px] font-bold tracking-wider text-white px-1.5 py-0.5 rounded-sm uppercase">
                              SPONSORED
                            </span>
                          </div>
                          <div className="p-3 space-y-1">
                            <h4 className="text-[11px] font-bold text-gray-800 leading-snug">{ad.title}</h4>
                            <a 
                              href={ad.link} 
                              target="_blank"
                              rel="noreferrer"
                              className="text-[10px] font-semibold text-emerald-600 hover:text-emerald-700 flex items-center space-x-1"
                            >
                              <span>Lihat Selengkapnya &rarr;</span>
                            </a>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

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

        {activeTab === 'dashboard' && currentUser && (currentUser.permissions.includes('view_dashboard') || currentUser.role === 'superadmin') && (
          <DashboardView
            stats={stats || { totalProperties: 0, totalTransactions: 0, revenue: 0, activeStays: 0, activeRentals: 0, unitsSold: 0 }}
            transactions={transactions}
            properties={properties}
            currentUser={currentUser}
            rooms={rooms}
            onRefreshAll={() => { fetchData(); fetchNotifications(); }}
          />
        )}

        {activeTab === 'schema' && devMode && currentUser && (currentUser.permissions.includes('view_schema') || currentUser.role === 'superadmin') && (
          <SqlSchemaViewer />
        )}

        {activeTab === 'users' && devMode && currentUser && (currentUser.permissions.includes('view_users') || currentUser.role === 'superadmin') && (
          <UserManagementPanel currentUser={currentUser} onUserUpdate={fetchData} initialTab="users" />
        )}

        {activeTab === 'menu-guide' && devMode && currentUser && (currentUser.permissions.includes('view_users') || currentUser.role === 'superadmin') && (
          <MenuGuidePanel />
        )}

        {activeTab === 'permissions' && devMode && currentUser && (currentUser.permissions.includes('view_permissions') || currentUser.role === 'superadmin') && (
          <UserManagementPanel currentUser={currentUser} onUserUpdate={fetchData} initialTab="permissions" />
        )}

        {activeTab === 'profiling' && devMode && currentUser && (currentUser.permissions.includes('view_profiling') || currentUser.role === 'superadmin') && (
          <ProfilingHub currentUser={currentUser} />
        )}

        {activeTab === 'ci3-template' && devMode && currentUser && (currentUser.permissions.includes('view_ci3_template') || currentUser.role === 'superadmin') && (
          <Ci3TemplateExplorer />
        )}

        {activeTab === 'ai-prediction' && devMode && currentUser && (currentUser.permissions.includes('view_ai_prediction') || currentUser.role === 'superadmin') && (
          <AiPredictionHub currentUser={currentUser} properties={properties} />
        )}

        {activeTab === 'operations' && currentUser && (currentUser.permissions.includes('view_operations') || currentUser.role === 'superadmin') && (
          <OperationsHub 
            properties={properties} 
            transactions={transactions} 
            currentUser={currentUser} 
            onRefreshAll={() => { fetchData(); fetchNotifications(); }} 
            notifications={notifications}
            onRefreshNotifications={fetchNotifications}
          />
        )}

        {activeTab === 'superadmin' && currentUser && (currentUser.permissions.includes('view_superadmin') || currentUser.role === 'superadmin') && (
          <SuperadminConsole
            currentUser={currentUser}
            properties={properties}
            rooms={rooms}
            transactions={transactions}
            onRefreshAll={() => { fetchData(); fetchNotifications(); }}
          />
        )}

        {activeTab === 'my-bookings' && currentUser && (
          <div className="space-y-6">
            <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-xs">
              <h2 className="font-sans font-bold text-lg text-gray-900 flex items-center space-x-2">
                <BookOpen className="h-5 w-5 text-blue-600" />
                <span>Transaksi & Pemesanan Saya</span>
              </h2>
              <p className="text-xs text-gray-400 mt-1">Daftar seluruh transaksi pemesanan stay harian, sewa bulanan, dan pembelian properti Anda di SewaBeliPro.</p>
            </div>

            <div className="bg-white rounded-2xl border border-gray-100 shadow-xs overflow-hidden">
              <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-3 px-6">ID Transaksi</th>
                      <th className="py-3 px-6">Properti</th>
                      <th className="py-3 px-6">Jenis Transaksi</th>
                      <th className="py-3 px-6">Rentang Waktu / Detail</th>
                      <th className="py-3 px-6 text-right">Biaya / Harga</th>
                      <th className="py-3 px-6 text-center">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-50 text-gray-700">
                    {userTransactions.map((tx) => (
                      <tr key={tx.id} className="hover:bg-gray-50/20">
                        <td className="py-4 px-6 font-mono text-gray-400 font-semibold">#{tx.id}</td>
                        <td className="py-4 px-6 font-semibold text-gray-900">
                          <span className="block">{tx.propertyName}</span>
                          <span className="text-[10px] text-gray-400 capitalize">{tx.propertyType}</span>
                        </td>
                        <td className="py-4 px-6">
                          <span className={`px-2.5 py-1 text-[10px] font-bold rounded-full ${
                            tx.type === 'stay' ? 'bg-blue-50 text-blue-700' :
                            tx.type === 'rent' ? 'bg-purple-50 text-purple-700' :
                            'bg-amber-50 text-amber-700'
                          }`}>
                            {tx.type === 'stay' ? 'Menginap Harian' : tx.type === 'rent' ? 'Sewa Bulanan' : 'Pembelian Unit'}
                          </span>
                        </td>
                        <td className="py-4 px-6 text-gray-500">
                          {tx.startDate ? (
                            <div className="flex items-center space-x-1">
                              <Clock className="h-3 w-3 shrink-0 text-gray-400" />
                              <span>{tx.startDate} s/d {tx.endDate}</span>
                            </div>
                          ) : (
                            <span className="text-gray-400">Cash / Lunas Kontrak</span>
                          )}
                        </td>
                        <td className="py-4 px-6 text-right font-extrabold text-gray-900">{formatRupiah(tx.totalPrice)}</td>
                        <td className="py-4 px-6 text-center">
                          <span className="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-bold bg-green-100 text-green-800">
                            Lunas / Berhasil
                          </span>
                        </td>
                      </tr>
                    ))}
                    {userTransactions.length === 0 && (
                      <tr>
                        <td colSpan={6} className="py-12 text-center text-gray-400 italic">Belum ada transaksi pemesanan. Jelajahi properti dan sewa sekarang!</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'cloud-storage' && devMode && currentUser && (currentUser.permissions.includes('view_cloud_storage') || currentUser.role === 'superadmin') && (
          <CloudStoragePanel currentUser={currentUser} />
        )}
      </main>

      {/* Footer */}
      <footer className="bg-white border-t border-gray-100 py-6 mt-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center text-xs text-gray-400">
          <p>© {new Date().getFullYear()} PropertyHub. Platform Multi-Hotel & Property Management Simulator.</p>
          <p className="mt-1">Dibuat menggunakan React + Express API + MySQLi/CI3 Blueprint untuk pengujian arsitektur aplikasi.</p>
        </div>
      </footer>
      </div>

      {/* Modals Mounting */}
      {selectedProperty && (
        <PropertyDetailsModal
          property={selectedProperty}
          currentUser={currentUser}
          onClose={() => setSelectedProperty(null)}
          onAction={handleTransaction}
          promos={promos}
          rooms={rooms}
          onOpenAuth={() => {
            setSelectedProperty(null);
            setShowAuthModal(true);
          }}
        />
      )}

      {showAuthModal && (
        <AuthModal
          onClose={() => {
            setShowAuthModal(false);
            setAuthModalInitialRegister(false);
          }}
          onLoginSuccess={handleLoginSuccess}
          initialIsRegistering={authModalInitialRegister}
          pendingBookingNotice={pendingBooking ? `Anda sedang memesan "${properties.find(p => p.id === pendingBooking.propertyId)?.name || 'Properti'}". Akun Anda akan otomatis didaftarkan sebagai Tamu dan pesanan Anda akan langsung diproses!` : undefined}
        />
      )}

      {showChangePasswordModal && currentUser && (
        <ChangePasswordModal
          currentUser={currentUser}
          onClose={() => setShowChangePasswordModal(false)}
        />
      )}

      {showAddPropertyModal && (
        <AddPropertyModal
          onClose={() => setShowAddPropertyModal(false)}
          onSubmit={handleAddProperty}
        />
      )}

      {/* Toast Alert */}
      {toast && (
        <div className="fixed bottom-5 right-5 z-50" id="global-toast-notification">
          <div className={`px-4 py-3 rounded-xl shadow-lg border text-xs font-semibold flex items-center space-x-2 animate-in fade-in slide-in-from-bottom-5 duration-300 ${
            toast.type === 'success' ? 'bg-emerald-50 text-emerald-800 border-emerald-100' :
            toast.type === 'error' ? 'bg-red-50 text-red-800 border-red-100' :
            'bg-blue-50 text-blue-800 border-blue-100'
          }`}>
            <span>{toast.message}</span>
            <button onClick={() => setToast(null)} className="hover:opacity-75 cursor-pointer text-current font-extrabold ml-1.5">✕</button>
          </div>
        </div>
      )}

      {/* Custom Confirmation Modal */}
      {confirmModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-xs" id="global-confirm-modal">
          <div className="bg-white rounded-2xl w-full max-w-md p-6 shadow-2xl border border-gray-100 space-y-4">
            <h4 className="font-sans font-bold text-base text-gray-900">{confirmModal.title}</h4>
            <p className="text-xs text-gray-600 leading-relaxed">{confirmModal.message}</p>
            <div className="flex justify-end space-x-3 pt-2">
              <button
                onClick={() => setConfirmModal(null)}
                className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-xs font-semibold hover:bg-gray-50 transition-colors cursor-pointer"
              >
                Batalkan
              </button>
              <button
                onClick={confirmModal.onConfirm}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-xs font-bold shadow-sm transition-colors cursor-pointer"
              >
                Ya, Lanjutkan
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
