import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertCircle,
  Save,
  User as UserIcon,
  Lock,
  LogOut,
  Trash2,
  Mail,
  ChefHat,
  CheckCircle2,
  X,
  Calendar,
  Sparkles,
  BookOpen,
  AlertTriangle,
} from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";

import { recipeService, Recipe } from "@/api/recipe";
import userService from "@/api/user";

// ---------------------------------------------------------------------------
// Types & constants
// ---------------------------------------------------------------------------

interface User {
  id: string;
  email: string;
  name: string;
  subscription?: string;
  createdAt: string;
  dietaryPreference?: string | null;
  allergies?: string | null;
  maxCookingTime?: number | null;
  equipment?: string[];
  cuisinePreference?: string | null;
  servingsDefault?: number | null;
}

const EQUIPMENT_OPTIONS = [
  { key: "plaque", label: "Plaque", emoji: "🔥" },
  { key: "four", label: "Four", emoji: "♨️" },
  { key: "micro-ondes", label: "Micro-ondes", emoji: "📡" },
  { key: "mixeur", label: "Mixeur", emoji: "🌀" },
  { key: "robot", label: "Robot pâtissier", emoji: "🍰" },
  { key: "friteuse", label: "Friteuse à air", emoji: "🍟" },
  { key: "barbecue", label: "Barbecue", emoji: "🔥" },
  { key: "cuiseur-vapeur", label: "Cuiseur vapeur", emoji: "💨" },
];

const DIET_LABELS: Record<string, string> = {
  none: "Omnivore",
  vegetarian: "Végétarien",
  vegan: "Végan",
  pescatarian: "Pescétarien",
};

// ---------------------------------------------------------------------------

export default function Profile() {
  const navigate = useNavigate();
  const [user, setUser] = useState<User | null>(null);
  const [userRecipes, setUserRecipes] = useState<Recipe[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletePassword, setDeletePassword] = useState("");

  const [profileForm, setProfileForm] = useState({ name: "" });
  const [passwordForm, setPasswordForm] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
  const [emailForm, setEmailForm] = useState({ newEmail: "", password: "" });
  const [prefsForm, setPrefsForm] = useState({
    dietaryPreference: "none",
    allergies: "",
    maxCookingTime: "",
    equipment: [] as string[],
    cuisinePreference: "",
    servingsDefault: "",
  });

  // --- Load user data ---
  useEffect(() => {
    const fetchUserData = async () => {
      try {
        setLoading(true);
        const userData = await userService.getCurrentUser();
        setUser(userData);
        setProfileForm({ name: userData.name || "" });
        setPrefsForm({
          dietaryPreference: userData.dietaryPreference || "none",
          allergies: userData.allergies || "",
          maxCookingTime: userData.maxCookingTime ? String(userData.maxCookingTime) : "",
          equipment: userData.equipment || [],
          cuisinePreference: userData.cuisinePreference || "",
          servingsDefault: userData.servingsDefault ? String(userData.servingsDefault) : "",
        });
        const recipes = await recipeService.getRecipes();
        setUserRecipes(recipes);
      } catch (err) {
        console.error("Erreur lors du chargement du profil:", err);
        setError("Impossible de charger les données du profil");
        if (err instanceof Error && err.message.includes("401")) {
          localStorage.removeItem("token");
          navigate("/auth/login");
        }
      } finally {
        setLoading(false);
      }
    };
    fetchUserData();
  }, [navigate]);

  // Auto-dismiss success messages
  useEffect(() => {
    if (!success) return;
    const id = setTimeout(() => setSuccess(""), 4000);
    return () => clearTimeout(id);
  }, [success]);

  // --- Handlers ---

  const handleProfileSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSuccess("");
    try {
      setSaving(true);
      const updatedUser = await userService.updateProfile(profileForm);
      setUser(updatedUser);
      setSuccess("Profil mis à jour");
    } catch {
      setError("Impossible de mettre à jour le profil");
    } finally {
      setSaving(false);
    }
  };

  const handlePrefsSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSuccess("");
    try {
      setSaving(true);
      await userService.updatePreferences({
        dietaryPreference: prefsForm.dietaryPreference === "none" ? null : prefsForm.dietaryPreference,
        allergies: prefsForm.allergies.trim() || null,
        maxCookingTime: prefsForm.maxCookingTime ? parseInt(prefsForm.maxCookingTime, 10) : null,
        equipment: prefsForm.equipment.length > 0 ? prefsForm.equipment : null,
        cuisinePreference: prefsForm.cuisinePreference.trim() || null,
        servingsDefault: prefsForm.servingsDefault ? parseInt(prefsForm.servingsDefault, 10) : null,
      });
      setSuccess("Préférences culinaires mises à jour");
    } catch {
      setError("Impossible de mettre à jour les préférences");
    } finally {
      setSaving(false);
    }
  };

  const toggleEquipment = (key: string) => {
    setPrefsForm((prev) => ({
      ...prev,
      equipment: prev.equipment.includes(key)
        ? prev.equipment.filter((e) => e !== key)
        : [...prev.equipment, key],
    }));
  };

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSuccess("");
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      setError("Les mots de passe ne correspondent pas");
      return;
    }
    if (passwordForm.newPassword.length < 8) {
      setError("Le mot de passe doit contenir au moins 8 caractères");
      return;
    }
    try {
      setSaving(true);
      await userService.changePassword({
        currentPassword: passwordForm.currentPassword,
        newPassword: passwordForm.newPassword,
      });
      setSuccess("Mot de passe modifié");
      setPasswordForm({ currentPassword: "", newPassword: "", confirmPassword: "" });
    } catch {
      setError("Mot de passe actuel incorrect");
    } finally {
      setSaving(false);
    }
  };

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSuccess("");
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(emailForm.newEmail)) {
      setError("Adresse email invalide");
      return;
    }
    try {
      setSaving(true);
      await userService.changeEmail({
        newEmail: emailForm.newEmail,
        password: emailForm.password,
      });
      setSuccess("Email modifié");
      if (user) setUser({ ...user, email: emailForm.newEmail });
      setEmailForm({ newEmail: "", password: "" });
    } catch {
      setError("Mot de passe incorrect");
    } finally {
      setSaving(false);
    }
  };

  const handleLogout = async () => {
    try {
      await userService.logout();
    } catch {/* ignore */}
    localStorage.removeItem("token");
    navigate("/auth/login");
  };

  const handleDeleteAccount = async () => {
    try {
      await userService.deleteAccount(deletePassword);
      localStorage.removeItem("token");
      navigate("/auth/login");
    } catch {
      setError("Mot de passe incorrect");
      setDeleteDialogOpen(false);
    }
  };

  // --- Render: loading ---
  if (loading) {
    return (
      <div className="mx-auto max-w-5xl px-4 py-8 space-y-6">
        <div className="flex items-center gap-4">
          <div className="h-24 w-24 rounded-full bg-muted/60 animate-pulse" />
          <div className="flex-1 space-y-2">
            <div className="h-6 w-48 bg-muted/60 rounded animate-pulse" />
            <div className="h-4 w-32 bg-muted/60 rounded animate-pulse" />
          </div>
        </div>
        <div className="grid grid-cols-3 gap-4">
          <div className="h-20 bg-muted/60 rounded-xl animate-pulse" />
          <div className="h-20 bg-muted/60 rounded-xl animate-pulse" />
          <div className="h-20 bg-muted/60 rounded-xl animate-pulse" />
        </div>
        <div className="h-12 bg-muted/60 rounded-xl animate-pulse" />
        <div className="h-96 bg-muted/60 rounded-xl animate-pulse" />
      </div>
    );
  }

  // --- Render: error ---
  if (!user) {
    return (
      <div className="mx-auto max-w-md px-4 py-16 text-center">
        <div className="inline-flex h-16 w-16 items-center justify-center rounded-full bg-red-50 dark:bg-red-950/40 mb-4">
          <AlertCircle className="h-8 w-8 text-red-500" />
        </div>
        <h2 className="text-2xl font-bold mb-2">Non connecté</h2>
        <p className="text-muted-foreground mb-6">
          Vous devez être connecté pour accéder à cette page.
        </p>
        <Button
          className="bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white rounded-full"
          onClick={() => navigate("/auth/login")}
        >
          Se connecter
        </Button>
      </div>
    );
  }

  const memberSince = new Date(user.createdAt).toLocaleDateString("fr-FR", {
    month: "long",
    year: "numeric",
  });
  const initial = (user.name || user.email)[0].toUpperCase();
  const isPremium = user.subscription && user.subscription !== "free";
  const hasPrefs =
    !!user.dietaryPreference && user.dietaryPreference !== "none" ||
    !!user.allergies ||
    !!user.maxCookingTime ||
    (user.equipment && user.equipment.length > 0) ||
    !!user.cuisinePreference;

  return (
    <div className="mx-auto max-w-5xl px-4 md:px-6 py-6 md:py-10">
      {/* --- Hero --- */}
      <motion.section
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
        className="mb-8"
      >
        <div className="flex flex-col sm:flex-row sm:items-center gap-5">
          {/* Avatar */}
          <div className="relative shrink-0 mx-auto sm:mx-0">
            <Avatar className="h-24 w-24 md:h-28 md:w-28 ring-4 ring-white dark:ring-slate-900 shadow-xl shadow-orange-500/10">
              <AvatarFallback className="bg-gradient-to-br from-orange-400 to-amber-500 text-white text-3xl md:text-4xl font-bold">
                {initial}
              </AvatarFallback>
            </Avatar>
            {isPremium && (
              <div className="absolute -bottom-1 -right-1 h-8 w-8 rounded-full bg-gradient-to-br from-amber-400 to-orange-500 ring-4 ring-background flex items-center justify-center">
                <Sparkles className="h-4 w-4 text-white" />
              </div>
            )}
          </div>

          {/* Infos */}
          <div className="flex-1 text-center sm:text-left">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div>
                <h1 className="text-3xl md:text-4xl font-bold tracking-tight">
                  {user.name || "Utilisateur"}
                </h1>
                <p className="text-muted-foreground text-sm md:text-base mt-0.5">
                  {user.email}
                </p>
              </div>
              <Button
                variant="ghost"
                size="sm"
                onClick={handleLogout}
                className="rounded-full text-muted-foreground hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30 w-full sm:w-auto"
              >
                <LogOut className="mr-2 h-4 w-4" />
                Déconnexion
              </Button>
            </div>

            {/* Badges */}
            <div className="flex flex-wrap gap-2 mt-3 justify-center sm:justify-start">
              <Badge
                variant="secondary"
                className={
                  isPremium
                    ? "bg-gradient-to-r from-amber-100 to-orange-100 text-orange-700 border border-orange-200/60 dark:from-amber-900/40 dark:to-orange-900/40 dark:text-orange-300 dark:border-orange-800/40"
                    : "bg-muted"
                }
              >
                {isPremium ? (
                  <>
                    <Sparkles className="mr-1 h-3 w-3" />
                    {user.subscription}
                  </>
                ) : (
                  "Plan gratuit"
                )}
              </Badge>
              <Badge variant="secondary" className="bg-muted">
                <Calendar className="mr-1 h-3 w-3" />
                Depuis {memberSince}
              </Badge>
              <Badge variant="secondary" className="bg-muted">
                <BookOpen className="mr-1 h-3 w-3" />
                {userRecipes.length} recette{userRecipes.length > 1 ? "s" : ""}
              </Badge>
            </div>
          </div>
        </div>
      </motion.section>

      {/* --- Alerts --- */}
      <AnimatePresence mode="popLayout">
        {error && (
          <motion.div
            key="error"
            initial={{ opacity: 0, y: -8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            className="mb-4"
          >
            <div className="flex items-start gap-3 rounded-xl bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-900/50 p-4 text-sm text-red-800 dark:text-red-200">
              <AlertCircle className="h-5 w-5 shrink-0 mt-0.5" />
              <div className="flex-1">{error}</div>
              <button
                onClick={() => setError("")}
                className="text-red-600 hover:text-red-800"
                aria-label="Fermer"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          </motion.div>
        )}
        {success && (
          <motion.div
            key="success"
            initial={{ opacity: 0, y: -8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            className="mb-4"
          >
            <div className="flex items-start gap-3 rounded-xl bg-emerald-50 dark:bg-emerald-950/40 border border-emerald-200 dark:border-emerald-900/50 p-4 text-sm text-emerald-800 dark:text-emerald-200">
              <CheckCircle2 className="h-5 w-5 shrink-0 mt-0.5" />
              <div className="flex-1">{success}</div>
              <button
                onClick={() => setSuccess("")}
                className="text-emerald-600 hover:text-emerald-800"
                aria-label="Fermer"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* --- Tabs --- */}
      <Tabs defaultValue="cuisine" className="w-full">
        <TabsList className="grid w-full grid-cols-4 bg-muted/60 backdrop-blur-sm p-1 h-auto">
          <TabsTrigger
            value="cuisine"
            className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm rounded-lg gap-1.5 py-2.5 transition-all"
          >
            <ChefHat className="h-4 w-4" />
            <span className="hidden sm:inline">Cuisine</span>
          </TabsTrigger>
          <TabsTrigger
            value="profile"
            className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm rounded-lg gap-1.5 py-2.5 transition-all"
          >
            <UserIcon className="h-4 w-4" />
            <span className="hidden sm:inline">Profil</span>
          </TabsTrigger>
          <TabsTrigger
            value="email"
            className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm rounded-lg gap-1.5 py-2.5 transition-all"
          >
            <Mail className="h-4 w-4" />
            <span className="hidden sm:inline">Email</span>
          </TabsTrigger>
          <TabsTrigger
            value="security"
            className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm rounded-lg gap-1.5 py-2.5 transition-all"
          >
            <Lock className="h-4 w-4" />
            <span className="hidden sm:inline">Sécurité</span>
          </TabsTrigger>
        </TabsList>

        {/* --- Tab Cuisine --- */}
        <TabsContent value="cuisine" className="mt-6">
          <Card className="border-border/60 bg-card/80 backdrop-blur-sm rounded-2xl shadow-sm">
            <CardHeader>
              <div className="flex items-start justify-between">
                <div>
                  <CardTitle className="text-xl flex items-center gap-2">
                    <ChefHat className="h-5 w-5 text-orange-500" />
                    Préférences culinaires
                  </CardTitle>
                  <CardDescription className="mt-1.5">
                    Ces infos sont envoyées au chef Antoine pour chaque nouvelle recette
                  </CardDescription>
                </div>
                {hasPrefs && (
                  <Badge variant="outline" className="border-emerald-200 bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-900/60 shrink-0">
                    <CheckCircle2 className="mr-1 h-3 w-3" />
                    Actif
                  </Badge>
                )}
              </div>
            </CardHeader>
            <CardContent>
              <form onSubmit={handlePrefsSubmit} className="space-y-8">
                {/* Régime */}
                <div className="space-y-3">
                  <Label className="text-base font-semibold">Régime alimentaire</Label>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                    {Object.entries(DIET_LABELS).map(([key, label]) => (
                      <button
                        key={key}
                        type="button"
                        onClick={() => setPrefsForm({ ...prefsForm, dietaryPreference: key })}
                        className={`rounded-xl border-2 px-3 py-3 text-sm font-medium transition-all ${
                          prefsForm.dietaryPreference === key
                            ? "border-orange-500 bg-orange-50 dark:bg-orange-950/30 text-orange-700 dark:text-orange-300"
                            : "border-border hover:border-orange-200 hover:bg-orange-50/50 dark:hover:bg-orange-950/20"
                        }`}
                      >
                        {label}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Allergies */}
                <div className="space-y-2">
                  <Label htmlFor="allergies" className="text-base font-semibold">
                    Allergies et intolérances
                  </Label>
                  <Input
                    id="allergies"
                    placeholder="arachides, gluten, lactose..."
                    value={prefsForm.allergies}
                    onChange={(e) => setPrefsForm({ ...prefsForm, allergies: e.target.value })}
                    className="rounded-xl h-11"
                  />
                  <p className="text-xs text-muted-foreground">
                    Séparées par des virgules. Le chef les évitera impérativement.
                  </p>
                </div>

                {/* Temps + portions */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="maxTime" className="text-base font-semibold">
                      Temps max
                    </Label>
                    <div className="relative">
                      <Input
                        id="maxTime"
                        type="number"
                        min="5"
                        max="600"
                        placeholder="60"
                        value={prefsForm.maxCookingTime}
                        onChange={(e) => setPrefsForm({ ...prefsForm, maxCookingTime: e.target.value })}
                        className="rounded-xl h-11 pr-12"
                      />
                      <span className="absolute right-4 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
                        min
                      </span>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="servings" className="text-base font-semibold">
                      Portions
                    </Label>
                    <div className="relative">
                      <Input
                        id="servings"
                        type="number"
                        min="1"
                        max="20"
                        placeholder="4"
                        value={prefsForm.servingsDefault}
                        onChange={(e) => setPrefsForm({ ...prefsForm, servingsDefault: e.target.value })}
                        className="rounded-xl h-11 pr-16"
                      />
                      <span className="absolute right-4 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
                        pers.
                      </span>
                    </div>
                  </div>
                </div>

                {/* Cuisine */}
                <div className="space-y-2">
                  <Label htmlFor="cuisine" className="text-base font-semibold">
                    Inspiration culinaire
                  </Label>
                  <Input
                    id="cuisine"
                    placeholder="française, italienne, asiatique, libanaise..."
                    value={prefsForm.cuisinePreference}
                    onChange={(e) => setPrefsForm({ ...prefsForm, cuisinePreference: e.target.value })}
                    className="rounded-xl h-11"
                  />
                </div>

                {/* Équipement */}
                <div className="space-y-3">
                  <Label className="text-base font-semibold">Équipement disponible</Label>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                    {EQUIPMENT_OPTIONS.map((opt) => {
                      const active = prefsForm.equipment.includes(opt.key);
                      return (
                        <button
                          key={opt.key}
                          type="button"
                          onClick={() => toggleEquipment(opt.key)}
                          className={`flex flex-col items-center justify-center gap-1 rounded-xl border-2 px-2 py-3 text-xs font-medium transition-all ${
                            active
                              ? "border-orange-500 bg-orange-50 dark:bg-orange-950/30 text-orange-700 dark:text-orange-300"
                              : "border-border hover:border-orange-200 hover:bg-orange-50/50 dark:hover:bg-orange-950/20 text-muted-foreground"
                          }`}
                        >
                          <Checkbox
                            checked={active}
                            className="pointer-events-none sr-only"
                            tabIndex={-1}
                          />
                          <span className="text-2xl leading-none">{opt.emoji}</span>
                          <span className="text-center leading-tight">{opt.label}</span>
                        </button>
                      );
                    })}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Le chef n'utilisera que des techniques compatibles.
                  </p>
                </div>

                <div className="pt-2">
                  <Button
                    type="submit"
                    disabled={saving}
                    className="w-full sm:w-auto h-12 px-8 rounded-full bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white shadow-md shadow-orange-500/20 hover:shadow-lg hover:shadow-orange-500/30 transition-all font-semibold"
                  >
                    {saving ? (
                      <>
                        <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                        Enregistrement…
                      </>
                    ) : (
                      <>
                        <Save className="mr-2 h-4 w-4" />
                        Enregistrer les préférences
                      </>
                    )}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* --- Tab Profile --- */}
        <TabsContent value="profile" className="mt-6">
          <Card className="border-border/60 bg-card/80 backdrop-blur-sm rounded-2xl shadow-sm">
            <CardHeader>
              <CardTitle className="text-xl">Informations du profil</CardTitle>
              <CardDescription>
                Mettez à jour vos informations personnelles
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleProfileSubmit} className="space-y-5">
                <div className="space-y-2">
                  <Label htmlFor="name" className="text-base font-semibold">
                    Nom d'affichage
                  </Label>
                  <Input
                    id="name"
                    name="name"
                    value={profileForm.name}
                    onChange={(e) => setProfileForm({ name: e.target.value })}
                    required
                    className="rounded-xl h-11"
                  />
                </div>
                <Button
                  type="submit"
                  disabled={saving}
                  className="h-12 px-8 rounded-full bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white shadow-md shadow-orange-500/20 hover:shadow-lg hover:shadow-orange-500/30 transition-all font-semibold"
                >
                  {saving ? (
                    <>
                      <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                      Enregistrement…
                    </>
                  ) : (
                    <>
                      <Save className="mr-2 h-4 w-4" />
                      Enregistrer
                    </>
                  )}
                </Button>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* --- Tab Email --- */}
        <TabsContent value="email" className="mt-6">
          <Card className="border-border/60 bg-card/80 backdrop-blur-sm rounded-2xl shadow-sm">
            <CardHeader>
              <CardTitle className="text-xl">Changer d'adresse email</CardTitle>
              <CardDescription>
                Votre email actuel : <span className="font-medium text-foreground">{user.email}</span>
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleEmailSubmit} className="space-y-5">
                <div className="space-y-2">
                  <Label htmlFor="newEmail" className="text-base font-semibold">
                    Nouvelle adresse email
                  </Label>
                  <Input
                    id="newEmail"
                    type="email"
                    placeholder="nouvelle@email.com"
                    value={emailForm.newEmail}
                    onChange={(e) => setEmailForm({ ...emailForm, newEmail: e.target.value })}
                    required
                    className="rounded-xl h-11"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="emailPassword" className="text-base font-semibold">
                    Confirmez avec votre mot de passe
                  </Label>
                  <Input
                    id="emailPassword"
                    type="password"
                    placeholder="••••••••"
                    value={emailForm.password}
                    onChange={(e) => setEmailForm({ ...emailForm, password: e.target.value })}
                    required
                    className="rounded-xl h-11"
                  />
                </div>
                <Button
                  type="submit"
                  disabled={saving}
                  className="h-12 px-8 rounded-full bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white shadow-md shadow-orange-500/20 hover:shadow-lg hover:shadow-orange-500/30 transition-all font-semibold"
                >
                  {saving ? (
                    <>
                      <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                      Mise à jour…
                    </>
                  ) : (
                    <>
                      <Mail className="mr-2 h-4 w-4" />
                      Changer l'email
                    </>
                  )}
                </Button>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* --- Tab Security --- */}
        <TabsContent value="security" className="mt-6">
          <Card className="border-border/60 bg-card/80 backdrop-blur-sm rounded-2xl shadow-sm">
            <CardHeader>
              <CardTitle className="text-xl">Sécurité du compte</CardTitle>
              <CardDescription>
                Choisissez un mot de passe d'au moins 8 caractères
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handlePasswordSubmit} className="space-y-5">
                <div className="space-y-2">
                  <Label htmlFor="currentPassword" className="text-base font-semibold">
                    Mot de passe actuel
                  </Label>
                  <Input
                    id="currentPassword"
                    type="password"
                    placeholder="••••••••"
                    value={passwordForm.currentPassword}
                    onChange={(e) => setPasswordForm({ ...passwordForm, currentPassword: e.target.value })}
                    required
                    className="rounded-xl h-11"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="newPassword" className="text-base font-semibold">
                    Nouveau mot de passe
                  </Label>
                  <Input
                    id="newPassword"
                    type="password"
                    placeholder="••••••••"
                    value={passwordForm.newPassword}
                    onChange={(e) => setPasswordForm({ ...passwordForm, newPassword: e.target.value })}
                    required
                    className="rounded-xl h-11"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="confirmPassword" className="text-base font-semibold">
                    Confirmer le nouveau mot de passe
                  </Label>
                  <Input
                    id="confirmPassword"
                    type="password"
                    placeholder="••••••••"
                    value={passwordForm.confirmPassword}
                    onChange={(e) => setPasswordForm({ ...passwordForm, confirmPassword: e.target.value })}
                    required
                    className="rounded-xl h-11"
                  />
                </div>
                <Button
                  type="submit"
                  disabled={saving}
                  className="h-12 px-8 rounded-full bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white shadow-md shadow-orange-500/20 hover:shadow-lg hover:shadow-orange-500/30 transition-all font-semibold"
                >
                  {saving ? (
                    <>
                      <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                      Mise à jour…
                    </>
                  ) : (
                    <>
                      <Lock className="mr-2 h-4 w-4" />
                      Changer le mot de passe
                    </>
                  )}
                </Button>
              </form>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* --- Danger zone --- */}
      <motion.section
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.2 }}
        className="mt-12"
      >
        <div className="rounded-2xl border-2 border-red-200/60 dark:border-red-900/40 bg-red-50/50 dark:bg-red-950/20 p-5 md:p-6">
          <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
            <div className="flex gap-3">
              <div className="h-10 w-10 shrink-0 rounded-full bg-red-100 dark:bg-red-950/60 flex items-center justify-center">
                <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400" />
              </div>
              <div>
                <h3 className="font-semibold text-red-900 dark:text-red-200">
                  Zone de danger
                </h3>
                <p className="text-sm text-red-700/80 dark:text-red-300/80 mt-0.5">
                  La suppression de votre compte est définitive et toutes vos recettes seront effacées.
                </p>
              </div>
            </div>
            <Button
              variant="outline"
              onClick={() => setDeleteDialogOpen(true)}
              className="border-red-300 bg-white text-red-600 hover:bg-red-50 hover:text-red-700 hover:border-red-400 dark:border-red-900/60 dark:bg-red-950/40 dark:hover:bg-red-950/60 shrink-0 rounded-full"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              Supprimer mon compte
            </Button>
          </div>
        </div>
      </motion.section>

      {/* --- Delete account dialog --- */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-red-500" />
              Supprimer votre compte ?
            </DialogTitle>
            <DialogDescription>
              Cette action est définitive. Toutes vos recettes, préférences et
              données personnelles seront supprimées de nos serveurs.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-2 py-2">
            <Label htmlFor="deletePassword">Entrez votre mot de passe pour confirmer</Label>
            <Input
              id="deletePassword"
              type="password"
              placeholder="••••••••"
              value={deletePassword}
              onChange={(e) => setDeletePassword(e.target.value)}
              className="rounded-xl"
            />
          </div>
          <DialogFooter className="gap-2 sm:gap-0">
            <Button
              variant="outline"
              onClick={() => {
                setDeleteDialogOpen(false);
                setDeletePassword("");
              }}
              className="rounded-full"
            >
              Annuler
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteAccount}
              disabled={!deletePassword}
              className="rounded-full"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              Supprimer définitivement
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
