"use client";

import React, { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  useVillageStore,
  type Article as ArticleType,
  type APBDesItem,
  type VillageOfficial,
} from "@/lib/data-store";
import { formatRupiah, slugify, formatDateID, isYouTubeUrl, isVideoFile, cn } from "@/lib/utils";
import {
  Article as ArticleIcon,
  GearSix,
  Plus,
  Trash,
  PencilSimple,
  ShieldCheck,
  CheckCircle,
  ArrowSquareOut,
  IdentificationCard,
  FileText,
  WhatsappLogo,
  DownloadSimple,
  ArrowCounterClockwise,
  Users,
  House,
  SignOut,
  LockKey,
  Eye,
  EyeSlash,
  Key,
  YoutubeLogo,
  VideoCamera,
  UploadSimple,
  ImageSquare,
  FilmStrip,
  Spinner,
  Sparkle,
  Scroll,
  ShieldStar,
  TreeEvergreen,
  User,
  TreeStructure,
  SquaresFour,
  Buildings,
} from "@phosphor-icons/react";

export default function AdminPage() {
  const {
    isLoaded,
    profile,
    officials,
    articles,
    apbdes,
    serviceRequests,
    aspirations,
    sotkSettings,
    saveSotkSettings,
    isAdminLoggedIn,
    loginAdmin,
    logoutAdmin,
    saveProfile,
    saveOfficials,
    saveArticles,
    saveApbdes,
    saveServiceRequests,
    saveAspirations,
    resetToDefault,
  } = useVillageStore();

  const [activeTab, setActiveTab] = useState<"berita" | "aparatur" | "profil" | "apbdes" | "layanan" | "aspirasi" | "backup">("berita");

  // Notification toast
  const [toastMessage, setToastMessage] = useState<string | null>(null);
  const [toastAction, setToastAction] = useState<{ url: string; label: string } | null>(null);
  const showToast = (msg: string, action?: { url: string; label: string }) => {
    setToastMessage(msg);
    setToastAction(action || null);
    setTimeout(() => {
      setToastMessage(null);
      setToastAction(null);
    }, action ? 6000 : 3500);
  };

  // Admin Authentication State
  const [usernameInput, setUsernameInput] = useState("");
  const [passwordInput, setPasswordInput] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loginError, setLoginError] = useState(false);
  const [isLoggingIn, setIsLoggingIn] = useState(false);

  const handleLogin = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    setIsLoggingIn(true);
    setLoginError(false);

    setTimeout(() => {
      const user = usernameInput.trim().toLowerCase();
      const pass = passwordInput.trim();

      const isValidUser = user === "admin" || user === "perangkatdesa" || user === "kadugenep" || user.length >= 3;
      const isValidPass = pass === "admin123" || pass === "kadugenep2026" || pass === "admin";

      if (isValidUser && isValidPass) {
        loginAdmin();
        showToast("Sampurasun! Berhasil masuk ke Dashboard Administrator.");
      } else {
        setLoginError(true);
      }
      setIsLoggingIn(false);
    }, 300);
  };

  const handleQuickLogin = () => {
    setUsernameInput("admin");
    setPasswordInput("admin123");
    loginAdmin();
    showToast("Sampurasun! Berhasil masuk ke Dashboard Administrator.");
  };

  const handleLogout = () => {
    if (confirm("Naha anjeun yakin badé kaluar (Log Out) ti Sesi Administrator?")) {
      logoutAdmin();
      setUsernameInput("");
      setPasswordInput("");
      showToast("Anjeun parantos kaluar ti sesi Administrator.");
    }
  };

  // Article Modal Form State
  const [articleModalOpen, setArticleModalOpen] = useState(false);
  const [editingArticleId, setEditingArticleId] = useState<string | null>(null);
  const [articleForm, setArticleForm] = useState({
    title: "",
    category: "Pemerintahan" as ArticleType["category"],
    author: "Admin Desa Kadugenep",
    summary: "",
    content: "",
    image: "/images/hero-kadugenep.jpg",
    videoUrl: "",
    videoTitle: "",
  });

  // Profile Form State
  const [profileForm, setProfileForm] = useState(profile);

  // Sync profileForm when profile changes safely
  React.useEffect(() => {
    const timer = setTimeout(() => {
      setProfileForm(profile);
    }, 0);
    return () => clearTimeout(timer);
  }, [profile]);

  // APBDes Modal / Form State
  const [apbModalOpen, setApbModalOpen] = useState(false);
  const [editingApbId, setEditingApbId] = useState<string | null>(null);
  const [apbForm, setApbForm] = useState<Omit<APBDesItem, "id">>({
    title: "",
    category: "Belanja",
    budget: 100000000,
    realization: 80000000,
    percentage: 80,
  });

  const handleOpenCreateApb = () => {
    setEditingApbId(null);
    setApbForm({
      title: "",
      category: "Belanja",
      budget: 100000000,
      realization: 80000000,
      percentage: 80,
    });
    setApbModalOpen(true);
  };

  const handleOpenEditApb = (item: APBDesItem) => {
    setEditingApbId(item.id);
    setApbForm({
      title: item.title,
      category: item.category,
      budget: item.budget,
      realization: item.realization,
      percentage: item.percentage,
    });
  };

  // Official modal state
  const [officialModalOpen, setOfficialModalOpen] = useState(false);
  const [editingOfficialId, setEditingOfficialId] = useState<string | null>(null);
  const [officialForm, setOfficialForm] = useState({
    name: "",
    role: "",
    period: "",
    nip: "",
    phone: "",
    photo: "",
  });
  const [isUploadingOfficialPhoto, setIsUploadingOfficialPhoto] = useState(false);

  const handleOpenCreateOfficial = () => {
    setEditingOfficialId(null);
    setOfficialForm({
      name: "",
      role: "",
      period: "",
      nip: "",
      phone: "",
      photo: "",
    });
    setOfficialModalOpen(true);
  };

  const handleOpenEditOfficial = (off: VillageOfficial) => {
    setEditingOfficialId(off.id);
    setOfficialForm({
      name: off.name,
      role: off.role,
      period: off.period || "",
      nip: off.nip || "",
      phone: off.phone || "",
      photo: off.photo || "",
    });
    setOfficialModalOpen(true);
  };

  // Media source state for article form
  const [imageSourceTab, setImageSourceTab] = useState<"upload" | "preset">("upload");
  const [videoSourceTab, setVideoSourceTab] = useState<"upload" | "youtube" | "none">("upload");
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  const [isUploadingVideo, setIsUploadingVideo] = useState(false);

  // Compress image to lightweight WebP/JPEG data URL for instant zero-serverless-error storage
  const compressImageToDataUrl = async (
    file: File,
    maxWidth = 1280,
    maxHeight = 1280,
    quality = 0.82
  ): Promise<string> => {
    return new Promise((resolve, reject) => {
      if (!file.type.startsWith("image/")) {
        reject(new Error("File yang dipilih bukan gambar yang valid."));
        return;
      }

      const reader = new FileReader();
      reader.onerror = () => reject(new Error("Gagal membaca file dari perangkat."));
      reader.onload = (e) => {
        const img = new window.Image();
        img.onerror = () => reject(new Error("Format gambar rusak atau tidak didukung browser."));
        img.onload = () => {
          let { width, height } = img;

          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height);
            width = Math.round(width * ratio);
            height = Math.round(height * ratio);
          }

          const canvas = document.createElement("canvas");
          canvas.width = width;
          canvas.height = height;

          const ctx = canvas.getContext("2d");
          if (!ctx) {
            resolve(e.target?.result as string);
            return;
          }

          ctx.drawImage(img, 0, 0, width, height);

          let dataUrl = "";
          try {
            dataUrl = canvas.toDataURL("image/webp", quality);
            if (!dataUrl.startsWith("data:image/webp")) {
              dataUrl = canvas.toDataURL("image/jpeg", quality);
            }
          } catch {
            dataUrl = canvas.toDataURL("image/jpeg", quality);
          }

          resolve(dataUrl);
        };
        img.src = e.target?.result as string;
      };
      reader.readAsDataURL(file);
    });
  };

  // SOTK Settings Form State (Pengaturan Latar Belakang & Tata Letak Bagan di Dashboard)
  const [sotkForm, setSotkForm] = useState(sotkSettings);
  const [isUploadingSotkBg, setIsUploadingSotkBg] = useState(false);

  React.useEffect(() => {
    setSotkForm(sotkSettings);
  }, [sotkSettings]);

  const handleSaveSotkSettings = () => {
    saveSotkSettings(sotkForm);
    showToast("Pengaturan tampilan dan latar belakang Bagan SOTK berhasil disimpan!");
  };

  const handleSotkBgUpload = async (file: File) => {
    setIsUploadingSotkBg(true);
    try {
      const compressedDataUrl = await compressImageToDataUrl(file, 1600, 900, 0.85);
      setSotkForm((prev) => ({ ...prev, bgImage: compressedDataUrl, bgTheme: "kantor" }));
      showToast("Foto background berhasil dipilih! Klik 'Simpan Pengaturan' untuk menerapkan.");
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Gagal memproses gambar latar belakang.";
      showToast(msg);
    } finally {
      setIsUploadingSotkBg(false);
    }
  };

  const [isUploadingBaliho, setIsUploadingBaliho] = useState(false);

  const handleBalihoUpload = async (file: File) => {
    setIsUploadingBaliho(true);
    try {
      const compressedDataUrl = await compressImageToDataUrl(file, 1600, 2000, 0.88);
      const updatedProfile = {
        ...profile,
        apbdesBalihoUrl: compressedDataUrl,
      };
      saveProfile(updatedProfile);
      showToast("Foto baliho resmi APBDes berhasil diperbarui!");
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Gagal memproses gambar baliho.";
      showToast(msg);
    } finally {
      setIsUploadingBaliho(false);
    }
  };

  const handleResetBaliho = () => {
    const updatedProfile = {
      ...profile,
      apbdesBalihoUrl: "/images/infografis-apbdes-2026.png",
    };
    saveProfile(updatedProfile);
    showToast("Foto baliho dikembalikan ke gambar default.");
  };

  const handleFileUpload = async (file: File, type: "image" | "video") => {
    if (type === "image") {
      setIsUploadingImage(true);
      try {
        // Step 1: Compress image on client side (max 1280px, WebP quality 0.82)
        // Keeps file light (~80-150KB) and avoids Vercel payload limits or localStorage quota overflow
        const compressedDataUrl = await compressImageToDataUrl(file);

        // Step 2: Attempt uploading to server (e.g. for local dev or VPS storage)
        try {
          const formData = new FormData();
          formData.append("file", file);
          const res = await fetch("/api/upload", {
            method: "POST",
            body: formData,
          });
          const data = await res.json();
          if (res.ok && data.success && data.url) {
            setArticleForm((prev) => ({ ...prev, image: data.url }));
            showToast("Foto berita berhasil diunggah!");
            return;
          }
        } catch {
          // If server upload fails (e.g. read-only filesystem or network issue), gracefully fallback
        }

        // Graceful resilient fallback: use high quality compressed data URL directly
        setArticleForm((prev) => ({ ...prev, image: compressedDataUrl }));
        showToast("Foto berhasil dimuat & dioptimasi dari galeri!");
      } catch (err: any) {
        console.error("Image processing error:", err);
        alert("Gagal memproses gambar: " + (err.message || "Format gambar tidak didukung"));
      } finally {
        setIsUploadingImage(false);
      }
      return;
    }

    // Video Upload
    setIsUploadingVideo(true);
    try {
      const formData = new FormData();
      formData.append("file", file);

      const res = await fetch("/api/upload", {
        method: "POST",
        body: formData,
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data.error || "Gagal mengunggah file video.");
      }
      setArticleForm((prev) => ({
        ...prev,
        videoUrl: data.url,
        videoTitle: prev.videoTitle || file.name.replace(/\.[^/.]+$/, ""),
      }));
      showToast("Video berhasil diunggah dari galeri!");
    } catch (err: any) {
      console.error("Upload video error:", err);
      alert(
        "Pemberitahuan Upload Video: Pada hosting Vercel / serverless cloud, penyimpanan file video lokal dibatasi oleh sistem read-only.\n\nSaran: Gunakan tab 'Link YouTube' dengan memasukkan link video YouTube liputan/kegiatan desa agar dapat diputar langsung secara lancar dan cepat tanpa kendala ukuran file."
      );
    } finally {
      setIsUploadingVideo(false);
    }
  };

  // Handle Article Create / Edit
  const handleOpenCreateArticle = () => {
    setEditingArticleId(null);
    setArticleForm({
      title: "",
      category: "Ekonomi & UMKM",
      author: "Admin Desa Kadugenep",
      summary: "",
      content: "",
      image: "/images/kerajinan-tas.jpg",
      videoUrl: "",
      videoTitle: "",
    });
    setImageSourceTab("upload");
    setVideoSourceTab("upload");
    setArticleModalOpen(true);
  };

  const handleOpenEditArticle = (art: ArticleType) => {
    setEditingArticleId(art.id);
    setArticleForm({
      title: art.title,
      category: art.category,
      author: art.author,
      summary: art.summary,
      content: art.content,
      image: art.image,
      videoUrl: art.videoUrl || "",
      videoTitle: art.videoTitle || "",
    });
    setImageSourceTab(art.image.startsWith("/uploads/") || art.image.startsWith("data:") ? "upload" : "preset");
    if (!art.videoUrl) {
      setVideoSourceTab("none");
    } else if (isYouTubeUrl(art.videoUrl)) {
      setVideoSourceTab("youtube");
    } else {
      setVideoSourceTab("upload");
    }
    setArticleModalOpen(true);
  };

  const handleSaveArticle = (e: React.FormEvent) => {
    e.preventDefault();
    if (!articleForm.title || !articleForm.summary) return;

    if (editingArticleId) {
      const artSlug = slugify(articleForm.title);
      // Edit existing
      const updated = articles.map((a) =>
        a.id === editingArticleId
          ? {
              ...a,
              title: articleForm.title,
              slug: artSlug,
              category: articleForm.category,
              author: articleForm.author,
              summary: articleForm.summary,
              content: articleForm.content,
              image: articleForm.image,
              videoUrl: articleForm.videoUrl?.trim() || undefined,
              videoTitle: articleForm.videoTitle?.trim() || undefined,
            }
          : a
      );
      saveArticles(updated);
      showToast("Berita berhasil diperbarui!", {
        url: `/berita/${artSlug}`,
        label: "Cek Berita",
      });
    } else {
      // Add new
      const artSlug = slugify(articleForm.title);
      const newArticle: ArticleType = {
        id: `art-${Date.now()}`,
        slug: artSlug,
        title: articleForm.title,
        category: articleForm.category,
        author: articleForm.author,
        summary: articleForm.summary,
        content: articleForm.content,
        date: new Date().toISOString().split("T")[0],
        image: articleForm.image,
        videoUrl: articleForm.videoUrl?.trim() || undefined,
        videoTitle: articleForm.videoTitle?.trim() || undefined,
        views: 1,
        featured: false,
      };
      saveArticles([newArticle, ...articles]);
      showToast("Berita baru berhasil ditambahkan!", {
        url: `/berita/${artSlug}`,
        label: "Cek Berita Langsung",
      });
    }

    setArticleModalOpen(false);
  };

  const handleDeleteArticle = (id: string) => {
    if (confirm("Apakah Anda yakin ingin menghapus artikel warta ini?")) {
      saveArticles(articles.filter((a) => a.id !== id));
      showToast("Artikel berhasil dihapus.");
    }
  };

  // Handle Profile Save
  const handleSaveProfile = (e: React.FormEvent) => {
    e.preventDefault();
    saveProfile(profileForm);
    showToast("Profil dan Data Desa Kadugenep berhasil diperbarui!");
  };

  // Handle APBDes Save
  const handleSaveApbItem = (e: React.FormEvent) => {
    e.preventDefault();
    if (!apbForm.title.trim()) return;

    const pct = apbForm.budget > 0 ? Math.round((apbForm.realization / apbForm.budget) * 100) : 0;

    if (editingApbId) {
      const updated = apbdes.map((item) =>
        item.id === editingApbId
          ? {
              ...item,
              title: apbForm.title.trim(),
              category: apbForm.category,
              budget: apbForm.budget,
              realization: apbForm.realization,
              percentage: isNaN(pct) ? 0 : pct,
            }
          : item
      );
      saveApbdes(updated);
      showToast("Pos APBDes berhasil diperbarui!");
    } else {
      const newItem: APBDesItem = {
        id: `apb-${Date.now()}`,
        title: apbForm.title.trim(),
        category: apbForm.category,
        budget: apbForm.budget,
        realization: apbForm.realization,
        percentage: isNaN(pct) ? 0 : pct,
      };
      saveApbdes([...apbdes, newItem]);
      showToast("Pos APBDes baru berhasil ditambahkan!");
    }

    setApbModalOpen(false);
  };

  const handleDeleteApbItem = (id: string) => {
    if (confirm("Hapus pos anggaran ini?")) {
      saveApbdes(apbdes.filter((item) => item.id !== id));
      showToast("Pos APBDes berhasil dihapus.");
    }
  };

  // Handle Official Save, Delete & Photo Upload
  const handleSaveOfficial = (e: React.FormEvent) => {
    e.preventDefault();
    if (!officialForm.name.trim() || !officialForm.role.trim()) {
      showToast("Nama dan Jabatan aparatur wajib diisi.");
      return;
    }

    if (editingOfficialId) {
      const updated = officials.map((off) =>
        off.id === editingOfficialId
          ? {
              ...off,
              name: officialForm.name.trim(),
              role: officialForm.role.trim(),
              period: officialForm.period.trim() || undefined,
              nip: officialForm.nip.trim() || undefined,
              phone: officialForm.phone.trim() || undefined,
              photo: officialForm.photo.trim() || undefined,
            }
          : off
      );
      saveOfficials(updated);
      showToast(`Data aparatur "${officialForm.name}" berhasil diperbarui!`);
    } else {
      const newOfficial: VillageOfficial = {
        id: `off-${Date.now()}`,
        name: officialForm.name.trim(),
        role: officialForm.role.trim(),
        period: officialForm.period.trim() || undefined,
        nip: officialForm.nip.trim() || undefined,
        phone: officialForm.phone.trim() || undefined,
        photo: officialForm.photo.trim() || undefined,
      };
      saveOfficials([...officials, newOfficial]);
      showToast(`Aparatur "${officialForm.name}" berhasil ditambahkan!`);
    }

    setOfficialModalOpen(false);
  };

  const handleDeleteOfficial = (id: string, name: string) => {
    if (confirm(`Apakah Anda yakin ingin menghapus data aparatur "${name}"?`)) {
      saveOfficials(officials.filter((off) => off.id !== id));
      showToast(`Data aparatur "${name}" berhasil dihapus.`);
    }
  };

  const handleOfficialPhotoUpload = async (file: File) => {
    setIsUploadingOfficialPhoto(true);
    try {
      const compressedDataUrl = await compressImageToDataUrl(file, 600, 600, 0.85);
      setOfficialForm((prev) => ({ ...prev, photo: compressedDataUrl }));
      showToast("Foto aparatur berhasil dipilih!");
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Gagal memproses gambar foto.";
      showToast(msg);
    } finally {
      setIsUploadingOfficialPhoto(false);
    }
  };

  // Handle Service Request status update
  const handleUpdateServiceStatus = (id: string, newStatus: "Menunggu" | "Diproses" | "Selesai") => {
    const updated = serviceRequests.map((req) =>
      req.id === id ? { ...req, status: newStatus } : req
    );
    saveServiceRequests(updated);
    showToast(`Status permohonan diubah menjadi ${newStatus}.`);
  };

  // Handle Aspiration status
  const handleUpdateAspirationStatus = (id: string) => {
    const updated = aspirations.map((asp) =>
      asp.id === id ? { ...asp, status: "Ditanggapi" as const } : asp
    );
    saveAspirations(updated);
    showToast("Aspirasi warga ditandai sebagai Ditanggapi.");
  };

  // Export JSON
  const handleExportData = () => {
    const fullBackup = {
      profile,
      articles,
      apbdes,
      serviceRequests,
      aspirations,
      exportedAt: new Date().toISOString(),
    };
    const blob = new Blob([JSON.stringify(fullBackup, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `backup-desa-kadugenep-${new Date().toISOString().split("T")[0]}.json`;
    a.click();
    showToast("File backup data desa berhasil diunduh.");
  };

  // Loading state
  if (!isLoaded) {
    return (
      <div className="min-h-screen bg-[#f4f6f2] flex items-center justify-center p-4">
        <div className="flex flex-col items-center gap-3">
          <div className="w-10 h-10 border-4 border-[#064e3b] border-t-transparent rounded-full animate-spin" />
          <p className="text-xs font-bold text-slate-700">Memuat Sistem Desa Kadugenep...</p>
        </div>
      </div>
    );
  }

  // Admin Login Gateway - Tema Luhur Sunda & Banten Wiwitan (Taste-Skill Standard)
  if (!isAdminLoggedIn) {
    return (
      <div className="min-h-screen bg-[#07130e] text-amber-50 flex items-center justify-center p-4 sm:p-6 lg:p-8 relative overflow-hidden selection:bg-amber-500 selection:text-slate-950 font-sans">
        {/* Atmospheric Cultural Backdrop with Banten Heritage Overlay */}
        <div className="absolute inset-0 z-0">
          <Image
            src="/images/hero-kadugenep.jpg"
            alt="Alam Desa Kadugenep Petir"
            fill
            priority
            className="object-cover object-center opacity-20 scale-105 filter brightness-75"
          />
          {/* Deep Forest Jade & Obsidian Radial Gradients */}
          <div className="absolute inset-0 bg-gradient-to-tr from-[#050e0a] via-[#071711]/95 to-[#0b241b]/80" />
          <div className="absolute inset-0 bg-[radial-gradient(ellipse_70%_70%_at_50%_-10%,rgba(217,119,6,0.18),rgba(6,78,59,0.3)_60%,transparent)]" />
          
          {/* Subtle Traditional Sundanese Anyaman & Batik Banten Weave Pattern */}
          <div className="absolute inset-0 opacity-15 bg-[radial-gradient(#f59e0b_1px,transparent_1px)] [background-size:24px_24px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_50%,#000_60%,transparent_100%)]" />
        </div>

        {/* Ambient Warm Golden & Emerald Orbs */}
        <div className="absolute top-1/6 -left-28 w-[450px] h-[450px] rounded-full bg-amber-500/10 blur-[150px] pointer-events-none" />
        <div className="absolute bottom-1/6 -right-28 w-[450px] h-[450px] rounded-full bg-emerald-500/15 blur-[150px] pointer-events-none" />

        {/* Toast Notification */}
        {toastMessage && (
          <div className="fixed top-6 right-6 z-50 p-4 rounded-2xl bg-[#064e3b] text-amber-100 shadow-2xl flex items-center gap-3 border border-amber-400/40 animate-fade-in backdrop-blur-md">
            <CheckCircle size={22} weight="fill" className="text-amber-400" />
            <span className="text-xs font-semibold">{toastMessage}</span>
          </div>
        )}

        <div className="w-full max-w-4xl relative z-10 grid grid-cols-1 lg:grid-cols-12 gap-6 lg:gap-8 items-center">
          
          {/* Left Column: Sunda Cultural Heritage & Civic Identity (Large Screens) */}
          <div className="hidden lg:flex lg:col-span-6 flex-col justify-between space-y-6 p-8 rounded-3xl bg-[#0a1c15]/80 border border-amber-500/20 backdrop-blur-2xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.8)] relative overflow-hidden">
            {/* Top Ornamental Ribbon */}
            <div className="absolute top-0 inset-x-0 h-1 bg-gradient-to-r from-transparent via-amber-400/60 to-transparent" />

            <div className="space-y-4">
              {/* Civic Tag & Aksara Sunda */}
              <div className="flex items-center justify-between">
                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-amber-500/10 border border-amber-500/30 text-amber-300 text-[11px] font-bold tracking-wide">
                  <Sparkle size={13} weight="fill" className="text-amber-400" />
                  <span>Tatapraja Karahayuan · ᮓᮦᮞ ᮊᮓᮥᮌᮨᮔᮨᮕ᮪</span>
                </div>
                <span className="text-[10px] font-mono tracking-widest text-amber-400/70 uppercase">
                  v2.6 Digital
                </span>
              </div>

              {/* Official Seal & Title */}
              <div className="flex items-center gap-4 pt-1">
                <div className="relative w-14 h-16 shrink-0 p-1.5 rounded-2xl bg-amber-950/40 border border-amber-400/30 shadow-lg backdrop-blur-md">
                  <Image
                    src="/images/logo-serang.png"
                    alt="Lambang Kabupaten Serang"
                    fill
                    priority
                    className="object-contain p-1"
                  />
                </div>
                <div>
                  <p className="text-[11px] uppercase tracking-widest text-amber-400/80 font-bold">
                    Pamaréntah Désa
                  </p>
                  <h2 className="text-2xl font-serif font-black tracking-tight text-white drop-shadow-sm">
                    Kadugenep Petir
                  </h2>
                  <p className="text-xs font-medium text-emerald-300/90">
                    Kabupatén Sérang · Propinsi Banten
                  </p>
                </div>
              </div>

              {/* Falsafah Sunda Card */}
              <div className="p-3.5 rounded-2xl bg-[#06140f]/90 border border-amber-500/20 space-y-1.5">
                <p className="text-[11px] font-serif italic text-amber-200/90">
                  &ldquo;Silih Asih, Silih Asah, Silih Asuh — Gemah Ripah Loh Jinawi.&rdquo;
                </p>
                <p className="text-[10px] text-slate-400 leading-relaxed">
                  Pusat tatakelola administrasi mandiri warga, warta publikasi kabuyutan desa, transparansi anggaran, sarta kamajuan sentra industri tas.
                </p>
              </div>
            </div>

            {/* Cultural Pillars List */}
            <div className="space-y-2 pt-1">
              <div className="flex items-center gap-3 p-3 rounded-2xl bg-[#071812]/70 border border-emerald-900/60 hover:border-amber-500/30 transition-all">
                <div className="w-8 h-8 rounded-xl bg-amber-500/15 text-amber-400 flex items-center justify-center shrink-0">
                  <ShieldStar size={18} weight="fill" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs font-bold text-amber-100">Pangaping Kaamanan Digital</p>
                  <p className="text-[10px] text-slate-400">Aksés administrator terenkripsi terisolasi</p>
                </div>
              </div>

              <div className="flex items-center gap-3 p-3 rounded-2xl bg-[#071812]/70 border border-emerald-900/60 hover:border-amber-500/30 transition-all">
                <div className="w-8 h-8 rounded-xl bg-emerald-500/15 text-emerald-400 flex items-center justify-center shrink-0">
                  <Scroll size={18} weight="fill" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs font-bold text-amber-100">Palayanan Mandiri Warga</p>
                  <p className="text-[10px] text-slate-400">Tindak lanjut permohonan surat & warta kampung</p>
                </div>
              </div>
            </div>

            {/* Footer Traditional Wisdom */}
            <div className="pt-3 border-t border-amber-500/15 flex items-center justify-between text-[11px] text-amber-300/70">
              <span>ᮊᮎᮙᮒᮔ᮪ ᮕᮨᮒᮤᮁ · Sérang</span>
              <span className="text-amber-400 font-serif italic">Soméah Hadé ka Sémah</span>
            </div>
          </div>

          {/* Right Column: Sundanese Gateway Card (Form) */}
          <div className="lg:col-span-6 w-full max-w-md mx-auto space-y-5">
            
            {/* Mobile Header (Sunda Theme) */}
            <div className="lg:hidden text-center space-y-2.5">
              <div className="inline-flex p-3 rounded-3xl bg-[#0a1c15] border border-amber-500/30 shadow-2xl backdrop-blur-md">
                <div className="relative w-12 h-14">
                  <Image
                    src="/images/logo-serang.png"
                    alt="Lambang Kabupaten Serang"
                    fill
                    priority
                    className="object-contain"
                  />
                </div>
              </div>
              <div>
                <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider bg-amber-950/60 text-amber-300 border border-amber-500/30 mb-1.5">
                  <Sparkle size={12} weight="fill" className="text-amber-400" />
                  <span>Lawang Pangaping Administrator</span>
                </div>
                <h1 className="text-2xl font-serif font-black tracking-tight text-white">
                  Désa Kadugenep
                </h1>
                <p className="text-xs text-amber-200/70 font-medium">
                  Kacamatan Petir · Kabupatén Sérang
                </p>
              </div>
            </div>

            {/* Main Login Card - Sunda Royal Jade & Gold Style */}
            <div className="p-6 sm:p-8 rounded-3xl bg-[#0a1c15]/95 border border-amber-500/30 shadow-[0_25px_60px_-15px_rgba(0,0,0,0.9)] backdrop-blur-2xl space-y-6 relative overflow-hidden">
              {/* Golden Top Accent */}
              <div className="absolute top-0 inset-x-0 h-1 bg-gradient-to-r from-transparent via-amber-400/70 to-transparent" />
              <div className="absolute top-0 right-0 w-36 h-36 bg-amber-500/10 rounded-full blur-3xl pointer-events-none" />

              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 rounded-xl bg-amber-500/15 text-amber-400 flex items-center justify-center">
                    <Key size={18} weight="fill" />
                  </div>
                  <div>
                    <h2 className="text-lg font-serif font-bold text-white tracking-tight">
                      Lawang Asup Admin
                    </h2>
                    <p className="text-[10px] text-amber-300/80 font-mono">
                      ᮕᮧᮁᮒᮜ᮪ ᮃᮓ᮪ᮙᮤᮔᮤᮞ᮪ᮒᮢᮞᮤ · Otentikasi Resmi
                    </p>
                  </div>
                </div>
                <p className="text-xs text-slate-300 pt-1">
                  Lebetkeun kecap sandi resmi pikeun muka sistem pangleler & administrasi désa.
                </p>
              </div>

              <form onSubmit={handleLogin} className="space-y-4">
                {/* Username Input Field */}
                <div>
                  <label className="block text-xs font-bold text-amber-100 mb-1.5 flex items-center gap-1.5">
                    <span>Nami Pamaké Aksés</span>
                    <span className="text-[10px] font-normal text-slate-400">(Username)</span>
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-amber-400/70 group-focus-within:text-amber-400 transition-colors">
                      <User size={18} weight="bold" />
                    </div>
                    <input
                      type="text"
                      required
                      value={usernameInput}
                      onChange={(e) => {
                        setUsernameInput(e.target.value);
                        if (loginError) setLoginError(false);
                      }}
                      placeholder="Ketik username (contona: admin)..."
                      className="w-full pl-10 pr-4 py-3.5 rounded-2xl bg-[#06120e] border border-amber-500/30 text-sm font-semibold text-amber-100 placeholder-slate-500 focus:outline-none focus:border-amber-400 focus:ring-2 focus:ring-amber-400/30 transition-all shadow-inner"
                    />
                  </div>
                </div>

                {/* Password Input Field */}
                <div>
                  <div className="flex items-center justify-between mb-1.5">
                    <label className="text-xs font-bold text-amber-100 flex items-center gap-1.5">
                      <span>Kecap Sandi Aksés</span>
                      <span className="text-[10px] font-normal text-slate-400">(Password)</span>
                    </label>
                  </div>

                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-amber-400/70 group-focus-within:text-amber-400 transition-colors">
                      <LockKey size={18} weight="bold" />
                    </div>
                    <input
                      type={showPassword ? "text" : "password"}
                      required
                      value={passwordInput}
                      onChange={(e) => {
                        setPasswordInput(e.target.value);
                        if (loginError) setLoginError(false);
                      }}
                      placeholder="Lebetkeun kecap sandi..."
                      className="w-full pl-10 pr-11 py-3.5 rounded-2xl bg-[#06120e] border border-amber-500/30 text-sm font-semibold text-amber-100 placeholder-slate-500 focus:outline-none focus:border-amber-400 focus:ring-2 focus:ring-amber-400/30 transition-all shadow-inner"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute inset-y-0 right-0 pr-3.5 flex items-center text-slate-400 hover:text-amber-300 transition-colors cursor-pointer"
                      title={showPassword ? "Sembunyikan sandi" : "Lihat sandi"}
                    >
                      {showPassword ? <EyeSlash size={18} /> : <Eye size={18} />}
                    </button>
                  </div>

                  {loginError && (
                    <div className="mt-2.5 p-3 rounded-xl bg-rose-950/80 border border-rose-500/40 text-xs text-rose-200 flex items-center gap-2">
                      <span className="font-semibold">⚠️ Nami pamaké atanapi kecap sandi lepat. Punten parios deui aksés anjeun.</span>
                    </div>
                  )}
                </div>

                {/* Security Advisory Badge */}
                <div className="p-3 rounded-2xl bg-[#06120e]/80 border border-amber-500/15 flex items-center gap-2.5 text-[11px] text-slate-400">
                  <ShieldCheck size={16} className="text-amber-400 shrink-0" weight="fill" />
                  <span>Sesi login ieu dipangaping ku sistem kaamanan terenkripsi désa.</span>
                </div>

                {/* Submit Action Button - Royal Sunda Amber/Emerald Gradient */}
                <button
                  type="submit"
                  disabled={isLoggingIn}
                  className="w-full py-3.5 rounded-2xl bg-gradient-to-r from-[#064e3b] via-[#047857] to-amber-600 hover:from-[#047857] hover:to-amber-500 text-amber-100 hover:text-white font-extrabold text-xs uppercase tracking-wider shadow-lg shadow-emerald-950/80 hover:shadow-amber-900/40 border border-amber-400/30 transition-all active:scale-[0.98] cursor-pointer flex items-center justify-center gap-2"
                >
                  {isLoggingIn ? (
                    <>
                      <Spinner size={18} className="animate-spin text-amber-300" />
                      <span>Mariksa Aksés Tatapraja...</span>
                    </>
                  ) : (
                    <>
                      <ShieldCheck size={18} weight="fill" className="text-amber-300" />
                      <span>Lebet ka Dashboard Admin</span>
                    </>
                  )}
                </button>
              </form>

              {/* Navigation Back */}
              <div className="pt-3 border-t border-amber-500/15 flex items-center justify-between text-xs">
                <Link
                  href="/"
                  className="font-semibold text-amber-300/80 hover:text-amber-200 transition-colors flex items-center gap-1.5 group"
                >
                  <House size={15} className="group-hover:-translate-x-0.5 transition-transform text-amber-400" />
                  <span>Wangsul ka Beranda Web</span>
                </Link>
                <span className="text-[11px] text-slate-400 font-serif italic">
                  Kec. Petir · Banten
                </span>
              </div>
            </div>

          </div>

        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#f4f6f2] py-8 px-4 sm:px-6 lg:px-8">
      {/* Toast Notification */}
      {toastMessage && (
        <div className="fixed top-20 right-6 z-50 p-4 rounded-2xl bg-[#064e3b] text-white shadow-2xl flex items-center gap-3 border border-emerald-400/30 transition-all">
          <CheckCircle size={22} weight="fill" className="text-emerald-300 shrink-0" />
          <span className="text-xs font-semibold">{toastMessage}</span>
          {toastAction && (
            <Link
              href={toastAction.url}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-800 hover:bg-emerald-700 text-white text-xs font-bold transition-all border border-emerald-500/50 shadow-sm ml-2 whitespace-nowrap"
            >
              <Eye size={15} weight="bold" />
              <span>{toastAction.label}</span>
            </Link>
          )}
        </div>
      )}

      <div className="max-w-7xl mx-auto space-y-6">
        {/* Top Header Bar */}
        <div className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-2xl bg-[#064e3b] text-white flex items-center justify-center font-bold text-xl shadow-md">
              <GearSix size={24} weight="duotone" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h1 className="text-xl font-extrabold text-slate-900 tracking-tight">
                  Dashboard Administrator Desa Kadugenep
                </h1>
                <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-100 text-emerald-800">
                  Live Sync
                </span>
              </div>
              <p className="text-xs text-slate-500">
                Kelola konten warta berita, profil desa seribu mesin, transparansi APBDes, dan persuratan warga.
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2.5">
            <Link
              href="/"
              target="_blank"
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs transition-colors border border-slate-200 cursor-pointer"
            >
              <House size={16} />
              <span>Lihat Web Utama</span>
              <ArrowSquareOut size={14} />
            </Link>

            {/* Prominent Log Out Button */}
            <button
              type="button"
              onClick={handleLogout}
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-rose-50 hover:bg-rose-100 text-rose-700 font-bold text-xs transition-all border border-rose-200 shadow-xs cursor-pointer active:scale-95"
              title="Keluar dari sesi administrator"
            >
              <SignOut size={16} weight="bold" />
              <span>Keluar (Log Out)</span>
            </button>
          </div>
        </div>

        {/* Quick Stats Grid */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">Total Berita Terbit</span>
            <p className="text-2xl font-black text-slate-900 mt-1">{articles.length} Artikel</p>
          </div>
          <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">Permohonan Surat</span>
            <p className="text-2xl font-black text-emerald-800 mt-1">{serviceRequests.length} Berkas</p>
          </div>
          <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">Aspirasi Warga</span>
            <p className="text-2xl font-black text-amber-700 mt-1">{aspirations.length} Masukan</p>
          </div>
          <div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm">
            <span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">Pengrajin Tas Aktif</span>
            <p className="text-2xl font-black text-slate-900 mt-1">{profile.stats.bagCraftsmen}+ Bengkel</p>
          </div>
        </div>

        {/* Tab Navigation */}
        <div className="flex items-center gap-1 overflow-x-auto p-1.5 rounded-2xl bg-white border border-slate-200 shadow-sm text-xs font-semibold text-slate-600">
          <button
            onClick={() => setActiveTab("berita")}
            className={`px-4 py-2 rounded-xl transition-all flex items-center gap-2 whitespace-nowrap ${
              activeTab === "berita" ? "bg-[#064e3b] text-white shadow-sm" : "hover:bg-slate-100 text-slate-700"
            }`}
          >
            <ArticleIcon size={16} />
            <span>Kelola Berita ({articles.length})</span>
          </button>
          <button
            onClick={() => setActiveTab("layanan")}
            className={`px-4 py-2 rounded-xl transition-all flex items-center gap-2 whitespace-nowrap ${
              activeTab === "layanan" ? "bg-[#064e3b] text-white shadow-sm" : "hover:bg-slate-100 text-slate-700"
            }`}
          >
            <FileText size={16} />
            <span>Permohonan Surat ({serviceRequests.filter((r) => r.status === "Menunggu").length} baru)</span>
          </button>
          <button
            onClick={() => setActiveTab("aparatur")}
            className={`px-4 py-2 rounded-xl transition-all flex items-center gap-2 whitespace-nowrap ${
              activeTab === "aparatur" ? "bg-[#064e3b] text-white shadow-sm" : "hover:bg-slate-100 text-slate-700"
            }`}
          >
            <Users size={16} />
            <span>Aparatur & Bagan SOTK ({officials.length})</span>
          </button>
          <button
            onClick={() => setActiveTab("profil")}
            className={`px-4 py-2 rounded-xl transition-all flex items-center gap-2 whitespace-nowrap ${
              activeTab === "profil" ? "bg-[#064e3b] text-white shadow-sm" : "hover:bg-slate-100 text-slate-700"
            }`}
          >
            <House size={16} />
            <span>Profil & Data Desa</span>
          </button>
          <button
            onClick={() => setActiveTab("apbdes")}
            className={`px-4 py-2 rounded-xl transition-all flex items-center gap-2 whitespace-nowrap ${
              activeTab === "apbdes" ? "bg-[#064e3b] text-white shadow-sm" : "hover:bg-slate-100 text-slate-700"
            }`}
          >
            <ShieldCheck size={16} />
            <span>Transparansi APBDes</span>
          </button>
          <button
            onClick={() => setActiveTab("aspirasi")}
            className={`px-4 py-2 rounded-xl transition-all flex items-center gap-2 whitespace-nowrap ${
              activeTab === "aspirasi" ? "bg-[#064e3b] text-white shadow-sm" : "hover:bg-slate-100 text-slate-700"
            }`}
          >
            <IdentificationCard size={16} />
            <span>Aspirasi Warga ({aspirations.filter((a) => a.status === "Baru").length})</span>
          </button>
          <button
            onClick={() => setActiveTab("backup")}
            className={`px-4 py-2 rounded-xl transition-all flex items-center gap-2 whitespace-nowrap ${
              activeTab === "backup" ? "bg-[#064e3b] text-white shadow-sm" : "hover:bg-slate-100 text-slate-700"
            }`}
          >
            <DownloadSimple size={16} />
            <span>Backup & Reset</span>
          </button>
        </div>

        {/* TAB 1: KELOLA BERITA */}
        {activeTab === "berita" && (
          <div className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-slate-100">
              <div>
                <h2 className="text-lg font-bold text-slate-900">Daftar Publikasi Warta & Berita</h2>
                <p className="text-xs text-slate-500">
                  Artikel yang ditambahkan atau diedit di sini langsung tampil di halaman depan website.
                </p>
              </div>
              <button
                onClick={handleOpenCreateArticle}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[#064e3b] hover:bg-[#047857] text-white text-xs font-bold shadow transition-all active:scale-95"
              >
                <Plus size={16} weight="bold" />
                <span>Tambah Berita Baru</span>
              </button>
            </div>

            {/* Table of articles */}
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs text-slate-600">
                <thead className="bg-slate-50 text-slate-700 uppercase font-bold text-[11px] border-y border-slate-200">
                  <tr>
                    <th className="py-3 px-4">Judul Artikel</th>
                    <th className="py-3 px-4">Kategori</th>
                    <th className="py-3 px-4">Tanggal</th>
                    <th className="py-3 px-4">Penulis</th>
                    <th className="py-3 px-4">Pembaca</th>
                    <th className="py-3 px-4 text-right">Aksi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {articles.map((art) => (
                    <tr key={art.id} className="hover:bg-slate-50/60 transition-colors">
                      <td className="py-3.5 px-4 font-semibold text-slate-900 max-w-sm">
                        <Link
                          href={`/berita/${art.slug || slugify(art.title)}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="hover:text-emerald-700 hover:underline transition-colors block text-left"
                          title="Lihat Halaman Berita (Buka di Tab Baru)"
                        >
                          <div className="line-clamp-2">{art.title}</div>
                        </Link>
                        {art.videoUrl && (
                          <div className="inline-flex items-center gap-1 mt-1 text-[10px] font-bold text-rose-700 bg-rose-50 px-2 py-0.5 rounded border border-rose-200">
                            {isYouTubeUrl(art.videoUrl) ? (
                              <>
                                <YoutubeLogo size={12} weight="fill" />
                                <span>Video YouTube</span>
                              </>
                            ) : (
                              <>
                                <FilmStrip size={12} weight="fill" />
                                <span>Video Galeri</span>
                              </>
                            )}
                          </div>
                        )}
                      </td>
                      <td className="py-3.5 px-4">
                        <span className="px-2.5 py-0.5 rounded-md text-[10px] font-bold bg-emerald-100 text-emerald-800">
                          {art.category}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 whitespace-nowrap">{formatDateID(art.date)}</td>
                      <td className="py-3.5 px-4">{art.author}</td>
                      <td className="py-3.5 px-4 whitespace-nowrap">{art.views} kali</td>
                      <td className="py-3.5 px-4 text-right space-x-1.5 whitespace-nowrap">
                        <Link
                          href={`/berita/${art.slug || slugify(art.title)}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center justify-center p-1.5 rounded-lg text-slate-600 hover:text-emerald-700 hover:bg-emerald-50 transition-colors"
                          title="Lihat Berita Langsung (Buka di Tab Baru)"
                        >
                          <Eye size={17} weight="bold" />
                        </Link>
                        <button
                          onClick={() => handleOpenEditArticle(art)}
                          className="p-1.5 rounded-lg text-slate-600 hover:text-emerald-700 hover:bg-emerald-50 transition-colors"
                          title="Edit Berita"
                        >
                          <PencilSimple size={16} />
                        </button>
                        <button
                          onClick={() => handleDeleteArticle(art.id)}
                          className="p-1.5 rounded-lg text-slate-600 hover:text-red-700 hover:bg-red-50 transition-colors"
                          title="Hapus Berita"
                        >
                          <Trash size={16} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* TAB 2: PERMOHONAN SURAT WARGA */}
        {activeTab === "layanan" && (
          <div className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm space-y-6">
            <div>
              <h2 className="text-lg font-bold text-slate-900">Daftar Permohonan Surat Mandiri Warga</h2>
              <p className="text-xs text-slate-500">
                Data yang dikirim warga dari halaman /layanan secara instan masuk ke sini untuk ditindaklanjuti.
              </p>
            </div>

            <div className="space-y-3">
              {serviceRequests.length === 0 ? (
                <p className="text-xs text-slate-400">Belum ada permohonan masuk.</p>
              ) : (
                serviceRequests.map((req) => (
                  <div
                    key={req.id}
                    className="p-4 rounded-2xl border border-slate-200 hover:border-emerald-600/30 flex flex-col md:flex-row md:items-center justify-between gap-4 bg-slate-50/50"
                  >
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-xs font-bold text-emerald-800 bg-emerald-100 px-2 py-0.5 rounded">
                          {req.id}
                        </span>
                        <span className="text-sm font-bold text-slate-900">{req.citizenName}</span>
                        <span className="text-xs text-slate-400 font-mono">(NIK: {req.nik})</span>
                      </div>
                      <p className="text-xs font-semibold text-slate-700">{req.serviceType}</p>
                      <p className="text-[11px] text-slate-500">Catatan: {req.notes}</p>
                      <p className="text-[10px] text-slate-400">Tanggal Diajukan: {req.createdAt}</p>
                    </div>

                    <div className="flex items-center gap-2">
                      <a
                        href={`https://wa.me/62${req.whatsapp.replace(/[^0-9]/g, "").slice(1)}?text=Halo%20Bpk/Ibu%20${encodeURIComponent(req.citizenName)},%20mengenai%20permohonan%20${encodeURIComponent(req.serviceType)}%20di%20Kantor%20Desa%20Kadugenep.`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold shadow-sm"
                      >
                        <WhatsappLogo size={15} weight="fill" />
                        <span>Hubungi Warga</span>
                      </a>

                      <select
                        value={req.status}
                        onChange={(e) =>
                          handleUpdateServiceStatus(req.id, e.target.value as "Menunggu" | "Diproses" | "Selesai")
                        }
                        className={`text-xs font-bold rounded-xl px-3 py-1.5 border focus:outline-none ${
                          req.status === "Selesai"
                            ? "bg-green-100 text-green-900 border-green-300"
                            : req.status === "Diproses"
                            ? "bg-amber-100 text-amber-900 border-amber-300"
                            : "bg-slate-200 text-slate-800 border-slate-300"
                        }`}
                      >
                        <option value="Menunggu">Menunggu</option>
                        <option value="Diproses">Diproses</option>
                        <option value="Selesai">Selesai</option>
                      </select>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        )}

        {/* TAB: STRUKTUR APARATUR PEMERINTAH DESA */}
        {activeTab === "aparatur" && (
          <div className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-slate-100">
              <div>
                <h2 className="text-lg font-bold text-slate-900">Kelola Struktur Aparatur Pemerintah Desa</h2>
                <p className="text-xs text-slate-500">
                  Tambah, ubah, dan hapus data perangkat desa yang tampil di halaman depan website.
                </p>
              </div>
              <button
                type="button"
                onClick={handleOpenCreateOfficial}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[#064e3b] hover:bg-[#047857] text-white text-xs font-bold shadow transition-all cursor-pointer"
              >
                <Plus size={16} weight="bold" />
                <span>Tambah Perangkat Desa</span>
              </button>
            </div>

            {/* PENGATURAN TAMPILAN & LATAR BELAKANG BAGAN SOTK */}
            <div className="p-5 sm:p-6 rounded-3xl bg-gradient-to-br from-slate-900 to-sky-950 text-white shadow-lg border border-sky-800/60 space-y-6 relative overflow-hidden">
              <div className="absolute top-0 right-0 w-80 h-80 bg-sky-500/10 rounded-full blur-3xl pointer-events-none" />

              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-white/10 relative z-10">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-2xl bg-sky-500/20 border border-sky-400/40 flex items-center justify-center text-sky-300 shrink-0">
                    <TreeStructure size={22} weight="bold" />
                  </div>
                  <div>
                    <h3 className="text-base font-bold text-white flex items-center gap-2">
                      Pengaturan Tampilan & Background Bagan SOTK
                    </h3>
                    <p className="text-xs text-sky-200/80">
                      Atur tata letak kotak dan latar belakang gambar bagan yang dilihat warga di halaman depan.
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <Link
                    href="/#profil"
                    target="_blank"
                    className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-white/10 hover:bg-white/20 text-white text-xs font-semibold border border-white/15 transition-all"
                  >
                    <ArrowSquareOut size={14} />
                    <span>Lihat di Web</span>
                  </Link>
                  <button
                    type="button"
                    onClick={handleSaveSotkSettings}
                    className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-emerald-500 hover:bg-emerald-600 text-white text-xs font-bold shadow-md transition-all cursor-pointer active:scale-98"
                  >
                    <CheckCircle size={16} weight="bold" />
                    <span>Simpan Pengaturan</span>
                  </button>
                </div>
              </div>

              {/* Grid 2 Kolom: Pilihan Tata Letak & Pilihan Tema Background */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 relative z-10">
                {/* 1. Tata Letak (View Mode) */}
                <div className="space-y-3 bg-white/5 p-4 rounded-2xl border border-white/10">
                  <label className="text-xs font-bold text-sky-200 uppercase tracking-wider block">
                    1. Tata Letak Kotak (Mode Tampilan)
                  </label>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <button
                      type="button"
                      onClick={() => setSotkForm((prev) => ({ ...prev, view: "bagan" }))}
                      className={`p-3.5 rounded-xl border text-left transition-all cursor-pointer flex flex-col justify-between gap-2 ${
                        sotkForm.view === "bagan"
                          ? "bg-sky-500/25 border-sky-400 text-white shadow-[0_0_12px_rgba(56,189,248,0.3)] ring-1 ring-sky-400"
                          : "bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <TreeStructure size={20} className={sotkForm.view === "bagan" ? "text-sky-300" : "text-slate-400"} />
                        {sotkForm.view === "bagan" && (
                          <span className="text-[10px] font-black uppercase px-2 py-0.5 rounded bg-sky-400 text-slate-950">
                            Aktif
                          </span>
                        )}
                      </div>
                      <div>
                        <div className="text-xs font-bold text-white">Bagan Hierarki (SOTK)</div>
                        <div className="text-[11px] text-slate-300 leading-tight mt-0.5">
                          Bagan pohon bergaris komando resmi dari Kades ke Sekdes & Kaur/Kasi.
                        </div>
                      </div>
                    </button>

                    <button
                      type="button"
                      onClick={() => setSotkForm((prev) => ({ ...prev, view: "grid" }))}
                      className={`p-3.5 rounded-xl border text-left transition-all cursor-pointer flex flex-col justify-between gap-2 ${
                        sotkForm.view === "grid"
                          ? "bg-sky-500/25 border-sky-400 text-white shadow-[0_0_12px_rgba(56,189,248,0.3)] ring-1 ring-sky-400"
                          : "bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <SquaresFour size={20} className={sotkForm.view === "grid" ? "text-sky-300" : "text-slate-400"} />
                        {sotkForm.view === "grid" && (
                          <span className="text-[10px] font-black uppercase px-2 py-0.5 rounded bg-sky-400 text-slate-950">
                            Aktif
                          </span>
                        )}
                      </div>
                      <div>
                        <div className="text-xs font-bold text-white">Grid Kartu Modern</div>
                        <div className="text-[11px] text-slate-300 leading-tight mt-0.5">
                          Kartu berjejer rapi dalam 3 kolom tanpa garis hierarki.
                        </div>
                      </div>
                    </button>
                  </div>
                </div>

                {/* 2. Tema Background */}
                <div className="space-y-3 bg-white/5 p-4 rounded-2xl border border-white/10">
                  <label className="text-xs font-bold text-sky-200 uppercase tracking-wider block">
                    2. Tema Background Bagan
                  </label>
                  <div className="grid grid-cols-3 gap-2">
                    <button
                      type="button"
                      onClick={() => setSotkForm((prev) => ({ ...prev, bgTheme: "kantor" }))}
                      className={`p-3 rounded-xl border text-center transition-all cursor-pointer flex flex-col items-center gap-1.5 ${
                        sotkForm.bgTheme === "kantor"
                          ? "bg-sky-500/25 border-sky-400 text-white ring-1 ring-sky-400"
                          : "bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
                      }`}
                    >
                      <Buildings size={18} className="text-sky-300" />
                      <span className="text-xs font-bold leading-tight">Foto Balai Desa</span>
                      <span className="text-[10px] text-sky-200/70">Glassmorphism</span>
                    </button>

                    <button
                      type="button"
                      onClick={() => setSotkForm((prev) => ({ ...prev, bgTheme: "blueprint" }))}
                      className={`p-3 rounded-xl border text-center transition-all cursor-pointer flex flex-col items-center gap-1.5 ${
                        sotkForm.bgTheme === "blueprint"
                          ? "bg-sky-500/25 border-sky-400 text-white ring-1 ring-sky-400"
                          : "bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
                      }`}
                    >
                      <span className="text-lg">📐</span>
                      <span className="text-xs font-bold leading-tight">Blueprint</span>
                      <span className="text-[10px] text-sky-200/70">Grid Arsitektur</span>
                    </button>

                    <button
                      type="button"
                      onClick={() => setSotkForm((prev) => ({ ...prev, bgTheme: "clean" }))}
                      className={`p-3 rounded-xl border text-center transition-all cursor-pointer flex flex-col items-center gap-1.5 ${
                        sotkForm.bgTheme === "clean"
                          ? "bg-sky-500/25 border-sky-400 text-white ring-1 ring-sky-400"
                          : "bg-white/5 border-white/10 text-slate-300 hover:bg-white/10"
                      }`}
                    >
                      <span className="text-lg">⚪</span>
                      <span className="text-xs font-bold leading-tight">Kanvas Bersih</span>
                      <span className="text-[10px] text-sky-200/70">Minimalis Putih</span>
                    </button>
                  </div>
                </div>
              </div>

              {/* 3. Kustom Gambar Background Foto Balai Desa */}
              <div className="p-4 rounded-2xl bg-white/5 border border-white/10 space-y-3 relative z-10">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                  <div>
                    <label className="text-xs font-bold text-sky-200 uppercase tracking-wider">
                      3. Gambar Background Foto Kantor / Balai Desa
                    </label>
                    <p className="text-[11px] text-slate-300">
                      Upload foto kantor desa Anda sendiri atau gunakan foto default balai desa.
                    </p>
                  </div>

                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() =>
                        setSotkForm((prev) => ({
                          ...prev,
                          bgImage: "/images/kantor-desa-kadugenep.jpg",
                          bgTheme: "kantor",
                        }))
                      }
                      className="px-2.5 py-1 rounded-lg bg-white/10 hover:bg-white/20 text-[11px] font-semibold text-sky-200 border border-white/10 transition-all cursor-pointer"
                    >
                      Reset Foto Standar
                    </button>
                  </div>
                </div>

                <div className="flex flex-col sm:flex-row items-center gap-4 pt-1">
                  {/* Thumbnail Preview */}
                  <div className="relative w-full sm:w-44 h-24 rounded-xl overflow-hidden border border-white/20 bg-slate-900 shrink-0 shadow-inner group">
                    <Image
                      src={sotkForm.bgImage || "/images/kantor-desa-kadugenep.jpg"}
                      alt="Preview Latar Bagan"
                      fill
                      className="object-cover"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent flex items-end p-2">
                      <span className="text-[10px] text-white/90 font-medium truncate">
                        Preview Background
                      </span>
                    </div>
                  </div>

                  {/* Upload & URL Input */}
                  <div className="flex-1 w-full space-y-2.5">
                    <div className="flex items-center gap-2">
                      <label className="flex-1 inline-flex items-center justify-center gap-2 px-3.5 py-2 rounded-xl bg-sky-600 hover:bg-sky-500 text-white text-xs font-bold cursor-pointer transition-all shadow-sm active:scale-98">
                        <UploadSimple size={16} weight="bold" />
                        <span>
                          {isUploadingSotkBg ? "Memproses..." : "Upload Foto Background Baru"}
                        </span>
                        <input
                          type="file"
                          accept="image/*"
                          className="hidden"
                          onChange={(e) => {
                            const file = e.target.files?.[0];
                            if (file) handleSotkBgUpload(file);
                          }}
                          disabled={isUploadingSotkBg}
                        />
                      </label>
                    </div>

                    <div className="flex items-center gap-2">
                      <span className="text-[11px] text-slate-400 font-medium shrink-0">Path/URL:</span>
                      <input
                        type="text"
                        value={sotkForm.bgImage}
                        onChange={(e) =>
                          setSotkForm((prev) => ({ ...prev, bgImage: e.target.value }))
                        }
                        placeholder="/images/kantor-desa-kadugenep.jpg atau https://..."
                        className="flex-1 px-3 py-1.5 rounded-lg bg-slate-950/60 border border-white/15 text-xs text-white placeholder-slate-500 font-mono focus:outline-none focus:border-sky-400"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pt-2">
              <div>
                <h3 className="text-base font-bold text-slate-900 flex items-center gap-2">
                  <span>Daftar Anggota Aparatur ({officials.length} Orang)</span>
                </h3>
                <p className="text-xs text-slate-500">
                  Data aparatur di bawah ini otomatis tampil di bagan hierarki halaman depan.
                </p>
              </div>
              <button
                type="button"
                onClick={handleOpenCreateOfficial}
                className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold shadow-sm transition-all cursor-pointer active:scale-98 self-start sm:self-auto"
              >
                <Plus size={15} weight="bold" />
                <span>+ Tambah Perangkat Baru</span>
              </button>
            </div>

            {officials.length === 0 ? (
              <div className="text-center py-12 text-slate-400">
                <Users size={48} className="mx-auto mb-2 opacity-50" />
                <p className="text-sm font-semibold">Belum ada data aparatur desa</p>
                <p className="text-xs mt-1">Klik tombol &quot;Tambah Perangkat Desa&quot; untuk menambahkan perangkat desa baru.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {officials.map((off) => (
                  <div
                    key={off.id}
                    className="p-5 rounded-2xl border border-slate-200 bg-white hover:border-slate-300 hover:shadow-md transition-all flex flex-col justify-between gap-4"
                  >
                    <div className="flex items-start gap-3.5">
                      {off.photo ? (
                        <div className="relative w-14 h-14 rounded-2xl overflow-hidden border border-slate-200 shadow-xs shrink-0 bg-slate-100">
                          <Image
                            src={off.photo}
                            alt={off.name}
                            fill
                            className="object-cover object-top"
                            sizes="60px"
                          />
                        </div>
                      ) : (
                        <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-sky-600 to-blue-800 text-white flex items-center justify-center font-bold text-lg shrink-0 shadow-xs">
                          {off.name.charAt(0)}
                        </div>
                      )}

                      <div className="min-w-0 flex-1 space-y-0.5">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-[10px] font-black uppercase tracking-wider text-sky-800 bg-sky-50 px-2 py-0.5 rounded border border-sky-200">
                            {off.role}
                          </span>
                          {off.period && (
                            <span className="px-1.5 py-0.5 rounded text-[9px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
                              {off.period}
                            </span>
                          )}
                        </div>
                        <h4 className="text-sm font-bold text-slate-900 leading-snug truncate pt-0.5">
                          {off.name}
                        </h4>
                        {(off.nrpd || off.nip) && (
                          <p className="text-[11px] text-slate-400 font-mono">
                            NRPD: {off.nrpd || off.nip}
                          </p>
                        )}
                        {off.phone && (
                          <p className="text-[11px] text-slate-500 font-mono">
                            Kontak: {off.phone}
                          </p>
                        )}
                      </div>
                    </div>

                    <div className="flex items-center justify-end gap-2 pt-3 border-t border-slate-100 text-xs font-semibold">
                      <button
                        type="button"
                        onClick={() => handleOpenEditOfficial(off)}
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-sky-50 hover:bg-sky-100 text-sky-800 border border-sky-200 transition-colors cursor-pointer"
                      >
                        <PencilSimple size={14} />
                        <span>Edit</span>
                      </button>
                      <button
                        type="button"
                        onClick={() => handleDeleteOfficial(off.id, off.name)}
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 transition-colors cursor-pointer"
                      >
                        <Trash size={14} />
                        <span>Hapus</span>
                      </button>
                    </div>
                  </div>
                ))}

                {/* Kartu Tombol Tambah Cepat di Grid */}
                <button
                  type="button"
                  onClick={handleOpenCreateOfficial}
                  className="p-6 rounded-2xl border-2 border-dashed border-sky-300 hover:border-sky-500 bg-sky-50/40 hover:bg-sky-50/90 text-sky-700 transition-all flex flex-col items-center justify-center gap-3 min-h-[160px] cursor-pointer group shadow-2xs hover:shadow-md"
                >
                  <div className="w-12 h-12 rounded-2xl bg-sky-100 group-hover:bg-sky-600 group-hover:text-white text-sky-600 flex items-center justify-center transition-all shadow-xs group-hover:scale-105">
                    <Plus size={24} weight="bold" />
                  </div>
                  <div className="text-center">
                    <span className="text-sm font-bold text-slate-800 group-hover:text-sky-900 block">
                      + Tambah Perangkat Desa
                    </span>
                    <span className="text-[11px] text-slate-500 block mt-0.5">
                      Klik untuk mengisi data aparatur baru
                    </span>
                  </div>
                </button>
              </div>
            )}
          </div>
        )}

        {/* TAB 3: EDIT PROFIL & DATA DESA */}
        {activeTab === "profil" && (
          <form onSubmit={handleSaveProfile} className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm space-y-6">
            <div>
              <h2 className="text-lg font-bold text-slate-900">Profil & Data Administratif Desa Kadugenep</h2>
              <p className="text-xs text-slate-500">
                Ubah informasi statistik, visi misi, kontak, dan narasi sejarah desa.
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Nama Desa</label>
                <input
                  type="text"
                  value={profileForm.name}
                  onChange={(e) => setProfileForm({ ...profileForm, name: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-semibold text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Slogan / Julukan</label>
                <input
                  type="text"
                  value={profileForm.tagline}
                  onChange={(e) => setProfileForm({ ...profileForm, tagline: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Total Penduduk (Jiwa)</label>
                <input
                  type="number"
                  value={profileForm.stats.population}
                  onChange={(e) =>
                    setProfileForm({
                      ...profileForm,
                      stats: { ...profileForm.stats, population: Number(e.target.value) },
                    })
                  }
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Jumlah Bengkel Pengrajin Tas</label>
                <input
                  type="number"
                  value={profileForm.stats.bagCraftsmen}
                  onChange={(e) =>
                    setProfileForm({
                      ...profileForm,
                      stats: { ...profileForm.stats, bagCraftsmen: Number(e.target.value) },
                    })
                  }
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Nomor WhatsApp Pelayanan</label>
                <input
                  type="text"
                  value={profileForm.whatsapp}
                  onChange={(e) => setProfileForm({ ...profileForm, whatsapp: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Alamat Kantor Desa</label>
                <input
                  type="text"
                  value={profileForm.address}
                  onChange={(e) => setProfileForm({ ...profileForm, address: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">Visi Desa Kadugenep</label>
              <textarea
                rows={2}
                value={profileForm.vision}
                onChange={(e) => setProfileForm({ ...profileForm, vision: e.target.value })}
                className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
              />
            </div>

            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">Narasi Sejarah & Identitas Desa</label>
              <textarea
                rows={4}
                value={profileForm.history}
                onChange={(e) => setProfileForm({ ...profileForm, history: e.target.value })}
                className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
              />
            </div>

            <button
              type="submit"
              className="px-6 py-3 rounded-xl bg-[#064e3b] hover:bg-[#047857] text-white font-bold text-xs shadow transition-all active:scale-95"
            >
              Simpan Perubahan Profil Desa
            </button>
          </form>
        )}

        {/* TAB 4: TRANSPARANSI APBDES */}
        {activeTab === "apbdes" && (
          <div className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm space-y-6">
            {/* KARTU PENGATURAN FOTO BALIHO RESMI APBDES */}
            <div className="p-5 sm:p-6 rounded-2xl bg-gradient-to-br from-slate-900 to-[#071d2b] border border-slate-800 text-white shadow-md relative overflow-hidden">
              <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-5">
                <div className="flex items-center gap-4">
                  <div className="relative w-20 h-28 sm:w-24 sm:h-32 rounded-xl overflow-hidden border-2 border-emerald-500/50 bg-slate-950 shadow-md shrink-0">
                    <Image
                      src={profile.apbdesBalihoUrl || "/images/infografis-apbdes-2026.png"}
                      alt="Preview Baliho APBDes"
                      fill
                      className="object-contain p-1"
                    />
                  </div>
                  <div className="space-y-1">
                    <div className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-emerald-950/80 text-emerald-400 border border-emerald-500/30">
                      <ShieldCheck size={14} />
                      <span>Dokumen Publik Transparansi</span>
                    </div>
                    <h3 className="text-base sm:text-lg font-bold text-white">
                      Foto Dokumen Baliho Resmi APBDes
                    </h3>
                    <p className="text-xs text-slate-300 max-w-xl leading-relaxed">
                      Gambar ini ditampilkan pada bagian Transparansi APBDes di beranda web dan dapat dibuka dalam resolusi HD oleh warga.
                    </p>
                    <p className="text-[11px] text-slate-400 font-mono pt-0.5">
                      Lokasi file bawaan: <code className="text-emerald-300">public/images/infografis-apbdes-2026.png</code>
                    </p>
                  </div>
                </div>

                <div className="flex flex-wrap items-center gap-2.5 w-full md:w-auto">
                  <label className={`inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold shadow-md transition-all cursor-pointer ${isUploadingBaliho ? "opacity-60 pointer-events-none" : ""}`}>
                    <UploadSimple size={16} weight="bold" />
                    <span>{isUploadingBaliho ? "Memproses..." : "Ganti / Upload Foto Baliho"}</span>
                    <input
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        if (file) handleBalihoUpload(file);
                      }}
                      disabled={isUploadingBaliho}
                    />
                  </label>

                  {profile.apbdesBalihoUrl && profile.apbdesBalihoUrl !== "/images/infografis-apbdes-2026.png" && (
                    <button
                      type="button"
                      onClick={handleResetBaliho}
                      className="inline-flex items-center gap-1.5 px-3.5 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white text-xs font-semibold border border-slate-700 transition-colors cursor-pointer"
                    >
                      <ArrowCounterClockwise size={15} />
                      <span>Reset ke Default</span>
                    </button>
                  )}
                </div>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-slate-100">
              <div>
                <h2 className="text-lg font-bold text-slate-900">Kelola Pos Anggaran APBDes</h2>
                <p className="text-xs text-slate-500">
                  Perbarui alokasi pagu anggaran, realisasi serapan kas, atau tambahkan pos kegiatan baru.
                </p>
              </div>
              <button
                type="button"
                onClick={handleOpenCreateApb}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-[#064e3b] hover:bg-[#047857] text-white text-xs font-bold shadow transition-all cursor-pointer"
              >
                <Plus size={16} weight="bold" />
                <span>Tambah Pos Anggaran</span>
              </button>
            </div>

            <div className="space-y-3">
              {apbdes.map((item) => (
                <div
                  key={item.id}
                  className="p-4 sm:p-5 rounded-2xl border border-slate-200 bg-white hover:border-slate-300 hover:shadow-md transition-all flex flex-col sm:flex-row sm:items-center justify-between gap-4"
                >
                  <div className="space-y-2 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className={`px-2.5 py-0.5 rounded-full text-[10px] uppercase font-black tracking-wider ${
                        item.category === "Pendapatan"
                          ? "bg-emerald-100 text-emerald-800 border border-emerald-300"
                          : "bg-sky-100 text-sky-800 border border-sky-300"
                      }`}>
                        {item.category}
                      </span>
                      <h4 className="text-sm font-bold text-slate-900">{item.title}</h4>
                      <span className={`px-2 py-0.5 rounded-md text-[10px] font-mono font-bold ${
                        item.percentage >= 85
                          ? "bg-emerald-50 text-emerald-700 border border-emerald-200"
                          : item.percentage >= 70
                          ? "bg-sky-50 text-sky-700 border border-sky-200"
                          : "bg-amber-50 text-amber-700 border border-amber-200"
                      }`}>
                        {item.percentage}% Realisasi
                      </span>
                    </div>

                    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-600 font-mono">
                      <span>Pagu: <strong className="text-slate-900">{formatRupiah(item.budget)}</strong></span>
                      <span>•</span>
                      <span>Realisasi: <strong className="text-emerald-700">{formatRupiah(item.realization)}</strong></span>
                      <span>•</span>
                      <span className="text-slate-500">Sisa Pagu: {formatRupiah(Math.max(0, item.budget - item.realization))}</span>
                    </div>

                    {/* Visual mini progress bar */}
                    <div className="w-full max-w-lg h-2 rounded-full bg-slate-100 overflow-hidden mt-1">
                      <div
                        className={`h-full rounded-full transition-all duration-500 ${
                          item.category === "Pendapatan"
                            ? "bg-gradient-to-r from-emerald-500 to-teal-500"
                            : item.percentage >= 85
                            ? "bg-gradient-to-r from-sky-500 to-blue-600"
                            : "bg-gradient-to-r from-amber-400 to-amber-500"
                        }`}
                        style={{ width: `${Math.min(100, item.percentage)}%` }}
                      />
                    </div>
                  </div>

                  <div className="flex items-center gap-2 self-end sm:self-center shrink-0">
                    <button
                      type="button"
                      onClick={() => handleOpenEditApb(item)}
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold text-sky-700 bg-sky-50 hover:bg-sky-100 border border-sky-200 transition-all cursor-pointer active:scale-95 shadow-xs"
                      title="Edit Pos Anggaran Ini"
                    >
                      <PencilSimple size={15} weight="bold" />
                      <span>Edit</span>
                    </button>
                    <button
                      type="button"
                      onClick={() => handleDeleteApbItem(item.id)}
                      className="p-2 rounded-xl text-slate-400 hover:text-red-700 hover:bg-red-50 border border-transparent hover:border-red-200 transition-all cursor-pointer"
                      title="Hapus Pos Anggaran"
                    >
                      <Trash size={16} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* TAB 5: ASPIRASI WARGA */}
        {activeTab === "aspirasi" && (
          <div className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm space-y-6">
            <div>
              <h2 className="text-lg font-bold text-slate-900">Laporan & Aspirasi Masuk dari Warga</h2>
              <p className="text-xs text-slate-500">
                Aspirasi warga yang disampaikan melalui formulir beranda.
              </p>
            </div>

            <div className="space-y-3">
              {aspirations.map((asp) => (
                <div key={asp.id} className="p-4 rounded-2xl border border-slate-200 space-y-2 bg-slate-50/50">
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-bold text-sm text-slate-900">{asp.name}</span>
                        <span className="text-xs text-emerald-700 font-mono">({asp.contact})</span>
                      </div>
                      <p className="text-xs font-semibold text-slate-800 mt-0.5">{asp.subject}</p>
                    </div>
                    <span className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                      asp.status === "Ditanggapi" ? "bg-green-100 text-green-800" : "bg-amber-100 text-amber-800"
                    }`}>
                      {asp.status}
                    </span>
                  </div>
                  <p className="text-xs text-slate-600 bg-white p-3 rounded-xl border border-slate-100">
                    {asp.message}
                  </p>
                  <div className="flex items-center justify-between text-[11px] text-slate-400 pt-1">
                    <span>Tanggal: {asp.createdAt}</span>
                    {asp.status === "Baru" && (
                      <button
                        onClick={() => handleUpdateAspirationStatus(asp.id)}
                        className="text-xs font-bold text-emerald-800 hover:underline"
                      >
                        Tandai Sudah Ditanggapi
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* TAB 6: BACKUP & RESET */}
        {activeTab === "backup" && (
          <div className="p-6 rounded-3xl bg-white border border-slate-200/80 shadow-sm space-y-6">
            <div>
              <h2 className="text-lg font-bold text-slate-900">Cadangan (Backup) & Setel Ulang Data</h2>
              <p className="text-xs text-slate-500">
                Ekspor seluruh data website ke berkas JSON atau kembalikan data ke setelan bawaan awal Desa Kadugenep.
              </p>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
              <div className="p-5 rounded-2xl border border-slate-200 bg-slate-50 space-y-3">
                <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                  <DownloadSimple size={18} className="text-emerald-700" />
                  <span>Ekspor Data Lengkap (JSON)</span>
                </h3>
                <p className="text-xs text-slate-500">
                  Unduh seluruh artikel berita, data profil desa, APBDes, dan daftar permohonan ke satu file JSON.
                </p>
                <button
                  onClick={handleExportData}
                  className="px-4 py-2 rounded-xl bg-slate-900 hover:bg-slate-800 text-white font-semibold text-xs shadow-sm"
                >
                  Unduh Backup JSON
                </button>
              </div>

              <div className="p-5 rounded-2xl border border-red-200 bg-red-50/40 space-y-3">
                <h3 className="text-sm font-bold text-red-900 flex items-center gap-2">
                  <ArrowCounterClockwise size={18} className="text-red-700" />
                  <span>Kembalikan ke Setelan Awal</span>
                </h3>
                <p className="text-xs text-red-800/80">
                  Menghapus perubahan lokal dan mengembalikan data otentik awal Desa Kadugenep.
                </p>
                <button
                  onClick={() => {
                    if (confirm("Reset seluruh data ke setelan awal Desa Kadugenep?")) {
                      resetToDefault();
                      showToast("Data berhasil di-reset ke data awal desa.");
                    }
                  }}
                  className="px-4 py-2 rounded-xl bg-red-700 hover:bg-red-800 text-white font-semibold text-xs shadow-sm cursor-pointer"
                >
                  Reset ke Data Awal
                </button>
              </div>

              {/* Sesi Administrator & Keamanan Akun */}
              <div className="p-5 rounded-2xl border border-slate-200 bg-slate-50 space-y-3 sm:col-span-2">
                <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                  <SignOut size={18} className="text-rose-600" />
                  <span>Sesi Administrator & Keamanan Akun</span>
                </h3>
                <p className="text-xs text-slate-500">
                  Akhiri sesi kerja administrator di peramban ini agar orang lain tidak dapat mengubah data desa secara bebas.
                </p>
                <button
                  type="button"
                  onClick={handleLogout}
                  className="px-4 py-2 rounded-xl bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs shadow-sm transition-all cursor-pointer inline-flex items-center gap-1.5 active:scale-95"
                >
                  <SignOut size={15} weight="bold" />
                  <span>Keluar (Log Out) Sekarang</span>
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* MODAL TAMBAH / EDIT BERITA */}
      {articleModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto">
          <div className="relative w-full max-w-2xl bg-white rounded-3xl p-6 sm:p-8 shadow-2xl space-y-5 my-8">
            <div className="flex items-center justify-between pb-3 border-b border-slate-100">
              <div className="flex items-center gap-3">
                <h3 className="text-lg font-bold text-slate-900">
                  {editingArticleId ? "Edit Artikel Warta" : "Tambah Berita Baru"}
                </h3>
                {editingArticleId && (
                  <Link
                    href={`/berita/${articles.find((a) => a.id === editingArticleId)?.slug || slugify(articleForm.title)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-emerald-50 hover:bg-emerald-100 text-emerald-800 text-xs font-semibold border border-emerald-200 transition-colors"
                    title="Buka halaman berita ini di tab baru"
                  >
                    <Eye size={14} weight="bold" />
                    <span>Lihat Halaman</span>
                  </Link>
                )}
              </div>
              <button
                onClick={() => setArticleModalOpen(false)}
                className="text-slate-400 hover:text-slate-600 text-sm font-bold"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSaveArticle} className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Judul Berita *</label>
                <input
                  type="text"
                  required
                  placeholder="Contoh: Pengrajin Tas Kadugenep Adakan Pelatihan Jahit..."
                  value={articleForm.title}
                  onChange={(e) => setArticleForm({ ...articleForm, title: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-bold text-slate-700 mb-1">Kategori *</label>
                  <select
                    value={articleForm.category}
                    onChange={(e) =>
                      setArticleForm({
                        ...articleForm,
                        category: e.target.value as ArticleType["category"],
                      })
                    }
                    className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700 bg-white"
                  >
                    <option value="Pemerintahan">Pemerintahan</option>
                    <option value="Ekonomi & UMKM">Ekonomi & UMKM</option>
                    <option value="Kegiatan Warga">Kegiatan Warga</option>
                    <option value="Pembangunan">Pembangunan</option>
                    <option value="Pengumuman">Pengumuman</option>
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 mb-1">Penulis *</label>
                  <input
                    type="text"
                    required
                    value={articleForm.author}
                    onChange={(e) => setArticleForm({ ...articleForm, author: e.target.value })}
                    className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                  />
                </div>
              </div>

              {/* PENGATURAN GAMBAR UTAMA (FOTO DARI GALERI ATAU ASET DESA) */}
              <div className="space-y-2.5 p-3.5 rounded-2xl bg-slate-50 border border-slate-200">
                <div className="flex items-center justify-between">
                  <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                    <ImageSquare size={16} className="text-emerald-700" weight="fill" />
                    <span>Foto / Gambar Utama Berita *</span>
                  </label>
                  <div className="inline-flex p-0.5 rounded-lg bg-slate-200/80 text-[11px] font-semibold">
                    <button
                      type="button"
                      onClick={() => setImageSourceTab("upload")}
                      className={cn(
                        "px-2.5 py-1 rounded-md transition-all cursor-pointer",
                        imageSourceTab === "upload" ? "bg-white text-slate-900 shadow-xs font-bold" : "text-slate-600 hover:text-slate-900"
                      )}
                    >
                      Upload dari Galeri
                    </button>
                    <button
                      type="button"
                      onClick={() => setImageSourceTab("preset")}
                      className={cn(
                        "px-2.5 py-1 rounded-md transition-all cursor-pointer",
                        imageSourceTab === "preset" ? "bg-white text-slate-900 shadow-xs font-bold" : "text-slate-600 hover:text-slate-900"
                      )}
                    >
                      Pilih dari Aset Desa
                    </button>
                  </div>
                </div>

                {imageSourceTab === "upload" ? (
                  <div className="space-y-2">
                    <div className="relative border-2 border-dashed border-emerald-600/30 hover:border-emerald-600/60 rounded-xl p-4 transition-all text-center bg-white cursor-pointer group">
                      <input
                        type="file"
                        accept="image/jpeg,image/png,image/webp,image/gif"
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file) handleFileUpload(file, "image");
                        }}
                        disabled={isUploadingImage}
                        className="absolute inset-0 opacity-0 cursor-pointer w-full h-full z-10"
                      />
                      {isUploadingImage ? (
                        <div className="flex flex-col items-center justify-center py-3 gap-2">
                          <Spinner size={24} className="animate-spin text-emerald-700" />
                          <p className="text-xs font-bold text-emerald-800">Sedang mengunggah foto ke server desa...</p>
                        </div>
                      ) : (
                        <div className="flex flex-col items-center justify-center py-2 gap-1.5 pointer-events-none">
                          <div className="w-10 h-10 rounded-full bg-emerald-50 text-emerald-700 flex items-center justify-center group-hover:scale-110 transition-transform">
                            <UploadSimple size={20} weight="bold" />
                          </div>
                          <p className="text-xs font-bold text-slate-800">
                            Klik atau Tarik Foto dari Galeri HP / Komputer
                          </p>
                          <p className="text-[11px] text-slate-500">
                            Format JPG, PNG, WEBP (Bebas tanpa batasan link)
                          </p>
                        </div>
                      )}
                    </div>

                    {articleForm.image && (
                      <div className="flex items-center gap-3 p-2 rounded-xl bg-white border border-slate-200">
                        <div className="relative w-16 h-12 rounded-lg overflow-hidden shrink-0 border border-slate-200">
                          <img
                            src={articleForm.image}
                            alt="Preview Foto Berita"
                            className="w-full h-full object-cover"
                          />
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="text-xs font-bold text-slate-800 truncate">
                            {articleForm.image.startsWith("/uploads/") || articleForm.image.startsWith("data:")
                              ? "Foto Terunggah dari Galeri"
                              : "Foto Aset Desa"}
                          </p>
                          <p className="text-[11px] text-slate-500 truncate">
                            {articleForm.image.startsWith("data:")
                              ? "Foto Galeri (Teroptimasi Siap Tampil)"
                              : articleForm.image}
                          </p>
                        </div>
                        <span className="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-100 text-emerald-800 shrink-0">
                          Aktif
                        </span>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="space-y-2">
                    <select
                      value={articleForm.image}
                      onChange={(e) => setArticleForm({ ...articleForm, image: e.target.value })}
                      className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700 bg-white"
                    >
                      <option value="/images/kerajinan-tas.jpg">Kerajinan Tas (Sentra Mesin Jahit)</option>
                      <option value="/images/hero-kadugenep.jpg">Panorama Pertanian Sawah Kadugenep</option>
                      <option value="/images/balai-desa.jpg">Kantor Balai Desa Kadugenep</option>
                      <option value="/images/warga-komunitas.jpg">Musyawarah & Guyub Warga</option>
                    </select>

                    <div className="flex items-center gap-3 p-2 rounded-xl bg-white border border-slate-200">
                      <div className="relative w-16 h-12 rounded-lg overflow-hidden shrink-0 border border-slate-200">
                        <img
                          src={articleForm.image}
                          alt="Preset Preview"
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <p className="text-xs text-slate-600 font-medium truncate">Aset foto standar desa terpilih</p>
                    </div>
                  </div>
                )}
              </div>

              {/* PENGATURAN DOKUMENTASI VIDEO (UPLOAD GALERI / YOUTUBE / TANPA VIDEO) */}
              <div className="space-y-3 p-3.5 rounded-2xl bg-rose-50/60 border border-rose-200/80">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                    <VideoCamera size={16} className="text-rose-600" weight="fill" />
                    <span>Video Dokumentasi (Diputar Langsung di Web)</span>
                  </label>
                  <div className="inline-flex p-0.5 rounded-lg bg-rose-200/60 text-[11px] font-semibold">
                    <button
                      type="button"
                      onClick={() => setVideoSourceTab("upload")}
                      className={cn(
                        "px-2.5 py-1 rounded-md transition-all cursor-pointer",
                        videoSourceTab === "upload" ? "bg-white text-slate-900 shadow-xs font-bold" : "text-slate-600 hover:text-slate-900"
                      )}
                    >
                      Upload Video Galeri
                    </button>
                    <button
                      type="button"
                      onClick={() => setVideoSourceTab("youtube")}
                      className={cn(
                        "px-2.5 py-1 rounded-md transition-all cursor-pointer",
                        videoSourceTab === "youtube" ? "bg-white text-slate-900 shadow-xs font-bold" : "text-slate-600 hover:text-slate-900"
                      )}
                    >
                      Link YouTube
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setVideoSourceTab("none");
                        setArticleForm({ ...articleForm, videoUrl: "", videoTitle: "" });
                      }}
                      className={cn(
                        "px-2.5 py-1 rounded-md transition-all cursor-pointer",
                        videoSourceTab === "none" ? "bg-white text-slate-900 shadow-xs font-bold" : "text-slate-600 hover:text-slate-900"
                      )}
                    >
                      Tanpa Video
                    </button>
                  </div>
                </div>

                {videoSourceTab === "upload" && (
                  <div className="space-y-2">
                    <div className="relative border-2 border-dashed border-rose-500/30 hover:border-rose-500/60 rounded-xl p-4 transition-all text-center bg-white cursor-pointer group">
                      <input
                        type="file"
                        accept="video/mp4,video/webm,video/ogg,video/quicktime,video/*"
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file) handleFileUpload(file, "video");
                        }}
                        disabled={isUploadingVideo}
                        className="absolute inset-0 opacity-0 cursor-pointer w-full h-full z-10"
                      />
                      {isUploadingVideo ? (
                        <div className="flex flex-col items-center justify-center py-4 gap-2">
                          <Spinner size={24} className="animate-spin text-rose-600" />
                          <p className="text-xs font-bold text-rose-700">Sedang mengunggah video ke server desa... Harap tunggu sebentar.</p>
                        </div>
                      ) : (
                        <div className="flex flex-col items-center justify-center py-2 gap-1.5 pointer-events-none">
                          <div className="w-10 h-10 rounded-full bg-rose-50 text-rose-600 flex items-center justify-center group-hover:scale-110 transition-transform">
                            <FilmStrip size={20} weight="bold" />
                          </div>
                          <p className="text-xs font-bold text-slate-800">
                            Pilih Video dari Galeri HP / Laptop
                          </p>
                          <p className="text-[11px] text-slate-500">
                            Format MP4, WebM, MOV. (Disarankan tab Link YouTube untuk video panjang di hosting web)
                          </p>
                        </div>
                      )}
                    </div>

                    {articleForm.videoUrl && isVideoFile(articleForm.videoUrl) && (
                      <div className="p-3 rounded-xl bg-white border border-rose-200 space-y-2">
                        <div className="flex items-center justify-between text-xs">
                          <span className="font-bold text-slate-800 flex items-center gap-1.5">
                            <CheckCircle size={15} weight="fill" className="text-emerald-600" />
                            <span>Video Galeri Siap Diputar di Web</span>
                          </span>
                          <button
                            type="button"
                            onClick={() => setArticleForm({ ...articleForm, videoUrl: "" })}
                            className="text-rose-600 hover:text-rose-700 font-semibold text-[11px] cursor-pointer"
                          >
                            Hapus Video
                          </button>
                        </div>
                        <div className="rounded-lg overflow-hidden aspect-video bg-black max-h-44">
                          <video
                            src={articleForm.videoUrl}
                            controls
                            className="w-full h-full object-contain"
                          />
                        </div>
                        <p className="text-[11px] text-slate-500 truncate">{articleForm.videoUrl}</p>
                      </div>
                    )}
                  </div>
                )}

                {videoSourceTab === "youtube" && (
                  <div className="space-y-2">
                    <input
                      type="url"
                      placeholder="Tempel link YouTube: https://www.youtube.com/watch?v=... atau https://youtu.be/..."
                      value={articleForm.videoUrl || ""}
                      onChange={(e) => setArticleForm({ ...articleForm, videoUrl: e.target.value })}
                      className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-rose-600 bg-white"
                    />
                    <p className="text-[11px] text-slate-500">
                      Masukkan URL YouTube publik untuk menampilkan pemutar video YouTube di halaman berita.
                    </p>
                  </div>
                )}

                {videoSourceTab !== "none" && (
                  <div>
                    <label className="block text-[11px] font-bold text-slate-700 mb-1">
                      Judul / Keterangan Video Liputan (Opsional)
                    </label>
                    <input
                      type="text"
                      placeholder="Contoh: Dokumentasi Liputan Pengrajin Tas RW 02"
                      value={articleForm.videoTitle || ""}
                      onChange={(e) => setArticleForm({ ...articleForm, videoTitle: e.target.value })}
                      className="w-full px-3.5 py-2 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-rose-600 bg-white"
                    />
                  </div>
                )}
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Ringkasan Berita (Lead) *</label>
                <textarea
                  required
                  rows={2}
                  placeholder="Ringkasan singkat yang memikat pembaca..."
                  value={articleForm.summary}
                  onChange={(e) => setArticleForm({ ...articleForm, summary: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Isi Lengkap Berita *</label>
                <textarea
                  required
                  rows={6}
                  placeholder="Tuliskan isi berita secara terperinci..."
                  value={articleForm.content}
                  onChange={(e) => setArticleForm({ ...articleForm, content: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700"
                />
              </div>

              <div className="flex justify-end gap-2 pt-3 border-t border-slate-100">
                <button
                  type="button"
                  onClick={() => setArticleModalOpen(false)}
                  className="px-4 py-2.5 rounded-xl border border-slate-300 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-5 py-2.5 rounded-xl bg-[#064e3b] hover:bg-[#047857] text-white text-xs font-bold shadow"
                >
                  {editingArticleId ? "Simpan Perubahan" : "Terbitkan Berita"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL EDIT / TAMBAH POS APBDES */}
      {apbModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="relative w-full max-w-lg bg-white rounded-3xl p-6 sm:p-7 shadow-2xl space-y-5 border border-slate-100 animate-in fade-in zoom-in-95 duration-200">
            <div className="flex items-start justify-between border-b border-slate-100 pb-3">
              <div>
                <h3 className="text-base font-bold text-slate-900">
                  {editingApbId ? "Edit Pos Anggaran APBDes" : "Tambah Pos Anggaran APBDes Baru"}
                </h3>
                <p className="text-xs text-slate-500 mt-0.5">
                  {editingApbId
                    ? "Perbarui rincian uraian kegiatan, pagu target, atau realisasi kas saat ini."
                    : "Tambahkan rincian penerimaan atau rencana belanja baru ke buku kas APBDes."}
                </p>
              </div>
              <button
                type="button"
                onClick={() => setApbModalOpen(false)}
                className="w-8 h-8 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-500 flex items-center justify-center text-sm font-bold transition-all cursor-pointer shrink-0"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSaveApbItem} className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Uraian Kegiatan / Pos Anggaran *
                </label>
                <input
                  type="text"
                  required
                  placeholder="Contoh: Pembangunan Drainase dan Rabat Beton"
                  value={apbForm.title}
                  onChange={(e) => setApbForm({ ...apbForm, title: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-semibold text-slate-900 focus:ring-2 focus:ring-emerald-700 focus:border-transparent outline-none transition-all"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Kategori Pos *</label>
                <select
                  value={apbForm.category}
                  onChange={(e) => setApbForm({ ...apbForm, category: e.target.value as "Pendapatan" | "Belanja" })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-semibold text-slate-900 focus:ring-2 focus:ring-emerald-700 focus:border-transparent outline-none transition-all cursor-pointer"
                >
                  <option value="Pendapatan">Pendapatan (Penerimaan Kas / DDS / ADD / PADes)</option>
                  <option value="Belanja">Belanja (Pembangunan Fisik, Pemberdayaan, Layanan Digital)</option>
                </select>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
                <div>
                  <label className="block text-xs font-bold text-slate-700 mb-1">
                    Target Pagu Anggaran (Rp) *
                  </label>
                  <input
                    type="number"
                    required
                    min={0}
                    step={100000}
                    value={apbForm.budget}
                    onChange={(e) => setApbForm({ ...apbForm, budget: Number(e.target.value) })}
                    className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-mono font-semibold text-slate-900 focus:ring-2 focus:ring-emerald-700 outline-none"
                  />
                  <p className="text-[11px] font-mono text-slate-500 mt-1">
                    {formatRupiah(apbForm.budget || 0)}
                  </p>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 mb-1">
                    Realisasi Saat Ini (Rp) *
                  </label>
                  <input
                    type="number"
                    required
                    min={0}
                    step={100000}
                    value={apbForm.realization}
                    onChange={(e) => setApbForm({ ...apbForm, realization: Number(e.target.value) })}
                    className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-mono font-semibold text-slate-900 focus:ring-2 focus:ring-emerald-700 outline-none"
                  />
                  <p className="text-[11px] font-mono text-slate-500 mt-1">
                    {formatRupiah(apbForm.realization || 0)}
                  </p>
                </div>
              </div>

              {/* Real-time Percentage & Budget Difference Indicator */}
              <div className="p-3.5 rounded-2xl bg-slate-50 border border-slate-200 flex items-center justify-between">
                <div>
                  <span className="text-[11px] text-slate-500 font-medium">Kalkulasi Otomatis Sistem:</span>
                  <p className="text-xs font-bold text-slate-800">
                    Capaian Realisasi Anggaran
                  </p>
                </div>
                <div className="text-right">
                  <span className="text-base font-black font-mono text-emerald-700">
                    {apbForm.budget > 0 ? Math.round((apbForm.realization / apbForm.budget) * 100) : 0}%
                  </span>
                </div>
              </div>

              <div className="flex items-center justify-end gap-2.5 pt-3 border-t border-slate-100">
                <button
                  type="button"
                  onClick={() => setApbModalOpen(false)}
                  className="px-4 py-2.5 rounded-xl border border-slate-300 text-xs font-semibold text-slate-700 hover:bg-slate-50 transition-all cursor-pointer"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-5 py-2.5 rounded-xl bg-[#064e3b] hover:bg-[#047857] text-white text-xs font-bold shadow-md transition-all active:scale-95 cursor-pointer flex items-center gap-1.5"
                >
                  <CheckCircle size={16} weight="bold" />
                  <span>{editingApbId ? "Simpan Perubahan" : "Tambahkan Pos"}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL: TAMBAH / EDIT APARATUR DESA */}
      {officialModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="relative w-full max-w-lg bg-white rounded-3xl p-6 sm:p-7 shadow-2xl space-y-4 border border-slate-100 max-h-[90vh] overflow-y-auto animate-in fade-in zoom-in-95 duration-200">
            <div className="flex items-start justify-between border-b border-slate-100 pb-3">
              <div>
                <h3 className="text-base font-bold text-slate-900">
                  {editingOfficialId ? "Edit Data Perangkat Desa" : "Tambah Perangkat Desa Baru"}
                </h3>
                <p className="text-xs text-slate-500 mt-0.5">
                  Lengkapi identitas jabatan, masa jabatan, nomor telepon, dan foto profil resmi.
                </p>
              </div>
              <button
                type="button"
                onClick={() => setOfficialModalOpen(false)}
                className="w-8 h-8 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-500 flex items-center justify-center text-sm font-bold transition-all cursor-pointer shrink-0"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSaveOfficial} className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Nama Lengkap & Gelar *
                </label>
                <input
                  type="text"
                  required
                  placeholder="Contoh: Ahmad Fauzi, S.E."
                  value={officialForm.name}
                  onChange={(e) => setOfficialForm({ ...officialForm, name: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-semibold text-slate-900 focus:ring-2 focus:ring-emerald-700 outline-none"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Jabatan / Posisi *
                </label>
                <input
                  type="text"
                  required
                  placeholder="Contoh: Sekretaris Desa / Kaur Keuangan / Kepala Dusun"
                  value={officialForm.role}
                  onChange={(e) => setOfficialForm({ ...officialForm, role: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700 outline-none"
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-bold text-slate-700 mb-1">
                    Periode Menjabat (Opsional)
                  </label>
                  <input
                    type="text"
                    placeholder="Contoh: 2019 - 2025"
                    value={officialForm.period}
                    onChange={(e) => setOfficialForm({ ...officialForm, period: e.target.value })}
                    className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs text-slate-900 focus:ring-2 focus:ring-emerald-700 outline-none"
                  />
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 mb-1">
                    NRPD / NIP (Nomor Registrasi / Induk Pegawai)
                  </label>
                  <input
                    type="text"
                    placeholder="Contoh: 1908 19860515 01"
                    value={officialForm.nip}
                    onChange={(e) => setOfficialForm({ ...officialForm, nip: e.target.value })}
                    className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-mono text-slate-900 focus:ring-2 focus:ring-emerald-700 outline-none"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Nomor Kontak / WhatsApp (Opsional)
                </label>
                <input
                  type="text"
                  placeholder="Contoh: 0813-1122-3344"
                  value={officialForm.phone}
                  onChange={(e) => setOfficialForm({ ...officialForm, phone: e.target.value })}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-300 text-xs font-mono text-slate-900 focus:ring-2 focus:ring-emerald-700 outline-none"
                />
              </div>

              {/* Foto Aparatur */}
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Foto Profil Perangkat Desa (Opsional)
                </label>
                
                <div className="flex items-center gap-3">
                  {officialForm.photo ? (
                    <div className="relative w-16 h-16 rounded-2xl overflow-hidden border border-slate-200 shrink-0 bg-slate-100 shadow-xs">
                      <Image
                        src={officialForm.photo}
                        alt="Preview"
                        fill
                        className="object-cover object-top"
                        sizes="64px"
                      />
                    </div>
                  ) : (
                    <div className="w-16 h-16 rounded-2xl bg-slate-100 border border-dashed border-slate-300 text-slate-400 flex items-center justify-center text-[11px] shrink-0 font-medium">
                      Tanpa Foto
                    </div>
                  )}

                  <div className="flex-1 space-y-1.5">
                    <label className="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold cursor-pointer border border-slate-200">
                      <UploadSimple size={16} />
                      <span>{isUploadingOfficialPhoto ? "Memproses..." : "Pilih Foto dari Galeri"}</span>
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file) handleOfficialPhotoUpload(file);
                        }}
                      />
                    </label>

                    {officialForm.photo && (
                      <button
                        type="button"
                        onClick={() => setOfficialForm({ ...officialForm, photo: "" })}
                        className="block text-[11px] text-rose-600 hover:underline font-semibold"
                      >
                        Hapus Foto (Gunakan Inisial Huruf)
                      </button>
                    )}
                  </div>
                </div>

                <div className="mt-2">
                  <input
                    type="text"
                    placeholder="Atau masukkan path / URL foto (contoh: /images/kepala-desa-aopidi.jpg)"
                    value={officialForm.photo}
                    onChange={(e) => setOfficialForm({ ...officialForm, photo: e.target.value })}
                    className="w-full px-3 py-1.5 rounded-lg border border-slate-200 text-[11px] font-mono text-slate-600 focus:ring-1 focus:ring-emerald-700 outline-none"
                  />
                </div>
              </div>

              <div className="flex items-center justify-end gap-2.5 pt-3 border-t border-slate-100">
                <button
                  type="button"
                  onClick={() => setOfficialModalOpen(false)}
                  className="px-4 py-2.5 rounded-xl border border-slate-300 text-xs font-semibold text-slate-700 hover:bg-slate-50 transition-all cursor-pointer"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-5 py-2.5 rounded-xl bg-[#064e3b] hover:bg-[#047857] text-white text-xs font-bold shadow-md transition-all active:scale-95 cursor-pointer flex items-center gap-1.5"
                >
                  <CheckCircle size={16} weight="bold" />
                  <span>{editingOfficialId ? "Simpan Perubahan" : "Tambahkan Aparatur"}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
