"use client";

import { useEffect, useState } from "react";
import { useSession, signOut } from "next-auth/react";
import { useEditMode } from "@/context/EditModeContext";
import {
  LayoutDashboard, Newspaper, Briefcase, Handshake, Mail, MapPin,
  Megaphone, UserCircle, X, ArrowLeft, Plus, Pencil, Trash2,
  Eye, EyeOff, ArrowUp, ArrowDown, User, Lock, Save, LogOut,
  CheckCircle, AlertCircle, EyeOff as EyeOffIcon, CheckCircle2, Copy,
  MailOpen, ChevronDown, ChevronUp,
  Image as ImageIcon, Video, Circle, Upload, Link,
} from "lucide-react";
import ArticleForm from "./ArticleForm";
import ProjectForm from "./ProjectForm";
import PartnerForm from "./PartnerForm";
import ZoneForm from "./ZoneForm";

// ── Types ──────────────────────────────────────────────────────────────────────

type Section =
  | "dashboard"
  | "articles"
  | "projects"
  | "partners"
  | "messages"
  | "zones"
  | "campaigns"
  | "profile";

type ViewState = "list" | "new" | `edit:${string}`;

type Stats = {
  articles: { total: number; published: number };
  projects: { total: number; published: number };
  partners: { total: number; published: number };
  messages: { total: number; unread: number };
};

type Article = {
  id: string;
  title: string;
  category: string;
  published: boolean;
  publishedAt: string | null;
  createdAt: string;
};

type Project = {
  id: string;
  title: string;
  tag: string;
  partner: string;
  published: boolean;
  order: number;
};

type Partner = {
  id: string;
  name: string;
  category: string;
  website: string | null;
  logo: string;
  published: boolean;
  order: number;
};

type Zone = {
  id: string;
  name: string;
  svgId: string;
  status: string;
  beneficiaries: string | null;
  published: boolean;
};

type Message = {
  id: string;
  name: string;
  email: string;
  subject: string;
  message: string;
  read: boolean;
  createdAt: string;
};

type Campaign = {
  id: string;
  title: string;
  slogan: string | null;
  description: string | null;
  amountRaised: string | null;
  mediaType: string;
  imageUrl: string | null;
  videoUrl: string | null;
  active: boolean;
  createdAt: string;
};

// ── Shared constants ───────────────────────────────────────────────────────────

const STATUS_COLORS: Record<string, string> = {
  priority: "#4A7C59",
  relationship: "#7F8C8D",
  inactive: "#BDC3C7",
};

const STATUS_LABELS: Record<string, string> = {
  priority: "Prioritaire",
  relationship: "Relation",
  inactive: "Inactif",
};

const VIDEO_MAX_BYTES = 100 * 1024 * 1024;

// ── Campaign Modal ─────────────────────────────────────────────────────────────

function CampaignModal({
  initial,
  onSave,
  onClose,
}: {
  initial: Partial<Campaign>;
  onSave: (data: Partial<Campaign>) => Promise<void>;
  onClose: () => void;
}) {
  const [form, setForm] = useState<Partial<Campaign>>({
    title: "",
    slogan: "",
    description: "",
    amountRaised: "",
    mediaType: "image",
    imageUrl: "",
    videoUrl: "",
    active: false,
    ...initial,
  });
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadError, setUploadError] = useState<string | null>(null);

  const [videoSource, setVideoSource] = useState<"file" | "url">(() => {
    if (initial.videoUrl?.includes("res.cloudinary.com")) return "file";
    if (initial.videoUrl) return "url";
    return "file";
  });

  const set = <K extends keyof Campaign>(k: K, v: Campaign[K]) =>
    setForm((f) => ({ ...f, [k]: v }));

  const switchVideoSource = (src: "file" | "url") => {
    setVideoSource(src);
    set("videoUrl", "");
    setUploadError(null);
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    const fd = new FormData();
    fd.append("file", file);
    try {
      const res = await fetch("/api/upload", { method: "POST", body: fd });
      const data = await res.json();
      set("imageUrl", data.url);
    } catch {
      alert("Erreur lors du téléchargement");
    } finally {
      setUploading(false);
    }
  };

  const handleVideoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > VIDEO_MAX_BYTES) {
      setUploadError(`Fichier trop volumineux. Maximum : 100 Mo (votre fichier : ${(file.size / 1024 / 1024).toFixed(1)} Mo)`);
      e.target.value = "";
      return;
    }
    setUploadError(null);
    setUploading(true);
    setUploadProgress(0);
    try {
      const sigRes = await fetch("/api/admin/cloudinary-signature");
      if (!sigRes.ok) throw new Error("Impossible d'obtenir la signature d'upload");
      const { signature, timestamp, api_key, cloud_name, folder, max_bytes } = await sigRes.json();
      await new Promise<void>((resolve, reject) => {
        const fd = new FormData();
        fd.append("file", file);
        fd.append("api_key", api_key);
        fd.append("timestamp", String(timestamp));
        fd.append("signature", signature);
        fd.append("folder", folder);
        fd.append("max_bytes", String(max_bytes));
        const xhr = new XMLHttpRequest();
        xhr.open("POST", `https://api.cloudinary.com/v1_1/${cloud_name}/video/upload`);
        xhr.upload.onprogress = (ev) => {
          if (ev.lengthComputable) setUploadProgress(Math.round((ev.loaded / ev.total) * 100));
        };
        xhr.onload = () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            const data = JSON.parse(xhr.responseText);
            set("videoUrl", data.secure_url);
            resolve();
          } else {
            const err = JSON.parse(xhr.responseText);
            reject(new Error(err?.error?.message ?? "Échec du téléchargement"));
          }
        };
        xhr.onerror = () => reject(new Error("Erreur réseau lors du téléchargement"));
        xhr.send(fd);
      });
    } catch (err) {
      setUploadError(err instanceof Error ? err.message : "Échec du téléchargement");
    } finally {
      setUploading(false);
      setUploadProgress(0);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      await onSave(form);
      onClose();
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-[70] flex items-center justify-center p-4">
      <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
            <Megaphone size={18} className="text-[#E67E22]" />
            {initial.id ? "Modifier la campagne" : "Nouvelle campagne"}
          </h2>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X size={20} />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Titre *</label>
            <input required value={form.title ?? ""} onChange={(e) => set("title", e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#4A7C59]"
              placeholder="Ex: Campagne contre la malnutrition 2026" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Slogan</label>
            <input value={form.slogan ?? ""} onChange={(e) => set("slogan", e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#4A7C59]"
              placeholder="Ex: Nourrir l'avenir de la Mauritanie" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
            <textarea value={form.description ?? ""} onChange={(e) => set("description", e.target.value)}
              rows={3} className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#4A7C59]"
              placeholder="Décrivez l'objectif de cette campagne..." />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Type de média</label>
            <div className="flex gap-2">
              <button type="button" onClick={() => set("mediaType", "image")}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border transition-all ${form.mediaType === "image" ? "bg-[#4A7C59] text-white border-[#4A7C59]" : "bg-white text-gray-600 border-gray-300 hover:border-gray-400"}`}>
                <ImageIcon size={16} /> Image
              </button>
              <button type="button" onClick={() => set("mediaType", "video")}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border transition-all ${form.mediaType === "video" ? "bg-[#4A7C59] text-white border-[#4A7C59]" : "bg-white text-gray-600 border-gray-300 hover:border-gray-400"}`}>
                <Video size={16} /> Vidéo
              </button>
            </div>
          </div>
          {form.mediaType === "image" && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Image</label>
              {form.imageUrl && (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={form.imageUrl} alt="Aperçu" className="w-full h-32 object-cover rounded-lg mb-2 border border-gray-200" />
              )}
              <label className="flex items-center gap-2 w-full border border-dashed border-gray-300 rounded-lg px-3 py-3 text-sm text-gray-600 hover:border-[#4A7C59] cursor-pointer transition-colors">
                <Upload size={16} />
                {uploading ? "Téléchargement..." : "Choisir une image"}
                <input type="file" accept="image/*" className="hidden" onChange={handleImageUpload} disabled={uploading} />
              </label>
            </div>
          )}
          {form.mediaType === "video" && (
            <div className="space-y-3">
              <label className="block text-sm font-medium text-gray-700">Vidéo</label>
              <div className="flex gap-1 p-1 bg-gray-100 rounded-lg w-fit">
                <button type="button" onClick={() => switchVideoSource("file")}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold transition-all ${videoSource === "file" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"}`}>
                  <Upload size={13} /> Fichier
                </button>
                <button type="button" onClick={() => switchVideoSource("url")}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold transition-all ${videoSource === "url" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"}`}>
                  <Link size={13} /> URL externe
                </button>
              </div>
              {videoSource === "file" && (
                <div>
                  {form.videoUrl?.includes("res.cloudinary.com") && (
                    <video src={form.videoUrl} controls className="w-full h-32 rounded-lg mb-2 bg-black object-contain" />
                  )}
                  {uploading && (
                    <div className="mb-2">
                      <div className="flex justify-between text-xs text-gray-500 mb-1">
                        <span>Téléchargement en cours…</span><span>{uploadProgress}%</span>
                      </div>
                      <div className="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
                        <div className="h-full bg-[#4A7C59] transition-all duration-200" style={{ width: `${uploadProgress}%` }} />
                      </div>
                    </div>
                  )}
                  {uploadError && <p className="text-xs text-red-600 mb-2">{uploadError}</p>}
                  <label className={`flex items-center gap-2 w-full border border-dashed rounded-lg px-3 py-3 text-sm transition-colors ${uploading ? "border-gray-200 text-gray-400 cursor-not-allowed" : "border-gray-300 text-gray-600 hover:border-[#4A7C59] cursor-pointer"}`}>
                    <Upload size={16} />
                    {uploading ? `Téléchargement… ${uploadProgress}%` : "Choisir un fichier vidéo"}
                    <span className="ml-auto text-xs text-gray-400">Max 100 Mo</span>
                    <input type="file" accept="video/*" className="hidden" onChange={handleVideoUpload} disabled={uploading} />
                  </label>
                  <p className="text-xs text-gray-400 mt-1">Formats acceptés : MP4, WebM, MOV, AVI — limite 100 Mo</p>
                </div>
              )}
              {videoSource === "url" && (
                <div>
                  <input value={form.videoUrl?.includes("res.cloudinary.com") ? "" : (form.videoUrl ?? "")}
                    onChange={(e) => set("videoUrl", e.target.value)}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#4A7C59]"
                    placeholder="https://www.youtube.com/watch?v=…" />
                  <p className="text-xs text-gray-400 mt-1">YouTube et Vimeo sont supportés</p>
                </div>
              )}
            </div>
          )}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Montant collecté</label>
            <input value={form.amountRaised ?? ""} onChange={(e) => set("amountRaised", e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#4A7C59]"
              placeholder="Ex: 45 000 MRU ou €5 000" />
            <p className="text-xs text-gray-400 mt-1">Mis à jour manuellement — affiché sur la page de la campagne</p>
          </div>
          <div className="flex items-center gap-2 pt-1">
            <input type="checkbox" id="campaign-active-modal" checked={form.active ?? false}
              onChange={(e) => set("active", e.target.checked)} className="w-4 h-4 accent-[#E67E22]" />
            <label htmlFor="campaign-active-modal" className="text-sm font-medium text-gray-700">
              Activer cette campagne{" "}
              <span className="text-gray-400 font-normal">(désactive automatiquement les autres)</span>
            </label>
          </div>
          <div className="flex justify-end gap-3 pt-2 border-t border-gray-100">
            <button type="button" onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
              Annuler
            </button>
            <button type="submit" disabled={saving || uploading}
              className="px-5 py-2 text-sm font-semibold bg-[#4A7C59] hover:bg-[#3d6849] text-white rounded-lg disabled:opacity-60">
              {saving ? "Enregistrement..." : "Enregistrer"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Dashboard Section ──────────────────────────────────────────────────────────

function DashboardSection({ onNavigate }: { onNavigate: (s: Section) => void }) {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/stats")
      .then((r) => r.json())
      .then((d) => { setStats(d); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="w-8 h-8 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
      </div>
    );
  }

  const statCards = [
    { icon: Newspaper, label: "Actualités", total: stats?.articles.total || 0, subtitle: `${stats?.articles.published || 0} publiées`, color: "#4A7C59", section: "articles" as Section },
    { icon: Briefcase, label: "Projets", total: stats?.projects.total || 0, subtitle: `${stats?.projects.published || 0} publiés`, color: "#1E40AF", section: "projects" as Section },
    { icon: Handshake, label: "Partenaires", total: stats?.partners.total || 0, subtitle: `${stats?.partners.published || 0} publiés`, color: "#E67E22", section: "partners" as Section },
    { icon: Mail, label: "Messages", total: stats?.messages.total || 0, subtitle: `${stats?.messages.unread || 0} non lus`, color: "#7D3C98", section: "messages" as Section },
  ];

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900 mb-1">Tableau de bord</h1>
        <p className="text-gray-500 text-sm">Vue d&apos;ensemble de l&apos;administration ANED</p>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {statCards.map((card) => {
          const Icon = card.icon;
          return (
            <button key={card.label} onClick={() => onNavigate(card.section)}
              className="bg-white rounded-xl border-2 border-gray-200 p-5 hover:border-gray-300 hover:shadow-md transition-all text-left group">
              <div className="w-10 h-10 rounded-lg flex items-center justify-center mb-3 group-hover:scale-110 transition-transform"
                style={{ backgroundColor: `${card.color}15` }}>
                <Icon size={22} style={{ color: card.color }} />
              </div>
              <p className="text-xs text-gray-500 mb-0.5">{card.label}</p>
              <p className="text-2xl font-bold text-gray-900">{card.total}</p>
              <p className="text-xs text-gray-400 mt-0.5">{card.subtitle}</p>
            </button>
          );
        })}
      </div>
      <div className="bg-white rounded-xl border-2 border-gray-200 p-5">
        <h2 className="text-base font-bold text-gray-900 mb-3">Actions rapides</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
          <button onClick={() => onNavigate("articles")}
            className="flex items-center gap-2 px-4 py-3 bg-[#4A7C59] hover:bg-[#3d6849] text-white rounded-lg transition-all font-medium text-sm">
            <Newspaper size={16} /> Nouvelle actualité
          </button>
          <button onClick={() => onNavigate("projects")}
            className="flex items-center gap-2 px-4 py-3 bg-[#1E40AF] hover:bg-[#1e3a8a] text-white rounded-lg transition-all font-medium text-sm">
            <Briefcase size={16} /> Nouveau projet
          </button>
          <button onClick={() => onNavigate("partners")}
            className="flex items-center gap-2 px-4 py-3 bg-[#E67E22] hover:bg-[#d35400] text-white rounded-lg transition-all font-medium text-sm">
            <Handshake size={16} /> Nouveau partenaire
          </button>
          <button onClick={() => onNavigate("messages")}
            className="flex items-center gap-2 px-4 py-3 bg-[#7D3C98] hover:bg-[#6c2d7d] text-white rounded-lg transition-all font-medium text-sm">
            <Mail size={16} /> Voir messages
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Articles Section ───────────────────────────────────────────────────────────

function ArticlesSection() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(true);
  const [view, setView] = useState<ViewState>("list");

  const fetchArticles = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/articles");
      const data = await res.json();
      setArticles(data);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchArticles(); }, []);

  const handleDelete = async (id: string) => {
    if (!confirm("Supprimer cet article ?")) return;
    await fetch(`/api/admin/articles/${id}`, { method: "DELETE" });
    fetchArticles();
  };

  const togglePublish = async (article: Article) => {
    await fetch(`/api/admin/articles/${article.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...article, published: !article.published }),
    });
    fetchArticles();
  };

  if (view === "new") {
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-2xl font-bold text-gray-900">Nouvelle actualité</h1>
        </div>
        <ArticleForm onSuccess={() => { setView("list"); fetchArticles(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  if (view.startsWith("edit:")) {
    const articleId = view.slice(5);
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-2xl font-bold text-gray-900">Modifier l&apos;actualité</h1>
        </div>
        <ArticleForm articleId={articleId} onSuccess={() => { setView("list"); fetchArticles(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 mb-1">Actualités</h1>
          <p className="text-gray-500 text-sm">Gérez les articles du site</p>
        </div>
        <button onClick={() => setView("new")}
          className="flex items-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white px-4 py-2.5 rounded-lg font-semibold transition-all text-sm">
          <Plus size={18} /> Nouveau
        </button>
      </div>
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="w-8 h-8 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
        </div>
      ) : (
        <div className="bg-white rounded-xl border-2 border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b-2 border-gray-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Titre</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Catégorie</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Statut</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Date</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {articles.length === 0 ? (
                  <tr><td colSpan={5} className="px-4 py-10 text-center text-gray-500 text-sm">Aucune actualité.</td></tr>
                ) : articles.map((article) => (
                  <tr key={article.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3 font-medium text-gray-900 max-w-xs truncate">{article.title}</td>
                    <td className="px-4 py-3">
                      <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-[#4A7C59]/10 text-[#4A7C59]">
                        {article.category}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => togglePublish(article)}
                        className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-all ${article.published ? "bg-green-100 text-green-700 hover:bg-green-200" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
                        {article.published ? <Eye size={12} /> : <EyeOff size={12} />}
                        {article.published ? "Publié" : "Brouillon"}
                      </button>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500">{new Date(article.createdAt).toLocaleDateString("fr-FR")}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <button onClick={() => setView(`edit:${article.id}`)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-all" title="Modifier">
                          <Pencil size={16} />
                        </button>
                        <button onClick={() => handleDelete(article.id)} className="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-all" title="Supprimer">
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Projects Section ───────────────────────────────────────────────────────────

function ProjectsSection() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [view, setView] = useState<ViewState>("list");

  const fetchProjects = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/projects");
      const data = await res.json();
      setProjects(data);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchProjects(); }, []);

  const handleDelete = async (id: string) => {
    if (!confirm("Supprimer ce projet ?")) return;
    await fetch(`/api/admin/projects/${id}`, { method: "DELETE" });
    fetchProjects();
  };

  const togglePublish = async (project: Project) => {
    await fetch(`/api/admin/projects/${project.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...project, published: !project.published }),
    });
    fetchProjects();
  };

  const moveProject = async (index: number, direction: "up" | "down") => {
    if ((direction === "up" && index === 0) || (direction === "down" && index === projects.length - 1)) return;
    const newProjects = [...projects];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    [newProjects[index], newProjects[targetIndex]] = [newProjects[targetIndex], newProjects[index]];
    await Promise.all(newProjects.map((p, idx) => fetch(`/api/admin/projects/${p.id}`, {
      method: "PUT", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...p, order: idx }),
    })));
    fetchProjects();
  };

  if (view === "new") {
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors"><ArrowLeft size={20} /></button>
          <h1 className="text-2xl font-bold text-gray-900">Nouveau projet</h1>
        </div>
        <ProjectForm onSuccess={() => { setView("list"); fetchProjects(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  if (view.startsWith("edit:")) {
    const projectId = view.slice(5);
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors"><ArrowLeft size={20} /></button>
          <h1 className="text-2xl font-bold text-gray-900">Modifier le projet</h1>
        </div>
        <ProjectForm projectId={projectId} onSuccess={() => { setView("list"); fetchProjects(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 mb-1">Projets</h1>
          <p className="text-gray-500 text-sm">Gérez les projets du site</p>
        </div>
        <button onClick={() => setView("new")}
          className="flex items-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white px-4 py-2.5 rounded-lg font-semibold transition-all text-sm">
          <Plus size={18} /> Nouveau
        </button>
      </div>
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="w-8 h-8 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
        </div>
      ) : (
        <div className="bg-white rounded-xl border-2 border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b-2 border-gray-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Titre</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Tag</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Partenaire</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Publié</th>
                  <th className="px-4 py-3 text-center text-xs font-bold text-gray-700 uppercase tracking-wider">Ordre</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {projects.length === 0 ? (
                  <tr><td colSpan={6} className="px-4 py-10 text-center text-gray-500 text-sm">Aucun projet.</td></tr>
                ) : projects.map((project, index) => (
                  <tr key={project.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3 font-medium text-gray-900 max-w-xs truncate">{project.title}</td>
                    <td className="px-4 py-3">
                      <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-[#1E40AF]/10 text-[#1E40AF]">{project.tag}</span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500 max-w-[120px] truncate">{project.partner}</td>
                    <td className="px-4 py-3">
                      <button onClick={() => togglePublish(project)}
                        className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-all ${project.published ? "bg-green-100 text-green-700 hover:bg-green-200" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
                        {project.published ? <Eye size={12} /> : <EyeOff size={12} />}
                        {project.published ? "Publié" : "Brouillon"}
                      </button>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-1">
                        <button onClick={() => moveProject(index, "up")} disabled={index === 0} className="p-1 hover:bg-gray-200 rounded disabled:opacity-30"><ArrowUp size={14} /></button>
                        <button onClick={() => moveProject(index, "down")} disabled={index === projects.length - 1} className="p-1 hover:bg-gray-200 rounded disabled:opacity-30"><ArrowDown size={14} /></button>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <button onClick={() => setView(`edit:${project.id}`)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"><Pencil size={16} /></button>
                        <button onClick={() => handleDelete(project.id)} className="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-all"><Trash2 size={16} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Partners Section ───────────────────────────────────────────────────────────

function PartnersSection() {
  const [partners, setPartners] = useState<Partner[]>([]);
  const [loading, setLoading] = useState(true);
  const [view, setView] = useState<ViewState>("list");

  const fetchPartners = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/partners");
      const data = await res.json();
      setPartners(data);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchPartners(); }, []);

  const handleDelete = async (id: string) => {
    if (!confirm("Supprimer ce partenaire ?")) return;
    await fetch(`/api/admin/partners/${id}`, { method: "DELETE" });
    fetchPartners();
  };

  const togglePublish = async (partner: Partner) => {
    await fetch(`/api/admin/partners/${partner.id}`, {
      method: "PUT", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...partner, published: !partner.published }),
    });
    fetchPartners();
  };

  const movePartner = async (index: number, direction: "up" | "down") => {
    if ((direction === "up" && index === 0) || (direction === "down" && index === partners.length - 1)) return;
    const newPartners = [...partners];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    [newPartners[index], newPartners[targetIndex]] = [newPartners[targetIndex], newPartners[index]];
    await Promise.all(newPartners.map((p, idx) => fetch(`/api/admin/partners/${p.id}`, {
      method: "PUT", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...p, order: idx }),
    })));
    fetchPartners();
  };

  if (view === "new") {
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors"><ArrowLeft size={20} /></button>
          <h1 className="text-2xl font-bold text-gray-900">Nouveau partenaire</h1>
        </div>
        <PartnerForm onSuccess={() => { setView("list"); fetchPartners(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  if (view.startsWith("edit:")) {
    const partnerId = view.slice(5);
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors"><ArrowLeft size={20} /></button>
          <h1 className="text-2xl font-bold text-gray-900">Modifier le partenaire</h1>
        </div>
        <PartnerForm partnerId={partnerId} onSuccess={() => { setView("list"); fetchPartners(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 mb-1">Partenaires</h1>
          <p className="text-gray-500 text-sm">Gérez les partenaires du site</p>
        </div>
        <button onClick={() => setView("new")}
          className="flex items-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white px-4 py-2.5 rounded-lg font-semibold transition-all text-sm">
          <Plus size={18} /> Nouveau
        </button>
      </div>
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="w-8 h-8 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
        </div>
      ) : (
        <div className="bg-white rounded-xl border-2 border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b-2 border-gray-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Logo</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Nom</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Catégorie</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Publié</th>
                  <th className="px-4 py-3 text-center text-xs font-bold text-gray-700 uppercase tracking-wider">Ordre</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {partners.length === 0 ? (
                  <tr><td colSpan={6} className="px-4 py-10 text-center text-gray-500 text-sm">Aucun partenaire.</td></tr>
                ) : partners.map((partner, index) => (
                  <tr key={partner.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3">
                      <div className="w-10 h-10 rounded-lg overflow-hidden border border-gray-200">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src={partner.logo} alt={partner.name} className="w-full h-full object-contain" />
                      </div>
                    </td>
                    <td className="px-4 py-3 font-medium text-gray-900">{partner.name}</td>
                    <td className="px-4 py-3">
                      <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-700">{partner.category}</span>
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => togglePublish(partner)}
                        className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-all ${partner.published ? "bg-green-100 text-green-700 hover:bg-green-200" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
                        {partner.published ? <Eye size={12} /> : <EyeOff size={12} />}
                        {partner.published ? "Publié" : "Brouillon"}
                      </button>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-1">
                        <button onClick={() => movePartner(index, "up")} disabled={index === 0} className="p-1 hover:bg-gray-200 rounded disabled:opacity-30"><ArrowUp size={14} /></button>
                        <button onClick={() => movePartner(index, "down")} disabled={index === partners.length - 1} className="p-1 hover:bg-gray-200 rounded disabled:opacity-30"><ArrowDown size={14} /></button>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <button onClick={() => setView(`edit:${partner.id}`)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"><Pencil size={16} /></button>
                        <button onClick={() => handleDelete(partner.id)} className="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-all"><Trash2 size={16} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Zones Section ──────────────────────────────────────────────────────────────

function ZonesSection() {
  const [zones, setZones] = useState<Zone[]>([]);
  const [loading, setLoading] = useState(true);
  const [view, setView] = useState<ViewState>("list");

  const fetchZones = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/zones");
      const data = await res.json();
      setZones(data);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchZones(); }, []);

  const handleDelete = async (id: string) => {
    if (!confirm("Supprimer cette zone ?")) return;
    await fetch(`/api/admin/zones/${id}`, { method: "DELETE" });
    fetchZones();
  };

  const togglePublish = async (zone: Zone) => {
    await fetch(`/api/admin/zones/${zone.id}`, {
      method: "PUT", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...zone, published: !zone.published }),
    });
    fetchZones();
  };

  if (view === "new") {
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors"><ArrowLeft size={20} /></button>
          <h1 className="text-2xl font-bold text-gray-900">Nouvelle zone</h1>
        </div>
        <ZoneForm onSuccess={() => { setView("list"); fetchZones(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  if (view.startsWith("edit:")) {
    const zoneId = view.slice(5);
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <button onClick={() => setView("list")} className="p-2 hover:bg-gray-100 rounded-lg transition-colors"><ArrowLeft size={20} /></button>
          <h1 className="text-2xl font-bold text-gray-900">Modifier la zone</h1>
        </div>
        <ZoneForm zoneId={zoneId} onSuccess={() => { setView("list"); fetchZones(); }} onCancel={() => setView("list")} />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 mb-1">Zones d&apos;intervention</h1>
          <p className="text-gray-500 text-sm">Gérez les zones pour la carte interactive</p>
        </div>
        <button onClick={() => setView("new")}
          className="flex items-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white px-4 py-2.5 rounded-lg font-semibold transition-all text-sm">
          <Plus size={18} /> Nouveau
        </button>
      </div>
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="w-8 h-8 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
        </div>
      ) : (
        <div className="bg-white rounded-xl border-2 border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b-2 border-gray-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Nom</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Statut</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Publié</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {zones.length === 0 ? (
                  <tr><td colSpan={4} className="px-4 py-10 text-center text-gray-500 text-sm">Aucune zone.</td></tr>
                ) : zones.map((zone) => (
                  <tr key={zone.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3 font-medium text-gray-900">{zone.name}</td>
                    <td className="px-4 py-3">
                      <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium text-white"
                        style={{ backgroundColor: STATUS_COLORS[zone.status] || "#BDC3C7" }}>
                        {STATUS_LABELS[zone.status] || zone.status}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => togglePublish(zone)}
                        className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-all ${zone.published ? "bg-green-100 text-green-700 hover:bg-green-200" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>
                        {zone.published ? <Eye size={12} /> : <EyeOff size={12} />}
                        {zone.published ? "Publié" : "Brouillon"}
                      </button>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <button onClick={() => setView(`edit:${zone.id}`)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"><Pencil size={16} /></button>
                        <button onClick={() => handleDelete(zone.id)} className="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-all"><Trash2 size={16} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Messages Section ───────────────────────────────────────────────────────────

function MessagesSection() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [copiedEmail, setCopiedEmail] = useState<string | null>(null);

  const fetchMessages = async () => {
    try {
      const res = await fetch("/api/admin/messages");
      const data = await res.json();
      setMessages(data);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchMessages(); }, []);

  const toggleRead = async (message: Message) => {
    await fetch(`/api/admin/messages/${message.id}`, {
      method: "PUT", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ read: !message.read }),
    });
    fetchMessages();
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Supprimer ce message ?")) return;
    await fetch(`/api/admin/messages/${id}`, { method: "DELETE" });
    fetchMessages();
  };

  const toggleExpanded = async (message: Message) => {
    const isExpanding = expandedId !== message.id;
    setExpandedId(isExpanding ? message.id : null);
    if (isExpanding && !message.read) {
      await fetch(`/api/admin/messages/${message.id}`, {
        method: "PUT", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ read: true }),
      });
      setMessages((prev) => prev.map((m) => (m.id === message.id ? { ...m, read: true } : m)));
    }
  };

  const copyEmail = async (email: string) => {
    await navigator.clipboard.writeText(email);
    setCopiedEmail(email);
    setTimeout(() => setCopiedEmail(null), 2000);
  };

  const formatDate = (dateString: string) => new Intl.DateTimeFormat("fr-FR", {
    day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit",
  }).format(new Date(dateString));

  const unreadCount = messages.filter((m) => !m.read).length;

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="w-8 h-8 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div>
      <div className="mb-6">
        <div className="flex items-center gap-3 mb-1">
          <h1 className="text-2xl font-bold text-gray-900">Messages</h1>
          {unreadCount > 0 && (
            <span className="px-2.5 py-0.5 bg-red-500 text-white text-xs font-semibold rounded-full">
              {unreadCount} non lu{unreadCount > 1 ? "s" : ""}
            </span>
          )}
        </div>
        <p className="text-gray-500 text-sm">Messages reçus via le formulaire de contact</p>
      </div>
      <div className="bg-white rounded-xl border-2 border-gray-200 overflow-hidden">
        {messages.length === 0 ? (
          <div className="px-6 py-12 text-center text-gray-500 text-sm">Aucun message reçu.</div>
        ) : (
          <div className="divide-y divide-gray-200">
            {messages.map((message) => (
              <div key={message.id} className={`transition-all ${message.read ? "bg-white" : "bg-blue-50/30"}`}>
                <div onClick={() => toggleExpanded(message)}
                  className="px-5 py-4 flex items-start gap-3 cursor-pointer hover:bg-gray-50/50 transition-colors">
                  <button onClick={(e) => { e.stopPropagation(); toggleRead(message); }}
                    className="flex-shrink-0 p-1.5 hover:bg-gray-100 rounded-lg transition-all"
                    title={message.read ? "Marquer comme non lu" : "Marquer comme lu"}>
                    {message.read ? <MailOpen size={18} className="text-gray-400" /> : <Mail size={18} className="text-blue-600" />}
                  </button>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5 flex-wrap">
                      <h3 className={`font-semibold text-sm ${message.read ? "text-gray-700" : "text-gray-900"}`}>{message.name}</h3>
                      <button onClick={(e) => { e.stopPropagation(); copyEmail(message.email); }}
                        className="text-xs text-[#4A7C59] hover:text-[#3d6849] font-medium hover:underline flex items-center gap-1">
                        {message.email}
                        {copiedEmail === message.email ? <CheckCircle2 size={12} className="text-green-600" /> : <Copy size={12} />}
                      </button>
                    </div>
                    <p className={`text-xs mb-1 ${message.read ? "text-gray-600" : "text-gray-900 font-medium"}`}>
                      <span className="uppercase tracking-wide text-gray-400 font-bold mr-1.5 text-[10px]">Objet:</span>{message.subject}
                    </p>
                    {expandedId !== message.id && (
                      <p className="text-xs text-gray-500 line-clamp-1">{message.message}</p>
                    )}
                    <p className="text-[10px] text-gray-400 mt-1">{formatDate(message.createdAt)}</p>
                  </div>
                  <div className="flex items-center gap-1 flex-shrink-0">
                    <span className="text-gray-300">{expandedId === message.id ? <ChevronUp size={14} /> : <ChevronDown size={14} />}</span>
                    <button onClick={(e) => { e.stopPropagation(); handleDelete(message.id); }}
                      className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg transition-all"><Trash2 size={14} /></button>
                  </div>
                </div>
                {expandedId === message.id && (
                  <div className="px-5 pb-5 pt-1">
                    <div className="bg-gray-50 rounded-xl p-4 border-l-4 border-[#4A7C59]">
                      <p className="text-[10px] uppercase tracking-wide text-gray-400 font-bold mb-2">Message complet</p>
                      <p className="text-sm text-gray-800 whitespace-pre-wrap leading-relaxed">{message.message}</p>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
      {messages.length > 0 && (
        <div className="mt-4 flex items-center gap-4 text-xs text-gray-500">
          <span>Total: {messages.length} message{messages.length > 1 ? "s" : ""}</span>
          <span>Non lus: {unreadCount}</span>
          <span>Lus: {messages.length - unreadCount}</span>
        </div>
      )}
    </div>
  );
}

// ── Campaigns Section ──────────────────────────────────────────────────────────

function CampaignsSection() {
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<Partial<Campaign> | null>(null);

  const fetchCampaigns = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/campaigns");
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      setCampaigns(Array.isArray(data) ? data : []);
    } catch (err) { console.error(err); setCampaigns([]); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchCampaigns(); }, []);

  const saveCampaign = async (data: Partial<Campaign>) => {
    if (data.id) {
      await fetch(`/api/admin/campaigns/${data.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
    } else {
      await fetch("/api/admin/campaigns", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
    }
    await fetchCampaigns();
  };

  const deleteCampaign = async (id: string) => {
    if (!confirm("Supprimer cette campagne ?")) return;
    await fetch(`/api/admin/campaigns/${id}`, { method: "DELETE" });
    await fetchCampaigns();
  };

  const toggleActive = async (campaign: Campaign) => {
    await fetch(`/api/admin/campaigns/${campaign.id}`, {
      method: "PUT", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...campaign, active: !campaign.active }),
    });
    await fetchCampaigns();
  };

  return (
    <div>
      {modal !== null && <CampaignModal initial={modal} onSave={saveCampaign} onClose={() => setModal(null)} />}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 mb-1">Campagnes</h1>
          <p className="text-gray-500 text-sm">Gérez la bannière de campagne en haut de la page d&apos;accueil</p>
        </div>
        <button onClick={() => setModal({})}
          className="flex items-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white px-4 py-2.5 rounded-lg font-semibold transition-all text-sm">
          <Plus size={18} /> Nouvelle
        </button>
      </div>
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="w-8 h-8 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
        </div>
      ) : (
        <div className="bg-white rounded-xl border-2 border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b-2 border-gray-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Titre</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Slogan</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Média</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Statut</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {campaigns.length === 0 ? (
                  <tr><td colSpan={5} className="px-4 py-10 text-center text-gray-500 text-sm">Aucune campagne.</td></tr>
                ) : campaigns.map((campaign) => (
                  <tr key={campaign.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3 font-medium text-gray-900 max-w-[180px] truncate">{campaign.title}</td>
                    <td className="px-4 py-3 text-sm text-gray-500 max-w-[160px] truncate">
                      {campaign.slogan ?? <span className="text-gray-300 italic">—</span>}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${campaign.mediaType === "video" ? "bg-purple-100 text-purple-700" : "bg-blue-100 text-blue-700"}`}>
                        {campaign.mediaType === "video" ? <Video size={12} /> : <ImageIcon size={12} />}
                        {campaign.mediaType === "video"
                          ? (campaign.videoUrl?.includes("res.cloudinary.com") ? "Vidéo (fichier)" : "Vidéo (URL)")
                          : "Image"}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => toggleActive(campaign)}
                        className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-all ${campaign.active ? "bg-[#E67E22]/10 text-[#E67E22] hover:bg-[#E67E22]/20" : "bg-gray-100 text-gray-500 hover:bg-gray-200"}`}>
                        {campaign.active ? <CheckCircle size={12} /> : <Circle size={12} />}
                        {campaign.active ? "Active" : "Inactive"}
                      </button>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <button onClick={() => setModal(campaign)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"><Pencil size={16} /></button>
                        <button onClick={() => deleteCampaign(campaign.id)} className="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-all"><Trash2 size={16} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Profile Section ────────────────────────────────────────────────────────────

function ProfileSection() {
  const { data: session, update } = useSession();
  const [name, setName] = useState(session?.user?.name || "");
  const [email, setEmail] = useState(session?.user?.email || "");
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMessage(null);
    if (!currentPassword) { setMessage({ type: "error", text: "Le mot de passe actuel est requis" }); return; }
    if (newPassword && newPassword !== confirmPassword) { setMessage({ type: "error", text: "Les nouveaux mots de passe ne correspondent pas" }); return; }
    if (newPassword && newPassword.length < 8) { setMessage({ type: "error", text: "Le nouveau mot de passe doit contenir au moins 8 caractères" }); return; }
    setLoading(true);
    try {
      const res = await fetch("/api/admin/account", {
        method: "PUT", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, currentPassword, newPassword: newPassword || undefined }),
      });
      const data = await res.json();
      if (!res.ok) {
        setMessage({ type: "error", text: data.error });
      } else {
        setMessage({ type: "success", text: "Profil mis à jour avec succès" });
        setCurrentPassword(""); setNewPassword(""); setConfirmPassword("");
        await update({ name, email });
        if (newPassword || email !== session?.user?.email) {
          setTimeout(() => signOut({ callbackUrl: "/admin/login" }), 1500);
        }
      }
    } catch { setMessage({ type: "error", text: "Une erreur s'est produite" }); }
    finally { setLoading(false); }
  };

  return (
    <div className="max-w-2xl">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 mb-1">Mon profil</h1>
        <p className="text-gray-500 text-sm">Gérez vos informations de connexion</p>
      </div>
      <div className="bg-white rounded-xl border-2 border-gray-200 p-5 mb-5">
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 rounded-full bg-[#4A7C59]/10 flex items-center justify-center">
            <User size={24} className="text-[#4A7C59]" />
          </div>
          <div>
            <p className="font-bold text-gray-900">{session?.user?.name || "Admin"}</p>
            <p className="text-xs text-gray-500">{session?.user?.email}</p>
          </div>
        </div>
      </div>
      <form onSubmit={handleSubmit} className="space-y-5">
        <div className="bg-white rounded-xl border-2 border-gray-200 p-5">
          <h2 className="text-base font-bold text-gray-900 mb-3 flex items-center gap-2">
            <User size={18} className="text-[#4A7C59]" /> Informations
          </h2>
          <div className="space-y-3">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1.5">Nom</label>
              <input type="text" value={name} onChange={(e) => setName(e.target.value)}
                className="w-full px-4 py-2.5 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59] transition text-sm" />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1.5">Email</label>
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required
                className="w-full px-4 py-2.5 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59] transition text-sm" />
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl border-2 border-gray-200 p-5">
          <h2 className="text-base font-bold text-gray-900 mb-3 flex items-center gap-2">
            <Lock size={18} className="text-[#4A7C59]" /> Mot de passe
          </h2>
          <div className="space-y-3">
            {[
              { label: "Mot de passe actuel *", val: currentPassword, set: setCurrentPassword, show: showCurrent, toggle: () => setShowCurrent(!showCurrent) },
              { label: "Nouveau mot de passe", val: newPassword, set: setNewPassword, show: showNew, toggle: () => setShowNew(!showNew) },
            ].map(({ label, val, set: setVal, show, toggle }, i) => (
              <div key={i}>
                <label className="block text-sm font-semibold text-gray-700 mb-1.5">{label}</label>
                <div className="relative">
                  <input type={show ? "text" : "password"} value={val} onChange={(e) => setVal(e.target.value)}
                    className="w-full px-4 py-2.5 pr-10 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59] transition text-sm"
                    placeholder="••••••••" />
                  <button type="button" onClick={toggle} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 p-0.5">
                    {show ? <EyeOffIcon size={16} /> : <Eye size={16} />}
                  </button>
                </div>
              </div>
            ))}
            {newPassword && (
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1.5">Confirmer le nouveau mot de passe</label>
                <div className="relative">
                  <input type={showConfirm ? "text" : "password"} value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)}
                    className="w-full px-4 py-2.5 pr-10 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59] transition text-sm"
                    placeholder="••••••••" />
                  <button type="button" onClick={() => setShowConfirm(!showConfirm)} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 p-0.5">
                    {showConfirm ? <EyeOffIcon size={16} /> : <Eye size={16} />}
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
        {message && (
          <div className={`flex items-center gap-2 px-4 py-3 rounded-xl border-2 text-sm font-medium ${message.type === "success" ? "bg-green-50 border-green-200 text-green-700" : "bg-red-50 border-red-200 text-red-700"}`}>
            {message.type === "success" ? <CheckCircle size={16} /> : <AlertCircle size={16} />}
            {message.text}
          </div>
        )}
        <div className="flex items-center gap-3">
          <button type="submit" disabled={loading}
            className="flex items-center gap-2 bg-[#4A7C59] hover:bg-[#3d6849] text-white font-semibold px-5 py-2.5 rounded-xl transition-all disabled:opacity-50 text-sm">
            {loading ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save size={16} />}
            Enregistrer
          </button>
          <button type="button" onClick={() => signOut({ callbackUrl: "/admin/login" })}
            className="flex items-center gap-2 text-red-600 hover:bg-red-50 font-medium px-5 py-2.5 rounded-xl transition-all text-sm">
            <LogOut size={16} /> Déconnexion
          </button>
        </div>
      </form>
    </div>
  );
}

// ── Sidebar nav ────────────────────────────────────────────────────────────────

const NAV_ITEMS: { icon: React.ComponentType<{ size?: number; className?: string }>; label: string; section: Section }[] = [
  { icon: LayoutDashboard, label: "Tableau de bord", section: "dashboard" },
  { icon: Newspaper, label: "Actualités", section: "articles" },
  { icon: Briefcase, label: "Projets", section: "projects" },
  { icon: Handshake, label: "Partenaires", section: "partners" },
  { icon: Mail, label: "Messages", section: "messages" },
  { icon: MapPin, label: "Zones", section: "zones" },
  { icon: Megaphone, label: "Campagnes", section: "campaigns" },
  { icon: UserCircle, label: "Mon profil", section: "profile" },
];

// ── Main ManagementPanel ────────────────────────────────────────────────────────

export function ManagementPanel() {
  const { adminPanelOpen, closeAdminPanel } = useEditMode();
  const [section, setSection] = useState<Section>("dashboard");

  const handleNavigate = (s: Section) => setSection(s);

  useEffect(() => {
    if (adminPanelOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [adminPanelOpen]);

  if (!adminPanelOpen) return null;

  return (
    <div className="fixed inset-0 z-[60] bg-white flex flex-col">
      {/* Top bar */}
      <div className="bg-[#0d1117] h-12 flex items-center justify-between px-4 flex-shrink-0">
        <div className="flex items-center gap-2">
          <div className="w-6 h-6 rounded bg-[#4A7C59] flex items-center justify-center">
            <span className="text-white text-xs font-bold">A</span>
          </div>
          <span className="text-white font-semibold text-sm">Gestion ANED</span>
        </div>
        <button onClick={closeAdminPanel}
          className="flex items-center gap-1.5 text-white/60 hover:text-white hover:bg-white/10 px-3 py-1.5 rounded-md transition-all text-xs font-medium">
          <X size={14} /> Retour au site
        </button>
      </div>

      {/* Body */}
      <div className="flex flex-1 overflow-hidden">
        {/* Sidebar */}
        <div className="w-56 bg-gray-50 border-r border-gray-200 flex flex-col flex-shrink-0 overflow-y-auto">
          <div className="px-3 py-4">
            <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 px-2 mb-2">Navigation</p>
            <nav className="space-y-0.5">
              {NAV_ITEMS.map(({ icon: Icon, label, section: s }) => (
                <button key={s} onClick={() => setSection(s)}
                  className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium transition-all ${section === s ? "bg-[#4A7C59] text-white" : "text-gray-600 hover:bg-gray-200 hover:text-gray-900"}`}>
                  <Icon size={16} />
                  {label}
                </button>
              ))}
            </nav>
          </div>
        </div>

        {/* Content area */}
        <div className="flex-1 overflow-y-auto p-6">
          {section === "dashboard" && <DashboardSection onNavigate={handleNavigate} />}
          {section === "articles" && <ArticlesSection />}
          {section === "projects" && <ProjectsSection />}
          {section === "partners" && <PartnersSection />}
          {section === "messages" && <MessagesSection />}
          {section === "zones" && <ZonesSection />}
          {section === "campaigns" && <CampaignsSection />}
          {section === "profile" && <ProfileSection />}
        </div>
      </div>
    </div>
  );
}
