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

import React, { useState, useEffect } from 'react';
import { 
  Sparkles, 
  TrendingUp, 
  DollarSign, 
  ShieldAlert, 
  Calendar, 
  Percent, 
  PlusCircle, 
  Building2, 
  FileText, 
  HelpCircle, 
  RefreshCw,
  Scale,
  Settings,
  AlertCircle,
  CheckCircle,
  BarChart3,
  Flame,
  Wrench,
  Clock,
  MapPin,
  Maximize2
} from 'lucide-react';
import { Property, User } from '../types';

interface AiPredictionHubProps {
  currentUser: User | null;
  properties: Property[];
}

type PredictionTab = 'price' | 'demand' | 'buy-vs-rent' | 'maintenance';

export default function AiPredictionHub({ currentUser, properties }: AiPredictionHubProps) {
  const [activeTab, setActiveTab] = useState<PredictionTab>('price');
  const [loading, setLoading] = useState(false);
  const [predictionResult, setPredictionResult] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  // --- Form States ---

  // 1. Price Predictor
  const [priceForm, setPriceForm] = useState({
    location: 'Jakarta Selatan',
    propertyType: 'apartment' as 'house' | 'apartment' | 'villa' | 'kos' | 'hotel',
    size: 70,
    bedrooms: 2,
    bathrooms: 1,
    amenities: ['Pool', 'Security', 'Fully Furnished'] as string[]
  });

  // 2. Demand Forecast
  const [demandForm, setDemandForm] = useState({
    propertyId: '',
    propertyName: ''
  });

  // 3. Buy vs Rent
  const [buyRentForm, setBuyRentForm] = useState({
    buyPrice: 1500000000,
    rentPrice: 6000000,
    interestRate: 6.5,
    years: 10,
    maintenance: 350000
  });

  // 4. Predictive Maintenance
  const [maintForm, setMaintForm] = useState({
    assetName: 'Lift Otis Penumpang Blok A',
    age: 4,
    loadFactor: 'medium' as 'low' | 'medium' | 'high',
    runtimeHours: 3400
  });

  // Pre-populate demand forecast select
  useEffect(() => {
    if (properties.length > 0) {
      setDemandForm({
        propertyId: properties[0].id,
        propertyName: properties[0].name
      });
    }
  }, [properties]);

  const toggleAmenity = (amenity: string) => {
    setPriceForm(prev => {
      const exists = prev.amenities.includes(amenity);
      return {
        ...prev,
        amenities: exists 
          ? prev.amenities.filter(a => a !== amenity)
          : [...prev.amenities, amenity]
      };
    });
  };

  const handlePredict = async (tabType: PredictionTab) => {
    setLoading(true);
    setPredictionResult(null);
    setError(null);

    let inputs: any = {};
    if (tabType === 'price') {
      inputs = priceForm;
    } else if (tabType === 'demand') {
      inputs = demandForm;
    } else if (tabType === 'buy-vs-rent') {
      inputs = buyRentForm;
    } else if (tabType === 'maintenance') {
      inputs = maintForm;
    }

    try {
      const res = await fetch('/api/gemini/predict', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: `${tabType}-prediction`, inputs })
      });

      if (!res.ok) {
        throw new Error('Gagal mendapatkan hasil prediksi dari server.');
      }

      const data = await res.json();
      setPredictionResult(data.insights);
    } catch (err: any) {
      console.error(err);
      setError(err.message || 'Koneksi terganggu. Silakan coba beberapa saat lagi.');
    } finally {
      setLoading(false);
    }
  };

  // Custom visual markdown splitter
  const renderMarkdown = (text: string) => {
    return (
      <div className="space-y-4 text-xs sm:text-sm text-gray-700 leading-relaxed">
        {text.split('\n').map((line, idx) => {
          const trimmed = line.trim();
          if (trimmed.startsWith('###')) {
            return (
              <h4 key={idx} className="text-base font-bold text-gray-900 border-b border-gray-100 pb-2 mt-5 flex items-center gap-2">
                <Sparkles className="h-4 w-4 text-blue-600 animate-pulse" />
                {trimmed.replace(/###/g, '').trim()}
              </h4>
            );
          }
          if (trimmed.startsWith('####')) {
            return (
              <h5 key={idx} className="text-sm font-semibold text-gray-800 mt-4 flex items-center gap-1.5">
                <div className="w-1.5 h-1.5 rounded-full bg-blue-500"></div>
                {trimmed.replace(/####/g, '').trim()}
              </h5>
            );
          }
          if (trimmed.startsWith('>') || trimmed.startsWith('💡')) {
            return (
              <div key={idx} className="p-3 bg-blue-50/50 border-l-4 border-blue-500 rounded-r-xl text-xs text-blue-700 font-medium my-3">
                {trimmed.replace(/^>\s*/, '').replace(/^💡\s*/, '').trim()}
              </div>
            );
          }
          if (trimmed.startsWith('*') || trimmed.startsWith('-')) {
            const cleanText = trimmed.replace(/^[-*]\s*/, '');
            // Highlight bold content inside bullet points
            if (cleanText.includes('**')) {
              const parts = cleanText.split('**');
              return (
                <li key={idx} className="ml-5 list-disc pl-1 text-gray-600 my-1">
                  {parts.map((p, pIdx) => pIdx % 2 === 1 ? <strong key={pIdx} className="text-gray-900 font-semibold">{p}</strong> : p)}
                </li>
              );
            }
            return <li key={idx} className="ml-5 list-disc pl-1 text-gray-600 my-1">{cleanText}</li>;
          }
          if (trimmed.includes('**')) {
            const parts = trimmed.split('**');
            return (
              <p key={idx} className="my-2">
                {parts.map((p, pIdx) => pIdx % 2 === 1 ? <strong key={pIdx} className="text-gray-900 font-semibold">{p}</strong> : p)}
              </p>
            );
          }
          return trimmed ? <p key={idx} className="my-2 text-gray-600">{trimmed}</p> : <div key={idx} className="h-2" />;
        })}
      </div>
    );
  };

  return (
    <div className="space-y-6" id="ai-prediction-hub">
      {/* Welcome Title */}
      <div className="bg-gradient-to-r from-blue-900 to-indigo-950 rounded-2xl p-6 sm:p-8 text-white shadow-md relative overflow-hidden" id="ai-banner">
        <div className="absolute right-0 top-0 translate-x-12 -translate-y-12 w-64 h-64 bg-blue-600 rounded-full opacity-20 blur-3xl pointer-events-none"></div>
        <div className="absolute left-1/3 bottom-0 w-48 h-48 bg-indigo-500 rounded-full opacity-10 blur-2xl pointer-events-none"></div>

        <div className="relative z-10 space-y-3 max-w-3xl">
          <span className="inline-flex items-center gap-1.5 px-3 py-1 text-[10px] font-bold text-blue-200 bg-blue-500/20 border border-blue-400/30 rounded-full uppercase tracking-wider">
            <Sparkles className="h-3.5 w-3.5 animate-pulse" />
            AI & Machine Learning Engine
          </span>
          <h2 className="font-sans font-extrabold text-2xl sm:text-3xl tracking-tight leading-none">
            Pusat Prediksi Cerdas SewaBeliPro
          </h2>
          <p className="text-sm text-blue-100/90 leading-relaxed font-normal">
            Bantu pengambilan keputusan investasi, pemeliharaan preventif, simulasi finansial, dan proyeksi okupansi properti Anda secara instan menggunakan algoritma statistik real-estate terintegrasi dan Gemini 3.5 AI.
          </p>
        </div>
      </div>

      {/* Navigation Tabs */}
      <div className="flex overflow-x-auto pb-1 gap-2 border-b border-gray-100 scrollbar-none" id="prediction-tabs">
        <button
          onClick={() => { setActiveTab('price'); setPredictionResult(null); setError(null); }}
          className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-semibold whitespace-nowrap transition-all cursor-pointer border ${
            activeTab === 'price'
              ? 'bg-blue-600 border-blue-600 text-white shadow-xs'
              : 'bg-white border-gray-200 text-gray-600 hover:text-gray-900 hover:border-gray-300'
          }`}
        >
          <Building2 className="h-4 w-4" />
          <span>Prediksi Nilai Properti</span>
        </button>

        <button
          onClick={() => { setActiveTab('demand'); setPredictionResult(null); setError(null); }}
          className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-semibold whitespace-nowrap transition-all cursor-pointer border ${
            activeTab === 'demand'
              ? 'bg-blue-600 border-blue-600 text-white shadow-xs'
              : 'bg-white border-gray-200 text-gray-600 hover:text-gray-900 hover:border-gray-300'
          }`}
        >
          <TrendingUp className="h-4 w-4" />
          <span>Prakiraan Okupansi</span>
        </button>

        <button
          onClick={() => { setActiveTab('buy-vs-rent'); setPredictionResult(null); setError(null); }}
          className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-semibold whitespace-nowrap transition-all cursor-pointer border ${
            activeTab === 'buy-vs-rent'
              ? 'bg-blue-600 border-blue-600 text-white shadow-xs'
              : 'bg-white border-gray-200 text-gray-600 hover:text-gray-900 hover:border-gray-300'
          }`}
        >
          <Scale className="h-4 w-4" />
          <span>Beli vs Sewa Decision</span>
        </button>

        <button
          onClick={() => { setActiveTab('maintenance'); setPredictionResult(null); setError(null); }}
          className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-semibold whitespace-nowrap transition-all cursor-pointer border ${
            activeTab === 'maintenance'
              ? 'bg-blue-600 border-blue-600 text-white shadow-xs'
              : 'bg-white border-gray-200 text-gray-600 hover:text-gray-900 hover:border-gray-300'
          }`}
        >
          <Wrench className="h-4 w-4" />
          <span>Pemeliharaan Prediktif</span>
        </button>
      </div>

      {/* Main Grid Content */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6" id="prediction-main-grid">
        {/* Left Form Column (4/12) */}
        <div className="lg:col-span-4 bg-white border border-gray-100 p-5 rounded-2xl shadow-xs space-y-5" id="prediction-form-panel">
          <div className="flex items-center gap-2 border-b border-gray-100 pb-3">
            <Settings className="h-4 w-4 text-blue-600" />
            <h3 className="font-bold text-gray-800 text-sm">Konfigurasi Input ML</h3>
          </div>

          {/* Render Active Tab Form */}
          {activeTab === 'price' && (
            <div className="space-y-4" id="form-price">
              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase">Lokasi / Wilayah</label>
                <input
                  type="text"
                  value={priceForm.location}
                  onChange={(e) => setPriceForm(prev => ({ ...prev, location: e.target.value }))}
                  placeholder="Contoh: Ubud, Bali / Kemang, Jakarta"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 bg-gray-50/25"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase">Tipe Properti</label>
                <select
                  value={priceForm.propertyType}
                  onChange={(e) => setPriceForm(prev => ({ ...prev, propertyType: e.target.value as any }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 bg-white"
                >
                  <option value="apartment">Apartemen</option>
                  <option value="house">Rumah Tapak (House)</option>
                  <option value="villa">Villa Resor</option>
                  <option value="kos">Kos-Kosan</option>
                  <option value="hotel">Kamar Hotel / Guest House</option>
                </select>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1.5">
                  <label className="text-[11px] font-extrabold text-gray-400 uppercase">Luas Bangunan (m²)</label>
                  <input
                    type="number"
                    value={priceForm.size}
                    onChange={(e) => setPriceForm(prev => ({ ...prev, size: Number(e.target.value) }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-[11px] font-extrabold text-gray-400 uppercase">Kamar Tidur</label>
                  <input
                    type="number"
                    value={priceForm.bedrooms}
                    onChange={(e) => setPriceForm(prev => ({ ...prev, bedrooms: Number(e.target.value) }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase">Kamar Mandi</label>
                <input
                  type="number"
                  value={priceForm.bathrooms}
                  onChange={(e) => setPriceForm(prev => ({ ...prev, bathrooms: Number(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                />
              </div>

              <div className="space-y-2 pt-2">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Fasilitas Utama</label>
                <div className="grid grid-cols-2 gap-2 text-[11px]">
                  {['Kolam Renang', 'Gym', 'Parkir Basement', 'Keamanan 24 Jam', 'Smart Lock', 'Fully Furnished'].map((item) => {
                    const isChecked = priceForm.amenities.includes(item);
                    return (
                      <label key={item} className="flex items-center gap-2 cursor-pointer p-1.5 border border-gray-50 rounded-lg hover:bg-gray-50">
                        <input
                          type="checkbox"
                          checked={isChecked}
                          onChange={() => toggleAmenity(item)}
                          className="rounded-sm border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                        <span className="text-gray-700">{item}</span>
                      </label>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'demand' && (
            <div className="space-y-4" id="form-demand">
              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase">Pilih Unit Properti</label>
                {properties.length === 0 ? (
                  <p className="text-xs text-red-500">Belum ada properti terdaftar. Buat properti terlebih dahulu.</p>
                ) : (
                  <select
                    value={demandForm.propertyId}
                    onChange={(e) => {
                      const prop = properties.find(p => p.id === e.target.value);
                      if (prop) {
                        setDemandForm({
                          propertyId: prop.id,
                          propertyName: prop.name
                        });
                      }
                    }}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 bg-white"
                  >
                    {properties.map(p => (
                      <option key={p.id} value={p.id}>{p.name} ({p.type})</option>
                    ))}
                  </select>
                )}
              </div>

              <div className="p-3 bg-indigo-50 border border-indigo-100 rounded-xl text-[11px] text-indigo-800 space-y-1">
                <p className="font-bold">💡 Apa itu Prakiraan Okupansi?</p>
                <p className="leading-relaxed text-indigo-700">Fitur ini menggunakan log historis transaksi transaksi SewaBeliPro, lokasi geografis, dan model musiman AI untuk menghitung potensi okupansi serta pendapatan kotor Anda selama setengah tahun ke depan.</p>
              </div>
            </div>
          )}

          {activeTab === 'buy-vs-rent' && (
            <div className="space-y-4" id="form-buy-rent">
              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Harga Pembelian Properti (Rp)</label>
                <input
                  type="number"
                  value={buyRentForm.buyPrice}
                  onChange={(e) => setBuyRentForm(prev => ({ ...prev, buyPrice: Number(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs font-semibold focus:outline-hidden focus:border-blue-500"
                />
                <span className="text-[10px] text-gray-400 font-medium">Contoh: 1.5 Milyar</span>
              </div>

              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Biaya Sewa Bulanan (Rp)</label>
                <input
                  type="number"
                  value={buyRentForm.rentPrice}
                  onChange={(e) => setBuyRentForm(prev => ({ ...prev, rentPrice: Number(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs font-semibold focus:outline-hidden focus:border-blue-500"
                />
                <span className="text-[10px] text-gray-400 font-medium">Contoh: 6 Juta / Bulan</span>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1.5">
                  <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Suku Bunga KPR (%)</label>
                  <input
                    type="number"
                    step="0.1"
                    value={buyRentForm.interestRate}
                    onChange={(e) => setBuyRentForm(prev => ({ ...prev, interestRate: Number(e.target.value) }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Durasi Tinggal (Tahun)</label>
                  <input
                    type="number"
                    value={buyRentForm.years}
                    onChange={(e) => setBuyRentForm(prev => ({ ...prev, years: Number(e.target.value) }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Biaya Pemeliharaan / IPL Bulanan (Rp)</label>
                <input
                  type="number"
                  value={buyRentForm.maintenance}
                  onChange={(e) => setBuyRentForm(prev => ({ ...prev, maintenance: Number(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                />
              </div>
            </div>
          )}

          {activeTab === 'maintenance' && (
            <div className="space-y-4" id="form-maintenance">
              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Pilih Nama Komponen / Fasilitas</label>
                <select
                  value={maintForm.assetName}
                  onChange={(e) => setMaintForm(prev => ({ ...prev, assetName: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500 bg-white"
                >
                  <option value="Lift Otis Penumpang Blok A">Lift Otis Penumpang Blok A</option>
                  <option value="Genset Kohler Standby 250kVA">Genset Kohler Standby 250kVA</option>
                  <option value="Pompa Booster Distribusi Utama Grundfos">Pompa Booster Distribusi Utama Grundfos</option>
                  <option value="Sistem Chiller AC Sentral Daikin">Sistem Chiller AC Sentral Daikin</option>
                  <option value="Instalasi Panel Listrik TM (Tegangan Menengah)">Instalasi Panel Listrik TM</option>
                </select>
              </div>

              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Usia Operasional (Tahun)</label>
                <input
                  type="number"
                  value={maintForm.age}
                  onChange={(e) => setMaintForm(prev => ({ ...prev, age: Number(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Jam Operasional Aktif (Jam)</label>
                <input
                  type="number"
                  value={maintForm.runtimeHours}
                  onChange={(e) => setMaintForm(prev => ({ ...prev, runtimeHours: Number(e.target.value) }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs focus:outline-hidden focus:border-blue-500"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[11px] font-extrabold text-gray-400 uppercase block">Tingkat Beban Kerja (Load Factor)</label>
                <div className="grid grid-cols-3 gap-2">
                  {(['low', 'medium', 'high'] as const).map(l => (
                    <button
                      key={l}
                      type="button"
                      onClick={() => setMaintForm(prev => ({ ...prev, loadFactor: l }))}
                      className={`py-1.5 rounded-lg border text-xs font-semibold uppercase cursor-pointer transition-all ${
                        maintForm.loadFactor === l
                          ? 'bg-blue-600 border-blue-600 text-white'
                          : 'bg-white border-gray-200 text-gray-600 hover:bg-gray-50'
                      }`}
                    >
                      {l}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Predict CTA button */}
          <button
            onClick={() => handlePredict(activeTab)}
            disabled={loading || (activeTab === 'demand' && properties.length === 0)}
            className="w-full flex items-center justify-center gap-2 px-4 py-3 text-xs font-bold text-white bg-blue-600 hover:bg-blue-700 rounded-xl shadow-xs transition-colors cursor-pointer disabled:bg-blue-300"
            id="btn-run-prediction"
          >
            {loading ? (
              <>
                <RefreshCw className="h-4 w-4 animate-spin" />
                <span>Memproses Hasil Analisis...</span>
              </>
            ) : (
              <>
                <Sparkles className="h-4 w-4" />
                <span>Jalankan Prediksi AI & ML</span>
              </>
            )}
          </button>
        </div>

        {/* Right Output Insights Column (8/12) */}
        <div className="lg:col-span-8 bg-white border border-gray-100 rounded-2xl shadow-xs overflow-hidden flex flex-col" id="prediction-output-panel">
          <div className="border-b border-gray-100 p-5 bg-gray-50/50 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div className="bg-blue-50 p-1.5 rounded-lg text-blue-600">
                <Sparkles className="h-4 w-4" />
              </div>
              <div>
                <h4 className="font-bold text-gray-900 text-sm">Output Laporan Analitik Cerdas AI</h4>
                <p className="text-[10px] text-gray-400">Diproses secara langsung menggunakan model inferensi kognitif Gemini</p>
              </div>
            </div>

            <span className="text-[10px] bg-emerald-50 text-emerald-700 font-extrabold px-2.5 py-1 rounded-full border border-emerald-200/50 flex items-center gap-1">
              <CheckCircle className="h-3 w-3" />
              Sistem Aktif
            </span>
          </div>

          <div className="p-6 flex-1 flex flex-col justify-center min-h-[300px]">
            {loading ? (
              <div className="text-center space-y-3 py-12 flex flex-col items-center" id="output-loading-state">
                <div className="p-4 bg-blue-50 rounded-full animate-bounce">
                  <Sparkles className="h-8 w-8 text-blue-600 animate-pulse" />
                </div>
                <h5 className="font-bold text-gray-800 text-sm animate-pulse">Menghubungi SewaBeliPro AI Brain...</h5>
                <p className="text-xs text-gray-400 max-w-sm mx-auto leading-relaxed">
                  Algoritma sedang menganalisis variabel input, menghitung deviasi devisa, memetakan kecenderungan tren, dan merangkum rekomendasi taktis.
                </p>
              </div>
            ) : error ? (
              <div className="text-center space-y-2 py-12 flex flex-col items-center text-red-500" id="output-error-state">
                <AlertCircle className="h-10 w-10 text-red-500" />
                <h5 className="font-bold text-sm">Gagal Mengambil Prediksi</h5>
                <p className="text-xs text-gray-400 max-w-sm mx-auto">{error}</p>
              </div>
            ) : predictionResult ? (
              <div className="bg-slate-50/50 border border-gray-100 rounded-2xl p-5 sm:p-6 text-left animate-in fade-in slide-in-from-bottom-2 duration-200" id="output-success-state">
                {renderMarkdown(predictionResult)}
              </div>
            ) : (
              <div className="text-center py-16 space-y-4 max-w-md mx-auto" id="output-empty-state">
                <div className="mx-auto w-12 h-12 bg-blue-50 rounded-full flex items-center justify-center text-blue-600">
                  <BarChart3 className="h-6 w-6" />
                </div>
                <div className="space-y-1">
                  <h5 className="font-bold text-gray-800 text-sm">Belum Ada Analisis yang Dijalankan</h5>
                  <p className="text-xs text-gray-400 leading-relaxed">
                    Tentukan parameter input di panel kiri, kemudian klik tombol **"Jalankan Prediksi AI & ML"** untuk mengaktifkan mesin kognitif.
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
