"use client";

import { useEffect, useState } from "react";
import {
  Plus, Trash, X, Check, CreditCard, User, UsersThree, Phone, AddressBook, Article,
  FacebookLogo, InstagramLogo, TiktokLogo, SnapchatLogo, TwitterLogo, WhatsappLogo, EnvelopeSimple,
} from "@phosphor-icons/react";
import type { ContactInfo } from "@/app/api/contact-info/route";
import { DEFAULT_ABOUT } from "@/lib/aboutContent";
import type { AboutContent } from "@/lib/aboutContent";

/* ─── Constants ──────────────────────────────────────────────────── */

interface PaymentMethodCfg {
  id:      string;
  name:    string;
  number:  string;
  enabled: boolean;
}

interface AdminUser {
  id:         number;
  username:   string;
  name:       string;
  email:      string;
  role:       string;
  created_at: string;
}

/* ─── Page ───────────────────────────────────────────────────────── */

const PLATFORM_OPTIONS = [
  { value: "facebook",  label: "Facebook",   icon: FacebookLogo  },
  { value: "instagram", label: "Instagram",  icon: InstagramLogo },
  { value: "tiktok",    label: "TikTok",     icon: TiktokLogo    },
  { value: "snapchat",  label: "Snapchat",   icon: SnapchatLogo  },
  { value: "twitter",   label: "Twitter / X", icon: TwitterLogo  },
  { value: "whatsapp",  label: "WhatsApp",   icon: WhatsappLogo  },
];

export default function ParametresPage() {
  const [settingsTab, setSettingsTab] = useState<"payment" | "profile" | "admins" | "responsables" | "contact" | "about">("payment");

  // Payment config
  const [paymentCfg,        setPaymentCfg]        = useState<PaymentMethodCfg[]>([]);
  const [paymentCfgLoading, setPaymentCfgLoading] = useState(false);
  const [paymentCfgSaving,  setPaymentCfgSaving]  = useState(false);
  const [paymentCfgMsg,     setPaymentCfgMsg]     = useState("");
  const [newMethodForm,     setNewMethodForm]     = useState({ name: "", number: "" });
  const [showNewMethod,     setShowNewMethod]     = useState(false);

  // Profile
  const [profileData,    setProfileData]    = useState({ name: "", email: "" });
  const [profilePwd,     setProfilePwd]     = useState({ current: "", next: "", confirm: "" });
  const [profileLoading, setProfileLoading] = useState(false);
  const [profileSaving,  setProfileSaving]  = useState(false);
  const [profileMsg,     setProfileMsg]     = useState("");

  // Contact info
  const [contactInfo,    setContactInfo]    = useState<ContactInfo>({ phone: "", whatsapp: "", email: "", socials: [] });
  const [contactLoading, setContactLoading] = useState(false);
  const [contactSaving,  setContactSaving]  = useState(false);
  const [contactMsg,     setContactMsg]     = useState("");

  // About page
  const [aboutContent,  setAboutContent]  = useState<AboutContent>(DEFAULT_ABOUT);
  const [aboutLoading,  setAboutLoading]  = useState(false);
  const [aboutSaving,   setAboutSaving]   = useState(false);
  const [aboutMsg,      setAboutMsg]      = useState("");

  // Admins
  const [adminsList,     setAdminsList]     = useState<AdminUser[]>([]);
  const [adminsLoading,  setAdminsLoading]  = useState(false);
  const [adminsMsg,      setAdminsMsg]      = useState("");
  const [deletingAdmin,  setDeletingAdmin]  = useState<number | null>(null);
  const [newAdminForm,       setNewAdminForm]       = useState({ username: "", name: "", email: "", password: "" });
  const [addingAdmin,        setAddingAdmin]        = useState(false);
  const [newResponsableForm, setNewResponsableForm] = useState({ username: "", name: "", email: "", password: "" });
  const [addingResponsable,  setAddingResponsable]  = useState(false);
  const [responsablesMsg,    setResponsablesMsg]    = useState("");
  const [currentAdminId,     setCurrentAdminId]     = useState<number | null>(null);

  /* ── Loaders ── */
  const loadPaymentCfg = async () => {
    setPaymentCfgLoading(true);
    const res  = await fetch("/api/admin/config");
    const data = await res.json();
    setPaymentCfg(Array.isArray(data) ? data : []);
    setPaymentCfgLoading(false);
  };

  const loadProfile = async () => {
    setProfileLoading(true);
    const res  = await fetch("/api/admin/profile");
    const data = await res.json();
    if (data) {
      setProfileData({ name: data.name ?? "", email: data.email ?? "" });
      setCurrentAdminId(data.id ?? null);
    }
    setProfileLoading(false);
  };

  const loadAdmins = async () => {
    setAdminsLoading(true);
    const res  = await fetch("/api/admin/admins");
    const data = await res.json();
    setAdminsList(Array.isArray(data) ? data : []);
    setAdminsLoading(false);
  };

  const loadContactInfo = async () => {
    setContactLoading(true);
    const res  = await fetch("/api/admin/config/contact");
    const data = await res.json();
    if (data && !data.error) setContactInfo(data);
    setContactLoading(false);
  };

  const loadAboutContent = async () => {
    setAboutLoading(true);
    const res  = await fetch("/api/admin/config/about");
    const data = await res.json();
    if (data && !data.error) setAboutContent(data);
    setAboutLoading(false);
  };

  useEffect(() => {
    loadPaymentCfg();
    loadProfile();
    loadAdmins();
    loadContactInfo();
    loadAboutContent();
  }, []);

  /* ── Handlers ── */
  const savePaymentCfg = async () => {
    setPaymentCfgSaving(true);
    setPaymentCfgMsg("");
    await fetch("/api/admin/config", {
      method:  "PUT",
      headers: { "Content-Type": "application/json" },
      body:    JSON.stringify(paymentCfg),
    });
    setPaymentCfgMsg("Enregistré ✓");
    setPaymentCfgSaving(false);
    setTimeout(() => setPaymentCfgMsg(""), 3000);
  };

  const saveProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setProfileSaving(true);
    setProfileMsg("");
    if (profilePwd.next && profilePwd.next !== profilePwd.confirm) {
      setProfileMsg("Les mots de passe ne correspondent pas");
      setProfileSaving(false);
      return;
    }
    const body: Record<string, string> = { name: profileData.name, email: profileData.email };
    if (profilePwd.next) {
      body.currentPassword = profilePwd.current;
      body.newPassword     = profilePwd.next;
    }
    const res  = await fetch("/api/admin/profile", {
      method:  "PUT",
      headers: { "Content-Type": "application/json" },
      body:    JSON.stringify(body),
    });
    const data = await res.json();
    if (!res.ok) {
      setProfileMsg(data.error ?? "Erreur");
    } else {
      setProfileMsg("Profil mis à jour ✓");
      setProfilePwd({ current: "", next: "", confirm: "" });
      setTimeout(() => setProfileMsg(""), 3000);
    }
    setProfileSaving(false);
  };

  const handleAddAdmin = async (e: React.FormEvent) => {
    e.preventDefault();
    setAddingAdmin(true);
    setAdminsMsg("");
    const res  = await fetch("/api/admin/admins", {
      method:  "POST",
      headers: { "Content-Type": "application/json" },
      body:    JSON.stringify(newAdminForm),
    });
    const data = await res.json();
    if (!res.ok) {
      setAdminsMsg(data.error ?? "Erreur");
    } else {
      setNewAdminForm({ username: "", name: "", email: "", password: "" });
      await loadAdmins();
    }
    setAddingAdmin(false);
    setTimeout(() => setAdminsMsg(""), 4000);
  };

  const saveContactInfo = async () => {
    setContactSaving(true);
    setContactMsg("");
    await fetch("/api/admin/config/contact", {
      method:  "PUT",
      headers: { "Content-Type": "application/json" },
      body:    JSON.stringify(contactInfo),
    });
    setContactMsg("Enregistré ✓");
    setContactSaving(false);
    setTimeout(() => setContactMsg(""), 3000);
  };

  const saveAboutContent = async () => {
    setAboutSaving(true);
    setAboutMsg("");
    await fetch("/api/admin/config/about", {
      method:  "PUT",
      headers: { "Content-Type": "application/json" },
      body:    JSON.stringify(aboutContent),
    });
    setAboutMsg("Enregistré ✓");
    setAboutSaving(false);
    setTimeout(() => setAboutMsg(""), 3000);
  };

  const handleAddResponsable = async (e: React.FormEvent) => {
    e.preventDefault();
    setAddingResponsable(true);
    setResponsablesMsg("");
    const res  = await fetch("/api/admin/admins", {
      method:  "POST",
      headers: { "Content-Type": "application/json" },
      body:    JSON.stringify({ ...newResponsableForm, role: "commandes" }),
    });
    const data = await res.json();
    if (!res.ok) {
      setResponsablesMsg(data.error ?? "Erreur");
    } else {
      setNewResponsableForm({ username: "", name: "", email: "", password: "" });
      await loadAdmins();
    }
    setAddingResponsable(false);
    setTimeout(() => setResponsablesMsg(""), 4000);
  };

  const handleDeleteAdmin = async (a: AdminUser) => {
    if (!confirm(`Supprimer l'admin "${a.username}" ?`)) return;
    setDeletingAdmin(a.id);
    await fetch(`/api/admin/admins/${a.id}`, { method: "DELETE" });
    await loadAdmins();
    setDeletingAdmin(null);
  };

  return (
    <main className="max-w-5xl mx-auto px-4 py-6 space-y-5">
      <div className="space-y-5">

        {/* Sub-tabs */}
        <div className="flex gap-2 bg-white border border-brand-dark/8 rounded-2xl p-1.5 w-fit">
          {([
            { key: "payment",       label: "Paiement",          icon: <CreditCard  size={13} weight="bold" /> },
            { key: "contact",       label: "Contact",            icon: <Phone       size={13} weight="bold" /> },
            { key: "about",         label: "À propos",           icon: <Article     size={13} weight="bold" /> },
            { key: "profile",       label: "Mon profil",         icon: <User        size={13} weight="bold" /> },
            { key: "admins",        label: "Admins",             icon: <UsersThree  size={13} weight="bold" /> },
            { key: "responsables",  label: "Resp. Commandes",    icon: <UsersThree  size={13} weight="bold" /> },
          ] as const).map(t => (
            <button
              key={t.key}
              onClick={() => setSettingsTab(t.key)}
              className={`flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-bold transition-colors duration-200 ${
                settingsTab === t.key
                  ? "bg-brand-dark text-brand-yellow"
                  : "text-brand-dark/50 hover:text-brand-dark"
              }`}
            >
              {t.icon}{t.label}
            </button>
          ))}
        </div>

        {/* ── A. Méthodes de paiement ── */}
        {settingsTab === "payment" && (
          <div className="bg-white border border-brand-dark/8 rounded-3xl p-6 space-y-5">
            <div className="flex items-center justify-between">
              <h3 className="font-bold text-brand-dark text-base" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                Méthodes de paiement
              </h3>
              {paymentCfgMsg && (
                <span className="text-xs font-semibold text-green-700 bg-green-50 border border-green-200 px-3 py-1 rounded-full">{paymentCfgMsg}</span>
              )}
            </div>

            {paymentCfgLoading ? (
              <div className="text-brand-dark/30 text-sm py-4">Chargement...</div>
            ) : (
              <div className="space-y-3">
                {paymentCfg.map((m, idx) => (
                  <div key={m.id} className="flex items-center gap-3 p-3 rounded-xl border border-brand-dark/10 bg-brand-sand-light">
                    <div className="flex-1 min-w-0 grid grid-cols-2 gap-2">
                      <input
                        value={m.name}
                        onChange={e => setPaymentCfg(cfg => cfg.map((c, i) => i === idx ? { ...c, name: e.target.value } : c))}
                        placeholder="Nom (ex: Bankily)"
                        className="px-3 py-2 rounded-xl border border-brand-dark/15 text-sm text-brand-dark bg-white focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 transition-all"
                      />
                      <input
                        value={m.number}
                        onChange={e => setPaymentCfg(cfg => cfg.map((c, i) => i === idx ? { ...c, number: e.target.value } : c))}
                        placeholder="Numéro"
                        className="px-3 py-2 rounded-xl border border-brand-dark/15 text-sm text-brand-dark bg-white focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 transition-all"
                      />
                    </div>
                    {/* Enabled toggle */}
                    <button
                      type="button"
                      onClick={() => setPaymentCfg(cfg => cfg.map((c, i) => i === idx ? { ...c, enabled: !c.enabled } : c))}
                      className={`relative w-10 h-5 rounded-full transition-colors duration-300 flex-shrink-0 ${m.enabled ? "bg-brand-dark" : "bg-brand-dark/20"}`}
                    >
                      <span className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow-sm transition-transform duration-300 ${m.enabled ? "translate-x-5" : "translate-x-0"}`} />
                    </button>
                    {/* Delete */}
                    <button
                      type="button"
                      onClick={() => setPaymentCfg(cfg => cfg.filter((_, i) => i !== idx))}
                      className="flex-shrink-0 text-brand-dark/25 hover:text-red-400 transition-colors"
                    >
                      <X size={14} weight="bold" />
                    </button>
                  </div>
                ))}
              </div>
            )}

            {/* Add new method */}
            {showNewMethod ? (
              <div className="p-3 rounded-xl border border-brand-yellow/40 bg-brand-yellow/8 space-y-3">
                <div className="grid grid-cols-2 gap-2">
                  <input
                    value={newMethodForm.name}
                    onChange={e => setNewMethodForm(f => ({ ...f, name: e.target.value }))}
                    placeholder="Nom (ex: Masrivi)"
                    className="px-3 py-2 rounded-xl border border-brand-dark/15 text-sm text-brand-dark bg-white focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 transition-all"
                  />
                  <input
                    value={newMethodForm.number}
                    onChange={e => setNewMethodForm(f => ({ ...f, number: e.target.value }))}
                    placeholder="Numéro"
                    className="px-3 py-2 rounded-xl border border-brand-dark/15 text-sm text-brand-dark bg-white focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 transition-all"
                  />
                </div>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => {
                      if (!newMethodForm.name.trim()) return;
                      const id = newMethodForm.name.toLowerCase().replace(/\s+/g, "_");
                      setPaymentCfg(cfg => [...cfg, { id, name: newMethodForm.name, number: newMethodForm.number, enabled: true }]);
                      setNewMethodForm({ name: "", number: "" });
                      setShowNewMethod(false);
                    }}
                    className="flex items-center gap-1.5 bg-brand-dark text-brand-yellow font-bold px-4 py-2 rounded-full text-xs tracking-wide"
                  >
                    <Check size={12} weight="bold" /> Ajouter
                  </button>
                  <button type="button" onClick={() => setShowNewMethod(false)} className="text-brand-dark/40 hover:text-brand-dark text-xs font-semibold px-3 py-2 transition-colors">
                    Annuler
                  </button>
                </div>
              </div>
            ) : (
              <button
                type="button"
                onClick={() => setShowNewMethod(true)}
                className="flex items-center gap-1.5 text-brand-dark/50 hover:text-brand-dark text-xs font-bold transition-colors"
              >
                <Plus size={13} weight="bold" /> Ajouter une méthode
              </button>
            )}

            <button
              type="button"
              onClick={savePaymentCfg}
              disabled={paymentCfgSaving}
              className="w-full bg-brand-dark text-brand-yellow font-bold py-3 rounded-full text-sm flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] transition-transform duration-200"
            >
              {paymentCfgSaving && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
              {paymentCfgSaving ? "Enregistrement..." : "Enregistrer"}
            </button>
          </div>
        )}

        {/* ── B. Contact ── */}
        {settingsTab === "contact" && (
          <div className="bg-white border border-brand-dark/8 rounded-3xl p-6 space-y-6">
            <div className="flex items-center justify-between">
              <h3 className="font-bold text-brand-dark text-base" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                Informations de contact
              </h3>
              {contactMsg && (
                <span className="text-xs font-semibold text-green-700 bg-green-50 border border-green-200 px-3 py-1 rounded-full">{contactMsg}</span>
              )}
            </div>

            {contactLoading ? (
              <div className="text-brand-dark/30 text-sm py-4">Chargement...</div>
            ) : (
              <div className="space-y-5">

                {/* Phone / WhatsApp / Email */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">
                      <span className="inline-flex items-center gap-1"><Phone size={10} weight="bold" /> Téléphone</span>
                    </label>
                    <input
                      value={contactInfo.phone}
                      onChange={e => setContactInfo(c => ({ ...c, phone: e.target.value }))}
                      placeholder="+222 XX XX XX XX"
                      className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">
                      <span className="inline-flex items-center gap-1"><WhatsappLogo size={10} weight="bold" /> WhatsApp (numéro)</span>
                    </label>
                    <input
                      value={contactInfo.whatsapp}
                      onChange={e => setContactInfo(c => ({ ...c, whatsapp: e.target.value }))}
                      placeholder="222XXXXXXXX"
                      className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                    />
                    <p className="text-brand-dark/30 text-[10px] mt-1">Sans le + (ex: 22241284479)</p>
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">
                      <span className="inline-flex items-center gap-1"><EnvelopeSimple size={10} weight="bold" /> Email</span>
                    </label>
                    <input
                      type="email"
                      value={contactInfo.email}
                      onChange={e => setContactInfo(c => ({ ...c, email: e.target.value }))}
                      placeholder="contact@example.com"
                      className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                    />
                  </div>
                </div>

                {/* Socials */}
                <div>
                  <div className="flex items-center justify-between mb-3">
                    <label className="text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase flex items-center gap-1">
                      <AddressBook size={10} weight="bold" /> Réseaux sociaux
                    </label>
                  </div>
                  <div className="space-y-2">
                    {contactInfo.socials.map((s, idx) => {
                      const PlatformIcon = PLATFORM_OPTIONS.find(p => p.value === s.platform)?.icon ?? FacebookLogo;
                      return (
                        <div key={idx} className="flex items-center gap-2 p-3 rounded-xl border border-brand-dark/10 bg-brand-sand-light">
                          {/* Platform select */}
                          <div className="flex items-center gap-1.5 flex-shrink-0">
                            <PlatformIcon size={15} weight="fill" className="text-brand-dark/60" />
                            <select
                              value={s.platform}
                              onChange={e => setContactInfo(c => ({
                                ...c,
                                socials: c.socials.map((ss, i) => i === idx ? { ...ss, platform: e.target.value } : ss),
                              }))}
                              className="text-xs text-brand-dark border border-brand-dark/15 rounded-lg px-2 py-1.5 bg-white focus:outline-none focus:border-brand-yellow transition-all"
                            >
                              {PLATFORM_OPTIONS.map(p => (
                                <option key={p.value} value={p.value}>{p.label}</option>
                              ))}
                            </select>
                          </div>
                          {/* Label */}
                          <input
                            value={s.label}
                            onChange={e => setContactInfo(c => ({
                              ...c,
                              socials: c.socials.map((ss, i) => i === idx ? { ...ss, label: e.target.value } : ss),
                            }))}
                            placeholder="@handle"
                            className="flex-1 min-w-0 px-3 py-1.5 rounded-lg border border-brand-dark/15 text-sm text-brand-dark bg-white focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 transition-all"
                          />
                          {/* URL */}
                          <input
                            value={s.href}
                            onChange={e => setContactInfo(c => ({
                              ...c,
                              socials: c.socials.map((ss, i) => i === idx ? { ...ss, href: e.target.value } : ss),
                            }))}
                            placeholder="https://..."
                            className="flex-[2] min-w-0 px-3 py-1.5 rounded-lg border border-brand-dark/15 text-sm text-brand-dark bg-white focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 transition-all"
                          />
                          {/* Delete */}
                          <button
                            type="button"
                            onClick={() => setContactInfo(c => ({ ...c, socials: c.socials.filter((_, i) => i !== idx) }))}
                            className="flex-shrink-0 text-brand-dark/25 hover:text-red-400 transition-colors"
                          >
                            <X size={14} weight="bold" />
                          </button>
                        </div>
                      );
                    })}
                  </div>

                  <button
                    type="button"
                    onClick={() => setContactInfo(c => ({ ...c, socials: [...c.socials, { platform: "facebook", label: "", href: "" }] }))}
                    className="mt-2 flex items-center gap-1.5 text-brand-dark/50 hover:text-brand-dark text-xs font-bold transition-colors"
                  >
                    <Plus size={13} weight="bold" /> Ajouter un réseau
                  </button>
                </div>

                <button
                  type="button"
                  onClick={saveContactInfo}
                  disabled={contactSaving}
                  className="w-full bg-brand-dark text-brand-yellow font-bold py-3 rounded-full text-sm flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] transition-transform duration-200"
                >
                  {contactSaving && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  {contactSaving ? "Enregistrement..." : "Enregistrer"}
                </button>
              </div>
            )}
          </div>
        )}

        {/* ── C. Mon profil ── */}
        {settingsTab === "profile" && (
          <div className="bg-white border border-brand-dark/8 rounded-3xl p-6">
            <h3 className="font-bold text-brand-dark text-base mb-5" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
              Mon profil
            </h3>
            {profileLoading ? (
              <div className="text-brand-dark/30 text-sm py-4">Chargement...</div>
            ) : (
              <form onSubmit={saveProfile} className="space-y-4">
                <div>
                  <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Nom</label>
                  <input
                    value={profileData.name}
                    onChange={e => setProfileData(d => ({ ...d, name: e.target.value }))}
                    placeholder="Votre nom"
                    className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Email</label>
                  <input
                    type="email"
                    value={profileData.email}
                    onChange={e => setProfileData(d => ({ ...d, email: e.target.value }))}
                    placeholder="votre@email.com"
                    className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                  />
                </div>

                <div className="border-t border-brand-dark/8 pt-4 space-y-3">
                  <p className="text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase">Changer le mot de passe <span className="normal-case font-normal text-brand-dark/30 tracking-normal">(optionnel)</span></p>
                  <input
                    type="password"
                    value={profilePwd.current}
                    onChange={e => setProfilePwd(p => ({ ...p, current: e.target.value }))}
                    placeholder="Mot de passe actuel"
                    className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                  />
                  <input
                    type="password"
                    value={profilePwd.next}
                    onChange={e => setProfilePwd(p => ({ ...p, next: e.target.value }))}
                    placeholder="Nouveau mot de passe"
                    className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                  />
                  <input
                    type="password"
                    value={profilePwd.confirm}
                    onChange={e => setProfilePwd(p => ({ ...p, confirm: e.target.value }))}
                    placeholder="Confirmer le nouveau mot de passe"
                    className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                  />
                </div>

                {profileMsg && (
                  <p className={`text-xs font-semibold px-3 py-2 rounded-xl border ${profileMsg.includes("✓") ? "bg-green-50 text-green-700 border-green-200" : "bg-red-50 text-red-600 border-red-200"}`}>
                    {profileMsg}
                  </p>
                )}

                <button
                  type="submit"
                  disabled={profileSaving}
                  className="w-full bg-brand-dark text-brand-yellow font-bold py-3 rounded-full text-sm flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] transition-transform duration-200"
                >
                  {profileSaving && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  {profileSaving ? "Enregistrement..." : "Enregistrer les modifications"}
                </button>
              </form>
            )}
          </div>
        )}

        {/* ── C. À propos ── */}
        {settingsTab === "about" && (
          <div className="bg-white border border-brand-dark/8 rounded-3xl p-6 space-y-5">
            <div className="flex items-center justify-between">
              <h3 className="font-bold text-brand-dark text-base" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                Page À propos
              </h3>
              {aboutMsg && (
                <span className="text-xs font-semibold text-green-700 bg-green-50 border border-green-200 px-3 py-1 rounded-full">{aboutMsg}</span>
              )}
            </div>

            {aboutLoading ? (
              <div className="text-brand-dark/30 text-sm">Chargement...</div>
            ) : (
              <div className="space-y-4">
                {/* Badge */}
                <div>
                  <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Badge</label>
                  <input
                    value={aboutContent.badge}
                    onChange={e => setAboutContent(c => ({ ...c, badge: e.target.value }))}
                    className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all"
                  />
                </div>

                {/* Title + subtitle */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Titre</label>
                    <input
                      value={aboutContent.title}
                      onChange={e => setAboutContent(c => ({ ...c, title: e.target.value }))}
                      className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Sous-titre</label>
                    <input
                      value={aboutContent.sub}
                      onChange={e => setAboutContent(c => ({ ...c, sub: e.target.value }))}
                      className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark transition-all"
                    />
                  </div>
                </div>

                {/* Paragraphs */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase">Paragraphes</label>
                    <button
                      type="button"
                      onClick={() => setAboutContent(c => ({ ...c, paragraphs: [...c.paragraphs, ""] }))}
                      className="flex items-center gap-1 text-[10px] font-bold text-brand-yellow bg-brand-dark px-2.5 py-1 rounded-full hover:scale-105 transition-transform"
                    >
                      <Plus size={10} weight="bold" /> Ajouter
                    </button>
                  </div>
                  <div className="space-y-2">
                    {aboutContent.paragraphs.map((p, i) => (
                      <div key={i} className="flex gap-2 items-start">
                        <textarea
                          rows={3}
                          value={p}
                          onChange={e => setAboutContent(c => {
                            const paragraphs = [...c.paragraphs];
                            paragraphs[i] = e.target.value;
                            return { ...c, paragraphs };
                          })}
                          placeholder={`Paragraphe ${i + 1}`}
                          className="flex-1 px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all resize-none"
                        />
                        {aboutContent.paragraphs.length > 1 && (
                          <button
                            type="button"
                            onClick={() => setAboutContent(c => ({ ...c, paragraphs: c.paragraphs.filter((_, j) => j !== i) }))}
                            className="mt-2 flex items-center justify-center w-7 h-7 border border-red-200 rounded-full hover:bg-red-50 text-red-400 transition-colors flex-shrink-0"
                          >
                            <X size={11} weight="bold" />
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                </div>

                {/* Stats cards */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase">Cartes statistiques</label>
                    <button
                      type="button"
                      onClick={() => setAboutContent(c => ({ ...c, stats: [...c.stats, { value: "", label: "" }] }))}
                      className="flex items-center gap-1 text-[10px] font-bold text-brand-yellow bg-brand-dark px-2.5 py-1 rounded-full hover:scale-105 transition-transform"
                    >
                      <Plus size={10} weight="bold" /> Ajouter
                    </button>
                  </div>
                  <div className="space-y-2">
                    {aboutContent.stats.map((stat, i) => (
                      <div key={i} className="flex gap-2 items-center">
                        <span className="text-[10px] font-bold text-brand-dark/30 w-4 flex-shrink-0">{i + 1}</span>
                        <input
                          value={stat.value}
                          onChange={e => setAboutContent(c => {
                            const stats = [...c.stats];
                            stats[i] = { ...stats[i], value: e.target.value };
                            return { ...c, stats };
                          })}
                          placeholder="Valeur (ex: 2020)"
                          className="w-24 px-3 py-2 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark transition-all font-bold"
                        />
                        <input
                          value={stat.label}
                          onChange={e => setAboutContent(c => {
                            const stats = [...c.stats];
                            stats[i] = { ...stats[i], label: e.target.value };
                            return { ...c, stats };
                          })}
                          placeholder="Étiquette (ex: Fondée)"
                          className="flex-1 px-3 py-2 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark transition-all"
                        />
                        {aboutContent.stats.length > 1 && (
                          <button
                            type="button"
                            onClick={() => setAboutContent(c => ({ ...c, stats: c.stats.filter((_, j) => j !== i) }))}
                            className="flex items-center justify-center w-7 h-7 border border-red-200 rounded-full hover:bg-red-50 text-red-400 transition-colors flex-shrink-0"
                          >
                            <X size={11} weight="bold" />
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                </div>

                <button
                  onClick={saveAboutContent}
                  disabled={aboutSaving}
                  className="w-full bg-brand-dark text-brand-yellow font-bold py-3 rounded-full text-sm flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] transition-transform duration-200"
                >
                  {aboutSaving && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  {aboutSaving ? "Enregistrement..." : "Enregistrer la page"}
                </button>
              </div>
            )}
          </div>
        )}

        {/* ── D. Administrateurs ── */}
        {settingsTab === "admins" && (
          <div className="space-y-4">
            <div className="bg-white border border-brand-dark/8 rounded-3xl p-6 space-y-4">
              <h3 className="font-bold text-brand-dark text-base" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                Administrateurs
              </h3>
              {adminsLoading ? (
                <div className="text-brand-dark/30 text-sm">Chargement...</div>
              ) : (
                <div className="space-y-2">
                  {adminsList.filter(a => a.role !== "commandes").map(a => (
                    <div key={a.id} className="flex items-center gap-3 p-3 rounded-xl border border-brand-dark/8 bg-brand-sand-light">
                      <div className="w-8 h-8 rounded-full bg-brand-dark/10 flex items-center justify-center flex-shrink-0">
                        <User size={14} weight="bold" className="text-brand-dark/50" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-brand-dark text-sm font-semibold">{a.name || a.username}</p>
                        <p className="text-brand-dark/40 text-xs">{a.username}{a.email ? ` · ${a.email}` : ""}</p>
                      </div>
                      {a.id !== currentAdminId && (
                        <button
                          onClick={() => handleDeleteAdmin(a)}
                          disabled={deletingAdmin === a.id}
                          className="flex items-center justify-center w-8 h-8 border border-red-200 rounded-full hover:bg-red-50 transition-colors text-red-500 disabled:opacity-40"
                        >
                          {deletingAdmin === a.id
                            ? <span className="w-3 h-3 border border-red-300 border-t-red-500 rounded-full animate-spin" />
                            : <Trash size={13} weight="bold" />
                          }
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Add admin form */}
            <div className="bg-white border border-brand-dark/8 rounded-3xl p-6">
              <h4 className="font-bold text-brand-dark text-sm mb-4" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                Ajouter un administrateur
              </h4>
              <form onSubmit={handleAddAdmin} className="space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Identifiant <span className="text-red-400">*</span></label>
                    <input required value={newAdminForm.username} onChange={e => setNewAdminForm(f => ({ ...f, username: e.target.value }))} placeholder="ex: admin2"
                      className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Nom</label>
                    <input value={newAdminForm.name} onChange={e => setNewAdminForm(f => ({ ...f, name: e.target.value }))} placeholder="Prénom Nom"
                      className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                  </div>
                </div>
                <input type="email" value={newAdminForm.email} onChange={e => setNewAdminForm(f => ({ ...f, email: e.target.value }))} placeholder="Email (optionnel)"
                  className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                <input required type="password" value={newAdminForm.password} onChange={e => setNewAdminForm(f => ({ ...f, password: e.target.value }))} placeholder="Mot de passe *"
                  className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                {adminsMsg && (
                  <p className={`text-xs font-semibold px-3 py-2 rounded-xl border ${adminsMsg.includes("✓") ? "bg-green-50 text-green-700 border-green-200" : "bg-red-50 text-red-600 border-red-200"}`}>{adminsMsg}</p>
                )}
                <button type="submit" disabled={addingAdmin}
                  className="w-full bg-brand-dark text-brand-yellow font-bold py-3 rounded-full text-sm flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] transition-transform duration-200">
                  {addingAdmin && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  <Plus size={13} weight="bold" />
                  {addingAdmin ? "Ajout en cours..." : "Ajouter l'administrateur"}
                </button>
              </form>
            </div>
          </div>
        )}

        {/* ── E. Responsables Commandes ── */}
        {settingsTab === "responsables" && (
          <div className="space-y-4">
            <div className="bg-white border border-brand-dark/8 rounded-3xl p-6 space-y-4">
              <div>
                <h3 className="font-bold text-brand-dark text-base" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                  Responsables Commandes
                </h3>
                <p className="text-brand-dark/40 text-xs mt-1">Accès limité à la page des commandes uniquement.</p>
              </div>
              {adminsLoading ? (
                <div className="text-brand-dark/30 text-sm">Chargement...</div>
              ) : adminsList.filter(a => a.role === "commandes").length === 0 ? (
                <p className="text-brand-dark/30 text-sm py-2">Aucun responsable commandes.</p>
              ) : (
                <div className="space-y-2">
                  {adminsList.filter(a => a.role === "commandes").map(a => (
                    <div key={a.id} className="flex items-center gap-3 p-3 rounded-xl border border-brand-peach bg-brand-peach/20">
                      <div className="w-8 h-8 rounded-full bg-brand-dark/10 flex items-center justify-center flex-shrink-0">
                        <User size={14} weight="bold" className="text-brand-dark/50" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-brand-dark text-sm font-semibold">{a.name || a.username}</p>
                        <p className="text-brand-dark/40 text-xs">{a.username}{a.email ? ` · ${a.email}` : ""}</p>
                      </div>
                      <span className="text-[9px] font-bold tracking-widest uppercase text-brand-dark/50 border border-brand-dark/15 px-2 py-1 rounded-full flex-shrink-0">
                        Commandes
                      </span>
                      <button
                        onClick={() => handleDeleteAdmin(a)}
                        disabled={deletingAdmin === a.id}
                        className="flex items-center justify-center w-8 h-8 border border-red-200 rounded-full hover:bg-red-50 transition-colors text-red-500 disabled:opacity-40"
                      >
                        {deletingAdmin === a.id
                          ? <span className="w-3 h-3 border border-red-300 border-t-red-500 rounded-full animate-spin" />
                          : <Trash size={13} weight="bold" />
                        }
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Add responsable form */}
            <div className="bg-white border border-brand-dark/8 rounded-3xl p-6">
              <h4 className="font-bold text-brand-dark text-sm mb-1" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                Ajouter un responsable commandes
              </h4>
              <p className="text-brand-dark/40 text-xs mb-4">Ce compte aura accès uniquement à la gestion des commandes.</p>
              <form onSubmit={handleAddResponsable} className="space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Identifiant <span className="text-red-400">*</span></label>
                    <input required value={newResponsableForm.username} onChange={e => setNewResponsableForm(f => ({ ...f, username: e.target.value }))} placeholder="ex: resp1"
                      className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Nom</label>
                    <input value={newResponsableForm.name} onChange={e => setNewResponsableForm(f => ({ ...f, name: e.target.value }))} placeholder="Prénom Nom"
                      className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                  </div>
                </div>
                <input type="email" value={newResponsableForm.email} onChange={e => setNewResponsableForm(f => ({ ...f, email: e.target.value }))} placeholder="Email (optionnel)"
                  className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                <input required type="password" value={newResponsableForm.password} onChange={e => setNewResponsableForm(f => ({ ...f, password: e.target.value }))} placeholder="Mot de passe *"
                  className="w-full px-3 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                {responsablesMsg && (
                  <p className={`text-xs font-semibold px-3 py-2 rounded-xl border ${responsablesMsg.includes("✓") ? "bg-green-50 text-green-700 border-green-200" : "bg-red-50 text-red-600 border-red-200"}`}>{responsablesMsg}</p>
                )}
                <button type="submit" disabled={addingResponsable}
                  className="w-full bg-brand-dark text-brand-yellow font-bold py-3 rounded-full text-sm flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] transition-transform duration-200">
                  {addingResponsable && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  <Plus size={13} weight="bold" />
                  {addingResponsable ? "Ajout en cours..." : "Créer le responsable"}
                </button>
              </form>
            </div>
          </div>
        )}

      </div>
    </main>
  );
}
