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

import React, { useState, useEffect, useRef } from 'react';
import { 
  User, 
  Building2, 
  TrendingUp, 
  Sparkles, 
  Clipboard, 
  Award, 
  MapPin, 
  DollarSign, 
  Calendar, 
  RefreshCw, 
  Star, 
  BarChart3, 
  ChevronRight,
  Shield,
  HelpCircle,
  AlertTriangle,
  Terminal,
  Search,
  Trash2,
  Play,
  Check,
  Activity,
  Copy,
  Layers,
  ArrowRight,
  Filter,
  SlidersHorizontal,
  Info
} from 'lucide-react';
import { 
  ResponsiveContainer, 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  Tooltip as ChartTooltip, 
  Cell, 
  PieChart, 
  Pie 
} from 'recharts';
import { User as UserType, Property, Transaction } from '../types';

interface ProfilingHubProps {
  currentUser: UserType | null;
}

type MainTab = 'profiling' | 'logs';
type ProfileTab = 'guest' | 'property' | 'owner' | 'buyer';

interface LogEntry {
  id: string;
  type: 'user' | 'system' | 'app' | 'api';
  message: string;
  user: string;
  timestamp: string;
}

export default function ProfilingHub({ currentUser }: ProfilingHubProps) {
  const [activeMainTab, setActiveMainTab] = useState<MainTab>('profiling');
  const [activeProfileTab, setActiveProfileTab] = useState<ProfileTab>('guest');
  
  // Data State
  const [users, setUsers] = useState<UserType[]>([]);
  const [properties, setProperties] = useState<Property[]>([]);
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  // AI State
  const [aiLoading, setAiLoading] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [aiInsights, setAiInsights] = useState<string | null>(null);

  // Live Logs State
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const [logFilter, setLogFilter] = useState<'all' | 'api' | 'user' | 'system' | 'app'>('all');
  const [logSearch, setLogSearch] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [apiTestStatus, setApiTestStatus] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  // Stats calculation
  const [stats, setStats] = useState({
    guest: { total: 0, silverPlus: 0, avgSpend: 0 },
    property: { total: 0, occupiedRate: 0, avgPrice: 0 },
    owner: { total: 0, avgProperties: 0, topEarners: 0 },
    buyer: { total: 0, completedBuys: 0, avgPurchase: 0 }
  });

  const fetchData = async (silent = false) => {
    if (!silent) setLoading(true);
    setError(null);
    try {
      const [usersRes, propRes, txRes] = await Promise.all([
        fetch('/api/users'),
        fetch('/api/properties'),
        fetch('/api/transactions')
      ]);

      if (!usersRes.ok || !propRes.ok || !txRes.ok) {
        throw new Error(`Server returned error status: ${usersRes.status}/${propRes.status}/${txRes.status}`);
      }

      const usersData: UserType[] = await usersRes.json();
      const propData: Property[] = await propRes.json();
      const txData: Transaction[] = await txRes.json();

      setUsers(usersData);
      setProperties(propData);
      setTransactions(txData);

      // Segment counts
      const guests = usersData.filter(u => u.roleId === '2' || txData.some(t => t.buyerId === u.id && t.type !== 'buy'));
      const owners = usersData.filter(u => u.roleId === '1');
      const buyers = usersData.filter(u => u.roleId === '2' || txData.some(t => t.buyerId === u.id && t.type === 'buy'));

      // Guest metrics
      const guestSpend = txData
        .filter(t => t.type !== 'buy' && t.status === 'paid')
        .reduce((sum, t) => sum + t.totalPrice, 0);
      const avgGuestSpend = guests.length ? Math.round(guestSpend / guests.length) : 0;

      // Property metrics
      const rentedCount = propData.filter(p => p.status === 'rented' || p.status === 'sold').length;
      const occupiedRate = propData.length ? Math.round((rentedCount / propData.length) * 100) : 0;
      const avgPrice = propData.length 
        ? Math.round(propData.reduce((sum, p) => sum + (p.priceDay || p.priceMonth || (p.priceBuy ? p.priceBuy / 100 : 0)), 0) / propData.length)
        : 0;

      // Owner metrics
      const avgProps = owners.length ? Number((propData.length / owners.length).toFixed(1)) : 0;

      // Buyer metrics
      const completedBuys = txData.filter(t => t.type === 'buy' && t.status === 'paid').length;
      const purchaseTotal = txData.filter(t => t.type === 'buy' && t.status === 'paid').reduce((sum, t) => sum + t.totalPrice, 0);
      const avgPurchase = completedBuys ? Math.round(purchaseTotal / completedBuys) : 0;

      setStats({
        guest: { total: guests.length, silverPlus: Math.ceil(guests.length * 0.4), avgSpend: avgGuestSpend },
        property: { total: propData.length, occupiedRate, avgPrice },
        owner: { total: owners.length, avgProperties: avgProps, topEarners: owners.filter(o => txData.some(t => t.status === 'paid')).length },
        buyer: { total: buyers.length, completedBuys, avgPurchase }
      });

      // Pre-select first item if exists
      if (!selectedItem) {
        if (activeProfileTab === 'guest' && guests.length) setSelectedItem(guests[0]);
        else if (activeProfileTab === 'property' && propData.length) setSelectedItem(propData[0]);
        else if (activeProfileTab === 'owner' && owners.length) setSelectedItem(owners[0]);
        else if (activeProfileTab === 'buyer' && buyers.length) setSelectedItem(buyers[0]);
      }
    } catch (err: any) {
      console.error('Error fetching profiling data', err);
      setError(err.message || 'Gagal memuat data analisis profiling.');
    } finally {
      setLoading(false);
    }
  };

  const fetchLogs = async (silent = false) => {
    if (!silent) setLogsLoading(true);
    try {
      const res = await fetch('/api/logs');
      if (res.ok) {
        const data = await res.json();
        setLogs(data);
      }
    } catch (error) {
      console.error('Failed to fetch API logs:', error);
    } finally {
      if (!silent) setLogsLoading(false);
    }
  };

  const clearLogs = async () => {
    if (!window.confirm('Apakah Anda yakin ingin menghapus seluruh log sistem & log API?')) return;
    setLogsLoading(true);
    try {
      const res = await fetch('/api/logs', { method: 'DELETE' });
      if (res.ok) {
        setApiTestStatus('Log berhasil dibersihkan!');
        setTimeout(() => setApiTestStatus(null), 3000);
        await fetchLogs();
      }
    } catch (error) {
      console.error('Failed to clear logs:', error);
    } finally {
      setLogsLoading(false);
    }
  };

  // Trigger test API endpoints to show live interception
  const triggerTestAPI = async (endpoint: string, method: 'GET' | 'POST' = 'GET') => {
    setApiTestStatus(`Mengirim request ke ${endpoint}...`);
    const start = Date.now();
    try {
      let res;
      if (method === 'GET') {
        res = await fetch(endpoint);
      } else {
        res = await fetch(endpoint, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ message: "Test log dari Profiling Console" })
        });
      }
      const latency = Date.now() - start;
      if (res.ok) {
        setApiTestStatus(`Sukses! ${method} ${endpoint} merespons ${res.status} dalam ${latency}ms.`);
        setTimeout(() => {
          fetchLogs(true);
          fetchData(true);
        }, 150);
      } else {
        setApiTestStatus(`Gagal! Status: ${res.status} (${latency}ms)`);
        setTimeout(() => fetchLogs(true), 150);
      }
    } catch (e: any) {
      setApiTestStatus(`Error: ${e.message}`);
    }
    setTimeout(() => setApiTestStatus(null), 4000);
  };

  const copyLogText = (text: string, id: string) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 1500);
  };

  // Lifecycle
  useEffect(() => {
    fetchData();
    fetchLogs();
  }, []);

  // Polling logic for logs
  useEffect(() => {
    let intervalId: any;
    if (autoRefresh && activeMainTab === 'logs') {
      intervalId = setInterval(() => {
        fetchLogs(true);
      }, 3000);
    }
    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [autoRefresh, activeMainTab]);

  // Handle active subsegment changes
  useEffect(() => {
    setAiInsights(null);
    const guests = users.filter(u => u.roleId === '2' || transactions.some(t => t.buyerId === u.id && t.type !== 'buy'));
    const owners = users.filter(u => u.roleId === '1');
    const buyers = users.filter(u => u.roleId === '2' || transactions.some(t => t.buyerId === u.id && t.type === 'buy'));

    if (activeProfileTab === 'guest') setSelectedItem(guests[0] || null);
    else if (activeProfileTab === 'property') setSelectedItem(properties[0] || null);
    else if (activeProfileTab === 'owner') setSelectedItem(owners[0] || null);
    else if (activeProfileTab === 'buyer') setSelectedItem(buyers[0] || null);
  }, [activeProfileTab, users, properties, transactions]);

  const generateAIInsights = async (item: any) => {
    if (!item) return;
    setAiLoading(true);
    setAiInsights(null);

    let payload: any = {};
    if (activeProfileTab === 'guest') {
      const personalTx = transactions.filter(t => t.buyerId === item.id);
      payload = {
        name: item.fullName,
        email: item.email,
        phone: item.phone,
        totalBookings: personalTx.length,
        totalSpending: personalTx.reduce((sum, t) => sum + t.totalPrice, 0),
        bookingTypes: personalTx.map(t => t.type),
        preferredProperties: personalTx.map(t => t.propertyName),
        registeredSince: item.created_at || "Juni 2026"
      };
    } else if (activeProfileTab === 'property') {
      const propTx = transactions.filter(t => t.propertyId === item.id);
      payload = {
        propertyName: item.name,
        type: item.type,
        address: item.address,
        priceDay: item.priceDay,
        priceMonth: item.priceMonth,
        priceBuy: item.priceBuy,
        status: item.status,
        totalBookings: propTx.length,
        totalRevenue: propTx.reduce((sum, t) => sum + t.totalPrice, 0),
        description: item.description
      };
    } else if (activeProfileTab === 'owner') {
      const ownerProps = properties.filter(p => p.ownerId === item.id);
      const ownerTx = transactions.filter(t => ownerProps.some(p => p.id === t.propertyId));
      payload = {
        hostName: item.fullName,
        email: item.email,
        phone: item.phone,
        listingsCount: ownerProps.length,
        listedProperties: ownerProps.map(p => ({ name: p.name, type: p.type, status: p.status })),
        totalEarnings: ownerTx.reduce((sum, t) => sum + t.totalPrice, 0),
        bookingsHandled: ownerTx.length
      };
    } else if (activeProfileTab === 'buyer') {
      const purchaseTx = transactions.filter(t => t.buyerId === item.id && t.type === 'buy');
      payload = {
        buyerName: item.fullName,
        email: item.email,
        phone: item.phone,
        purchasedPropertiesCount: purchaseTx.length,
        purchasedList: purchaseTx.map(t => ({ name: t.propertyName, price: t.totalPrice, date: t.createdAt })),
        estimatedBudgetRange: purchaseTx.length 
          ? `Rp ${Math.round(purchaseTx.reduce((sum, t) => sum + t.totalPrice, 0) / purchaseTx.length).toLocaleString('id-ID')}`
          : 'Rp 1.000.000.000 - Rp 3.000.000.000 (Potensial)'
      };
    }

    try {
      const res = await fetch('/api/gemini/profile-insights', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: activeProfileTab, data: payload })
      });

      if (res.ok) {
        const result = await res.json();
        setAiInsights(result.insights);
      } else {
        const errData = await res.json();
        setAiInsights(`**Error:** ${errData.error || 'Gagal terhubung dengan layanan AI.'}`);
      }
    } catch (err: any) {
      setAiInsights(`**Error:** Gagal memproses AI Insights. Pastikan koneksi dan kunci API valid.`);
    } finally {
      setAiLoading(false);
    }
  };

  const getFilteredItems = () => {
    if (activeProfileTab === 'guest') {
      return users.filter(u => u.roleId === '2' || transactions.some(t => t.buyerId === u.id && t.type !== 'buy'));
    }
    if (activeProfileTab === 'property') {
      return properties;
    }
    if (activeProfileTab === 'owner') {
      return users.filter(u => u.roleId === '1');
    }
    if (activeProfileTab === 'buyer') {
      return users.filter(u => u.roleId === '2' || transactions.some(t => t.buyerId === u.id && t.type === 'buy'));
    }
    return [];
  };

  const getGuestStats = (guestId: string) => {
    const personalTx = transactions.filter(t => t.buyerId === guestId);
    const stayTx = personalTx.filter(t => t.type === 'stay');
    const rentTx = personalTx.filter(t => t.type === 'rent');
    const totalSpend = personalTx.reduce((sum, t) => sum + t.totalPrice, 0);

    let tier = 'Bronze member';
    let color = 'bg-amber-100 text-amber-800 border-amber-200';
    if (totalSpend > 5000000) {
      tier = 'Gold Ambassador';
      color = 'bg-yellow-100 text-yellow-800 border-yellow-200';
    } else if (totalSpend > 2000000) {
      tier = 'Silver Premium';
      color = 'bg-slate-100 text-slate-800 border-slate-200';
    }

    let tag = 'Casual Leisure';
    if (stayTx.length > rentTx.length) tag = 'Staycation Lover';
    if (rentTx.length > stayTx.length) tag = 'Long-term Tenant';

    return { totalSpend, stayCount: stayTx.length, rentCount: rentTx.length, tier, color, tag };
  };

  const getPropertyStats = (prop: Property) => {
    const propTx = transactions.filter(t => t.propertyId === prop.id && t.status === 'paid');
    const revenue = propTx.reduce((sum, t) => sum + t.totalPrice, 0);
    const popularityScore = Math.min(100, propTx.length * 25 + 40);

    let targetAudience = 'Keluarga & Wisatawan';
    if (prop.type === 'kos') targetAudience = 'Mahasiswa & Pekerja';
    if (prop.type === 'apartment') targetAudience = 'Profesional Muda';
    if (prop.type === 'villa') targetAudience = 'Premium Holidaymaker';

    return { revenue, bookingCount: propTx.length, popularityScore, targetAudience };
  };

  const getOwnerStats = (ownerId: string) => {
    const ownerProps = properties.filter(p => p.ownerId === ownerId);
    const propIds = ownerProps.map(p => p.id);
    const ownerTx = transactions.filter(t => propIds.includes(t.propertyId) && t.status === 'paid');
    const totalEarnings = ownerTx.reduce((sum, t) => sum + t.totalPrice, 0);

    let specialization = 'General Host';
    const types = ownerProps.map(p => p.type);
    if (types.includes('villa')) specialization = 'Luxury Villa Manager';
    else if (types.includes('hotel')) specialization = 'Hotelier Professional';
    else if (types.includes('apartment') || types.includes('kos')) specialization = 'Urban Rentals Owner';

    return { listingsCount: ownerProps.length, totalEarnings, transactionsCount: ownerTx.length, specialization };
  };

  const getBuyerStats = (buyerId: string) => {
    const personalTx = transactions.filter(t => t.buyerId === buyerId);
    const buyTx = personalTx.filter(t => t.type === 'buy');
    const totalInvested = buyTx.reduce((sum, t) => sum + t.totalPrice, 0);

    let capacity = 'Potential Buyer';
    let color = 'bg-sky-50 text-sky-700';
    if (totalInvested > 1500000000) {
      capacity = 'High-Net-Worth Investor';
      color = 'bg-purple-100 text-purple-800 border-purple-200';
    } else if (totalInvested > 500000000) {
      capacity = 'Mid-Tier Investor';
      color = 'bg-blue-100 text-blue-800 border-blue-200';
    }

    return { purchaseCount: buyTx.length, totalInvested, capacity, color };
  };

  const filteredItems = getFilteredItems();

  // Chart Data Preparation
  const chartDataSegments = [
    { name: 'Tamu', jumlah: stats.guest.total, fill: '#3b82f6' },
    { name: 'Aset Properti', jumlah: stats.property.total, fill: '#10b981' },
    { name: 'Mitra Host', jumlah: stats.owner.total, fill: '#a855f7' },
    { name: 'Investor/Buyer', jumlah: stats.buyer.total, fill: '#f43f5e' }
  ];

  const chartDataRentStatus = [
    { name: 'Tersedia', value: properties.filter(p => p.status === 'available').length, fill: '#10b981' },
    { name: 'Disewa/Terisi', value: properties.filter(p => p.status === 'rented').length, fill: '#f59e0b' },
    { name: 'Terjual', value: properties.filter(p => p.status === 'sold').length, fill: '#ef4444' }
  ];

  // Logs Filtered View
  const filteredLogs = logs.filter(log => {
    const matchesFilter = logFilter === 'all' || log.type === logFilter;
    const matchesSearch = 
      log.message.toLowerCase().includes(logSearch.toLowerCase()) ||
      log.user.toLowerCase().includes(logSearch.toLowerCase()) ||
      log.type.toLowerCase().includes(logSearch.toLowerCase());
    return matchesFilter && matchesSearch;
  });

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6" id="profiling-hub-root">
      
      {/* Upper Brand Header */}
      <div className="bg-gradient-to-r from-slate-900 via-indigo-950 to-slate-900 rounded-2xl p-6 text-white shadow-xl border border-slate-800 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div className="space-y-1.5">
          <div className="flex items-center gap-2">
            <Activity className="h-6 w-6 text-indigo-400 animate-pulse" />
            <h1 className="text-xl font-bold tracking-tight">Profiling & Analisis Log Sistem</h1>
          </div>
          <p className="text-xs text-slate-300 leading-relaxed max-w-2xl">
            Sistem analisis data untuk segmentasi profil pengguna (tamu, host, investor), popularitas hunian, serta logger API real-time terintegrasi untuk kenyamanan debugging platform <strong>PropertyHub</strong>.
          </p>
        </div>
        
        {/* Main Tab Switcher */}
        <div className="bg-slate-950/80 p-1 rounded-xl border border-slate-800 flex self-start md:self-auto shrink-0">
          <button
            onClick={() => setActiveMainTab('profiling')}
            className={`px-4 py-2 rounded-lg text-xs font-bold transition-all flex items-center gap-2 cursor-pointer ${
              activeMainTab === 'profiling'
                ? 'bg-indigo-600 text-white shadow-sm'
                : 'text-slate-400 hover:text-white'
            }`}
          >
            <BarChart3 className="h-3.5 w-3.5" />
            <span>Segmentasi & AI Profiling</span>
          </button>
          <button
            onClick={() => setActiveMainTab('logs')}
            className={`px-4 py-2 rounded-lg text-xs font-bold transition-all flex items-center gap-2 cursor-pointer ${
              activeMainTab === 'logs'
                ? 'bg-indigo-600 text-white shadow-sm'
                : 'text-slate-400 hover:text-white'
            }`}
          >
            <Terminal className="h-3.5 w-3.5" />
            <span>Log Analisis & API Monitor</span>
            <span className="h-1.5 w-1.5 rounded-full bg-emerald-400 animate-ping" />
          </button>
        </div>
      </div>

      {activeMainTab === 'profiling' ? (
        // PROFILING AND SEGMENTATION VIEW
        <div className="space-y-6">
          
          {/* Segment Summary Cards Grid */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4" id="profiling-selectors-grid">
            {/* Tamu Card */}
            <button
              onClick={() => {
                setActiveProfileTab('guest');
                setSelectedItem(null);
              }}
              className={`p-4 rounded-2xl border text-left transition-all cursor-pointer relative overflow-hidden ${
                activeProfileTab === 'guest'
                  ? 'bg-blue-600 text-white border-blue-600 shadow-lg transform scale-[1.01]'
                  : 'bg-white text-gray-800 border-slate-100 hover:border-blue-200 hover:bg-slate-50'
              }`}
            >
              <div className="flex items-center justify-between">
                <User className={`h-5 w-5 ${activeProfileTab === 'guest' ? 'text-blue-100' : 'text-blue-600'}`} />
                <span className={`text-[9px] font-extrabold px-1.5 py-0.5 rounded-full ${activeProfileTab === 'guest' ? 'bg-blue-700 text-blue-100' : 'bg-blue-50 text-blue-600'}`}>TAMU</span>
              </div>
              <p className="text-xs font-semibold opacity-80 mt-3">Segmentasi Tamu</p>
              <p className="text-xl font-black mt-0.5">{stats.guest.total} Akun</p>
              <div className="text-[10px] mt-2 opacity-75 border-t border-current/20 pt-1.5 flex justify-between">
                <span>Rata Spend:</span>
                <span className="font-bold">Rp {stats.guest.avgSpend.toLocaleString('id-ID')}</span>
              </div>
            </button>

            {/* Property Card */}
            <button
              onClick={() => {
                setActiveProfileTab('property');
                setSelectedItem(null);
              }}
              className={`p-4 rounded-2xl border text-left transition-all cursor-pointer relative overflow-hidden ${
                activeProfileTab === 'property'
                  ? 'bg-emerald-600 text-white border-emerald-600 shadow-lg transform scale-[1.01]'
                  : 'bg-white text-gray-800 border-slate-100 hover:border-emerald-200 hover:bg-slate-50'
              }`}
            >
              <div className="flex items-center justify-between">
                <Building2 className={`h-5 w-5 ${activeProfileTab === 'property' ? 'text-emerald-100' : 'text-emerald-600'}`} />
                <span className={`text-[9px] font-extrabold px-1.5 py-0.5 rounded-full ${activeProfileTab === 'property' ? 'bg-emerald-700 text-emerald-100' : 'bg-emerald-50 text-emerald-600'}`}>ASET</span>
              </div>
              <p className="text-xs font-semibold opacity-80 mt-3">Profiling Properti</p>
              <p className="text-xl font-black mt-0.5">{stats.property.total} Listing</p>
              <div className="text-[10px] mt-2 opacity-75 border-t border-current/20 pt-1.5 flex justify-between">
                <span>Okupansi/Sold:</span>
                <span className="font-bold">{stats.property.occupiedRate}% Terisi</span>
              </div>
            </button>

            {/* Host Card */}
            <button
              onClick={() => {
                setActiveProfileTab('owner');
                setSelectedItem(null);
              }}
              className={`p-4 rounded-2xl border text-left transition-all cursor-pointer relative overflow-hidden ${
                activeProfileTab === 'owner'
                  ? 'bg-purple-600 text-white border-purple-600 shadow-lg transform scale-[1.01]'
                  : 'bg-white text-gray-800 border-slate-100 hover:border-purple-200 hover:bg-slate-50'
              }`}
            >
              <div className="flex items-center justify-between">
                <Shield className={`h-5 w-5 ${activeProfileTab === 'owner' ? 'text-purple-100' : 'text-purple-600'}`} />
                <span className={`text-[9px] font-extrabold px-1.5 py-0.5 rounded-full ${activeProfileTab === 'owner' ? 'bg-purple-700 text-purple-100' : 'bg-purple-50 text-purple-600'}`}>HOST</span>
              </div>
              <p className="text-xs font-semibold opacity-80 mt-3">Mitra Host</p>
              <p className="text-xl font-black mt-0.5">{stats.owner.total} Pemilik</p>
              <div className="text-[10px] mt-2 opacity-75 border-t border-current/20 pt-1.5 flex justify-between">
                <span>Avg Unit:</span>
                <span className="font-bold">{stats.owner.avgProperties} unit</span>
              </div>
            </button>

            {/* Buyer Card */}
            <button
              onClick={() => {
                setActiveProfileTab('buyer');
                setSelectedItem(null);
              }}
              className={`p-4 rounded-2xl border text-left transition-all cursor-pointer relative overflow-hidden ${
                activeProfileTab === 'buyer'
                  ? 'bg-rose-600 text-white border-rose-600 shadow-lg transform scale-[1.01]'
                  : 'bg-white text-gray-800 border-slate-100 hover:border-rose-200 hover:bg-slate-50'
              }`}
            >
              <div className="flex items-center justify-between">
                <TrendingUp className={`h-5 w-5 ${activeProfileTab === 'buyer' ? 'text-rose-100' : 'text-rose-600'}`} />
                <span className={`text-[9px] font-extrabold px-1.5 py-0.5 rounded-full ${activeProfileTab === 'buyer' ? 'bg-rose-700 text-rose-100' : 'bg-rose-50 text-rose-600'}`}>BUYER</span>
              </div>
              <p className="text-xs font-semibold opacity-80 mt-3">Investasi Pembeli</p>
              <p className="text-xl font-black mt-0.5">{stats.buyer.total} Investor</p>
              <div className="text-[10px] mt-2 opacity-75 border-t border-current/20 pt-1.5 flex justify-between">
                <span>Rata-rata Buy:</span>
                <span className="font-bold">Rp {stats.buyer.avgPurchase.toLocaleString('id-ID')}</span>
              </div>
            </button>
          </div>

          {/* Visual Charts Analytics Bar */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            {/* Chart 1: Segment Distribusi */}
            <div className="bg-white rounded-2xl p-5 border border-slate-100 shadow-xs space-y-3">
              <div className="flex items-center justify-between">
                <h3 className="text-xs font-bold text-slate-700 uppercase tracking-wider">Perbandingan Volume Kategori</h3>
                <span className="text-[10px] bg-indigo-50 text-indigo-600 font-bold px-2 py-0.5 rounded">Bar Chart</span>
              </div>
              <div className="h-44 w-full text-xs">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={chartDataSegments} margin={{ top: 10, right: 10, left: -20, bottom: 5 }}>
                    <XAxis dataKey="name" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} />
                    <ChartTooltip 
                      contentStyle={{ background: '#0f172a', border: 'none', borderRadius: '8px', color: '#fff' }}
                      labelStyle={{ fontWeight: 'bold' }}
                    />
                    <Bar dataKey="jumlah" radius={[6, 6, 0, 0]}>
                      {chartDataSegments.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.fill} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* Chart 2: Status Properti Pie */}
            <div className="bg-white rounded-2xl p-5 border border-slate-100 shadow-xs space-y-3">
              <div className="flex items-center justify-between">
                <h3 className="text-xs font-bold text-slate-700 uppercase tracking-wider">Okupansi Hunian & Unit</h3>
                <span className="text-[10px] bg-emerald-50 text-emerald-600 font-bold px-2 py-0.5 rounded">Pie Chart</span>
              </div>
              <div className="flex items-center justify-between h-44">
                <div className="w-1/2 h-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={chartDataRentStatus}
                        cx="50%"
                        cy="50%"
                        innerRadius={35}
                        outerRadius={55}
                        paddingAngle={5}
                        dataKey="value"
                      >
                        {chartDataRentStatus.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={entry.fill} />
                        ))}
                      </Pie>
                    </PieChart>
                  </ResponsiveContainer>
                </div>
                {/* Legends */}
                <div className="w-1/2 space-y-2 text-xs">
                  {chartDataRentStatus.map((item, idx) => (
                    <div key={idx} className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <span className="h-2 w-2 rounded-full" style={{ backgroundColor: item.fill }} />
                        <span className="text-slate-600">{item.name}</span>
                      </div>
                      <span className="font-bold text-slate-800">{item.value} unit</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Platform Health Metrics Panel */}
            <div className="bg-gradient-to-br from-indigo-950 to-slate-900 rounded-2xl p-5 text-slate-300 shadow-sm flex flex-col justify-between">
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-indigo-400">
                  <Sparkles className="h-4 w-4" />
                  <span className="text-xs font-bold uppercase tracking-wider text-indigo-300">Saran AI Optimizer</span>
                </div>
                <h4 className="text-white text-sm font-bold leading-snug">
                  Gunakan dynamic pricing di akhir pekan untuk meningkatkan okupansi properti kategori "VILLA"!
                </h4>
                <p className="text-[10.5px] text-slate-400 leading-relaxed">
                  Berdasarkan pemetaan otomatis platform, rata-rata rasio booking tamu untuk harian (staycation) naik sebesar 42% pada libur panjang nasional.
                </p>
              </div>

              <div className="pt-3 border-t border-indigo-900/50 flex justify-between items-center text-[10px] text-indigo-300">
                <span>Model AI: Gemini 3.5 Flash</span>
                <span className="bg-indigo-900 px-2 py-0.5 rounded font-mono font-bold">100% READY</span>
              </div>
            </div>

          </div>

          {/* Profiling Split Content Panel */}
          {error ? (
            <div className="p-12 text-center bg-white border border-red-100 rounded-2xl shadow-xs" id="profiling-error-state">
              <div className="max-w-md mx-auto flex flex-col items-center">
                <span className="inline-flex items-center justify-center p-3 bg-red-50 text-red-600 rounded-full mb-4">
                  <AlertTriangle className="h-6 w-6" />
                </span>
                <p className="text-red-800 font-semibold text-lg mb-1">Gagal Memuat Profiling</p>
                <p className="text-sm text-red-600 mb-6">{error}</p>
                <button
                  onClick={() => {
                    setError(null);
                    fetchData();
                  }}
                  className="inline-flex items-center gap-2 px-5 py-2.5 bg-red-600 text-white rounded-xl text-sm font-medium hover:bg-red-700 transition cursor-pointer"
                >
                  <RefreshCw className="h-4 w-4" />
                  Coba Lagi
                </button>
              </div>
            </div>
          ) : loading ? (
            <div className="flex flex-col items-center justify-center p-20 bg-white border border-slate-100 rounded-2xl" id="profiling-loading-state">
              <RefreshCw className="h-8 w-8 text-indigo-600 animate-spin mb-4" />
              <p className="text-sm text-slate-500 font-medium">Memproses data segmentasi & profiling secara dinamis...</p>
            </div>
          ) : filteredItems.length === 0 ? (
            <div className="p-16 text-center bg-white border border-slate-100 rounded-2xl" id="profiling-empty-state">
              <HelpCircle className="h-10 w-10 text-slate-300 mx-auto mb-3" />
              <p className="text-slate-500 font-medium">Belum ada profil subjek terdeteksi untuk kategori ini.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6" id="profiling-content-layout">
              {/* Left Column: List of items */}
              <div className="lg:col-span-4 space-y-3 max-h-[620px] overflow-y-auto pr-1" id="profiling-items-column">
                <p className="text-xs font-bold text-slate-400 uppercase tracking-wider px-1">Daftar Subjek Kategori ({filteredItems.length})</p>
                {filteredItems.map((item) => {
                  const isSelected = selectedItem && selectedItem.id === item.id;
                  
                  let subTitle = '';
                  let badgeText = '';
                  let badgeColor = '';

                  if (activeProfileTab === 'guest') {
                    const info = getGuestStats(item.id);
                    subTitle = `Spend: Rp ${info.totalSpend.toLocaleString('id-ID')}`;
                    badgeText = info.tier;
                    badgeColor = info.color;
                  } else if (activeProfileTab === 'property') {
                    subTitle = `${item.address.substring(0, 32)}...`;
                    badgeText = item.type.toUpperCase();
                    badgeColor = item.status === 'available' ? 'bg-green-50 text-green-700 border-green-100' : 'bg-amber-50 text-amber-700 border-amber-100';
                  } else if (activeProfileTab === 'owner') {
                    const info = getOwnerStats(item.id);
                    subTitle = `${info.listingsCount} Unit • Rp ${info.totalEarnings.toLocaleString('id-ID')}`;
                    badgeText = info.specialization;
                    badgeColor = 'bg-purple-50 text-purple-700 border-purple-100';
                  } else if (activeProfileTab === 'buyer') {
                    const info = getBuyerStats(item.id);
                    subTitle = `${info.purchaseCount} unit dibeli • Total Rp ${info.totalInvested.toLocaleString('id-ID')}`;
                    badgeText = info.capacity;
                    badgeColor = info.color;
                  }

                  return (
                    <button
                      key={item.id}
                      onClick={() => {
                        setSelectedItem(item);
                        setAiInsights(null);
                      }}
                      className={`w-full p-4 text-left rounded-xl border transition-all flex items-center justify-between cursor-pointer ${
                        isSelected
                          ? 'bg-indigo-50/50 border-indigo-500 shadow-sm ring-1 ring-indigo-500/20'
                          : 'bg-white border-slate-100 hover:border-slate-300'
                      }`}
                    >
                      <div className="space-y-1">
                        <p className="font-bold text-slate-900 text-sm">{item.fullName || item.name}</p>
                        <p className="text-xs text-slate-500">{subTitle}</p>
                        <div className="pt-1">
                          <span className={`inline-block text-[9px] font-extrabold px-2 py-0.5 rounded-full border ${badgeColor}`}>
                            {badgeText}
                          </span>
                        </div>
                      </div>
                      <ChevronRight className={`h-4 w-4 ${isSelected ? 'text-indigo-600' : 'text-slate-400'}`} />
                    </button>
                  );
                })}
              </div>

              {/* Right Column: Detailed Profiling & AI Insights */}
              <div className="lg:col-span-8 bg-white border border-slate-100 rounded-2xl shadow-xs overflow-hidden" id="profiling-details-column">
                {selectedItem ? (
                  <div className="p-6 space-y-6">
                    {/* Header Profile Title */}
                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-100 pb-5" id="profile-detail-header">
                      <div className="flex items-center gap-3">
                        <div className={`p-3 rounded-xl ${
                          activeProfileTab === 'guest' ? 'bg-blue-100 text-blue-600' :
                          activeProfileTab === 'property' ? 'bg-emerald-100 text-emerald-600' :
                          activeProfileTab === 'owner' ? 'bg-purple-100 text-purple-600' :
                          'bg-rose-100 text-rose-600'
                        }`}>
                          {activeProfileTab === 'guest' && <User className="h-6 w-6" />}
                          {activeProfileTab === 'property' && <Building2 className="h-6 w-6" />}
                          {activeProfileTab === 'owner' && <Shield className="h-6 w-6" />}
                          {activeProfileTab === 'buyer' && <TrendingUp className="h-6 w-6" />}
                        </div>
                        <div>
                          <h3 className="font-bold text-lg text-slate-900">{selectedItem.fullName || selectedItem.name}</h3>
                          <p className="text-xs text-slate-500 flex items-center gap-1.5 mt-0.5">
                            {activeProfileTab === 'guest' && `Tamu ID: #${selectedItem.id} • ${selectedItem.email}`}
                            {activeProfileTab === 'property' && `Properti ID: #${selectedItem.id} • ${selectedItem.address}`}
                            {activeProfileTab === 'owner' && `Host ID: #${selectedItem.id} • ${selectedItem.email}`}
                            {activeProfileTab === 'buyer' && `Pembeli ID: #${selectedItem.id} • ${selectedItem.email}`}
                          </p>
                        </div>
                      </div>

                      <button
                        onClick={() => generateAIInsights(selectedItem)}
                        disabled={aiLoading}
                        className="flex items-center gap-1.5 px-4 py-2.5 text-xs font-bold text-white bg-indigo-600 hover:bg-indigo-700 rounded-xl shadow-xs transition-colors cursor-pointer disabled:bg-indigo-300"
                        id="btn-generate-ai-profiling"
                      >
                        <Sparkles className={`h-4 w-4 ${aiLoading ? 'animate-spin' : ''}`} />
                        <span>{aiLoading ? 'Menganalisis...' : 'Analisis AI Smart Profiling'}</span>
                      </button>
                    </div>

                    {/* Behavioral & Context Profiling Metrics */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4" id="profile-metrics-grid">
                      {activeProfileTab === 'guest' && (
                        <>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Loyalty Tier</p>
                            <p className="text-sm font-bold text-slate-800 mt-1 flex items-center gap-1.5">
                              <Award className="h-4 w-4 text-yellow-600" />
                              <span>{getGuestStats(selectedItem.id).tier}</span>
                            </p>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Rasio Aktivitas</p>
                            <p className="text-sm font-bold text-slate-800 mt-1">
                              {getGuestStats(selectedItem.id).stayCount} Stay • {getGuestStats(selectedItem.id).rentCount} Rent
                            </p>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Total Pengeluaran</p>
                            <p className="text-sm font-bold text-indigo-600 mt-1">
                              Rp {getGuestStats(selectedItem.id).totalSpend.toLocaleString('id-ID')}
                            </p>
                          </div>
                        </>
                      )}

                      {activeProfileTab === 'property' && (
                        <>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Skor Popularitas</p>
                            <div className="flex items-center gap-1.5 mt-1">
                              <Star className="h-4 w-4 text-yellow-500 fill-yellow-500" />
                              <span className="text-sm font-bold text-slate-800">{getPropertyStats(selectedItem).popularityScore}% Okupansi</span>
                            </div>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Target Pasar</p>
                            <p className="text-sm font-bold text-slate-800 mt-1">
                              {getPropertyStats(selectedItem).targetAudience}
                            </p>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Total Omzet</p>
                            <p className="text-sm font-bold text-emerald-600 mt-1">
                              Rp {getPropertyStats(selectedItem).revenue.toLocaleString('id-ID')}
                            </p>
                          </div>
                        </>
                      )}

                      {activeProfileTab === 'owner' && (
                        <>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Spesialisasi Host</p>
                            <p className="text-sm font-bold text-slate-800 mt-1 flex items-center gap-1.5">
                              <Clipboard className="h-4 w-4 text-purple-600" />
                              <span>{getOwnerStats(selectedItem.id).specialization}</span>
                            </p>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Listing Aktif</p>
                            <p className="text-sm font-bold text-slate-800 mt-1">
                              {getOwnerStats(selectedItem.id).listingsCount} Unit Terdaftar
                            </p>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Total Keuntungan</p>
                            <p className="text-sm font-bold text-purple-600 mt-1">
                              Rp {getOwnerStats(selectedItem.id).totalEarnings.toLocaleString('id-ID')}
                            </p>
                          </div>
                        </>
                      )}

                      {activeProfileTab === 'buyer' && (
                        <>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Profil Finansial</p>
                            <p className="text-sm font-bold text-slate-800 mt-1">
                              {getBuyerStats(selectedItem.id).capacity}
                            </p>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Aset Dibeli</p>
                            <p className="text-sm font-bold text-slate-800 mt-1">
                              {getBuyerStats(selectedItem.id).purchaseCount} Unit
                            </p>
                          </div>
                          <div className="p-4 rounded-xl border border-slate-100 bg-slate-50/50">
                            <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-wider">Total Investasi</p>
                            <p className="text-sm font-bold text-rose-600 mt-1">
                              Rp {getBuyerStats(selectedItem.id).totalInvested.toLocaleString('id-ID')}
                            </p>
                          </div>
                        </>
                      )}
                    </div>

                    {/* Sub-lists: Detailed History or Data */}
                    <div className="border border-slate-100 rounded-xl p-5 space-y-3" id="profile-detailed-records">
                      <h4 className="font-bold text-sm text-slate-800 border-b border-slate-50 pb-2 flex items-center gap-1.5">
                        <BarChart3 className="h-4 w-4 text-slate-400" />
                        <span>
                          {activeProfileTab === 'guest' && 'Riwayat Akomodasi & Staying'}
                          {activeProfileTab === 'property' && 'Riwayat Transaksi Properti'}
                          {activeProfileTab === 'owner' && 'Properti Terdaftar'}
                          {activeProfileTab === 'buyer' && 'Daftar Pembelian & Penawaran'}
                        </span>
                      </h4>

                      {activeProfileTab === 'guest' && (
                        <div className="space-y-2">
                          {transactions.filter(t => t.buyerId === selectedItem.id).length === 0 ? (
                            <p className="text-xs text-slate-400 italic">Belum ada transaksi staying atau rental terdaftar.</p>
                          ) : (
                            transactions.filter(t => t.buyerId === selectedItem.id).map(t => (
                              <div key={t.id} className="flex justify-between items-center bg-slate-50 p-3 rounded-lg border border-slate-100 text-xs">
                                <div className="space-y-0.5">
                                  <p className="font-semibold text-slate-800">{t.propertyName}</p>
                                  <p className="text-slate-500 font-mono">Tipe: {t.type.toUpperCase()} • {t.startDate} s/d {t.endDate}</p>
                                </div>
                                <span className="font-bold text-blue-600">Rp {t.totalPrice.toLocaleString('id-ID')}</span>
                              </div>
                            ))
                          )}
                        </div>
                      )}

                      {activeProfileTab === 'property' && (
                        <div className="space-y-2">
                          <div className="bg-indigo-50/40 p-3 rounded-lg border border-indigo-100/50 text-xs space-y-1">
                            <p className="text-indigo-950 font-bold">Deskripsi Unit Properti:</p>
                            <p className="text-slate-700 leading-relaxed">{selectedItem.description}</p>
                          </div>
                          {transactions.filter(t => t.propertyId === selectedItem.id).length === 0 ? (
                            <p className="text-xs text-slate-400 italic">Belum ada transaksi historis untuk properti ini.</p>
                          ) : (
                            transactions.filter(t => t.propertyId === selectedItem.id).map(t => (
                              <div key={t.id} className="flex justify-between items-center bg-slate-50 p-3 rounded-lg border border-slate-100 text-xs">
                                <div>
                                  <p className="font-semibold text-slate-800">Transaksi oleh {t.buyerName}</p>
                                  <p className="text-slate-500">Tanggal: {new Date(t.createdAt).toLocaleDateString('id-ID')}</p>
                                </div>
                                <span className="font-bold text-emerald-600">Rp {t.totalPrice.toLocaleString('id-ID')}</span>
                              </div>
                            ))
                          )}
                        </div>
                      )}

                      {activeProfileTab === 'owner' && (
                        <div className="space-y-2">
                          {properties.filter(p => p.ownerId === selectedItem.id).length === 0 ? (
                            <p className="text-xs text-slate-400 italic">Belum mendaftarkan properti.</p>
                          ) : (
                            properties.filter(p => p.ownerId === selectedItem.id).map(p => (
                              <div key={p.id} className="flex justify-between items-center bg-slate-50 p-3 rounded-lg border border-slate-100 text-xs">
                                <div>
                                  <p className="font-semibold text-slate-800">{p.name}</p>
                                  <p className="text-slate-500">{p.address}</p>
                                </div>
                                <span className="font-bold text-purple-600 capitalize">{p.type} • {p.status}</span>
                              </div>
                            ))
                          )}
                        </div>
                      )}

                      {activeProfileTab === 'buyer' && (
                        <div className="space-y-2">
                          {transactions.filter(t => t.buyerId === selectedItem.id && t.type === 'buy').length === 0 ? (
                            <p className="text-xs text-slate-400 italic">Belum ada transaksi pembelian properti selesai.</p>
                          ) : (
                            transactions.filter(t => t.buyerId === selectedItem.id && t.type === 'buy').map(t => (
                              <div key={t.id} className="flex justify-between items-center bg-slate-50 p-3 rounded-lg border border-slate-100 text-xs">
                                <div>
                                  <p className="font-semibold text-slate-800">{t.propertyName}</p>
                                  <p className="text-slate-500">Pembelian pada {new Date(t.createdAt).toLocaleDateString('id-ID')}</p>
                                </div>
                                <span className="font-bold text-rose-600">Rp {t.totalPrice.toLocaleString('id-ID')}</span>
                              </div>
                            ))
                          )}
                        </div>
                      )}
                    </div>

                    {/* AI-Generated Insight Panel */}
                    <div className="bg-slate-50 border border-slate-200 rounded-xl p-5 space-y-3" id="ai-insight-panel">
                      <h4 className="font-sans font-bold text-sm text-slate-800 flex items-center gap-2">
                        <Sparkles className="h-4 w-4 text-indigo-600 animate-pulse" />
                        <span>Hasil Analisis AI SewaBeliPro Agent</span>
                      </h4>

                      {aiLoading ? (
                        <div className="flex flex-col items-center justify-center py-8 text-slate-500" id="ai-insight-loading">
                          <RefreshCw className="h-6 w-6 text-indigo-600 animate-spin mb-2" />
                          <p className="text-xs font-semibold animate-pulse text-indigo-900">Menghubungi SewaBeliPro AI model...</p>
                        </div>
                      ) : aiInsights ? (
                        <div className="text-xs text-slate-700 leading-relaxed space-y-3 border-l-2 border-indigo-500 pl-4 bg-white p-4 rounded-lg border border-slate-100 prose prose-slate max-w-none" id="ai-insight-content">
                          {aiInsights.split('\n').map((line, idx) => {
                            if (line.startsWith('#')) {
                              return <h5 key={idx} className="font-bold text-sm text-slate-950 mt-3 border-b border-slate-50 pb-1">{line.replace(/#/g, '').trim()}</h5>;
                            }
                            if (line.startsWith('**') || line.startsWith('- **')) {
                              return <p key={idx} className="font-semibold text-slate-800 mt-2">{line.replace(/\*\*/g, '').replace(/^- /g, '• ').trim()}</p>;
                            }
                            if (line.trim().startsWith('-') || line.trim().startsWith('*')) {
                              return <li key={idx} className="ml-4 list-disc text-slate-600">{line.replace(/^-\s*/, '').replace(/^\*\s*/, '').trim()}</li>;
                            }
                            return line.trim() ? <p key={idx} className="text-slate-600">{line}</p> : <div key={idx} className="h-2" />;
                          })}
                        </div>
                      ) : (
                        <div className="text-center py-6 text-slate-400 border border-dashed border-slate-200 rounded-lg bg-white" id="ai-insight-prompt-state">
                          <Sparkles className="h-6 w-6 text-slate-300 mx-auto mb-2" />
                          <p className="text-xs">Klik tombol <strong>"Analisis AI Smart Profiling"</strong> di atas untuk mendapatkan profil segmentasi cerdas dan saran strategis instan berbasis Gemini AI.</p>
                        </div>
                      )}
                    </div>
                  </div>
                ) : (
                  <div className="p-16 text-center text-slate-400" id="profiling-no-selection-state">
                    <User className="h-10 w-10 mx-auto text-slate-300 mb-2" />
                    <p className="text-sm font-semibold">Silakan pilih salah satu item dari daftar di samping kiri untuk melihat visualisasi data.</p>
                  </div>
                )}
              </div>
            </div>
          )}

        </div>
      ) : (
        // REALTIME SYSTEM & API LOG MONITOR VIEW
        <div className="bg-slate-950 rounded-2xl border border-slate-800 p-6 shadow-2xl space-y-6 text-slate-300">
          
          {/* Header Area inside logs with live indicators */}
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-slate-800 pb-4">
            <div className="flex items-center gap-2.5">
              <Terminal className="h-6 w-6 text-indigo-400 animate-pulse" />
              <div>
                <h3 className="text-base font-bold text-white flex items-center gap-2">
                  <span>Audit Logs & Real-time API Interceptor</span>
                  <span className="flex items-center gap-1 text-[9px] font-extrabold text-emerald-400 uppercase tracking-widest font-mono bg-emerald-950/50 px-2.5 py-0.5 rounded-full border border-emerald-900/30">
                    <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-ping" />
                    <span>LOGGER LIVE</span>
                  </span>
                </h3>
                <p className="text-xs text-slate-400 mt-0.5">Memantau lalu lintas API HTTP, latensi milidetik, status HTTP, dan aktivitas database secara real-time.</p>
              </div>
            </div>

            {/* Toolbar Buttons */}
            <div className="flex flex-wrap items-center gap-2">
              <button
                onClick={() => setAutoRefresh(!autoRefresh)}
                className={`px-3 py-1.5 rounded-lg text-xs font-bold border transition-all flex items-center gap-1.5 cursor-pointer ${
                  autoRefresh
                    ? 'bg-emerald-950/60 text-emerald-400 border-emerald-800 hover:bg-emerald-900/40'
                    : 'bg-slate-900 text-slate-400 border-slate-800 hover:bg-slate-800'
                }`}
                title="Aktifkan/Matikan polling otomatis (setiap 3 detik)"
              >
                <Activity className={`h-3.5 w-3.5 ${autoRefresh ? 'animate-pulse' : ''}`} />
                <span>{autoRefresh ? "Polling: Aktif (3s)" : "Polling: Mati"}</span>
              </button>

              <button
                onClick={() => fetchLogs()}
                disabled={logsLoading}
                className="px-3 py-1.5 bg-slate-900 hover:bg-slate-800 border border-slate-800 text-slate-200 rounded-lg text-xs font-bold flex items-center gap-1.5 transition cursor-pointer disabled:opacity-50"
                title="Segarkan Log Sekarang"
              >
                <RefreshCw className={`h-3.5 w-3.5 ${logsLoading ? 'animate-spin' : ''}`} />
                <span>Refresh</span>
              </button>

              <button
                onClick={clearLogs}
                disabled={logsLoading}
                className="px-3 py-1.5 bg-red-950/60 hover:bg-red-900/50 border border-red-900/40 text-red-400 rounded-lg text-xs font-bold flex items-center gap-1.5 transition cursor-pointer"
                title="Wipe database logs"
              >
                <Trash2 className="h-3.5 w-3.5" />
                <span>Clear All Logs</span>
              </button>
            </div>
          </div>

          {/* Quick Trigger / API Simulator Panel */}
          <div className="bg-slate-900/70 p-4 rounded-xl border border-slate-800/80 space-y-3">
            <div className="flex items-center gap-2 text-xs font-bold text-slate-300">
              <SlidersHorizontal className="h-3.5 w-3.5 text-indigo-400" />
              <span>SIMULATOR INTERCEPTOR: Ketuk endpoint untuk memicu aktivitas log langsung</span>
            </div>
            
            <div className="flex flex-wrap gap-2">
              <button
                onClick={() => triggerTestAPI('/api/users')}
                className="px-3 py-1.5 bg-slate-950/90 hover:bg-slate-900 border border-slate-800 text-slate-300 rounded-lg font-mono text-[11px] flex items-center gap-1.5 transition cursor-pointer"
              >
                <Play className="h-3 w-3 text-cyan-400" />
                <span className="text-cyan-400">GET</span>
                <span>/api/users</span>
              </button>

              <button
                onClick={() => triggerTestAPI('/api/properties')}
                className="px-3 py-1.5 bg-slate-950/90 hover:bg-slate-900 border border-slate-800 text-slate-300 rounded-lg font-mono text-[11px] flex items-center gap-1.5 transition cursor-pointer"
              >
                <Play className="h-3 w-3 text-emerald-400" />
                <span className="text-emerald-400">GET</span>
                <span>/api/properties</span>
              </button>

              <button
                onClick={() => triggerTestAPI('/api/maintenances')}
                className="px-3 py-1.5 bg-slate-950/90 hover:bg-slate-900 border border-slate-800 text-slate-300 rounded-lg font-mono text-[11px] flex items-center gap-1.5 transition cursor-pointer"
              >
                <Play className="h-3 w-3 text-yellow-400" />
                <span className="text-yellow-400">GET</span>
                <span>/api/maintenances</span>
              </button>

              <button
                onClick={() => triggerTestAPI('/api/logs', 'POST')}
                className="px-3 py-1.5 bg-slate-950/90 hover:bg-slate-900 border border-slate-800 text-slate-300 rounded-lg font-mono text-[11px] flex items-center gap-1.5 transition cursor-pointer"
              >
                <Play className="h-3 w-3 text-purple-400" />
                <span className="text-purple-400">POST</span>
                <span>/api/logs</span>
              </button>
            </div>

            {apiTestStatus && (
              <div className="text-[11px] bg-slate-950 text-indigo-300 p-2 rounded-lg border border-indigo-950/50 font-mono animate-pulse flex items-center gap-1.5">
                <Info className="h-3.5 w-3.5" />
                <span>{apiTestStatus}</span>
              </div>
            )}
          </div>

          {/* Filters and search input */}
          <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 text-xs bg-slate-900/40 p-4 rounded-xl border border-slate-900">
            {/* Type Filters */}
            <div className="flex flex-wrap gap-1.5">
              {(['all', 'api', 'system', 'user', 'app'] as const).map(type => {
                const count = type === 'all' ? logs.length : logs.filter(l => l.type === type).length;
                return (
                  <button
                    key={type}
                    onClick={() => setLogFilter(type)}
                    className={`px-3 py-1.5 rounded-lg font-bold transition-all cursor-pointer border ${
                      logFilter === type
                        ? 'bg-indigo-600 border-indigo-600 text-white shadow-sm'
                        : 'bg-slate-900 text-slate-400 border-slate-800 hover:text-white'
                    }`}
                  >
                    <span className="capitalize">{type === 'all' ? 'Semua Log' : type.toUpperCase()}</span>
                    <span className="ml-1.5 opacity-60 text-[10px]">({count})</span>
                  </button>
                );
              })}
            </div>

            {/* Search Bar */}
            <div className="relative w-full lg:w-72">
              <Search className="absolute left-3 top-2.5 h-4 w-4 text-slate-500" />
              <input
                type="text"
                placeholder="Saring berdasarkan kata kunci..."
                value={logSearch}
                onChange={(e) => setLogSearch(e.target.value)}
                className="w-full bg-slate-900/80 border border-slate-800 rounded-lg pl-9 pr-3 py-2 text-xs text-white focus:outline-none focus:border-indigo-500 transition-all placeholder:text-slate-500"
              />
            </div>
          </div>

          {/* Terminal Box UI */}
          <div className="border border-slate-800 rounded-xl overflow-hidden shadow-2xl bg-slate-950 flex flex-col">
            {/* Terminal Top Bar */}
            <div className="bg-slate-900/70 px-4 py-2.5 border-b border-slate-800/80 flex items-center justify-between text-[11px] text-slate-400 font-mono">
              <div className="flex items-center gap-2">
                <span className="h-3 w-3 rounded-full bg-red-500/80"></span>
                <span className="h-3 w-3 rounded-full bg-yellow-500/80"></span>
                <span className="h-3 w-3 rounded-full bg-green-500/80"></span>
                <span className="ml-2 font-semibold text-slate-300">propertyhub_activity_stream.log</span>
              </div>
              <span className="text-xs bg-indigo-950 px-2 py-0.5 rounded border border-indigo-900/50 text-indigo-300">JSON Interceptor</span>
            </div>

            {/* Logging Area - Scrolling downwards chronologically */}
            <div className="p-4 font-mono text-[11px] space-y-3 max-h-[380px] overflow-y-auto bg-slate-950/95 flex flex-col-reverse divide-y divide-slate-900">
              {filteredLogs.length === 0 ? (
                <div className="text-center py-16 text-slate-600 italic">
                  Belum ada log yang cocok dengan kriteria pencarian Anda.
                </div>
              ) : (
                filteredLogs.map((log) => {
                  let badgeColor = 'text-slate-500';
                  let tagLabel = '[INFO]';
                  
                  if (log.type === 'api') {
                    badgeColor = 'text-cyan-400 font-bold';
                    tagLabel = '[API ROUTE]';
                  } else if (log.type === 'system') {
                    badgeColor = 'text-amber-400 font-bold';
                    tagLabel = '[SYSTEM]';
                  } else if (log.type === 'user') {
                    badgeColor = 'text-emerald-400 font-bold';
                    tagLabel = '[AUTH/USER]';
                  } else if (log.type === 'app') {
                    badgeColor = 'text-purple-400 font-bold';
                    tagLabel = '[APPLICATION]';
                  }

                  return (
                    <div key={log.id} className="pt-3 flex items-start justify-between gap-4 group hover:bg-slate-900/20 px-2 rounded-lg transition-colors">
                      <div className="space-y-1 select-text leading-relaxed w-full">
                        <div className="flex items-center flex-wrap gap-2 text-[10px]">
                          <span className="text-slate-500">{log.timestamp}</span>
                          <span className={`font-mono ${badgeColor}`}>{tagLabel}</span>
                          <span className="text-slate-600">• Initiated by:</span>
                          <span className="text-slate-300 bg-slate-900 px-1.5 py-0.5 rounded border border-slate-800 text-[9px]">{log.user}</span>
                          
                          {(log as any).ip && (
                            <span className="text-cyan-400 bg-cyan-950/40 px-1.5 py-0.5 rounded border border-cyan-900/30 text-[9px] font-mono">
                              🌐 IP: {(log as any).ip}
                            </span>
                          )}
                          
                          {(log as any).device && (
                            <span className="text-indigo-400 bg-indigo-950/40 px-1.5 py-0.5 rounded border border-indigo-900/30 text-[9px]">
                              💻 {(log as any).device}
                            </span>
                          )}
                          
                          {(log as any).location && (
                            <span className="text-emerald-400 bg-emerald-950/40 px-1.5 py-0.5 rounded border border-emerald-900/30 text-[9px]">
                              📍 {(log as any).location}
                            </span>
                          )}
                        </div>
                        
                        <p className="text-slate-200 break-all">{log.message}</p>
                      </div>

                      {/* Action buttons */}
                      <button
                        onClick={() => copyLogText(`${log.timestamp} ${tagLabel} ${log.message} (Initiator: ${log.user})`, log.id)}
                        className="text-slate-500 hover:text-slate-300 opacity-0 group-hover:opacity-100 transition p-1 hover:bg-slate-900 rounded shrink-0 cursor-pointer"
                        title="Salin Log Baris Ini"
                      >
                        {copiedId === log.id ? (
                          <Check className="h-3.5 w-3.5 text-emerald-400" />
                        ) : (
                          <Copy className="h-3.5 w-3.5" />
                        )}
                      </button>
                    </div>
                  );
                })
              )}
            </div>
          </div>
        </div>
      )}

    </div>
  );
}
