import React, { useState, useEffect, FormEvent, useMemo } from 'react';
import ReactDOM from 'react-dom/client';

// =================================================================
// PENTING: Ganti dengan URL Web App dari Google Apps Script Anda
// =================================================================
const SCRIPT_URL = "https://script.google.com/macros/s/AKfycbwMeQnZXwHszl0qdb2z_9egd69eVipRXCk97CAUt9c75j40Kzr2MMLNp3OV5bdRYLA/exec";
// =================================================================

// Tipe data
interface User {
  name: string;
  email: string;
  role: 'user' | 'admin';
}

interface SewaData {
  ID: string;
  Status_Pembayaran?: string;
  Jenis_Kegiatan?: string;
  Tempat?: string;
  Nama_Pengguna?: string;
  Tanggal_Pelaksanaan?: string;
  Tanggal_Berakhir?: string;
  Total_Tagihan?: number;
  Surat_Permohonan_Link?: string;
  Bukti_Bayar_Link?: string;
  Biaya_Tenda?: number;
  Biaya_Listrik?: number;
  [key: string]: any;
}

// Komponen Ikon
const Icon = ({ name, className = '' }: { name: string; className?: string }) => (
  <span className={`material-icons-outlined ${className}`}>{name}</span>
);

// Helper untuk VAPID key
function urlBase64ToUint8Array(base64String: string) {
    const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);
    for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}

// Helper untuk konversi file ke Base64
const fileToBase64 = (file: File): Promise<string> => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
        const result = reader.result as string;
        resolve(result.split(',')[1]); // Hapus prefix data URL
    };
    reader.onerror = error => reject(error);
});


// Komponen utama aplikasi
const App: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const [sewaData, setSewaData] = useState<SewaData[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [view, setView] = useState<'login' | 'register'>('login');
  const [activeScreen, setActiveScreen] = useState<'Dashboard' | 'Sewa Lahan' | 'Biaya'>('Dashboard');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<SewaData | null>(null); // State for editing
  const [isMenuModalOpen, setIsMenuModalOpen] = useState(false);
  const [toastMessage, setToastMessage] = useState<string | null>(null);

  // Coba ambil data user dari local storage
  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    } else {
      setIsLoading(false);
    }
  }, []);

  // Fetch data sewa ketika user sudah login
  useEffect(() => {
    if (user) {
      fetchData();
    }
  }, [user]);

  // Toast notification effect
  useEffect(() => {
    if (toastMessage) {
      const timer = setTimeout(() => setToastMessage(null), 3000);
      return () => clearTimeout(timer);
    }
  }, [toastMessage]);

  const handleError = (err: any) => {
    const errorMessage = err.message || 'Terjadi kesalahan.';
    setError(errorMessage);
    setIsLoading(false);
    setToastMessage(`Error: ${errorMessage}`);
  };
    
  const getFromAction = async (action: string, params: Record<string, string> = {}) => {
      if (!SCRIPT_URL.includes('macros/s')) {
          setError("URL Google Apps Script belum diisi. Edit SCRIPT_URL di index.tsx.");
          return null;
      }
      const url = new URL(SCRIPT_URL);
      url.searchParams.append('action', action);
      for (const key in params) {
          url.searchParams.append(key, params[key]);
      }
      const response = await fetch(url.toString());
      const result = await response.json();
      if (result.success) {
          return result;
      } else {
          throw new Error(result.error || 'Gagal mengambil data.');
      }
  };

  const fetchData = async () => {
    if (!user) return;
    setIsLoading(true);
    setError(null);
    try {
      const result = await getFromAction('getData', { email: user.email, role: user.role });
      if (result) setSewaData(result.data as SewaData[]);
    } catch (err) {
      handleError(err);
    } finally {
      setIsLoading(false);
    }
  };

  const postToAction = async (action: string, payload: object) => {
    if (!SCRIPT_URL.includes('macros/s')) {
        setError("URL Google Apps Script belum diisi. Edit SCRIPT_URL di index.tsx.");
        return null;
    }
    
    try {
        const response = await fetch(SCRIPT_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'text/plain;charset=utf-8' },
            body: JSON.stringify({ action, payload }),
        });

        const resultText = await response.text();
        
        // Coba parse JSON, jika gagal (misal error HTML dari Google), throw error dengan teks aslinya
        let result;
        try {
            result = JSON.parse(resultText);
        } catch (e) {
            // Jika HTML error page dari Google, biasanya panjang. Ambil snippetnya.
            const cleanError = resultText.replace(/<[^>]*>?/gm, '').substring(0, 200);
            throw new Error(`Server Error: ${cleanError}...`);
        }

        if (!result.success) throw new Error(`Gagal: ${result.error || 'Tidak diketahui'}`);
        return result;
        
    } catch (err: any) {
        throw new Error(err.message || "Gagal menghubungi server.");
    }
  }

  const handleLogin = async (email: string) => {
    if (!email) { setError("Email tidak boleh kosong."); return; }
    setIsLoading(true); setError(null);
    try {
      const result = await postToAction('login', { email });
      if (result && result.success) {
        setUser(result.user);
        localStorage.setItem('user', JSON.stringify(result.user));
      }
    } catch (err) { handleError(err); } finally { setIsLoading(false); }
  };
    
  const handleRegister = async (name: string, email: string) => {
    if (!name || !email) { setError("Nama dan Email tidak boleh kosong."); return; }
    setIsLoading(true); setError(null);
    try {
        const result = await postToAction('register', { name, email });
        if (result && result.success) {
            setUser(result.user);
            localStorage.setItem('user', JSON.stringify(result.user));
        }
    } catch (err) { handleError(err); } finally { setIsLoading(false); }
  };

  const handleFormSubmit = async (e: FormEvent<HTMLFormElement>, action: 'create' | 'update') => {
      e.preventDefault();
      if (!user && action === 'create') return;
      if (!editingItem && action === 'update') return;

      const form = e.currentTarget;
      const formData = new FormData(form);
      const data: { [key: string]: any } = Object.fromEntries(formData.entries());

      if (action === 'create') data.Email_Penyewa = user!.email;
      if (action === 'update') data.ID = editingItem!.ID;
      
      // === SAFEGUARD DATA TYPES ===
      // Bersihkan input angka dari karakter non-digit (misal titik ribuan)
      const cleanInt = (val: any) => {
          if (!val) return 0;
          // Hapus semua karakter kecuali angka dan minus
          const str = String(val).replace(/[^0-9\-]/g, ''); 
          const parsed = parseInt(str, 10);
          return isNaN(parsed) ? 0 : parsed;
      };
      
      const parseSafeFloat = (val: any) => {
          if (!val) return 0;
          const str = String(val).replace(',', '.'); // Handle koma desimal
          const parsed = parseFloat(str);
          return isNaN(parsed) ? 0 : parsed;
      };

      // Pastikan Biaya Tenda dan Listrik dikirim sebagai integer murni tanpa format
      // Jika checkbox tidak dicentang, input field tidak ada di formData, jadi undefined -> 0
      data.Biaya_Tenda = cleanInt(data.Biaya_Tenda);
      data.Biaya_Listrik = cleanInt(data.Biaya_Listrik);
      
      if (data.Panjang) data.Panjang = parseSafeFloat(data.Panjang);
      if (data.Lebar) data.Lebar = parseSafeFloat(data.Lebar);

      setIsLoading(true);
      setError(null);
      
      try {
        // Handle file uploads
        const suratInput = form.elements.namedItem('Surat_Permohonan') as HTMLInputElement | null;
        if (suratInput && suratInput.files && suratInput.files[0]) {
            const file = suratInput.files[0];
            data.Surat_Permohonan_PDF = await fileToBase64(file);
            data.Surat_Permohonan_Name = file.name;
        }

        const buktiInput = form.elements.namedItem('Bukti_Bayar') as HTMLInputElement | null;
        if (buktiInput && buktiInput.files && buktiInput.files[0]) {
            const file = buktiInput.files[0];
            data.Bukti_Bayar_PDF = await fileToBase64(file);
            data.Bukti_Bayar_Name = file.name;
        }

        const result = await postToAction(action, data);

        if (result && result.success) {
            setToastMessage(action === 'create' ? 'Pengajuan sewa berhasil dibuat!' : 'Data sewa berhasil diperbarui!');
            
            if (action === 'create' && result.data) {
              setSewaData(prevData => [result.data, ...prevData]);
            } else if (action === 'update' && result.data) {
              setSewaData(prevData => prevData.map(item => item.ID === result.data.ID ? result.data : item));
            } else {
              fetchData(); 
            }

            form.reset();
            setIsModalOpen(false);
            setEditingItem(null);
        }
      } catch (err) {
          handleError(err);
      } finally {
          setIsLoading(false);
      }
  };

  const handleCreateSewa = (e: FormEvent<HTMLFormElement>) => handleFormSubmit(e, 'create');
  const handleUpdateSewa = (e: FormEvent<HTMLFormElement>) => handleFormSubmit(e, 'update');


  const handleLogout = () => {
    setUser(null);
    setSewaData([]);
    localStorage.removeItem('user');
  };
  
  // =================================================================
  // KOMPONEN UI BARU
  // =================================================================

  const InputField = ({ id, label, type, name, required = false, placeholder = '', ...props }: any) => (
    <div>
      <label htmlFor={id} className="block text-sm font-semibold text-gray-800 mb-1">{label}</label>
      <div className="relative">
        {type === 'date' && <Icon name="calendar_today" className="absolute left-3 top-1/2 -translate-y-1/2 text-red-600 text-lg" />}
        <input
            id={id}
            type={type}
            name={name}
            required={required}
            placeholder={placeholder}
            className={`w-full px-4 py-3 bg-red-50 border border-red-200 text-gray-900 rounded-lg shadow-sm 
                        focus:ring-2 focus:ring-red-400 focus:border-red-400 transition duration-150 ease-in-out 
                        placeholder-red-500
                        ${type === 'date' ? 'pl-10' : ''}`}
            {...props}
        />
      </div>
    </div>
  );
  
  const FileInputField = ({ id, label, name, accept, disabled = false, required = false, currentFileUrl }: {
      id: string; label: string; name: string; accept: string; disabled?: boolean; required?: boolean; currentFileUrl?: string | null;
  }) => {
      const [fileName, setFileName] = useState('');
      const [isReplacing, setIsReplacing] = useState(false);
      
      const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
          setFileName(e.target.files?.[0]?.name || '');
      };

      const showInput = !currentFileUrl || isReplacing;

      return (
        <div>
          <div className="flex justify-between items-center mb-1">
            <label htmlFor={id} className={`block text-sm font-semibold ${disabled ? 'text-gray-500' : 'text-gray-800'}`}>{label}</label>
            {currentFileUrl && !disabled && !isReplacing && (
               <button 
                 type="button" 
                 onClick={() => setIsReplacing(true)} 
                 className="text-xs text-red-600 font-medium hover:underline"
               >
                 Ganti File
               </button>
            )}
            {currentFileUrl && isReplacing && (
                <button 
                 type="button" 
                 onClick={() => { setIsReplacing(false); setFileName(''); }} 
                 className="text-xs text-gray-500 font-medium hover:underline"
               >
                 Batal Ganti
               </button>
            )}
          </div>
          
          {!showInput ? (
             <div className="flex items-center gap-2 text-sm bg-green-50 p-3 rounded-lg border border-green-200">
                <Icon name="check_circle" className="text-green-600" />
                <div className="flex-1 overflow-hidden">
                    <a href={currentFileUrl!} target="_blank" rel="noopener noreferrer" className="font-medium text-green-700 hover:underline truncate block">
                      Lihat Dokumen Terlampir
                    </a>
                </div>
             </div>
          ) : (
            <div className="relative group">
              <input
                id={id}
                type="file"
                name={name}
                accept={accept}
                disabled={disabled}
                required={!disabled && required && !currentFileUrl}
                onChange={handleFileChange}
                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
              />
              <div className={`w-full px-4 py-3 rounded-lg shadow-sm transition duration-150 ease-in-out flex items-center justify-between
                           ${disabled ? 'bg-gray-200 text-gray-500 cursor-not-allowed' : 'bg-red-50 border border-red-200 text-gray-900 group-hover:bg-red-100'}`}>
                <span className={`truncate pr-2 ${fileName ? 'text-gray-900' : 'text-red-500'}`}>
                  {fileName || 'Pilih file...'}
                </span>
                <Icon name="attach_file" className={disabled ? 'text-gray-400' : 'text-red-600'} />
              </div>
            </div>
          )}
        </div>
      )
  };

  const AuthView = () => (
    <div className="min-h-screen bg-gray-100 flex flex-col justify-center items-center p-4">
      <div className="w-full max-w-md bg-white rounded-2xl shadow-xl p-8 space-y-6">
        <div className="text-center">
            <h2 className="text-3xl font-bold text-gray-900">{view === 'login' ? 'Masuk ke Akun' : 'Buat Akun Baru'}</h2>
        </div>
        <form className="space-y-6" onSubmit={(e) => {
            e.preventDefault();
            const email = (e.currentTarget.elements.namedItem('email') as HTMLInputElement).value;
            if (view === 'login') {
                handleLogin(email);
            } else {
                const name = (e.currentTarget.elements.namedItem('name') as HTMLInputElement).value;
                handleRegister(name, email);
            }
        }}>
            {view === 'register' && (
                <InputField id="name-input" label="Nama Lengkap" type="text" name="name" required placeholder="John Doe" />
            )}
            <InputField id="email-input" label="Alamat Email" type="email" name="email" required placeholder="email@example.com" />
            <button type="submit" disabled={isLoading} className="w-full py-3 px-4 bg-red-600 hover:bg-red-700 text-white font-bold rounded-lg shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50 transition-all duration-200">
                {isLoading ? 'Memproses...' : (view === 'login' ? 'Login' : 'Register')}
            </button>
        </form>
        <p className="text-center text-sm">
            <button onClick={() => { setView(view === 'login' ? 'register' : 'login'); setError(null); }} className="font-medium text-red-600 hover:text-red-500">
            {view === 'login' ? 'Belum punya akun? Daftar' : 'Sudah punya akun? Login'}
            </button>
        </p>
        {error && <p className="text-center text-sm font-medium text-red-600 bg-red-100 p-3 rounded-lg">{error}</p>}
      </div>
    </div>
  );
    
  const NotificationBell = () => {
    const [permission, setPermission] = useState('default');
    const [isSubscribing, setIsSubscribing] = useState(false);

    useEffect(() => {
        if ('Notification' in window) {
            setPermission(Notification.permission);
        }
    }, []);

    const subscribeUser = async () => {
        if (!user || !('serviceWorker' in navigator) || !('PushManager' in window)) return;
        
        setIsSubscribing(true);
        try {
            const permissionResult = await Notification.requestPermission();
            setPermission(permissionResult);
            if (permissionResult !== 'granted') {
                setToastMessage('Izin notifikasi tidak diberikan.');
                return;
            }

            const { publicKey } = await getFromAction('getVapidPublicKey');
            if (!publicKey) throw new Error('VAPID public key tidak ditemukan.');

            const swRegistration = await navigator.serviceWorker.ready;
            const subscription = await swRegistration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlBase64ToUint8Array(publicKey),
            });
            
            await postToAction('saveSubscription', { email: user.email, subscription });
            setToastMessage('Berhasil mengaktifkan notifikasi!');

        } catch (err: any) {
            console.error('Gagal berlangganan notifikasi:', err);
            setToastMessage(`Error: ${err.message}`);
            setPermission('default');
        } finally {
            setIsSubscribing(false);
        }
    };

    const getIconName = () => {
        if (permission === 'granted') return 'notifications_active';
        if (permission === 'denied') return 'notifications_off';
        return 'notifications';
    };

    const isDisabled = permission === 'denied' || isSubscribing;

    return (
        <button 
            onClick={subscribeUser} 
            disabled={isDisabled}
            className="p-2 disabled:opacity-50 disabled:cursor-not-allowed"
            aria-label="Toggle notifications"
        >
            {isSubscribing ? 
                <div className="w-5 h-5 border-2 border-gray-400 border-t-gray-700 rounded-full animate-spin"></div> : 
                <Icon name={getIconName()} />
            }
        </button>
    );
  };

  const MenuModal = ({ onClose }: { onClose: () => void }) => (
    <div className="fixed inset-0 bg-black bg-opacity-50 z-40 flex items-center justify-center p-4" onClick={onClose}>
      <div className="w-full max-w-xs bg-white rounded-2xl shadow-2xl p-6 animate-slide-up" onClick={e => e.stopPropagation()}>
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-lg font-bold text-gray-800">Informasi Kontak</h2>
          <button onClick={onClose} className="p-2 rounded-full hover:bg-gray-100 -mr-2"><Icon name="close" /></button>
        </div>
        <p className="text-gray-700">
          Kontak : <span className="font-semibold text-gray-900">082129164090 (Dian)</span>
        </p>
      </div>
    </div>
  );

  const MainAppView = () => {
    const closeModal = () => {
        setIsModalOpen(false);
        setEditingItem(null);
    };

    return (
      <div className="flex flex-col h-screen bg-gray-100 font-sans">
        <Header title={activeScreen} onMenuClick={() => setIsMenuModalOpen(true)} />
        <main className="flex-1 overflow-y-auto pb-20">
          <div className="p-4 sm:p-6">
            {activeScreen === 'Dashboard' && <DashboardScreen />}
            {activeScreen === 'Sewa Lahan' && <SewaLahanScreen />}
            {activeScreen === 'Biaya' && <BiayaScreen />}
          </div>
        </main>
        <BottomNavBar />
        {isModalOpen && <SewaFormModal 
            onSubmit={editingItem ? handleUpdateSewa : handleCreateSewa}
            onClose={closeModal}
            itemToEdit={editingItem}
        />}
        {isMenuModalOpen && <MenuModal onClose={() => setIsMenuModalOpen(false)} />}
      </div>
    );
  }

  const Header = ({ title, onMenuClick }: { title: string; onMenuClick: () => void }) => (
    <header className="bg-white/80 backdrop-blur-lg sticky top-0 z-30 flex items-center justify-between px-4 py-3 border-b border-gray-200">
      <button onClick={onMenuClick} className="p-2 -ml-2">
        <Icon name="menu" />
      </button>
      <h1 className="text-lg font-bold text-gray-800">{title}</h1>
      <div className="flex items-center gap-1 -mr-2">
        <NotificationBell />
        <button onClick={handleLogout} className="p-2">
          <Icon name="logout" />
        </button>
      </div>
    </header>
  );

  const BottomNavBar = () => {
    const navItems = [
      { name: 'Dashboard', icon: 'dashboard' },
      { name: 'Sewa Lahan', icon: 'article' },
      { name: 'Biaya', icon: 'auto_awesome' },
    ];
    return (
      <nav className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 flex justify-around z-30 h-16">
        {navItems.map(item => (
          <button
            key={item.name}
            onClick={() => setActiveScreen(item.name as any)}
            className={`flex flex-col items-center justify-center w-full text-xs transition-colors duration-200 ${activeScreen === item.name ? 'text-red-600' : 'text-gray-500 hover:text-red-500'}`}
          >
            <Icon name={item.icon} className="mb-1 text-2xl" />
            <span>{item.name}</span>
          </button>
        ))}
      </nav>
    );
  };
  
  const Calendar = ({ events }: { events: SewaData[] }) => {
    const [currentDate, setCurrentDate] = useState(new Date());
    const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  
    const daysInMonth = useMemo(() => {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const firstDayOfMonth = new Date(year, month, 1);
        const lastDateOfMonth = new Date(year, month + 1, 0);
        
        const firstDayOfWeek = firstDayOfMonth.getDay(); // 0 for Sunday, 1 for Monday, etc.
        const lastDate = lastDateOfMonth.getDate();
        
        const dates: (Date | null)[] = Array.from({ length: firstDayOfWeek }, () => null); // padding
        for (let i = 1; i <= lastDate; i++) dates.push(new Date(year, month, i));
        return dates;
    }, [currentDate]);

    const changeMonth = (offset: number) => {
        setCurrentDate(prev => new Date(prev.getFullYear(), prev.getMonth() + offset, 1));
    };
    
    const getEventsOnDate = (date: Date) => {
      if (!date) return [];
      return events.filter(event => {
          if (!event.Tanggal_Pelaksanaan || !event.Tanggal_Berakhir) return false;
          const startDate = new Date(event.Tanggal_Pelaksanaan);
          startDate.setHours(0,0,0,0);
          const endDate = new Date(event.Tanggal_Berakhir);
          endDate.setHours(0,0,0,0);
          return date >= startDate && date <= endDate;
      }).sort((a,b) => (a.Jenis_Kegiatan || '').localeCompare(b.Jenis_Kegiatan || ''));
    }

    const handleDateClick = (date: Date | null) => {
        if (!date) return;
        const eventsOnDate = getEventsOnDate(date);
        if (eventsOnDate.length > 0) {
            setSelectedDate(date);
        }
    };

    const EventModal = ({ date, events: modalEvents, onClose }: { date: Date, events: SewaData[], onClose: () => void }) => (
      <div className="fixed inset-0 bg-black bg-opacity-50 z-40 flex items-center justify-center p-4" onClick={onClose}>
        <div className="w-full max-w-sm bg-white rounded-2xl shadow-2xl p-6 animate-slide-up" onClick={e => e.stopPropagation()}>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-bold text-gray-800">
              Kegiatan: {date.toLocaleDateString('id-ID', { day: 'numeric', month: 'long' })}
            </h2>
            <button onClick={onClose} className="p-2 rounded-full hover:bg-gray-100 -mr-2"><Icon name="close" /></button>
          </div>
          <div className="space-y-3 max-h-60 overflow-y-auto">
            {modalEvents.length > 0 ? (
              modalEvents.map(event => (
                <div key={event.ID} className="bg-red-50 p-3 rounded-lg border border-red-100">
                  <p className="font-semibold text-red-800">{event.Jenis_Kegiatan}</p>
                  <p className="text-sm text-red-700">Oleh: {event.Nama_Pengguna}</p>
                </div>
              ))
            ) : (
              <p className="text-gray-500">Tidak ada kegiatan pada tanggal ini.</p>
            )}
          </div>
        </div>
      </div>
    );

    return (
      <div className="bg-white p-4 rounded-xl shadow-md">
        <div className="flex justify-between items-center mb-4">
          <button onClick={() => changeMonth(-1)} className="p-2 rounded-full hover:bg-gray-100"><Icon name="chevron_left" className="text-gray-600 hover:text-gray-800" /></button>
          <h3 className="font-bold text-lg text-gray-800">{currentDate.toLocaleDateString('id-ID', { month: 'long', year: 'numeric' })}</h3>
          <button onClick={() => changeMonth(1)} className="p-2 rounded-full hover:bg-gray-100"><Icon name="chevron_right" className="text-gray-600 hover:text-gray-800" /></button>
        </div>
        <div className="grid grid-cols-7 text-center text-xs font-semibold text-gray-500 border-b-2 pb-2 mb-2">
          {['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'].map(d => <div key={d}>{d}</div>)}
        </div>
        <div className="grid grid-cols-7">
          {daysInMonth.map((date, i) => {
            const eventsOnDate = date ? getEventsOnDate(date) : [];
            const isToday = date && new Date().toDateString() === date.toDateString();
            const hasEvents = eventsOnDate.length > 0;
            return (
              <div 
                key={i} 
                onClick={() => handleDateClick(date)}
                onTouchEnd={(e) => {
                  e.preventDefault();
                  handleDateClick(date);
                }}
                className={`aspect-square flex flex-col p-1 border-t border-l border-gray-200 ${date ? '' : 'bg-gray-50'} ${hasEvents ? 'cursor-pointer hover:bg-red-50 transition-colors' : ''}`}>
                {date && (
                   <>
                    <span className={`self-start text-sm font-medium mb-1 ${isToday ? 'bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center' : 'text-gray-600'}`}>
                        {date.getDate()}
                    </span>
                    <div className="flex-grow overflow-hidden space-y-1">
                        {eventsOnDate.slice(0, 2).map(event => (
                            <div key={event.ID} title={event.Jenis_Kegiatan} className="bg-red-100 text-red-800 rounded px-1.5 py-0.5 text-xs truncate font-medium">
                                {event.Jenis_Kegiatan || 'Event'}
                            </div>
                        ))}
                        {eventsOnDate.length > 2 && (
                            <div className="text-xs text-gray-500 font-medium mt-1">
                                + {eventsOnDate.length - 2} lainnya
                            </div>
                        )}
                    </div>
                   </>
                )}
              </div>
            );
          })}
        </div>
        {selectedDate && (
          <EventModal 
            date={selectedDate} 
            events={getEventsOnDate(selectedDate)}
            onClose={() => setSelectedDate(null)}
          />
        )}
      </div>
    );
  };

const TotalRevenueCard = ({ data, setToastMessage }: { data: SewaData[], setToastMessage: (msg: string) => void }) => {
    const [selectedYear, setSelectedYear] = useState<string>('all');

    const formatCurrency = (amount?: number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(amount || 0);

    const availableYears = useMemo(() => {
        const years = new Set<string>();
        data.forEach(item => {
            if (item.Tanggal_Pelaksanaan) {
                try {
                    const year = new Date(item.Tanggal_Pelaksanaan).getFullYear().toString();
                    years.add(year);
                } catch (e) {
                    // ignore invalid dates
                }
            }
        });
        return ['all', ...Array.from(years).sort((a, b) => parseInt(b) - parseInt(a))];
    }, [data]);

    const totalRevenue = useMemo(() => {
        return data
            .filter(item => {
                const status = item.Status_Pembayaran?.toLowerCase();
                const isPaid = status === 'diterima' || status === 'lunas';
                if (!isPaid || !item.Tanggal_Pelaksanaan) return false;

                if (selectedYear === 'all') return true;

                try {
                    const itemYear = new Date(item.Tanggal_Pelaksanaan).getFullYear().toString();
                    return itemYear === selectedYear;
                } catch(e) {
                    return false;
                }
            })
            .reduce((sum, item) => sum + (item.Total_Tagihan || 0), 0);
    }, [data, selectedYear]);
    
    const handleCopy = () => {
        navigator.clipboard.writeText(totalRevenue.toString());
        setToastMessage('Total pendapatan disalin!');
    };

    return (
        <div className="bg-white p-4 rounded-xl shadow-md">
            <div className="flex justify-between items-center mb-4">
                <h3 className="font-bold text-lg text-gray-800">Total Pendapatan</h3>
                <select 
                    value={selectedYear} 
                    onChange={e => setSelectedYear(e.target.value)}
                    className="bg-gray-100 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-red-500 focus:border-red-500 block p-2"
                >
                    {availableYears.map(year => (
                        <option key={year} value={year}>
                            {year === 'all' ? 'Semua Tahun' : year}
                        </option>
                    ))}
                </select>
            </div>
            <div className="flex items-center justify-center gap-2 bg-red-50 p-4 rounded-lg">
                <p className="text-3xl font-bold text-red-700 tracking-tight">{formatCurrency(totalRevenue)}</p>
                <button 
                    onClick={handleCopy} 
                    className="p-2 rounded-full hover:bg-red-100 text-red-600 transition-colors"
                    aria-label="Salin nilai"
                >
                    <Icon name="content_copy" className="text-xl" />
                </button>
            </div>
        </div>
    );
};


const RevenueChart = ({ data }: { data: SewaData[] }) => {
    const formatCurrency = (amount?: number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(amount || 0);

    const chartData = useMemo(() => {
        const revenueByMonth: { [key: string]: { total: number; date: Date } } = {};
        const monthNames = ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"];
        
        data.forEach(item => {
            const status = item.Status_Pembayaran?.toLowerCase();
            if ((status === 'diterima' || status === 'lunas') && item.Tanggal_Pelaksanaan && item.Total_Tagihan) {
                const date = new Date(item.Tanggal_Pelaksanaan);
                const monthKey = `${monthNames[date.getMonth()]} '${date.getFullYear().toString().slice(-2)}`;
                if (!revenueByMonth[monthKey]) {
                    revenueByMonth[monthKey] = { total: 0, date: new Date(date.getFullYear(), date.getMonth(), 1) };
                }
                revenueByMonth[monthKey].total += item.Total_Tagihan;
            }
        });

        const today = new Date();
        for (let i = 5; i >= 0; i--) {
            const d = new Date(today.getFullYear(), today.getMonth() - i, 1);
            const key = `${monthNames[d.getMonth()]} '${d.getFullYear().toString().slice(-2)}`;
            if(!revenueByMonth[key]) {
                revenueByMonth[key] = { total: 0, date: d };
            }
        }

        return Object.entries(revenueByMonth)
            .map(([month, data]) => ({ month, total: data.total, date: data.date }))
            .sort((a, b) => a.date.getTime() - b.date.getTime())
            .slice(-6);

    }, [data]);

    if (chartData.every(d => d.total === 0)) {
        return (
            <div className="bg-white p-4 rounded-xl shadow-md text-center">
                <h3 className="font-bold text-lg text-gray-800 mb-2">Pendapatan</h3>
                <Icon name="monitoring" className="text-6xl text-gray-300 mt-4 mb-4" />
                <p className="text-gray-500">Belum ada data pendapatan yang tercatat.</p>
            </div>
        );
    }
    
    const maxRevenue = Math.max(...chartData.map(d => d.total), 1);
    const chartHeight = 150;
    
    return (
        <div className="bg-white p-4 rounded-xl shadow-md">
            <h3 className="font-bold text-lg text-gray-800 mb-4">Pendapatan per Bulan</h3>
            <div className="flex justify-around items-end" style={{ height: `${chartHeight}px` }}>
                {chartData.map(({ month, total }) => {
                    const barHeight = total > 0 ? (total / maxRevenue) * chartHeight : 0;
                    return (
                        <div key={month} className="flex flex-col items-center gap-2 h-full justify-end w-12" title={`${month}: ${formatCurrency(total)}`}>
                             <div className="text-xs font-semibold text-gray-600" style={{ transform: 'translateY(-4px)' }}>
                                {total > 100000 ? `${(total / 1000000).toFixed(1).replace('.0','')}jt` : ''}
                            </div>
                            <div 
                                className="w-8 bg-red-500 hover:bg-red-600 rounded-t-md transition-all duration-300 ease-out" 
                                style={{ height: `${barHeight}px` }}
                            ></div>
                            <div className="text-xs font-medium text-gray-500 text-center">{month}</div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};


  const DashboardScreen = () => {
    const procedures = [
        { icon: 'visibility', text: "Pantau status pengajuan Anda di menu 'Sewa Lahan'." },
        { icon: 'payments', text: "Lakukan pembayaran setelah status pengajuan 'Diterima'." },
        { icon: 'event_repeat', text: "Jadwal dapat berubah jika berbenturan dengan acara universitas." },
        { icon: 'notification_important', text: "Informasi penjadwalan ulang akan diberikan maksimal H-3 acara." },
    ];

    return (
        <div className="space-y-6">
            <Calendar events={sewaData} />
            <div className="bg-red-100 p-4 rounded-xl shadow-md">
                <h3 className="font-bold text-red-800 mb-3 text-base">PROSEDUR BAZZAR</h3>
                <div className="space-y-3">
                    {procedures.map((item, index) => (
                        <div key={index} className="flex items-start gap-3">
                            <Icon name={item.icon} className="text-red-700 text-xl mt-0.5" />
                            <p className="text-red-900 text-sm flex-1">{item.text}</p>
                        </div>
                    ))}
                </div>
            </div>
            {user?.role === 'admin' && (
              <>
                <RevenueChart data={sewaData} />
                <TotalRevenueCard data={sewaData} setToastMessage={setToastMessage} />
              </>
            )}
        </div>
    );
  };

  interface SewaCardProps {
    item: SewaData;
    onEditClick: () => void;
  }
  const SewaCard: React.FC<SewaCardProps> = ({ item, onEditClick }) => {
    const getStatusChip = (status?: string) => {
      const s = status?.toLowerCase();
      if (s === 'lunas') return 'text-white bg-green-600';
      if (s === 'disetujui' || s === 'diterima') return 'text-blue-800 bg-blue-100';
      if (s === 'ditolak') return 'text-red-800 bg-red-100';
      return 'text-orange-800 bg-orange-100';
    };

    const formatCurrency = (amount?: number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(amount || 0);

    return (
      <div className="bg-white rounded-xl shadow-md overflow-hidden transition-all duration-300">
        <div className="p-4 flex flex-col gap-2">
          <div className="flex justify-between items-start">
            <p className="text-red-600 font-bold">{formatCurrency(item.Total_Tagihan)} | LUAS = {item.Luas || 'N/A'} M2</p>
            <button onClick={onEditClick} className="text-gray-400 -mt-1 -mr-1 p-1"><Icon name="more_horiz" /></button>
          </div>
          <div>
              <h3 className="font-semibold text-gray-800 leading-tight">{item.Nama_Pengguna} : {item.Jenis_Kegiatan}</h3>
              <p className="text-sm text-gray-500 leading-tight">{item.Tempat}</p>
          </div>
          {(item.Surat_Permohonan_Link || item.Bukti_Bayar_Link) && (
              <div className="flex items-center gap-4 text-xs border-t border-gray-100 pt-2">
                  {item.Surat_Permohonan_Link && (
                    <a href={item.Surat_Permohonan_Link} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-blue-600 hover:underline">
                      <Icon name="attach_file" className="text-sm" /> Surat Permohonan
                    </a>
                  )}
                  {item.Bukti_Bayar_Link && (
                    <a href={item.Bukti_Bayar_Link} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-green-600 hover:underline">
                      <Icon name="receipt_long" className="text-sm" /> Bukti Bayar
                    </a>
                  )}
              </div>
          )}
          <div className="flex justify-between items-center mt-1">
            <p className="text-sm text-gray-500 truncate pr-2">{user?.role === 'admin' ? item.Email_Penyewa : ''}</p>
            <span className={`px-2 py-0.5 text-xs font-semibold rounded-full shrink-0 ${getStatusChip(item.Status_Pembayaran)}`}>
              {item.Status_Pembayaran || 'Diproses'}
            </span>
          </div>
        </div>
      </div>
    );
  };
  
  const SewaLahanScreen = () => {
    const [activeFilter, setActiveFilter] = useState('All');
    const [searchTerm, setSearchTerm] = useState('');

    const filterOptions = useMemo(() => {
        const statuses = [...new Set(sewaData.map(item => item.Status_Pembayaran).filter(Boolean) as string[])];
        return ['All', ...statuses];
    }, [sewaData]);

    const filteredData = useMemo(() => {
        const lowercasedFilter = searchTerm.toLowerCase();
        
        const data = sewaData.filter(item => {
            const matchesFilter = activeFilter === 'All' || item.Status_Pembayaran === activeFilter;
            
            if (!matchesFilter) return false;
            if (searchTerm === '') return true;
            
            return (
                item.Nama_Pengguna?.toLowerCase().includes(lowercasedFilter) ||
                item.Jenis_Kegiatan?.toLowerCase().includes(lowercasedFilter) ||
                item.Tempat?.toLowerCase().includes(lowercasedFilter)
            );
        });
        
        return data.sort((a, b) => {
            const idA = parseInt(a.ID, 10) || 0;
            const idB = parseInt(b.ID, 10) || 0;
            return idB - idA;
        });
    }, [sewaData, activeFilter, searchTerm]);

    return (
        <div className="relative">
            <h2 className="text-2xl font-bold text-gray-800 mb-4">Sewa Lahan</h2>
            
            <div className="relative mb-4">
                <input 
                    type="search" 
                    placeholder="Cari nama, kegiatan, tempat..." 
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-full bg-white shadow-sm" 
                />
                <Icon name="search" className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
            </div>

            <div className="flex space-x-2 overflow-x-auto pb-4 -mx-4 px-4 whitespace-nowrap scrollbar-hide">
              {filterOptions.map(status => (
                <button
                  key={status}
                  onClick={() => setActiveFilter(status as string)}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-colors duration-200 shrink-0 ${
                    activeFilter === status 
                      ? 'bg-red-600 text-white shadow' 
                      : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                  }`}
                >
                  {status}
                </button>
              ))}
            </div>

            {isLoading ? (
                <div className="text-center p-10"><div className="w-8 h-8 border-2 border-gray-200 border-t-red-600 rounded-full animate-spin mx-auto"></div></div>
            ) : filteredData.length > 0 ? (
                <div className="space-y-4 mt-4">
                    {filteredData.map(item => <SewaCard key={item.ID} item={item} onEditClick={() => { setEditingItem(item); setIsModalOpen(true); }} />)}
                </div>
            ) : (
                <div className="text-center bg-white p-12 rounded-2xl shadow-md mt-4">
                    <Icon name="search_off" className="text-6xl text-gray-300" />
                    <p className="mt-4 text-gray-500">
                      Tidak ada data yang cocok untuk "{searchTerm || activeFilter}".
                    </p>
                </div>
            )}
            <button onClick={() => { setEditingItem(null); setIsModalOpen(true); }} className="fixed bottom-20 right-4 w-12 h-12 bg-red-600 text-white rounded-full flex items-center justify-center shadow-lg z-30 transform active:scale-90 transition-transform">
                <Icon name="add" className="text-2xl" />
            </button>
        </div>
    );
  };

  const SewaFormModal = ({ onSubmit, onClose, itemToEdit }: { 
    onSubmit: (e: FormEvent<HTMLFormElement>) => void; 
    onClose: () => void;
    itemToEdit: SewaData | null;
  }) => {
    const isEditMode = !!itemToEdit;
    const isPaymentApproved = itemToEdit?.Status_Pembayaran?.toLowerCase() === 'disetujui' || itemToEdit?.Status_Pembayaran?.toLowerCase() === 'diterima';
    
    // State untuk checkbox biaya tambahan
    const [isTendaChecked, setIsTendaChecked] = useState(false);
    const [isListrikChecked, setIsListrikChecked] = useState(false);

    useEffect(() => {
        if (itemToEdit) {
            if (itemToEdit.Biaya_Tenda && Number(itemToEdit.Biaya_Tenda) > 0) setIsTendaChecked(true);
            if (itemToEdit.Biaya_Listrik && Number(itemToEdit.Biaya_Listrik) > 0) setIsListrikChecked(true);
        }
    }, [itemToEdit]);
    
    const formatDateForInput = (dateString?: string) => {
        if (!dateString) return '';
        try { return new Date(dateString).toISOString().split('T')[0]; } 
        catch { return ''; }
    };

    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 z-40 flex items-end" onClick={onClose}>
        <div className="w-full bg-white rounded-t-2xl shadow-2xl p-6 animate-slide-up max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-xl font-bold text-gray-800">{isEditMode ? 'Edit Sewa' : 'Sewa Lahan'}</h2>
            <button onClick={onClose} className="p-2 rounded-full hover:bg-gray-100 -mr-2"><Icon name="close" /></button>
          </div>
          <form onSubmit={onSubmit} className="space-y-4">
            <InputField id="tgl-pelaksanaan" label="Tanggal Pelaksanaan" name="Tanggal_Pelaksanaan" type="date" required defaultValue={formatDateForInput(itemToEdit?.Tanggal_Pelaksanaan)} />
            <InputField id="tgl-berakhir" label="Tanggal Berakhir" name="Tanggal_Berakhir" type="date" required defaultValue={formatDateForInput(itemToEdit?.Tanggal_Berakhir)} />
            <InputField id="nama-pengguna" label="Nama Pengguna" name="Nama_Pengguna" type="text" defaultValue={itemToEdit?.Nama_Pengguna || user?.name} required placeholder="Nama lengkap Anda"/>
            <InputField id="jenis-kegiatan" label="Jenis Kegiatan" name="Jenis_Kegiatan" type="text" required placeholder="Contoh: Bazar Makanan" defaultValue={itemToEdit?.Jenis_Kegiatan}/>
            <div>
              <label htmlFor="tempat" className="block text-sm font-semibold text-gray-800 mb-1">Tempat</label>
              <select id="tempat" name="Tempat" required className="w-full px-4 py-3 bg-red-50 border border-red-200 text-gray-900 rounded-lg shadow-sm focus:ring-2 focus:ring-red-400 focus:border-red-400 transition duration-150 ease-in-out" defaultValue={itemToEdit?.Tempat || ""}>
                <option value="">-- Pilih Tempat --</option>
                <option value="Hlm. Gd Ahmad Sanusi">Hlm. Gd Ahmad Sanusi</option>
                <option value="Area Gymnasium">Area Gymnasium</option>
                <option value="Parkiran ATM">Parkiran ATM</option>
                <option value="Hlm. Amphi Teather">Hlm. Amphi Teather</option>
              </select>
            </div>
            <InputField id="pic-kontak" label="No Kontak/HP" name="PIC_Kontak" type="tel" required placeholder="08123456789" defaultValue={itemToEdit?.PIC_Kontak} />
            <div className="grid grid-cols-2 gap-4">
              <InputField id="panjang" label="Panjang (m)" name="Panjang" type="number" required placeholder="misal: 2" defaultValue={itemToEdit?.Panjang} />
              <InputField id="lebar" label="Lebar (m)" name="Lebar" type="number" required placeholder="misal: 2" defaultValue={itemToEdit?.Lebar} />
            </div>
            
            {/* Bagian Biaya Tambahan */}
            <div className="space-y-3 border-t border-gray-200 pt-4">
                <label className="block text-sm font-semibold text-gray-800 mb-1">Biaya Tambahan</label>
                
                {/* Biaya Tenda */}
                <div className="flex flex-col gap-2">
                    <div className="flex items-center gap-2">
                        <input 
                            type="checkbox" 
                            id="check-tenda" 
                            checked={isTendaChecked} 
                            onChange={(e) => setIsTendaChecked(e.target.checked)}
                            className="w-5 h-5 text-red-600 rounded border-gray-300 focus:ring-red-500"
                        />
                        <label htmlFor="check-tenda" className="text-gray-700 text-sm">Sewa Tenda</label>
                    </div>
                    {isTendaChecked && (
                        <div className="ml-7">
                             <InputField id="biaya-tenda" label="Biaya Tenda per Hari (Rp)" name="Biaya_Tenda" type="number" placeholder="Masukkan biaya per hari" defaultValue={itemToEdit?.Biaya_Tenda} />
                        </div>
                    )}
                </div>

                 {/* Biaya Listrik */}
                 <div className="flex flex-col gap-2">
                    <div className="flex items-center gap-2">
                        <input 
                            type="checkbox" 
                            id="check-listrik" 
                            checked={isListrikChecked} 
                            onChange={(e) => setIsListrikChecked(e.target.checked)}
                            className="w-5 h-5 text-red-600 rounded border-gray-300 focus:ring-red-500"
                        />
                        <label htmlFor="check-listrik" className="text-gray-700 text-sm">Sewa Listrik</label>
                    </div>
                    {isListrikChecked && (
                        <div className="ml-7">
                             <InputField id="biaya-listrik" label="Biaya Listrik per Hari (Rp)" name="Biaya_Listrik" type="number" placeholder="Masukkan biaya per hari" defaultValue={itemToEdit?.Biaya_Listrik} />
                        </div>
                    )}
                </div>
            </div>
            
            <hr className="my-4"/>
            
            <FileInputField id="surat-permohonan" name="Surat_Permohonan" label="Surat Permohonan (PDF)" accept=".pdf" currentFileUrl={itemToEdit?.Surat_Permohonan_Link} />
            
            <FileInputField id="bukti-bayar" name="Bukti_Bayar" label="Bukti Bayar (PDF)" accept=".pdf" disabled={!isEditMode || !isPaymentApproved} currentFileUrl={itemToEdit?.Bukti_Bayar_Link}/>
            {isEditMode && !isPaymentApproved && (
                <p className="text-xs text-gray-500 -mt-2">Upload bukti bayar hanya bisa dilakukan jika status "Disetujui".</p>
            )}

            <div className="flex gap-4 pt-4">
              <button type="button" onClick={onClose} className="w-full py-3 px-4 bg-gray-200 text-gray-700 font-bold rounded-lg hover:bg-gray-300">Batal</button>
              <button type="submit" disabled={isLoading} className="w-full py-3 px-4 bg-red-600 text-white font-bold rounded-lg hover:bg-red-700 disabled:opacity-50">
                {isLoading ? 'Memproses...' : (isEditMode ? 'Update' : 'Kirim')}
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  };

  const BiayaScreen = () => {
    const accountNumber = '9881954325712301';
    const copyToClipboard = () => {
      navigator.clipboard.writeText(accountNumber);
      setToastMessage('Nomor rekening berhasil disalin!');
    };

    return (
<div className="bg-white p-8 rounded-2xl shadow-lg space-y-8 max-w-2xl mx-auto">
  {/* Bagian BIAYA */}
  <div>
    <h2 className="text-2xl font-semibold text-gray-800 mb-3 border-b border-gray-200 pb-2">
      BIAYA
    </h2>
    <p className="text-gray-700 text-justify leading-relaxed">
      Biaya dihitung berdasarkan <span className="font-medium">Peraturan Rektor No. 80 Tahun 2024</span> 
      tentang Tarif. Untuk sewa bazar berukuran <span className="font-medium">2 x 2 meter</span> 
      dikenakan biaya sebesar <span className="font-semibold text-gray-900">Rp 224.000,-</span>.
    </p>
  </div>

  {/* Bagian CARA PEMBAYARAN */}
  <div>
    <h2 className="text-2xl font-semibold text-gray-800 mb-3 border-b border-gray-200 pb-2">
      CARA PEMBAYARAN
    </h2>
    <ul className="list-disc list-inside text-gray-700 text-justify leading-relaxed space-y-3">
      <li>
        Pembayaran sewa sebagaimana dimaksud pada Pasal 3 ayat (1) dilakukan oleh 
        <span className="font-medium"> PIHAK KEDUA</span> kepada 
        <span className="font-medium"> PIHAK PERTAMA</span> dengan cara disetorkan ke rekening 
        atas nama <span className="font-semibold">IGU Dit. Bisnis Sewa Lahan dan Booth</span> 
        dengan nomor rekening <span className="font-semibold">{accountNumber}</span> pada Bank BNI.
      </li>
      <li>
        Setelah pembayaran dilakukan, <span className="font-medium">PIHAK KEDUA</span> wajib 
        menyerahkan bukti transfer kepada <span className="font-medium">PIHAK PERTAMA</span>. 
        Selanjutnya akan diterbitkan <span className="italic">invoice</span> dan/atau tanda terima 
        yang sah atas penerimaan sejumlah uang tersebut.
      </li>
    </ul>
  </div>

  {/* Tombol Salin Nomor Rekening */}
  <button
    onClick={copyToClipboard}
    className="w-full bg-gradient-to-r from-red-100 to-red-50 hover:from-red-200 hover:to-red-100 
               text-red-800 font-semibold p-4 rounded-xl flex items-center justify-center gap-3 
               transition-all border border-red-200 shadow-sm active:scale-[0.98]"
  >
    <Icon name="content_copy" className="w-5 h-5" />
    <span>{accountNumber}</span>
  </button>
</div>

    );
  };

  const Toast = () => {
    if (!toastMessage) return null;
    return <div className="toast-notification">{toastMessage}</div>;
  };

  if (isLoading && !user) {
    return <div className="min-h-screen flex items-center justify-center"><div className="w-12 h-12 border-4 border-gray-200 border-t-red-600 rounded-full animate-spin"></div></div>;
  }
  
  return (
    <>
      {user ? <MainAppView /> : <AuthView />}
      <Toast />
    </>
  );
};

// Daftarkan Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('sw.js')
      .then(registration => {
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
      })
      .catch(error => {
        console.log('ServiceWorker registration failed: ', error);
      });
  });
}

// Render aplikasi
const container = document.getElementById('root');
if (container) {
  const root = ReactDOM.createRoot(container);
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
}