import React, { useState, useEffect } from 'react';
import { 
  LayoutDashboard, 
  Image as ImageIcon, 
  Wrench, 
  FileText, 
  Star, 
  Mail, 
  Users, 
  BarChart3, 
  FolderGit2, 
  Settings as SettingsIcon, 
  User, 
  LogOut, 
  Menu, 
  X, 
  Plus, 
  Edit, 
  Trash2, 
  Check, 
  Search, 
  Filter, 
  ChevronDown, 
  ChevronUp, 
  ArrowUpRight, 
  Eye, 
  FileDown, 
  UploadCloud, 
  Save, 
  Lock, 
  EyeOff, 
  Clock, 
  Phone, 
  MapPin, 
  ShieldCheck,
  AlertCircle
} from 'lucide-react';
import { useData, AdminMessage } from '../context/DataContext';
import { PortfolioItem, ServiceItem, TestimonialItem, TeamMember } from '../types';

export const AdminDashboard: React.FC<{ onClose: () => void }> = ({ onClose }) => {
  // Authentication State
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loginEmail, setLoginEmail] = useState('admin@tukangdekorasi.com');
  const [loginPassword, setLoginPassword] = useState('admin');
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(true);
  const [loginError, setLoginError] = useState('');
  
  // Layout States
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
  const [activeMenu, setActiveMenu] = useState<'dashboard' | 'portfolio' | 'services' | 'about' | 'testi' | 'messages' | 'team' | 'settings' | 'profile'>('dashboard');

  // Load DataContext
  const { 
    reasons,
    stats,
    mainServices,
    detailedServices,
    workflowSteps,
    testimonials,
    portfolios,
    team,
    timeline,
    aboutInfo,
    settings,
    messages,
    saveContent,
    updateMessageStatus,
    deleteMessage
  } = useData();

  // Toast System
  const [toasts, setToasts] = useState<{ id: string; type: 'success' | 'error' | 'info'; text: string }[]>([]);
  const showToast = (text: string, type: 'success' | 'error' | 'info' = 'success') => {
    const id = Math.random().toString();
    setToasts(prev => [...prev, { id, type, text }]);
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 4000);
  };

  // CRUD States
  const [searchQuery, setSearchQuery] = useState('');
  const [filterCategory, setFilterCategory] = useState('all');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalType, setModalType] = useState<'add_portfolio' | 'edit_portfolio' | 'add_service' | 'edit_service' | 'add_testimonial' | 'edit_testimonial' | 'add_team' | 'edit_team' | 'view_message'>('add_portfolio');
  const [selectedItem, setSelectedItem] = useState<any>(null);
  
  // Confirmation Modal
  const [confirmModal, setConfirmModal] = useState<{ isOpen: boolean; title: string; desc: string; onConfirm: () => void } | null>(null);

  // Form states
  const [formPortfolio, setFormPortfolio] = useState<Partial<PortfolioItem>>({
    title: '', category: 'wedding', location: '', year: '2026', shortDesc: '', fullDesc: '', imageUrl: '', isHighlight: false
  });
  const [formService, setFormService] = useState<Partial<ServiceItem>>({
    title: '', category: 'wedding', shortDesc: '', fullDesc: '', features: [], imageUrl: '', iconName: 'Sparkles'
  });
  const [formTestimonial, setFormTestimonial] = useState<Partial<TestimonialItem>>({
    name: '', role: '', comment: '', rating: 5, avatarUrl: '', projectType: ''
  });
  const [formTeam, setFormTeam] = useState<Partial<TeamMember>>({
    name: '', role: '', experience: '', imageUrl: ''
  });
  const [formAbout, setFormAbout] = useState(aboutInfo);
  const [formSettings, setFormSettings] = useState(settings);
  const [formProfile, setFormProfile] = useState({
    name: 'Super Admin',
    email: 'admin@tukangdekorasi.com',
    password: 'admin',
    newPassword: '',
    avatarUrl: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=200&q=80'
  });

  // Simulated Drag & Drop File Upload
  const [uploadProgress, setUploadProgress] = useState<number | null>(null);
  const [uploadedImageUrl, setUploadedImageUrl] = useState('');

  const handleSimulateUpload = (e: React.ChangeEvent<HTMLInputElement>, callback: (url: string) => void) => {
    if (!e.target.files || e.target.files.length === 0) return;
    setUploadProgress(10);
    const interval = setInterval(() => {
      setUploadProgress(prev => {
        if (prev === null) return null;
        if (prev >= 100) {
          clearInterval(interval);
          setTimeout(() => setUploadProgress(null), 1000);
          // Pick a beautiful random unsplash placeholder for demo
          const randomImages = [
            'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=800&q=80',
            'https://images.unsplash.com/photo-1511795409834-ef04bbd61622?auto=format&fit=crop&w=800&q=80',
            'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?auto=format&fit=crop&w=800&q=80',
            'https://images.unsplash.com/photo-1558904541-efa8c3c8cac1?auto=format&fit=crop&w=800&q=80',
            'https://images.unsplash.com/photo-1508873696983-2df5293cb92b?auto=format&fit=crop&w=800&q=80'
          ];
          const selectedUrl = randomImages[Math.floor(Math.random() * randomImages.length)];
          callback(selectedUrl);
          showToast('Gambar berhasil diunggah (Simulasi Cloud Storage)', 'success');
          return 100;
        }
        return prev + 30;
      });
    }, 200);
  };

  // Check LocalStorage Session
  useEffect(() => {
    const isRemembered = localStorage.getItem('admin_session') === 'true';
    if (isRemembered) {
      setIsAuthenticated(true);
    }
  }, []);

  // Sync form states when database loads asynchronously
  useEffect(() => {
    setFormSettings(settings);
  }, [settings]);

  useEffect(() => {
    setFormAbout(aboutInfo);
  }, [aboutInfo]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoginError('');
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: loginEmail, password: loginPassword })
      });
      if (res.ok) {
        const data = await res.json();
        setIsAuthenticated(true);
        if (rememberMe) {
          localStorage.setItem('admin_session', 'true');
        }
        showToast('Selamat Datang Kembali, Admin!', 'success');
      } else {
        const errorData = await res.json();
        setLoginError(errorData.message || 'Login gagal');
      }
    } catch (error) {
      // Fallback local auth for testing
      if (loginEmail === 'admin@tukangdekorasi.com' && loginPassword === 'admin') {
        setIsAuthenticated(true);
        if (rememberMe) {
          localStorage.setItem('admin_session', 'true');
        }
        showToast('Selamat Datang Kembali (Simulasi Offline)', 'success');
      } else {
        setLoginError('Kombinasi Email dan Sandi salah.');
      }
    }
  };

  const handleLogout = () => {
    setConfirmModal({
      isOpen: true,
      title: 'Konfirmasi Keluar',
      desc: 'Apakah Anda yakin ingin keluar dari Admin Dashboard ini?',
      onConfirm: () => {
        setIsAuthenticated(false);
        localStorage.removeItem('admin_session');
        setConfirmModal(null);
        showToast('Berhasil keluar dari dashboard', 'info');
      }
    });
  };

  // Delete handlers with validation
  const triggerDeletePortfolio = (id: string) => {
    setConfirmModal({
      isOpen: true,
      title: 'Hapus Portofolio',
      desc: 'Apakah Anda yakin ingin menghapus portofolio ini secara permanen dari website?',
      onConfirm: async () => {
        const updated = portfolios.filter(p => p.id !== id);
        const success = await saveContent({ portfolios: updated });
        if (success) showToast('Portofolio berhasil dihapus', 'success');
        else showToast('Gagal menyimpan perubahan', 'error');
        setConfirmModal(null);
      }
    });
  };

  const triggerDeleteService = (id: string) => {
    setConfirmModal({
      isOpen: true,
      title: 'Hapus Layanan',
      desc: 'Apakah Anda yakin ingin menghapus layanan ini?',
      onConfirm: async () => {
        const updated = detailedServices.filter(s => s.id !== id);
        const success = await saveContent({ detailedServices: updated });
        if (success) showToast('Layanan berhasil dihapus', 'success');
        setConfirmModal(null);
      }
    });
  };

  const triggerDeleteTestimonial = (id: string) => {
    setConfirmModal({
      isOpen: true,
      title: 'Hapus Testimoni',
      desc: 'Apakah Anda yakin ingin menghapus testimoni ini?',
      onConfirm: async () => {
        const updated = testimonials.filter(t => t.id !== id);
        const success = await saveContent({ testimonials: updated });
        if (success) showToast('Testimoni berhasil dihapus', 'success');
        setConfirmModal(null);
      }
    });
  };

  const triggerDeleteTeam = (name: string) => {
    setConfirmModal({
      isOpen: true,
      title: 'Hapus Anggota Tim',
      desc: `Apakah Anda yakin ingin menghapus ${name} dari daftar tim?`,
      onConfirm: async () => {
        const updated = team.filter(t => t.name !== name);
        const success = await saveContent({ team: updated });
        if (success) showToast('Anggota tim berhasil dihapus', 'success');
        setConfirmModal(null);
      }
    });
  };

  // Submit Portfolio
  const handleSavePortfolio = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formPortfolio.title) {
      showToast('Judul portofolio wajib diisi', 'error');
      return;
    }
    
    let updatedList = [...portfolios];
    if (modalType === 'add_portfolio') {
      const newItem: PortfolioItem = {
        id: 'p_' + Date.now(),
        title: formPortfolio.title,
        category: formPortfolio.category as any,
        location: formPortfolio.location || 'Workshop Utama',
        year: formPortfolio.year || '2026',
        shortDesc: formPortfolio.shortDesc || '',
        fullDesc: formPortfolio.fullDesc || '',
        imageUrl: formPortfolio.imageUrl || 'https://images.unsplash.com/photo-1519741497674-611481863552?auto=format&fit=crop&w=1000&q=80',
        isHighlight: formPortfolio.isHighlight ?? false
      };
      updatedList.unshift(newItem);
      showToast('Portofolio baru berhasil ditambahkan!', 'success');
    } else {
      updatedList = updatedList.map(item => 
        item.id === selectedItem.id ? { ...item, ...formPortfolio } : item
      );
      showToast('Portofolio berhasil diperbarui!', 'success');
    }

    const ok = await saveContent({ portfolios: updatedList });
    if (ok) setIsModalOpen(false);
  };

  // Submit Service
  const handleSaveService = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formService.title) {
      showToast('Nama Layanan wajib diisi', 'error');
      return;
    }

    let updatedList = [...detailedServices];
    if (modalType === 'add_service') {
      const newItem: ServiceItem = {
        id: 's_' + Date.now(),
        category: formService.category as any,
        title: formService.title,
        shortDesc: formService.shortDesc || '',
        fullDesc: formService.fullDesc || '',
        features: formService.features || [],
        imageUrl: formService.imageUrl || 'https://images.unsplash.com/photo-1511795409834-ef04bbd61622?auto=format&fit=crop&w=800&q=80',
        iconName: formService.iconName || 'Sparkles'
      };
      updatedList.push(newItem);
      showToast('Layanan berhasil ditambahkan!', 'success');
    } else {
      updatedList = updatedList.map(item => 
        item.id === selectedItem.id ? { ...item, ...formService } : item
      );
      showToast('Layanan berhasil diperbarui!', 'success');
    }

    const ok = await saveContent({ detailedServices: updatedList });
    if (ok) setIsModalOpen(false);
  };

  // Submit Testimonial
  const handleSaveTestimonial = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formTestimonial.name || !formTestimonial.comment) {
      showToast('Nama dan Komentar wajib diisi', 'error');
      return;
    }

    let updatedList = [...testimonials];
    if (modalType === 'add_testimonial') {
      const newItem: TestimonialItem = {
        id: 't_' + Date.now(),
        name: formTestimonial.name,
        role: formTestimonial.role || 'Klien',
        comment: formTestimonial.comment,
        rating: Number(formTestimonial.rating || 5),
        avatarUrl: formTestimonial.avatarUrl || 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=200&q=80',
        projectType: formTestimonial.projectType || 'Custom Project'
      };
      updatedList.unshift(newItem);
      showToast('Testimoni berhasil ditambahkan!', 'success');
    } else {
      updatedList = updatedList.map(item => 
        item.id === selectedItem.id ? { ...item, ...formTestimonial } : item
      );
      showToast('Testimoni berhasil diperbarui!', 'success');
    }

    const ok = await saveContent({ testimonials: updatedList });
    if (ok) setIsModalOpen(false);
  };

  // Submit Team Member
  const handleSaveTeam = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formTeam.name || !formTeam.role) {
      showToast('Nama dan Jabatan wajib diisi', 'error');
      return;
    }

    let updatedList = [...team];
    if (modalType === 'add_team') {
      const newItem: TeamMember = {
        name: formTeam.name,
        role: formTeam.role,
        experience: formTeam.experience || '',
        imageUrl: formTeam.imageUrl || 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=400&q=80'
      };
      updatedList.push(newItem);
      showToast('Anggota tim baru berhasil ditambahkan!', 'success');
    } else {
      updatedList = updatedList.map(item => 
        item.name === selectedItem.name ? { ...item, ...formTeam } : item
      );
      showToast('Anggota tim berhasil diperbarui!', 'success');
    }

    const ok = await saveContent({ team: updatedList });
    if (ok) setIsModalOpen(false);
  };

  // Save General About
  const handleSaveAbout = async (e: React.FormEvent) => {
    e.preventDefault();
    const ok = await saveContent({ aboutInfo: formAbout });
    if (ok) showToast('Tentang Perusahaan berhasil diperbarui!', 'success');
    else showToast('Gagal menyimpan perubahan', 'error');
  };

  // Save Settings
  const handleSaveSettings = async (e: React.FormEvent) => {
    e.preventDefault();
    const ok = await saveContent({ settings: formSettings });
    if (ok) showToast('Pengaturan website berhasil disimpan!', 'success');
    else showToast('Gagal menyimpan perubahan', 'error');
  };

  // Update Profile admin
  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/admin/profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formProfile.name,
          email: formProfile.email,
          password: formProfile.newPassword || formProfile.password,
          avatarUrl: formProfile.avatarUrl
        })
      });
      if (res.ok) {
        showToast('Profil Admin berhasil diperbarui!', 'success');
        setFormProfile(prev => ({ ...prev, password: prev.newPassword || prev.password, newPassword: '' }));
      } else {
        showToast('Gagal memperbarui profil', 'error');
      }
    } catch (err) {
      showToast('Profil berhasil diperbarui (Simulasi Lokal)', 'success');
    }
  };

  // Export messages to CSV simulation
  const handleExportCSV = () => {
    const csvContent = "data:text/csv;charset=utf-8," 
      + ["Nama,Email,WhatsApp,Layanan,Tanggal,Status,Pesan"].join(",") + "\n"
      + messages.map(m => `"${m.name}","${m.email}","${m.whatsapp}","${m.serviceType}","${m.date}","${m.status}","${m.message.replace(/"/g, '""')}"`).join("\n");
    
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `tukang_dekorasi_messages_${new Date().toISOString().split('T')[0]}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    showToast('Pesan WhatsApp berhasil diekspor ke CSV', 'success');
  };

  // Filtering lists based on search
  const filteredPortfolios = portfolios.filter(p => {
    const matchesSearch = p.title.toLowerCase().includes(searchQuery.toLowerCase()) || 
                          p.location.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = filterCategory === 'all' || p.category === filterCategory;
    return matchesSearch && matchesCategory;
  });

  const filteredServices = detailedServices.filter(s => {
    const matchesSearch = s.title.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = filterCategory === 'all' || s.category === filterCategory;
    return matchesSearch && matchesCategory;
  });

  const filteredMessages = messages.filter(m => {
    const matchesSearch = m.name.toLowerCase().includes(searchQuery.toLowerCase()) || 
                          m.whatsapp.includes(searchQuery) ||
                          m.message.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterCategory === 'all' || m.status.toLowerCase() === filterCategory.toLowerCase();
    return matchesSearch && matchesStatus;
  });


  // ---------------------- LOGIN LAYOUT ----------------------
  if (!isAuthenticated) {
    return (
      <div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 px-4 sm:px-6 lg:px-8 selection:bg-[#6B8E5A] selection:text-white">
        <div className="sm:mx-auto sm:w-full sm:max-w-md">
          <div className="flex justify-center">
            <div className="w-14 h-14 rounded-2xl bg-[#EFF4ED] flex items-center justify-center text-[#6B8E5A] shadow-md">
              <ShieldCheck className="w-8 h-8" />
            </div>
          </div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-950 tracking-tight">
            Tukang Dekorasi Admin Panel
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            Masuk untuk mengelola portofolio, layanan, dan pesan klien secara langsung.
          </p>
        </div>

        <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
          <div className="bg-white py-8 px-6 shadow-xl rounded-3xl border border-gray-100 sm:px-10">
            <form className="space-y-6" onSubmit={handleLogin}>
              {loginError && (
                <div className="p-4 rounded-xl bg-red-50 border border-red-200 text-red-600 flex items-start gap-3 text-sm">
                  <AlertCircle className="w-5 h-5 shrink-0 mt-0.5" />
                  <span>{loginError}</span>
                </div>
              )}

              <div>
                <label className="block text-sm font-semibold text-gray-700">Email Admin</label>
                <div className="mt-1 relative">
                  <input
                    type="email"
                    required
                    value={loginEmail}
                    onChange={(e) => setLoginEmail(e.target.value)}
                    className="w-full px-4 py-3 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#6B8E5A] focus:border-[#6B8E5A] text-sm text-gray-900 shadow-sm"
                    placeholder="nama@tukangdekorasi.com"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700">Kata Sandi</label>
                <div className="mt-1 relative rounded-md shadow-sm">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    required
                    value={loginPassword}
                    onChange={(e) => setLoginPassword(e.target.value)}
                    className="w-full px-4 py-3 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#6B8E5A] focus:border-[#6B8E5A] text-sm text-gray-900 shadow-sm pr-10"
                    placeholder="Sandi Rahasia"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 right-0 pr-3.5 flex items-center text-gray-400 hover:text-gray-600"
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <input
                    id="remember-me"
                    type="checkbox"
                    checked={rememberMe}
                    onChange={(e) => setRememberMe(e.target.checked)}
                    className="h-4 w-4 text-[#6B8E5A] focus:ring-[#6B8E5A] border-gray-300 rounded cursor-pointer"
                  />
                  <label htmlFor="remember-me" className="ml-2 block text-xs font-medium text-gray-600 cursor-pointer select-none">
                    Ingat Saya di Browser Ini
                  </label>
                </div>

                <div className="text-xs">
                  <span 
                    onClick={() => alert('Gunakan email: admin@tukangdekorasi.com dan password: admin')}
                    className="font-semibold text-[#6B8E5A] hover:text-[#5A7B4A] cursor-pointer"
                  >
                    Lupa Sandi?
                  </span>
                </div>
              </div>

              <div>
                <button
                  type="submit"
                  className="w-full py-3.5 px-4 border border-transparent rounded-2xl shadow-lg shadow-[#6B8E5A]/20 text-sm font-bold text-white bg-[#6B8E5A] hover:bg-[#5A7B4A] transition-all flex items-center justify-center gap-2 cursor-pointer"
                >
                  <Lock className="w-4 h-4" />
                  <span>Masuk Ke Dashboard</span>
                </button>
              </div>
            </form>

            <div className="mt-6 pt-6 border-t border-gray-100 flex items-center justify-center">
              <button 
                onClick={onClose}
                className="text-xs font-medium text-gray-500 hover:text-gray-800 flex items-center gap-1.5 cursor-pointer"
              >
                <span>← Kembali Ke Website</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ---------------------- MAIN ADMIN PANEL LAYOUT ----------------------
  return (
    <div className="min-h-screen bg-gray-50 flex selection:bg-[#6B8E5A] selection:text-white">
      {/* Toast Notification Container */}
      <div className="fixed top-5 right-5 z-50 flex flex-col gap-3">
        {toasts.map(t => (
          <div 
            key={t.id} 
            className={`p-4 rounded-2xl shadow-xl flex items-center gap-3 border animate-fadeIn min-w-[300px] ${
              t.type === 'success' ? 'bg-white text-gray-900 border-[#6B8E5A]/30' : 
              t.type === 'error' ? 'bg-red-50 text-red-900 border-red-200' : 'bg-gray-900 text-white border-transparent'
            }`}
          >
            <div className={`w-6 h-6 rounded-full flex items-center justify-center shrink-0 ${
              t.type === 'success' ? 'bg-[#EFF4ED] text-[#6B8E5A]' : 
              t.type === 'error' ? 'bg-red-200 text-red-700' : 'bg-gray-800 text-gray-300'
            }`}>
              {t.type === 'success' ? <Check className="w-3.5 h-3.5" /> : <AlertCircle className="w-3.5 h-3.5" />}
            </div>
            <span className="text-xs font-semibold">{t.text}</span>
          </div>
        ))}
      </div>

      {/* Sidebar - Desktop */}
      <aside className={`bg-gray-950 text-gray-300 border-r border-gray-800 flex flex-col justify-between transition-all duration-300 shrink-0 ${
        isSidebarCollapsed ? 'w-20' : 'w-64'
      } hidden md:flex`}>
        <div>
          {/* Logo Brand Header */}
          <div className="p-6 border-b border-gray-900 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-[#6B8E5A] flex items-center justify-center text-white shrink-0">
              <ShieldCheck className="w-6 h-6" />
            </div>
            {!isSidebarCollapsed && (
              <div className="flex flex-col">
                <span className="font-extrabold text-white text-base leading-none">Admin CMS</span>
                <span className="text-[10px] text-[#6B8E5A] font-bold tracking-widest mt-0.5">TUKANG DEKOR</span>
              </div>
            )}
          </div>

          {/* Menus */}
          <nav className="p-4 space-y-1">
            {[
              { id: 'dashboard', label: 'Dashboard Home', icon: LayoutDashboard },
              { id: 'portfolio', label: 'Portofolio', icon: ImageIcon },
              { id: 'services', label: 'Layanan Utama', icon: Wrench },
              { id: 'about', label: 'Profil Perusahaan', icon: FileText },
              { id: 'team', label: 'Kelola Tim', icon: Users },
              { id: 'testi', label: 'Testimoni', icon: Star },
              { id: 'messages', label: 'Pesan Klien (Inbox)', icon: Mail, badge: messages.filter(m => m.status === 'Unread').length },
              { id: 'settings', label: 'Pengaturan Web', icon: SettingsIcon },
              { id: 'profile', label: 'Profil Admin', icon: User }
            ].map(menu => {
              const Icon = menu.icon;
              const isActive = activeMenu === menu.id;
              return (
                <button
                  key={menu.id}
                  onClick={() => setActiveMenu(menu.id as any)}
                  className={`w-full flex items-center rounded-xl p-3 text-sm font-medium transition-all group relative cursor-pointer ${
                    isActive 
                      ? 'bg-[#6B8E5A] text-white shadow-md' 
                      : 'hover:bg-gray-900 text-gray-400 hover:text-white'
                  }`}
                >
                  <Icon className="w-5 h-5 shrink-0" />
                  {!isSidebarCollapsed && <span className="ml-3 font-semibold">{menu.label}</span>}
                  {!isSidebarCollapsed && menu.badge && menu.badge > 0 ? (
                    <span className="ml-auto bg-red-500 text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full">
                      {menu.badge}
                    </span>
                  ) : null}

                  {isSidebarCollapsed && (
                    <div className="absolute left-full ml-2 px-2.5 py-1.5 rounded-md bg-gray-900 text-white text-xs font-bold invisible opacity-0 group-hover:visible group-hover:opacity-100 transition-all shadow-md z-30 whitespace-nowrap">
                      {menu.label}
                    </div>
                  )}
                </button>
              );
            })}
          </nav>
        </div>

        {/* Sidebar Footer Controls */}
        <div className="p-4 border-t border-gray-900 space-y-2">
          <button 
            onClick={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
            className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-gray-900 text-gray-500 hover:text-white text-xs font-semibold cursor-pointer"
          >
            <Menu className="w-4 h-4 shrink-0" />
            {!isSidebarCollapsed && <span>Sembunyikan Menu</span>}
          </button>
          
          <button 
            onClick={handleLogout}
            className="w-full flex items-center gap-3 p-3 rounded-xl bg-red-950/40 text-red-400 hover:bg-red-900/40 hover:text-red-300 text-xs font-bold cursor-pointer"
          >
            <LogOut className="w-4 h-4 shrink-0" />
            {!isSidebarCollapsed && <span>Keluar Panel</span>}
          </button>
        </div>
      </aside>

      {/* Mobile Drawer Sidebar */}
      {isMobileSidebarOpen && (
        <div className="fixed inset-0 z-40 flex md:hidden">
          <div className="fixed inset-0 bg-gray-900/50 backdrop-blur-sm" onClick={() => setIsMobileSidebarOpen(false)}></div>
          <div className="relative flex flex-col w-64 max-w-xs bg-gray-950 text-gray-300">
            <div className="p-6 border-b border-gray-900 flex items-center justify-between">
              <span className="font-extrabold text-white text-base">Tukang Dekor Admin</span>
              <button onClick={() => setIsMobileSidebarOpen(false)} className="p-2 text-gray-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>
            <nav className="p-4 space-y-1 flex-1 overflow-y-auto">
              {[
                { id: 'dashboard', label: 'Dashboard Home', icon: LayoutDashboard },
                { id: 'portfolio', label: 'Portofolio', icon: ImageIcon },
                { id: 'services', label: 'Layanan Utama', icon: Wrench },
                { id: 'about', label: 'Profil Perusahaan', icon: FileText },
                { id: 'team', label: 'Kelola Tim', icon: Users },
                { id: 'testi', label: 'Testimoni', icon: Star },
                { id: 'messages', label: 'Pesan Klien (Inbox)', icon: Mail, badge: messages.filter(m => m.status === 'Unread').length },
                { id: 'settings', label: 'Pengaturan Web', icon: SettingsIcon },
                { id: 'profile', label: 'Profil Admin', icon: User }
              ].map(menu => {
                const Icon = menu.icon;
                return (
                  <button
                    key={menu.id}
                    onClick={() => {
                      setActiveMenu(menu.id as any);
                      setIsMobileSidebarOpen(false);
                    }}
                    className={`w-full flex items-center rounded-xl p-3.5 text-sm font-semibold transition-colors ${
                      activeMenu === menu.id ? 'bg-[#6B8E5A] text-white' : 'hover:bg-gray-900 text-gray-400'
                    }`}
                  >
                    <Icon className="w-5 h-5 shrink-0" />
                    <span className="ml-3">{menu.label}</span>
                    {menu.badge && menu.badge > 0 ? (
                      <span className="ml-auto bg-red-500 text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full">
                        {menu.badge}
                      </span>
                    ) : null}
                  </button>
                );
              })}
            </nav>
            <div className="p-4 border-t border-gray-900">
              <button 
                onClick={handleLogout}
                className="w-full flex items-center justify-center gap-3 p-3.5 rounded-xl bg-red-950 text-red-400 text-sm font-extrabold"
              >
                <LogOut className="w-5 h-5" />
                <span>Keluar Panel</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Main Content Pane */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Top Navbar */}
        <header className="bg-white border-b border-gray-200 h-16 flex items-center justify-between px-6 z-10 shrink-0">
          <div className="flex items-center gap-4">
            <button 
              onClick={() => setIsMobileSidebarOpen(true)}
              className="md:hidden p-2 rounded-xl hover:bg-gray-100 text-gray-700 focus:outline-none"
            >
              <Menu className="w-6 h-6" />
            </button>
            <div className="hidden md:flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-[#6B8E5A]">
              <span>TUKANG DEKORASI WEBSITE CMS</span>
              <span>•</span>
              <span className="text-gray-500">KONDISI SISTEM: AKTIF & DURABLE</span>
            </div>
          </div>

          <div className="flex items-center gap-4">
            {/* Direct Close Panel (Returns to Live Website) */}
            <button
              onClick={onClose}
              className="px-4 py-2 rounded-xl text-xs font-bold text-gray-700 bg-gray-100 hover:bg-gray-200 transition-all flex items-center gap-1 cursor-pointer"
            >
              <span>← Kembali ke Website</span>
            </button>

            {/* Admin mini info */}
            <div className="flex items-center gap-3 pl-4 border-l border-gray-200">
              <img
                src={formProfile.avatarUrl}
                alt="Avatar"
                className="w-8 h-8 rounded-full border border-gray-200"
              />
              <div className="hidden sm:flex flex-col text-left">
                <span className="text-sm font-bold text-gray-900 leading-none">{formProfile.name}</span>
                <span className="text-[10px] text-gray-500 mt-0.5">Administrator</span>
              </div>
            </div>
          </div>
        </header>

        {/* Scrollable View Area */}
        <main className="flex-1 overflow-y-auto p-6 md:p-8 space-y-8 bg-[#F9FAFB]">
          
          {/* 1. VIEW: DASHBOARD HOME */}
          {activeMenu === 'dashboard' && (
            <div className="space-y-8 animate-fadeIn">
              {/* Heading */}
              <div>
                <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Ringkasan Statistik</h1>
                <p className="text-sm text-gray-500 mt-1">Laporan metrik performa utama website Tukang Dekorasi Anda.</p>
              </div>

              {/* Statistics Counters cards */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-5">
                  <div className="w-14 h-14 rounded-2xl bg-[#EFF4ED] text-[#6B8E5A] flex items-center justify-center shrink-0">
                    <FolderGit2 className="w-7 h-7" />
                  </div>
                  <div>
                    <span className="text-3xl font-extrabold text-gray-900 font-mono tracking-tight">{portfolios.length}</span>
                    <h4 className="text-xs uppercase font-bold text-gray-400 mt-1">Total Portofolio</h4>
                  </div>
                </div>

                <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-5">
                  <div className="w-14 h-14 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
                    <Star className="w-7 h-7 fill-current" />
                  </div>
                  <div>
                    <span className="text-3xl font-extrabold text-gray-900 font-mono tracking-tight">{testimonials.length}</span>
                    <h4 className="text-xs uppercase font-bold text-gray-400 mt-1">Klien Memberi Ulasan</h4>
                  </div>
                </div>

                <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-5">
                  <div className="w-14 h-14 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center shrink-0">
                    <Mail className="w-7 h-7" />
                  </div>
                  <div>
                    <span className="text-3xl font-extrabold text-gray-900 font-mono tracking-tight">{messages.length}</span>
                    <h4 className="text-xs uppercase font-bold text-gray-400 mt-1">Total Pesan Masuk</h4>
                  </div>
                </div>

                <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-5">
                  <div className="w-14 h-14 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
                    <Users className="w-7 h-7" />
                  </div>
                  <div>
                    <span className="text-3xl font-extrabold text-gray-900 font-mono tracking-tight">{team.length}</span>
                    <h4 className="text-xs uppercase font-bold text-gray-400 mt-1">Personel Ahli</h4>
                  </div>
                </div>
              </div>

              {/* Dynamic visual dashboard charts (Elegantly custom made in SVG!) */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                {/* Chart 1: Portofolio per Category */}
                <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-6">
                  <div className="flex items-center justify-between">
                    <h3 className="font-bold text-gray-900 text-lg">Distribusi Kategori Portofolio</h3>
                    <span className="text-xs font-semibold px-2.5 py-1 bg-gray-100 rounded-full text-gray-500">Real-time</span>
                  </div>
                  
                  <div className="space-y-4">
                    {['wedding', 'garden', 'landscape', 'event'].map(cat => {
                      const count = portfolios.filter(p => p.category === cat).length;
                      const percentage = portfolios.length > 0 ? (count / portfolios.length) * 100 : 0;
                      const displayNames: any = { wedding: 'Wedding Decor', garden: 'Garden Decor', landscape: 'Landscape Design', event: 'Corporate Event' };
                      const colors: any = { wedding: 'bg-[#6B8E5A]', garden: 'bg-emerald-500', landscape: 'bg-amber-500', event: 'bg-indigo-500' };
                      return (
                        <div key={cat} className="space-y-1.5">
                          <div className="flex items-center justify-between text-xs font-bold text-gray-700">
                            <span>{displayNames[cat]}</span>
                            <span>{count} Proyek ({percentage.toFixed(0)}%)</span>
                          </div>
                          <div className="w-full bg-gray-100 h-3 rounded-full overflow-hidden">
                            <div className={`h-full ${colors[cat]} transition-all duration-1000`} style={{ width: `${percentage}%` }}></div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {/* Quick actions box */}
                <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-6 flex flex-col justify-between">
                  <div>
                    <h3 className="font-bold text-gray-900 text-lg mb-2">Aksi Cepat Admin</h3>
                    <p className="text-xs text-gray-500">Pilih salah satu pintasan di bawah untuk mempercepat pengelolaan.</p>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <button
                      onClick={() => {
                        setFormPortfolio({ title: '', category: 'wedding', location: '', year: '2026', shortDesc: '', fullDesc: '', imageUrl: '', isHighlight: false });
                        setModalType('add_portfolio');
                        setIsModalOpen(true);
                      }}
                      className="p-4 rounded-2xl bg-[#EFF4ED] text-[#6B8E5A] hover:bg-[#6B8E5A] hover:text-white transition-all text-sm font-bold text-center flex flex-col items-center justify-center gap-2 shadow-sm border border-[#6B8E5A]/20 cursor-pointer"
                    >
                      <Plus className="w-5 h-5" />
                      <span>Tambah Portofolio</span>
                    </button>

                    <button
                      onClick={() => {
                        setFormService({ title: '', category: 'wedding', shortDesc: '', fullDesc: '', features: [], imageUrl: '', iconName: 'Sparkles' });
                        setModalType('add_service');
                        setIsModalOpen(true);
                      }}
                      className="p-4 rounded-2xl bg-amber-50 text-amber-700 hover:bg-amber-500 hover:text-white transition-all text-sm font-bold text-center flex flex-col items-center justify-center gap-2 shadow-sm border border-amber-200 cursor-pointer"
                    >
                      <Plus className="w-5 h-5" />
                      <span>Tambah Layanan</span>
                    </button>

                    <button
                      onClick={() => {
                        setFormTestimonial({ name: '', role: '', comment: '', rating: 5, avatarUrl: '', projectType: '' });
                        setModalType('add_testimonial');
                        setIsModalOpen(true);
                      }}
                      className="p-4 rounded-2xl bg-blue-50 text-blue-700 hover:bg-blue-500 hover:text-white transition-all text-sm font-bold text-center flex flex-col items-center justify-center gap-2 shadow-sm border border-blue-200 cursor-pointer"
                    >
                      <Plus className="w-5 h-5" />
                      <span>Tambah Testimoni</span>
                    </button>

                    <button
                      onClick={() => setActiveMenu('messages')}
                      className="p-4 rounded-2xl bg-emerald-50 text-emerald-700 hover:bg-emerald-500 hover:text-white transition-all text-sm font-bold text-center flex flex-col items-center justify-center gap-2 shadow-sm border border-emerald-200 cursor-pointer"
                    >
                      <Mail className="w-5 h-5" />
                      <span>Buka Inbox Pesan</span>
                    </button>
                  </div>
                </div>
              </div>

              {/* Recent messages preview */}
              <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-bold text-gray-900 text-lg">Pesan WhatsApp Klien Terbaru</h3>
                  <button 
                    onClick={() => setActiveMenu('messages')}
                    className="text-xs font-bold text-[#6B8E5A] hover:underline cursor-pointer"
                  >
                    Buka Seluruh Inbox →
                  </button>
                </div>
                
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-sm text-gray-500">
                    <thead className="text-xs text-gray-700 uppercase bg-gray-50">
                      <tr>
                        <th className="px-6 py-4 rounded-l-2xl">Nama Pengirim</th>
                        <th className="px-6 py-4">WhatsApp</th>
                        <th className="px-6 py-4">Pilihan Layanan</th>
                        <th className="px-6 py-4">Status</th>
                        <th className="px-6 py-4 rounded-r-2xl">Aksi</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {messages.slice(0, 3).map((msg) => (
                        <tr key={msg.id} className="hover:bg-gray-50/50">
                          <td className="px-6 py-4 font-bold text-gray-900">{msg.name}</td>
                          <td className="px-6 py-4 font-mono">{msg.whatsapp}</td>
                          <td className="px-6 py-4">{msg.serviceType}</td>
                          <td className="px-6 py-4">
                            <span className={`px-2.5 py-1 rounded-full text-[10px] font-bold ${
                              msg.status === 'Unread' ? 'bg-red-50 text-red-600 border border-red-200' :
                              msg.status === 'Read' ? 'bg-yellow-50 text-yellow-600 border border-yellow-200' :
                              'bg-green-50 text-green-600 border border-green-200'
                            }`}>
                              {msg.status === 'Unread' ? 'Belum Dibaca' : msg.status === 'Read' ? 'Sudah Dibaca' : 'Dibalas'}
                            </span>
                          </td>
                          <td className="px-6 py-4">
                            <button
                              onClick={() => {
                                setSelectedItem(msg);
                                updateMessageStatus(msg.id, 'Read');
                                setModalType('view_message');
                                setIsModalOpen(true);
                              }}
                              className="p-1.5 rounded-lg bg-[#EFF4ED] text-[#6B8E5A] hover:bg-[#6B8E5A] hover:text-white transition-all cursor-pointer"
                            >
                              <Eye className="w-4 h-4" />
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* 2. VIEW: PORTFOLIO MANAGEMENT */}
          {activeMenu === 'portfolio' && (
            <div className="space-y-6 animate-fadeIn">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Manajemen Portofolio</h1>
                  <p className="text-sm text-gray-500 mt-1">Kelola seluruh foto hasil dekorasi dan proyek selesai di sini.</p>
                </div>
                <button
                  onClick={() => {
                    setFormPortfolio({ title: '', category: 'wedding', location: '', year: '2026', shortDesc: '', fullDesc: '', imageUrl: '', isHighlight: false });
                    setModalType('add_portfolio');
                    setIsModalOpen(true);
                  }}
                  className="px-5 py-3 rounded-2xl bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white text-sm font-bold flex items-center gap-2 shadow-lg shadow-[#6B8E5A]/15 cursor-pointer self-start sm:self-auto"
                >
                  <Plus className="w-5 h-5" />
                  <span>Tambah Portofolio</span>
                </button>
              </div>

              {/* Filtering & Searching Controls */}
              <div className="bg-white p-4 rounded-3xl border border-gray-100 shadow-sm flex flex-col md:flex-row items-center justify-between gap-4">
                <div className="w-full md:w-80 relative">
                  <Search className="w-4 h-4 text-gray-400 absolute left-3.5 top-3.5" />
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Cari nama atau lokasi..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-100 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#6B8E5A] text-sm text-gray-800"
                  />
                </div>

                <div className="flex items-center gap-2 self-stretch md:self-auto overflow-x-auto pb-1 md:pb-0">
                  <span className="text-xs font-semibold text-gray-400 shrink-0">Filter Kategori:</span>
                  {['all', 'wedding', 'garden', 'landscape', 'event'].map(cat => (
                    <button
                      key={cat}
                      onClick={() => setFilterCategory(cat)}
                      className={`px-4 py-1.5 rounded-full text-xs font-bold transition-all shrink-0 cursor-pointer ${
                        filterCategory === cat 
                          ? 'bg-[#6B8E5A] text-white shadow-sm' 
                          : 'bg-gray-100 hover:bg-gray-200 text-gray-600'
                      }`}
                    >
                      {cat.toUpperCase()}
                    </button>
                  ))}
                </div>
              </div>

              {/* Portfolio Grid list */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredPortfolios.map((item) => (
                  <div key={item.id} className="bg-white rounded-3xl overflow-hidden border border-gray-200/50 shadow-sm flex flex-col justify-between group">
                    <div>
                      {/* Thumbnail frame */}
                      <div className="relative h-48 bg-gray-100 overflow-hidden">
                        <img
                          src={item.imageUrl}
                          alt={item.title}
                          className="w-full h-full object-cover"
                        />
                        {item.isHighlight && (
                          <span className="absolute top-3 left-3 px-2.5 py-1 bg-amber-500 text-white text-[10px] font-extrabold rounded-full shadow-sm">
                            Highlighted
                          </span>
                        )}
                        <span className="absolute bottom-3 right-3 px-2.5 py-1 bg-gray-950/80 backdrop-blur-sm text-white text-[10px] font-bold rounded-full uppercase tracking-wider">
                          {item.category}
                        </span>
                      </div>

                      <div className="p-6 space-y-2">
                        <h3 className="font-extrabold text-gray-900 text-lg group-hover:text-[#6B8E5A] transition-colors leading-tight">
                          {item.title}
                        </h3>
                        <div className="flex items-center gap-1 text-xs text-gray-500 font-medium">
                          <MapPin className="w-3.5 h-3.5 text-[#6B8E5A]" />
                          <span>{item.location} ({item.year})</span>
                        </div>
                        <p className="text-xs text-gray-600 line-clamp-2 leading-relaxed pt-1">
                          {item.shortDesc}
                        </p>
                      </div>
                    </div>

                    <div className="p-6 pt-0 border-t border-gray-50 flex items-center justify-end gap-2 bg-gray-50/20">
                      <button
                        onClick={() => {
                          setSelectedItem(item);
                          setFormPortfolio(item);
                          setModalType('edit_portfolio');
                          setIsModalOpen(true);
                        }}
                        className="px-3.5 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold text-xs flex items-center gap-1 cursor-pointer"
                      >
                        <Edit className="w-3.5 h-3.5" />
                        <span>Edit</span>
                      </button>

                      <button
                        onClick={() => triggerDeletePortfolio(item.id)}
                        className="px-3.5 py-2 rounded-xl bg-red-50 hover:bg-red-500 hover:text-white text-red-600 font-bold text-xs flex items-center gap-1 transition-colors cursor-pointer"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                        <span>Hapus</span>
                      </button>
                    </div>
                  </div>
                ))}

                {filteredPortfolios.length === 0 && (
                  <div className="col-span-full py-16 text-center bg-white rounded-3xl border border-dashed border-gray-200 text-gray-500">
                    <AlertCircle className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                    <p className="font-bold">Tidak ada portofolio yang cocok.</p>
                    <p className="text-xs mt-1 text-gray-400">Silakan ubah kata kunci pencarian atau bersihkan filter.</p>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 3. VIEW: SERVICE MANAGEMENT */}
          {activeMenu === 'services' && (
            <div className="space-y-6 animate-fadeIn">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Manajemen Layanan</h1>
                  <p className="text-sm text-gray-500 mt-1">Atur deskripsi, spesifikasi, dan keunggulan jasa yang ditawarkan.</p>
                </div>
                <button
                  onClick={() => {
                    setFormService({ title: '', category: 'wedding', shortDesc: '', fullDesc: '', features: [], imageUrl: '', iconName: 'Sparkles' });
                    setModalType('add_service');
                    setIsModalOpen(true);
                  }}
                  className="px-5 py-3 rounded-2xl bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white text-sm font-bold flex items-center gap-2 shadow-lg cursor-pointer"
                >
                  <Plus className="w-5 h-5" />
                  <span>Tambah Layanan</span>
                </button>
              </div>

              {/* Services List Grid */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                {detailedServices.map((srv) => (
                  <div key={srv.id} className="bg-white rounded-3xl overflow-hidden border border-gray-100 shadow-sm flex flex-col justify-between">
                    <div className="p-6 space-y-6">
                      <div className="flex items-start justify-between gap-4">
                        <div className="space-y-1">
                          <span className="px-2.5 py-0.5 bg-[#EFF4ED] text-[#6B8E5A] text-[10px] font-bold rounded-full uppercase">
                            {srv.category}
                          </span>
                          <h3 className="text-xl font-extrabold text-gray-950">{srv.title}</h3>
                        </div>
                        <div className="w-12 h-12 bg-gray-100 rounded-xl flex items-center justify-center text-gray-600 font-mono font-bold shrink-0">
                          {srv.iconName}
                        </div>
                      </div>

                      <p className="text-xs text-gray-600 leading-relaxed leading-relaxed">{srv.shortDesc}</p>

                      <div className="space-y-2">
                        <span className="text-xs font-bold text-gray-400 uppercase tracking-wider block">Fitur & Spesifikasi Layanan:</span>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                          {srv.features.map((ft, i) => (
                            <div key={i} className="flex items-center gap-2 text-xs text-gray-700 font-semibold bg-gray-50 p-2 rounded-xl">
                              <Check className="w-4 h-4 text-[#6B8E5A] shrink-0" />
                              <span className="line-clamp-1">{ft}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>

                    <div className="p-6 pt-0 border-t border-gray-50 flex items-center justify-end gap-2 bg-gray-50/30">
                      <button
                        onClick={() => {
                          setSelectedItem(srv);
                          setFormService(srv);
                          setModalType('edit_service');
                          setIsModalOpen(true);
                        }}
                        className="px-3.5 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold text-xs flex items-center gap-1 cursor-pointer"
                      >
                        <Edit className="w-3.5 h-3.5" />
                        <span>Edit</span>
                      </button>

                      <button
                        onClick={() => triggerDeleteService(srv.id)}
                        className="px-3.5 py-2 rounded-xl bg-red-50 hover:bg-red-500 hover:text-white text-red-600 font-bold text-xs flex items-center gap-1 transition-colors cursor-pointer"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                        <span>Hapus</span>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 4. VIEW: ABOUT MANAGEMENT */}
          {activeMenu === 'about' && (
            <div className="space-y-6 animate-fadeIn max-w-4xl">
              <div>
                <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Profil Perusahaan</h1>
                <p className="text-sm text-gray-500 mt-1">Perbarui sejarah, visi, misi, dan nilai-nilai (values) Tukang Dekorasi.</p>
              </div>

              <form onSubmit={handleSaveAbout} className="bg-white p-6 md:p-8 rounded-3xl border border-gray-100 shadow-sm space-y-6">
                <div className="space-y-2">
                  <label className="text-sm font-bold text-gray-800">Judul Besar Profil</label>
                  <input
                    type="text"
                    value={formAbout.title}
                    onChange={(e) => setFormAbout({ ...formAbout, title: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A]"
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold text-gray-800">Subjudul Profil</label>
                  <input
                    type="text"
                    value={formAbout.subtitle}
                    onChange={(e) => setFormAbout({ ...formAbout, subtitle: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A]"
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold text-gray-800">Penjelasan Lengkap (Profil Narasi)</label>
                  <textarea
                    rows={6}
                    value={formAbout.desc}
                    onChange={(e) => setFormAbout({ ...formAbout, desc: e.target.value })}
                    className="w-full px-4 py-3 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm text-gray-700 leading-relaxed"
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <label className="text-sm font-bold text-gray-800">Visi Utama</label>
                    <textarea
                      rows={4}
                      value={formAbout.vision}
                      onChange={(e) => setFormAbout({ ...formAbout, vision: e.target.value })}
                      className="w-full px-4 py-3 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm text-gray-700"
                    />
                  </div>

                  <div className="space-y-2">
                    <label className="text-sm font-bold text-gray-800">Fokus Area (Pisahkan dengan baris baru)</label>
                    <textarea
                      rows={4}
                      value={formAbout.focusAreas.join('\n')}
                      onChange={(e) => setFormAbout({ ...formAbout, focusAreas: e.target.value.split('\n') })}
                      className="w-full px-4 py-3 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm text-gray-700 font-mono"
                    />
                  </div>
                </div>

                <div className="pt-4 border-t border-gray-100 flex items-center justify-end">
                  <button
                    type="submit"
                    className="px-6 py-3.5 bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white font-bold text-sm rounded-2xl shadow-lg flex items-center gap-2 cursor-pointer"
                  >
                    <Save className="w-4.5 h-4.5" />
                    <span>Simpan Profil Perusahaan</span>
                  </button>
                </div>
              </form>
            </div>
          )}

          {/* 5. VIEW: TESTIMONI MANAGEMENT */}
          {activeMenu === 'testi' && (
            <div className="space-y-6 animate-fadeIn">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Kelola Ulasan & Testimoni</h1>
                  <p className="text-sm text-gray-500 mt-1">Ulasan pelanggan bintang 5 yang ditampilkan pada website utama.</p>
                </div>
                <button
                  onClick={() => {
                    setFormTestimonial({ name: '', role: '', comment: '', rating: 5, avatarUrl: '', projectType: '' });
                    setModalType('add_testimonial');
                    setIsModalOpen(true);
                  }}
                  className="px-5 py-3 rounded-2xl bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white text-sm font-bold flex items-center gap-2 shadow-lg cursor-pointer animate-fadeIn"
                >
                  <Plus className="w-5 h-5" />
                  <span>Tambah Testimoni</span>
                </button>
              </div>

              {/* Testimonials grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {testimonials.map((t) => (
                  <div key={t.id} className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm flex flex-col justify-between space-y-6">
                    <div className="space-y-4">
                      <div className="flex items-center gap-3.5">
                        <img
                          src={t.avatarUrl}
                          alt={t.name}
                          className="w-12 h-12 rounded-xl object-cover border border-gray-100"
                        />
                        <div>
                          <h4 className="font-bold text-gray-950">{t.name}</h4>
                          <p className="text-[10px] text-gray-500 uppercase tracking-wider font-semibold">{t.role}</p>
                        </div>
                      </div>

                      <div className="flex items-center gap-0.5 text-amber-400">
                        {[...Array(t.rating)].map((_, i) => (
                          <Star key={i} className="w-4 h-4 fill-current" />
                        ))}
                      </div>

                      <p className="text-xs text-gray-600 italic leading-relaxed">
                        "{t.comment}"
                      </p>

                      <span className="text-[10px] font-bold text-[#6B8E5A] bg-[#EFF4ED] px-2 py-0.5 rounded-full inline-block">
                        {t.projectType}
                      </span>
                    </div>

                    <div className="pt-4 border-t border-gray-50 flex items-center justify-end gap-2">
                      <button
                        onClick={() => {
                          setSelectedItem(t);
                          setFormTestimonial(t);
                          setModalType('edit_testimonial');
                          setIsModalOpen(true);
                        }}
                        className="p-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 cursor-pointer"
                      >
                        <Edit className="w-4 h-4" />
                      </button>

                      <button
                        onClick={() => triggerDeleteTestimonial(t.id)}
                        className="p-2 rounded-xl bg-red-50 hover:bg-red-500 hover:text-white text-red-600 cursor-pointer"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 6. VIEW: TEAM MANAGEMENT */}
          {activeMenu === 'team' && (
            <div className="space-y-6 animate-fadeIn">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Manajemen Personel Tim</h1>
                  <p className="text-sm text-gray-500 mt-1">Daftar tim profesional pembuat dekorasi dan lanskap taman.</p>
                </div>
                <button
                  onClick={() => {
                    setFormTeam({ name: '', role: '', experience: '', imageUrl: '' });
                    setModalType('add_team');
                    setIsModalOpen(true);
                  }}
                  className="px-5 py-3 rounded-2xl bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white text-sm font-bold flex items-center gap-2 shadow-lg cursor-pointer"
                >
                  <Plus className="w-5 h-5" />
                  <span>Tambah Anggota Tim</span>
                </button>
              </div>

              {/* Team list */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                {team.map((member) => (
                  <div key={member.name} className="bg-white rounded-3xl overflow-hidden border border-gray-100 shadow-sm flex flex-col justify-between">
                    <div>
                      <div className="h-64 bg-gray-50 overflow-hidden relative">
                        <img
                          src={member.imageUrl}
                          alt={member.name}
                          className="w-full h-full object-cover object-top"
                        />
                      </div>
                      <div className="p-5 space-y-1">
                        <h4 className="font-bold text-gray-950 text-base">{member.name}</h4>
                        <p className="text-xs text-[#6B8E5A] font-bold uppercase">{member.role}</p>
                        <p className="text-xs text-gray-500 leading-relaxed pt-2">
                          {member.experience}
                        </p>
                      </div>
                    </div>

                    <div className="p-4 pt-0 border-t border-gray-50 flex items-center justify-end gap-2">
                      <button
                        onClick={() => {
                          setSelectedItem(member);
                          setFormTeam(member);
                          setModalType('edit_team');
                          setIsModalOpen(true);
                        }}
                        className="p-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 cursor-pointer"
                      >
                        <Edit className="w-4 h-4" />
                      </button>

                      <button
                        onClick={() => triggerDeleteTeam(member.name)}
                        className="p-2 rounded-xl bg-red-50 hover:bg-red-500 hover:text-white text-red-600 cursor-pointer"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 7. VIEW: CONTACT MESSAGES (INBOX) */}
          {activeMenu === 'messages' && (
            <div className="space-y-6 animate-fadeIn">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Pesan Masuk (WhatsApp Inbox)</h1>
                  <p className="text-sm text-gray-500 mt-1">Daftar calon klien yang meminta konsultasi gratis dari formulir web.</p>
                </div>
                <button
                  onClick={handleExportCSV}
                  className="px-5 py-3 rounded-2xl bg-[#EFF4ED] hover:bg-[#6B8E5A] text-[#6B8E5A] hover:text-white transition-all text-sm font-bold flex items-center gap-2 border border-[#6B8E5A]/20 cursor-pointer"
                >
                  <FileDown className="w-5 h-5" />
                  <span>Ekspor CSV (Excel)</span>
                </button>
              </div>

              {/* Filtering Controls */}
              <div className="bg-white p-4 rounded-3xl border border-gray-100 shadow-sm flex flex-col md:flex-row items-center justify-between gap-4">
                <div className="w-full md:w-80 relative">
                  <Search className="w-4 h-4 text-gray-400 absolute left-3.5 top-3.5" />
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Cari nama, WhatsApp, isi pesan..."
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-100 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#6B8E5A] text-sm text-gray-800"
                  />
                </div>

                <div className="flex items-center gap-2 self-stretch md:self-auto overflow-x-auto">
                  <span className="text-xs font-semibold text-gray-400 shrink-0">Status Pesan:</span>
                  {['all', 'unread', 'read', 'replied'].map(status => (
                    <button
                      key={status}
                      onClick={() => setFilterCategory(status)}
                      className={`px-4 py-1.5 rounded-full text-xs font-bold transition-all shrink-0 cursor-pointer ${
                        filterCategory === status 
                          ? 'bg-[#6B8E5A] text-white shadow-sm' 
                          : 'bg-gray-100 hover:bg-gray-200 text-gray-600'
                      }`}
                    >
                      {status === 'all' ? 'SEMUA' : status === 'unread' ? 'BELUM DIBACA' : status === 'read' ? 'DIBACA' : 'DIBALAS'}
                    </button>
                  ))}
                </div>
              </div>

              {/* Messages Table inbox */}
              <div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-sm text-gray-500">
                    <thead className="text-xs text-gray-700 uppercase bg-gray-50 border-b border-gray-100">
                      <tr>
                        <th className="px-6 py-4">Pengirim / Tanggal</th>
                        <th className="px-6 py-4">WhatsApp / Email</th>
                        <th className="px-6 py-4">Layanan</th>
                        <th className="px-6 py-4">Isi Pesan</th>
                        <th className="px-6 py-4">Status</th>
                        <th className="px-6 py-4 text-right">Aksi</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {filteredMessages.map((msg) => (
                        <tr key={msg.id} className={`hover:bg-gray-50/50 ${msg.status === 'Unread' ? 'bg-red-50/10 font-semibold' : ''}`}>
                          <td className="px-6 py-4 text-left">
                            <div className="font-bold text-gray-900 leading-none">{msg.name}</div>
                            <span className="text-[10px] text-gray-400 font-mono mt-1 block">
                              {new Date(msg.date).toLocaleString('id-ID', { dateStyle: 'short', timeStyle: 'short' })}
                            </span>
                          </td>
                          <td className="px-6 py-4 font-mono text-xs">
                            <div className="text-[#6B8E5A] font-bold">{msg.whatsapp}</div>
                            <div className="text-gray-400">{msg.email || '-'}</div>
                          </td>
                          <td className="px-6 py-4 text-xs font-semibold text-gray-700">
                            {msg.serviceType}
                          </td>
                          <td className="px-6 py-4 text-xs max-w-xs truncate">
                            {msg.message}
                          </td>
                          <td className="px-6 py-4">
                            <span className={`px-2.5 py-1 rounded-full text-[10px] font-bold uppercase ${
                              msg.status === 'Unread' ? 'bg-red-50 text-red-600 border border-red-200' :
                              msg.status === 'Read' ? 'bg-yellow-50 text-yellow-600 border border-yellow-200' :
                              'bg-green-50 text-green-600 border border-green-200'
                            }`}>
                              {msg.status === 'Unread' ? 'Belum Dibaca' : msg.status === 'Read' ? 'Dibaca' : 'Dibalas'}
                            </span>
                          </td>
                          <td className="px-6 py-4 text-right space-x-2">
                            <button
                              onClick={() => {
                                setSelectedItem(msg);
                                updateMessageStatus(msg.id, 'Read');
                                setModalType('view_message');
                                setIsModalOpen(true);
                              }}
                              className="p-1.5 rounded-lg bg-[#EFF4ED] text-[#6B8E5A] hover:bg-[#6B8E5A] hover:text-white transition-all cursor-pointer inline-flex"
                              title="Detail Pesan"
                            >
                              <Eye className="w-4 h-4" />
                            </button>

                            <button
                              onClick={async () => {
                                setConfirmModal({
                                  isOpen: true,
                                  title: 'Hapus Pesan',
                                  desc: 'Apakah Anda yakin ingin menghapus pesan inbox ini?',
                                  onConfirm: async () => {
                                    await deleteMessage(msg.id);
                                    showToast('Pesan berhasil dihapus', 'success');
                                    setConfirmModal(null);
                                  }
                                });
                              }}
                              className="p-1.5 rounded-lg bg-red-50 text-red-600 hover:bg-red-500 hover:text-white transition-all cursor-pointer inline-flex"
                              title="Hapus Pesan"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {filteredMessages.length === 0 && (
                  <div className="py-16 text-center text-gray-500">
                    <Mail className="w-12 h-12 text-gray-300 mx-auto mb-3 animate-pulse" />
                    <p className="font-bold">Inbox Anda sedang kosong.</p>
                    <p className="text-xs mt-1 text-gray-400">Tidak ada pesan yang cocok dengan kriteria filter saat ini.</p>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 8. VIEW: SETTINGS */}
          {activeMenu === 'settings' && (
            <div className="space-y-6 animate-fadeIn max-w-4xl">
              <div>
                <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Pengaturan Website</h1>
                <p className="text-sm text-gray-500 mt-1">Konfigurasi alamat, nomor WhatsApp, jam operasional, dan SEO.</p>
              </div>

              <form onSubmit={handleSaveSettings} className="bg-white p-6 md:p-8 rounded-3xl border border-gray-100 shadow-sm space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <label className="text-sm font-bold text-gray-800">Nama Website</label>
                    <input
                      type="text"
                      value={formSettings.websiteName}
                      onChange={(e) => setFormSettings({ ...formSettings, websiteName: e.target.value })}
                      className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A]"
                    />
                  </div>

                  <div className="space-y-2">
                    <label className="text-sm font-bold text-gray-800">Email Operasional</label>
                    <input
                      type="email"
                      value={formSettings.email}
                      onChange={(e) => setFormSettings({ ...formSettings, email: e.target.value })}
                      className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A]"
                    />
                  </div>

                  <div className="space-y-2">
                    <label className="text-sm font-bold text-gray-800">Nomor WhatsApp Admin</label>
                    <input
                      type="text"
                      value={formSettings.whatsapp}
                      onChange={(e) => setFormSettings({ ...formSettings, whatsapp: e.target.value })}
                      className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A]"
                    />
                  </div>

                  <div className="space-y-2">
                    <label className="text-sm font-bold text-gray-800">Jam Kerja / Operasional</label>
                    <input
                      type="text"
                      value={formSettings.operatingHours}
                      onChange={(e) => setFormSettings({ ...formSettings, operatingHours: e.target.value })}
                      className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A]"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold text-gray-800">Alamat Lengkap Workshop</label>
                  <textarea
                    rows={3}
                    value={formSettings.address}
                    onChange={(e) => setFormSettings({ ...formSettings, address: e.target.value })}
                    className="w-full px-4 py-3 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm text-gray-700"
                  />
                </div>

                {/* SEO & Google Search Console Section */}
                <div className="pt-6 border-t border-gray-100 space-y-4">
                  <div className="flex items-center gap-2">
                    <Search className="w-5 h-5 text-[#6B8E5A]" />
                    <h3 className="text-base font-bold text-gray-900">SEO & Google Search Console</h3>
                  </div>
                  <p className="text-xs text-gray-500">Konfigurasi metadata untuk meningkatkan visibilitas di hasil pencarian Google dan verifikasi kepemilikan situs.</p>
                  
                  <div className="space-y-4">
                    <div className="space-y-2">
                      <label className="text-sm font-bold text-gray-800">Judul Meta SEO (Meta Title)</label>
                      <input
                        type="text"
                        placeholder="Tukang Dekorasi - Jasa Dekorasi & Landscape Estetik"
                        value={formSettings.metaTitle || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, metaTitle: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm"
                      />
                      <p className="text-xs text-gray-400">Panjang yang disarankan: 50-60 karakter.</p>
                    </div>

                    <div className="space-y-2">
                      <label className="text-sm font-bold text-gray-800">Deskripsi Meta SEO (Meta Description)</label>
                      <textarea
                        rows={3}
                        placeholder="Spesialis dekorasi pernikahan mewah dan pengerjaan lanskap taman rumah modern."
                        value={formSettings.metaDescription || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, metaDescription: e.target.value })}
                        className="w-full px-4 py-3 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm text-gray-700"
                      />
                      <p className="text-xs text-gray-400">Panjang yang disarankan: 150-160 karakter.</p>
                    </div>

                    <div className="space-y-2">
                      <label className="text-sm font-bold text-gray-800">Kata Kunci SEO (Meta Keywords)</label>
                      <input
                        type="text"
                        placeholder="dekorasi pernikahan, landscape taman, dekorasi estetik, tukang dekorasi"
                        value={formSettings.metaKeywords || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, metaKeywords: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm"
                      />
                      <p className="text-xs text-gray-400">Pisahkan setiap kata kunci atau frasa pencarian dengan tanda koma (,).</p>
                    </div>

                    <div className="space-y-2">
                      <label className="text-sm font-bold text-gray-800">Kode Verifikasi Google (Google Site Verification)</label>
                      <input
                        type="text"
                        placeholder="e.g. AbC_123xyz_example_code..."
                        value={formSettings.googleVerificationCode || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, googleVerificationCode: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm font-mono text-xs"
                      />
                      <p className="text-xs text-gray-400">
                        Digunakan untuk mendaftarkan website ke <strong>Google Search Console</strong>. Cukup masukkan nilai <code>content</code> dari meta tag HTML yang diberikan oleh Google.
                        <br />
                        Contoh jika kodenya: <code>&lt;meta name="google-site-verification" content="xyz123" /&gt;</code>, cukup masukkan <code>xyz123</code>.
                      </p>
                    </div>
                  </div>
                </div>

                {/* Background Images Section */}
                <div className="pt-6 border-t border-gray-100 space-y-4">
                  <h3 className="text-base font-bold text-gray-900">Gambar Latar Belakang Header (Background Images)</h3>
                  <p className="text-xs text-gray-500">Ubah gambar latar belakang di bagian atas (header) untuk setiap halaman agar lebih menarik.</p>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label className="text-xs font-bold text-gray-700">Gambar Hero Beranda (Home Hero)</label>
                      <input
                        type="text"
                        placeholder="https://images.unsplash.com/..."
                        value={formSettings.heroBgUrl || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, heroBgUrl: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                      />
                    </div>

                    <div className="space-y-2">
                      <label className="text-xs font-bold text-gray-700">Gambar Header Tentang Kami (About Page)</label>
                      <input
                        type="text"
                        placeholder="https://images.unsplash.com/..."
                        value={formSettings.aboutBgUrl || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, aboutBgUrl: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                      />
                    </div>

                    <div className="space-y-2">
                      <label className="text-xs font-bold text-gray-700">Gambar Header Layanan (Service Page)</label>
                      <input
                        type="text"
                        placeholder="https://images.unsplash.com/..."
                        value={formSettings.serviceBgUrl || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, serviceBgUrl: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                      />
                    </div>

                    <div className="space-y-2">
                      <label className="text-xs font-bold text-gray-700">Gambar Header Portofolio (Portfolio Page)</label>
                      <input
                        type="text"
                        placeholder="https://images.unsplash.com/..."
                        value={formSettings.portfolioBgUrl || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, portfolioBgUrl: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                      />
                    </div>

                    <div className="space-y-2">
                      <label className="text-xs font-bold text-gray-700">Gambar Header Kontak (Contact Page)</label>
                      <input
                        type="text"
                        placeholder="https://images.unsplash.com/..."
                        value={formSettings.contactBgUrl || ''}
                        onChange={(e) => setFormSettings({ ...formSettings, contactBgUrl: e.target.value })}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                      />
                    </div>
                  </div>
                </div>

                <div className="pt-6 border-t border-gray-100 flex items-center justify-end">
                  <button
                    type="submit"
                    className="px-6 py-3.5 bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white font-bold text-sm rounded-2xl shadow-lg flex items-center gap-2 cursor-pointer"
                  >
                    <Save className="w-4.5 h-4.5" />
                    <span>Simpan Pengaturan Web</span>
                  </button>
                </div>
              </form>
            </div>
          )}

          {/* 9. VIEW: PROFILE ADMIN */}
          {activeMenu === 'profile' && (
            <div className="space-y-6 animate-fadeIn max-w-xl">
              <div>
                <h1 className="text-3xl font-extrabold text-gray-950 tracking-tight">Profil Akun Admin</h1>
                <p className="text-sm text-gray-500 mt-1">Ganti nama, email login, dan kata sandi panel Admin.</p>
              </div>

              <form onSubmit={handleUpdateProfile} className="bg-white p-6 md:p-8 rounded-3xl border border-gray-100 shadow-sm space-y-6">
                <div className="flex flex-col items-center space-y-3 pb-4">
                  <img
                    src={formProfile.avatarUrl}
                    alt="Profile Avatar"
                    className="w-24 h-24 rounded-full border-2 border-[#6B8E5A] object-cover"
                  />
                  <div className="relative">
                    <label className="px-4 py-2 bg-[#EFF4ED] text-[#6B8E5A] rounded-xl text-xs font-bold border border-[#6B8E5A]/20 cursor-pointer hover:bg-[#6B8E5A] hover:text-white transition-all block">
                      <span>Unggah Foto Profil</span>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleSimulateUpload(e, (url) => setFormProfile({ ...formProfile, avatarUrl: url }))}
                        className="hidden"
                      />
                    </label>
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold text-gray-800">Nama Lengkap</label>
                  <input
                    type="text"
                    value={formProfile.name}
                    onChange={(e) => setFormProfile({ ...formProfile, name: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm"
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold text-gray-800">Email Login</label>
                  <input
                    type="email"
                    value={formProfile.email}
                    onChange={(e) => setFormProfile({ ...formProfile, email: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm"
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-bold text-gray-800">Ubah Kata Sandi Baru (Opsional)</label>
                  <input
                    type="password"
                    value={formProfile.newPassword}
                    onChange={(e) => setFormProfile({ ...formProfile, newPassword: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-2xl focus:ring-2 focus:ring-[#6B8E5A] text-sm"
                    placeholder="Biarkan kosong jika tidak ingin mengganti"
                  />
                </div>

                <div className="pt-4 border-t border-gray-100 flex items-center justify-end">
                  <button
                    type="submit"
                    className="px-6 py-3.5 bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white font-bold text-sm rounded-2xl shadow-lg flex items-center gap-2 cursor-pointer"
                  >
                    <Save className="w-4.5 h-4.5" />
                    <span>Perbarui Profil</span>
                  </button>
                </div>
              </form>
            </div>
          )}

        </main>
      </div>

      {/* ----------------- CORE MODALS / FORMS CONTAINER ----------------- */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          {/* Backdrop blur */}
          <div className="fixed inset-0 bg-gray-900/50 backdrop-blur-sm" onClick={() => setIsModalOpen(false)}></div>
          
          <div className="relative bg-white rounded-3xl border border-gray-100 shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto z-10 p-6 md:p-8 space-y-6">
            <div className="flex items-center justify-between border-b border-gray-100 pb-4">
              <h3 className="font-extrabold text-gray-950 text-xl leading-none">
                {modalType === 'add_portfolio' ? 'Tambah Portofolio Baru' :
                 modalType === 'edit_portfolio' ? 'Ubah Rincian Portofolio' :
                 modalType === 'add_service' ? 'Tambah Layanan Baru' :
                 modalType === 'edit_service' ? 'Edit Layanan' :
                 modalType === 'add_testimonial' ? 'Tambah Testimoni' :
                 modalType === 'edit_testimonial' ? 'Ubah Testimoni' :
                 modalType === 'add_team' ? 'Tambah Personel' :
                 modalType === 'edit_team' ? 'Edit Personel' : 'Detail Pesan Masuk'}
              </h3>
              <button onClick={() => setIsModalOpen(false)} className="p-2 rounded-xl hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors">
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Simulated Drag & Drop Progress bar */}
            {uploadProgress !== null && (
              <div className="p-4 rounded-xl bg-gray-50 border border-gray-100 space-y-2">
                <div className="flex items-center justify-between text-xs font-bold text-[#6B8E5A]">
                  <span>Sedang Mengunggah Gambar...</span>
                  <span>{uploadProgress}%</span>
                </div>
                <div className="w-full bg-gray-200 h-2 rounded-full overflow-hidden">
                  <div className="h-full bg-[#6B8E5A] transition-all" style={{ width: `${uploadProgress}%` }}></div>
                </div>
              </div>
            )}

            {/* FORM: ADD/EDIT PORTFOLIO */}
            {(modalType === 'add_portfolio' || modalType === 'edit_portfolio') && (
              <form onSubmit={handleSavePortfolio} className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Nama Proyek Dekorasi / Judul *</label>
                    <input
                      type="text"
                      required
                      value={formPortfolio.title}
                      onChange={(e) => setFormPortfolio({ ...formPortfolio, title: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                      placeholder="Contoh: The Royal White Room"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Kategori Dekorasi *</label>
                    <select
                      value={formPortfolio.category}
                      onChange={(e) => setFormPortfolio({ ...formPortfolio, category: e.target.value as any })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] bg-white cursor-pointer"
                    >
                      <option value="wedding">Wedding Decoration</option>
                      <option value="garden">Garden & Living Wall</option>
                      <option value="landscape">Landscape Design & Kolam</option>
                      <option value="event">Corporate Event & Backdrop</option>
                    </select>
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Lokasi / Venue *</label>
                    <input
                      type="text"
                      value={formPortfolio.location}
                      onChange={(e) => setFormPortfolio({ ...formPortfolio, location: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                      placeholder="Contoh: Hotel Ritz-Carlton Jakarta"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Tahun Selesai *</label>
                    <input
                      type="text"
                      value={formPortfolio.year}
                      onChange={(e) => setFormPortfolio({ ...formPortfolio, year: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                    />
                  </div>
                </div>

                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Deskripsi Singkat (Muncul di List Card)</label>
                  <input
                    type="text"
                    value={formPortfolio.shortDesc}
                    onChange={(e) => setFormPortfolio({ ...formPortfolio, shortDesc: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                    placeholder="Rangkuman 1 baris mengenai proyek ini..."
                  />
                </div>

                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Deskripsi Lengkap (Muncul di Popup Lightbox)</label>
                  <textarea
                    rows={4}
                    value={formPortfolio.fullDesc}
                    onChange={(e) => setFormPortfolio({ ...formPortfolio, fullDesc: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] text-sm"
                    placeholder="Ceritakan proses pembuatan, tantangan lapangan, dan hasil akhir..."
                  />
                </div>

                {/* Drag & Drop simulated image uploader */}
                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Foto Utama Portofolio (Unggah Gambar)</label>
                  <div className="border-2 border-dashed border-gray-200 rounded-2xl p-6 text-center hover:border-[#6B8E5A] transition-all relative">
                    <UploadCloud className="w-10 h-10 text-gray-300 mx-auto mb-2" />
                    <p className="text-xs text-gray-500 font-semibold">Tarik & Lepas gambar Anda di sini, atau</p>
                    <label className="mt-2 inline-block px-4 py-1.5 bg-[#EFF4ED] text-[#6B8E5A] border border-[#6B8E5A]/20 text-xs font-extrabold rounded-lg cursor-pointer hover:bg-[#6B8E5A] hover:text-white">
                      <span>Pilih File Gambar</span>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleSimulateUpload(e, (url) => setFormPortfolio({ ...formPortfolio, imageUrl: url }))}
                        className="hidden"
                      />
                    </label>
                    {formPortfolio.imageUrl && (
                      <div className="mt-4 flex items-center gap-3 p-2 bg-gray-50 rounded-xl border border-gray-100">
                        <img src={formPortfolio.imageUrl} alt="Preview" className="w-12 h-12 rounded-lg object-cover" />
                        <span className="text-[10px] text-gray-500 font-mono truncate flex-1 text-left">{formPortfolio.imageUrl}</span>
                      </div>
                    )}
                  </div>
                </div>

                <div className="flex items-center">
                  <input
                    id="is-highlight"
                    type="checkbox"
                    checked={formPortfolio.isHighlight}
                    onChange={(e) => setFormPortfolio({ ...formPortfolio, isHighlight: e.target.checked })}
                    className="h-4 w-4 text-[#6B8E5A] focus:ring-[#6B8E5A] border-gray-300 rounded cursor-pointer"
                  />
                  <label htmlFor="is-highlight" className="ml-2 block text-xs font-semibold text-gray-700 cursor-pointer select-none">
                    Tampilkan sebagai Highlight Unggulan di Halaman Utama (Featured)
                  </label>
                </div>

                <div className="pt-4 border-t border-gray-100 flex items-center justify-end gap-2">
                  <button
                    type="button"
                    onClick={() => setIsModalOpen(false)}
                    className="px-4 py-2 bg-gray-100 text-gray-600 rounded-xl font-bold text-xs"
                  >
                    Batal
                  </button>
                  <button
                    type="submit"
                    className="px-5 py-2.5 bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white font-bold text-xs rounded-xl shadow-md"
                  >
                    Simpan Portofolio
                  </button>
                </div>
              </form>
            )}

            {/* FORM: ADD/EDIT SERVICE */}
            {(modalType === 'add_service' || modalType === 'edit_service') && (
              <form onSubmit={handleSaveService} className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Nama Layanan *</label>
                    <input
                      type="text"
                      required
                      value={formService.title}
                      onChange={(e) => setFormService({ ...formService, title: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                      placeholder="Contoh: Pembuatan Taman Vertikal"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Kategori Jasa *</label>
                    <select
                      value={formService.category}
                      onChange={(e) => setFormService({ ...formService, category: e.target.value as any })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] bg-white cursor-pointer"
                    >
                      <option value="wedding">Wedding Decoration</option>
                      <option value="landscape">Landscape & Garden</option>
                    </select>
                  </div>
                </div>

                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Deskripsi Singkat</label>
                  <input
                    type="text"
                    value={formService.shortDesc}
                    onChange={(e) => setFormService({ ...formService, shortDesc: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                  />
                </div>

                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Deskripsi Detail Lengkap</label>
                  <textarea
                    rows={3}
                    value={formService.fullDesc}
                    onChange={(e) => setFormService({ ...formService, fullDesc: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                  />
                </div>

                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Fitur / Spesifikasi Jasa (Pisahkan dengan baris baru)</label>
                  <textarea
                    rows={3}
                    value={formService.features?.join('\n')}
                    onChange={(e) => setFormService({ ...formService, features: e.target.value.split('\n') })}
                    className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] text-xs font-mono"
                    placeholder="Contoh:&#10;Sistem penyiraman otomatis&#10;Bunga segar berkualitas"
                  />
                </div>

                <div className="pt-4 border-t border-gray-100 flex items-center justify-end gap-2">
                  <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 bg-gray-100 rounded-xl font-bold text-xs text-gray-600">
                    Batal
                  </button>
                  <button type="submit" className="px-5 py-2.5 bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white font-bold text-xs rounded-xl shadow-md">
                    Simpan Layanan
                  </button>
                </div>
              </form>
            )}

            {/* FORM: ADD/EDIT TESTIMONIAL */}
            {(modalType === 'add_testimonial' || modalType === 'edit_testimonial') && (
              <form onSubmit={handleSaveTestimonial} className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Nama Pelanggan / Klien *</label>
                    <input
                      type="text"
                      required
                      value={formTestimonial.name}
                      onChange={(e) => setFormTestimonial({ ...formTestimonial, name: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                      placeholder="Contoh: Rendi & Maya"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Jabatan / Pekerjaan / Asal *</label>
                    <input
                      type="text"
                      value={formTestimonial.role}
                      onChange={(e) => setFormTestimonial({ ...formTestimonial, role: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                      placeholder="Contoh: Mempelai Pengantin - Depok"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Jenis Proyek Dekorasi *</label>
                    <input
                      type="text"
                      value={formTestimonial.projectType}
                      onChange={(e) => setFormTestimonial({ ...formTestimonial, projectType: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                      placeholder="Contoh: Intimate Garden Wedding"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Rating Bintang (1-5) *</label>
                    <select
                      value={formTestimonial.rating}
                      onChange={(e) => setFormTestimonial({ ...formTestimonial, rating: Number(e.target.value) })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] bg-white cursor-pointer"
                    >
                      <option value="5">⭐⭐⭐⭐⭐ 5 Bintang</option>
                      <option value="4">⭐⭐⭐⭐ 4 Bintang</option>
                      <option value="3">⭐⭐⭐ 3 Bintang</option>
                    </select>
                  </div>
                </div>

                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Isi Komentar Ulasan *</label>
                  <textarea
                    rows={4}
                    required
                    value={formTestimonial.comment}
                    onChange={(e) => setFormTestimonial({ ...formTestimonial, comment: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                    placeholder="Tulis ulasan klien di sini..."
                  />
                </div>

                <div className="pt-4 border-t border-gray-100 flex items-center justify-end gap-2">
                  <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 bg-gray-100 rounded-xl font-bold text-xs text-gray-600">
                    Batal
                  </button>
                  <button type="submit" className="px-5 py-2.5 bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white font-bold text-xs rounded-xl shadow-md">
                    Simpan Testimoni
                  </button>
                </div>
              </form>
            )}

            {/* FORM: ADD/EDIT TEAM */}
            {(modalType === 'add_team' || modalType === 'edit_team') && (
              <form onSubmit={handleSaveTeam} className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Nama Personel *</label>
                    <input
                      type="text"
                      required
                      value={formTeam.name}
                      onChange={(e) => setFormTeam({ ...formTeam, name: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-xs font-bold text-gray-700">Jabatan / Role Ahli *</label>
                    <input
                      type="text"
                      required
                      value={formTeam.role}
                      onChange={(e) => setFormTeam({ ...formTeam, role: e.target.value })}
                      className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A]"
                      placeholder="Contoh: Senior Floral Designer"
                    />
                  </div>
                </div>

                <div className="space-y-1">
                  <label className="text-xs font-bold text-gray-700">Pengalaman / Bio Singkat</label>
                  <textarea
                    rows={3}
                    value={formTeam.experience}
                    onChange={(e) => setFormTeam({ ...formTeam, experience: e.target.value })}
                    className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#6B8E5A] text-xs"
                  />
                </div>

                <div className="pt-4 border-t border-gray-100 flex items-center justify-end gap-2">
                  <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 bg-gray-100 rounded-xl font-bold text-xs text-gray-600">
                    Batal
                  </button>
                  <button type="submit" className="px-5 py-2.5 bg-[#6B8E5A] hover:bg-[#5A7B4A] text-white font-bold text-xs rounded-xl shadow-md">
                    Simpan Personel
                  </button>
                </div>
              </form>
            )}

            {/* VIEW MODAL: CONTACT MESSAGE DETAIL */}
            {modalType === 'view_message' && selectedItem && (
              <div className="space-y-6">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 bg-gray-50 p-4 rounded-2xl border border-gray-100">
                  <div className="text-xs">
                    <span className="text-gray-400 font-bold uppercase block mb-1">Nama Calon Klien:</span>
                    <span className="text-sm font-extrabold text-gray-900">{selectedItem.name}</span>
                  </div>
                  <div className="text-xs">
                    <span className="text-gray-400 font-bold uppercase block mb-1">Pilihan Layanan:</span>
                    <span className="text-sm font-extrabold text-gray-900">{selectedItem.serviceType}</span>
                  </div>
                  <div className="text-xs">
                    <span className="text-gray-400 font-bold uppercase block mb-1">Nomor WhatsApp:</span>
                    <span className="text-sm font-extrabold text-[#6B8E5A] font-mono">{selectedItem.whatsapp}</span>
                  </div>
                  <div className="text-xs">
                    <span className="text-gray-400 font-bold uppercase block mb-1">Waktu Masuk:</span>
                    <span className="text-sm font-medium text-gray-800">
                      {new Date(selectedItem.date).toLocaleString('id-ID', { dateStyle: 'long', timeStyle: 'short' })}
                    </span>
                  </div>
                </div>

                <div className="space-y-2">
                  <span className="text-xs font-bold text-gray-400 uppercase">Pesan / Isi Permintaan Konsultasi:</span>
                  <div className="p-4 bg-gray-950 text-gray-200 font-sans text-xs sm:text-sm rounded-2xl leading-relaxed whitespace-pre-wrap border border-gray-900">
                    {selectedItem.message || '(Tidak menulis isi pesan)'}
                  </div>
                </div>

                <div className="pt-4 border-t border-gray-100 flex items-center justify-between gap-4">
                  <div className="flex gap-2">
                    <button
                      onClick={() => {
                        updateMessageStatus(selectedItem.id, 'Replied');
                        showToast('Pesan ditandai sudah dibalas', 'success');
                        setIsModalOpen(false);
                      }}
                      className="px-4 py-2 bg-green-50 text-green-700 hover:bg-green-600 hover:text-white rounded-xl text-xs font-bold flex items-center gap-1.5 cursor-pointer"
                    >
                      <Check className="w-4 h-4" />
                      <span>Tandai Dibalas</span>
                    </button>
                    
                    <a
                      href={`https://wa.me/${selectedItem.whatsapp.replace(/[^0-9]/g, '')}?text=Halo%20${encodeURIComponent(selectedItem.name)}%20dari%20Tukang%20Dekorasi%20di%20sini...`}
                      target="_blank"
                      rel="noreferrer"
                      className="px-4 py-2 bg-[#25D366] text-white rounded-xl text-xs font-bold flex items-center gap-1.5 shadow-md"
                    >
                      <Phone className="w-4 h-4" />
                      <span>Balas Via WhatsApp</span>
                    </a>
                  </div>

                  <button
                    onClick={() => setIsModalOpen(false)}
                    className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl font-bold text-xs cursor-pointer"
                  >
                    Tutup
                  </button>
                </div>
              </div>
            )}

          </div>
        </div>
      )}

      {/* ----------------- CORE CONFIRMATION MODALS ----------------- */}
      {confirmModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm" onClick={() => setConfirmModal(null)}></div>
          <div className="relative bg-white p-6 rounded-3xl max-w-sm w-full z-10 text-center space-y-5 border border-gray-100 shadow-2xl animate-scaleIn">
            <div className="w-12 h-12 rounded-full bg-red-50 text-red-600 flex items-center justify-center mx-auto">
              <Trash2 className="w-6 h-6" />
            </div>
            <div className="space-y-1">
              <h4 className="font-extrabold text-gray-900 text-lg leading-tight">{confirmModal.title}</h4>
              <p className="text-xs text-gray-500 leading-relaxed">{confirmModal.desc}</p>
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setConfirmModal(null)}
                className="flex-1 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold text-xs"
              >
                Batal
              </button>
              <button
                onClick={confirmModal.onConfirm}
                className="flex-1 py-2.5 rounded-xl bg-red-600 hover:bg-red-700 text-white font-bold text-xs shadow-md shadow-red-600/10"
              >
                Hapus Sekarang
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
};
