"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import {
  Plus, PencilSimple, Trash, BookOpen, X, UploadSimple, Check, ShoppingBag,
} from "@phosphor-icons/react";

/* ─── Types ───────────────────────────────────────────────────────── */

interface Recette {
  id:                       number;
  title:                    string;
  description:              string;
  ingredients:              string[];
  steps:                    string[];
  image_url:                string;
  image_public_id:          string;
  astuces:                  string[];
  bien_fait:                string[];
  product_id:               number | null;
  product_name:             string | null;
  product_ingredient_index: number | null;
  published:                boolean;
  created_at:               string;
  updated_at:               string;
}

interface ProductOption {
  id:   number;
  name: string;
}

interface IngrRow {
  text:       string;
  product_id: number | null;
}

const EMPTY_FORM = {
  title:       "",
  description: "",
  ingredients: [{ text: "", product_id: null }] as IngrRow[],
  steps:       [""] as string[],
  astuces:     [""] as string[],
  bien_fait:   [""] as string[],
  published:   true,
};

type ModalMode = "add" | "edit" | null;

/* ─── Ingredient row with product autocomplete ───────────────────── */

function IngrInput({
  row,
  index,
  products,
  onChange,
  onSelectProduct,
  onUnlink,
  onRemove,
  canRemove,
}: {
  row:             IngrRow;
  index:           number;
  products:        ProductOption[];
  onChange:        (text: string) => void;
  onSelectProduct: (p: ProductOption) => void;
  onUnlink:        () => void;
  onRemove:        () => void;
  canRemove:       boolean;
}) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  const suggestions = row.product_id == null && row.text.trim().length > 0
    ? products.filter(p => p.name.toLowerCase().includes(row.text.toLowerCase().trim()))
    : [];

  // Close dropdown on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  return (
    <div ref={wrapRef} className="relative">
      <div className={`flex gap-2 items-center px-1 py-1 rounded-xl border transition-colors ${
        row.product_id != null ? "border-brand-yellow/50 bg-brand-yellow/6" : "border-transparent"
      }`}>
        <span className="w-5 h-5 rounded-full bg-brand-dark/10 text-brand-dark/40 text-[10px] font-bold flex items-center justify-center flex-shrink-0">
          {index + 1}
        </span>

        <div className="flex-1 relative">
          <input
            value={row.text}
            onChange={(e) => {
              onChange(e.target.value);
              setOpen(true);
            }}
            onFocus={() => setOpen(true)}
            placeholder={`Ingrédient ${index + 1}`}
            className={`w-full px-3 py-2 rounded-xl border 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 ${
              row.product_id != null ? "border-brand-yellow/40 font-semibold bg-white" : "border-brand-dark/15"
            }`}
          />
          {/* Linked badge inside input row */}
          {row.product_id != null && (
            <span className="absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-1 text-[10px] font-black text-brand-section pointer-events-none">
              <ShoppingBag size={10} weight="bold" /> Asli Food
            </span>
          )}
        </div>

        {/* Unlink button — only shown when a product is linked */}
        {row.product_id != null && (
          <button
            type="button"
            title="Retirer le lien produit"
            onClick={onUnlink}
            className="w-7 h-7 flex items-center justify-center rounded-full bg-brand-yellow/20 hover:bg-red-50 text-brand-section hover:text-red-400 transition-colors flex-shrink-0"
          >
            <X size={11} weight="bold" />
          </button>
        )}

        {canRemove && (
          <button type="button" onClick={onRemove} className="text-brand-dark/25 hover:text-red-400 transition-colors flex-shrink-0">
            <X size={14} weight="bold" />
          </button>
        )}
      </div>

      {/* Autocomplete dropdown */}
      {open && suggestions.length > 0 && (
        <div className="absolute z-20 left-7 right-0 mt-1 bg-white border border-brand-dark/10 rounded-2xl shadow-xl overflow-hidden">
          <p className="px-3 pt-2 pb-1 text-[10px] font-bold text-brand-dark/35 tracking-widest uppercase">
            Produits Asli Food
          </p>
          {suggestions.map(p => (
            <button
              key={p.id}
              type="button"
              onMouseDown={(e) => {
                e.preventDefault(); // keep focus
                onSelectProduct(p);
                setOpen(false);
              }}
              className="w-full flex items-center gap-2.5 px-3 py-2.5 hover:bg-brand-yellow/10 transition-colors text-left"
            >
              <ShoppingBag size={13} weight="bold" className="text-brand-section flex-shrink-0" />
              <span className="text-sm font-semibold text-brand-dark">{p.name}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

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

export default function RecettesPage() {
  const [recettes,        setRecettes]        = useState<Recette[]>([]);
  const [recettesLoading, setRecettesLoading] = useState(false);
  const [recetteModal,    setRecetteModal]    = useState<ModalMode>(null);
  const [editingRecette,  setEditingRecette]  = useState<Recette | null>(null);
  const [form,            setForm]            = useState(EMPTY_FORM);
  const [recetteImage,    setRecetteImage]    = useState<File | null>(null);
  const [recettePreview,  setRecettePreview]  = useState("");
  const [savingRecette,   setSavingRecette]   = useState(false);
  const [deletingRecette, setDeletingRecette] = useState<number | null>(null);
  const [products,        setProducts]        = useState<ProductOption[]>([]);

  const recetteFileRef = useRef<HTMLInputElement>(null);

  const loadRecettes = async () => {
    setRecettesLoading(true);
    const res  = await fetch("/api/recettes");
    const data = await res.json();
    setRecettes(Array.isArray(data) ? data : []);
    setRecettesLoading(false);
  };

  useEffect(() => {
    loadRecettes();
    fetch("/api/products")
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data))
          setProducts(data.map((p: { id: number; name: string }) => ({ id: p.id, name: p.name })));
      })
      .catch(() => {});
  }, []);

  /* ── Modal helpers ── */
  const openAddRecette = () => {
    setEditingRecette(null);
    setForm(EMPTY_FORM);
    setRecetteImage(null);
    setRecettePreview("");
    setRecetteModal("add");
  };

  const openEditRecette = (r: Recette) => {
    setEditingRecette(r);
    const rows: IngrRow[] = (r.ingredients?.length ? r.ingredients : [""]).map((text, i) => ({
      text,
      product_id: (r.product_ingredient_index === i && r.product_id != null) ? r.product_id : null,
    }));
    setForm({
      title:       r.title,
      description: r.description,
      ingredients: rows,
      steps:       r.steps?.length    ? r.steps    : [""],
      astuces:     r.astuces?.length  ? r.astuces  : [""],
      bien_fait:   r.bien_fait?.length ? r.bien_fait : [""],
      published:   r.published,
    });
    setRecetteImage(null);
    setRecettePreview(r.image_url ?? "");
    setRecetteModal("edit");
  };

  const closeRecetteModal = () => { setRecetteModal(null); setEditingRecette(null); };

  const handleRecetteImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setRecetteImage(file);
    setRecettePreview(URL.createObjectURL(file));
  };

  /* ── Ingredient helpers ── */
  const updateIngr = (i: number, text: string) =>
    setForm(f => {
      const rows = [...f.ingredients];
      // Typing clears product link
      rows[i] = { text, product_id: null };
      return { ...f, ingredients: rows };
    });

  const selectProduct = (i: number, p: ProductOption) =>
    setForm(f => {
      const rows = f.ingredients.map((row, idx) =>
        idx === i
          ? { text: p.name, product_id: p.id }
          // unlink any other row that had a product (only 1 per recipe)
          : { ...row, product_id: null }
      );
      return { ...f, ingredients: rows };
    });

  const unlinkProduct = (i: number) =>
    setForm(f => {
      const rows = [...f.ingredients];
      rows[i] = { ...rows[i], product_id: null };
      return { ...f, ingredients: rows };
    });

  const removeIngr = (i: number) =>
    setForm(f => ({ ...f, ingredients: f.ingredients.filter((_, j) => j !== i) }));

  const addIngr = () =>
    setForm(f => ({ ...f, ingredients: [...f.ingredients, { text: "", product_id: null }] }));

  /* ── Save ── */
  const handleSaveRecette = async (e: React.FormEvent) => {
    e.preventDefault();
    setSavingRecette(true);
    try {
      let image_url       = editingRecette?.image_url       ?? "";
      let image_public_id = editingRecette?.image_public_id ?? "";

      if (recetteImage) {
        const fd = new FormData();
        fd.append("file", recetteImage);
        if (image_public_id) fd.append("old_public_id", image_public_id);
        const up     = await fetch("/api/upload", { method: "POST", body: fd });
        const upData = await up.json();
        image_url       = upData.url;
        image_public_id = upData.public_id;
      }

      const validRows = form.ingredients.filter(r => r.text.trim());
      const ingredients = validRows.map(r => r.text.trim());

      const productRowIdx = validRows.findIndex(r => r.product_id != null);
      const product_id               = productRowIdx >= 0 ? validRows[productRowIdx].product_id : null;
      const product_ingredient_index = productRowIdx >= 0 ? productRowIdx : null;

      const steps = form.steps.map(s => s.trim()).filter(Boolean);

      const astuces   = form.astuces.map(s => s.trim()).filter(Boolean);
      const bien_fait = form.bien_fait.map(s => s.trim()).filter(Boolean);

      const body = {
        title:                    form.title,
        description:              form.description,
        ingredients,
        steps,
        astuces,
        bien_fait,
        image_url,
        image_public_id,
        published:                form.published,
        product_id,
        product_ingredient_index,
      };

      if (recetteModal === "add") {
        await fetch("/api/recettes", {
          method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
        });
      } else if (editingRecette) {
        await fetch(`/api/recettes/${editingRecette.id}`, {
          method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
        });
      }

      await loadRecettes();
      closeRecetteModal();
    } finally {
      setSavingRecette(false);
    }
  };

  const handleDeleteRecette = async (r: Recette) => {
    if (!confirm(`Supprimer "${r.title}" ? Cette action est irréversible.`)) return;
    setDeletingRecette(r.id);
    await fetch(`/api/recettes/${r.id}`, { method: "DELETE" });
    await loadRecettes();
    setDeletingRecette(null);
  };

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

      <div className="flex justify-end">
        <button onClick={openAddRecette} 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 hover:scale-105 transition-transform duration-200">
          <Plus size={14} weight="bold" /> <span>Ajouter une recette</span>
        </button>
      </div>

      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-3">
          {[
            { label: "Total",    value: recettes.length,                            bg: "bg-white"           },
            { label: "Publiées", value: recettes.filter(r => r.published).length,   bg: "bg-brand-yellow/15" },
          ].map(s => (
            <div key={s.label} className={`${s.bg} rounded-2xl p-4 border border-brand-dark/8`}>
              <div className="text-2xl font-bold text-brand-dark" style={{ fontFamily: "var(--font-space,sans-serif)" }}>{s.value}</div>
              <div className="text-[10px] font-bold text-brand-dark/40 tracking-wider uppercase mt-0.5">{s.label}</div>
            </div>
          ))}
        </div>

        {recettesLoading ? (
          <LoadingSkeleton />
        ) : recettes.length === 0 ? (
          <div className="text-center py-20 bg-white rounded-3xl border border-brand-dark/8">
            <BookOpen size={52} weight="light" className="text-brand-dark/20 mx-auto mb-4" />
            <h3 className="text-base font-bold text-brand-dark mb-1.5">Aucune recette</h3>
            <p className="text-brand-dark/40 text-sm mb-6">Commencez par ajouter votre première recette.</p>
            <button onClick={openAddRecette} className="inline-flex items-center gap-2 bg-brand-dark text-brand-yellow font-bold px-6 py-3 rounded-full text-sm hover:scale-105 transition-transform duration-200">
              <Plus size={15} weight="bold" /> Ajouter une recette
            </button>
          </div>
        ) : (
          <div className="space-y-3">
            {recettes.map(r => (
              <div key={r.id} className="bg-white rounded-3xl border border-brand-dark/8 p-4 flex items-start gap-4">
                {r.image_url ? (
                  <div className="relative w-24 h-24 flex-shrink-0 rounded-2xl overflow-hidden bg-brand-off-white">
                    <Image src={r.image_url} alt={r.title} fill className="object-cover" />
                  </div>
                ) : (
                  <div className="w-24 h-24 flex-shrink-0 rounded-2xl bg-brand-off-white flex items-center justify-center">
                    <BookOpen size={28} weight="light" className="text-brand-dark/20" />
                  </div>
                )}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1.5">
                    <h3 className="font-bold text-brand-dark text-sm leading-tight flex-1" style={{ fontFamily: "var(--font-space,sans-serif)" }}>{r.title}</h3>
                    <span className={`text-[10px] font-bold px-2.5 py-0.5 rounded-full border flex-shrink-0 ${r.published ? "bg-green-100 text-green-700 border-green-200" : "bg-brand-dark/8 text-brand-dark/40 border-brand-dark/10"}`}>
                      {r.published ? "Publiée" : "Brouillon"}
                    </span>
                  </div>
                  {r.description && <p className="text-brand-dark/60 text-xs leading-relaxed line-clamp-2 mb-1.5">{r.description}</p>}
                  <div className="flex gap-3 text-brand-dark/45 text-[10px] font-semibold flex-wrap">
                    <span>{r.ingredients?.length ?? 0} ingrédients</span>
                    <span>{r.steps?.length ?? 0} étapes</span>
                    {r.product_name && (
                      <span className="flex items-center gap-1 text-brand-section font-bold">
                        <ShoppingBag size={10} weight="bold" /> {r.product_name}
                      </span>
                    )}
                  </div>
                </div>
                <div className="flex gap-2 flex-shrink-0">
                  <button onClick={() => openEditRecette(r)} className="flex items-center justify-center w-8 h-8 border border-brand-dark/15 rounded-full hover:border-brand-dark transition-colors text-brand-dark" title="Modifier">
                    <PencilSimple size={13} weight="bold" />
                  </button>
                  <button onClick={() => handleDeleteRecette(r)} disabled={deletingRecette === r.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" title="Supprimer">
                    {deletingRecette === r.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>
        )}
      </div>

      {/* ─── Modal ─────────────────────────────────────────────────── */}
      {recetteModal && (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center" onClick={e => { if (e.target === e.currentTarget) closeRecetteModal(); }}>
          <div className="absolute inset-0 bg-brand-dark/50 backdrop-blur-sm" />
          <div className="relative w-full sm:max-w-lg bg-white rounded-t-3xl sm:rounded-3xl shadow-2xl max-h-[92dvh] flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-300">
            <div className="flex items-center justify-between px-5 pt-5 pb-4 border-b border-brand-dark/8 flex-shrink-0">
              <div className="absolute top-2 left-1/2 -translate-x-1/2 w-10 h-1 bg-brand-dark/15 rounded-full sm:hidden" />
              <h2 className="font-bold text-brand-dark" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                {recetteModal === "add" ? "Nouvelle recette" : "Modifier la recette"}
              </h2>
              <button type="button" onClick={closeRecetteModal} className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-brand-dark/8 text-brand-dark/50 hover:text-brand-dark transition-colors">
                <X size={16} weight="bold" />
              </button>
            </div>

            <form onSubmit={handleSaveRecette} className="overflow-y-auto overscroll-contain flex-1 px-5 py-5 space-y-4" onWheel={e => e.stopPropagation()}>

              {/* Image */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-2">Image</label>
                <div role="button" tabIndex={0} onClick={() => recetteFileRef.current?.click()} onKeyDown={e => e.key === "Enter" && recetteFileRef.current?.click()} className="relative h-36 bg-brand-off-white rounded-2xl border-2 border-dashed border-brand-dark/15 flex items-center justify-center cursor-pointer hover:border-brand-yellow transition-colors overflow-hidden group">
                  {recettePreview ? (
                    <>
                      <Image src={recettePreview} alt="aperçu" fill className="object-cover" />
                      <div className="absolute inset-0 bg-black/0 group-hover:bg-black/15 transition-colors flex items-center justify-center">
                        <UploadSimple size={22} weight="bold" className="text-white opacity-0 group-hover:opacity-100 transition-opacity drop-shadow" />
                      </div>
                    </>
                  ) : (
                    <div className="flex flex-col items-center gap-1.5 text-brand-dark/30 group-hover:text-brand-dark/60 transition-colors select-none">
                      <UploadSimple size={30} weight="light" />
                      <span className="text-xs font-semibold">Appuyez pour choisir</span>
                    </div>
                  )}
                </div>
                <input ref={recetteFileRef} type="file" accept="image/*" className="hidden" onChange={handleRecetteImageChange} />
              </div>

              {/* Title */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Titre <span className="text-red-400">*</span></label>
                <input required value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} placeholder="Nom de la recette" 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>

              {/* Description */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Description <span className="normal-case font-normal text-brand-dark/30">(optionnel)</span></label>
                <textarea rows={3} value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} placeholder="Description courte de la recette..." 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 resize-none" />
              </div>

              {/* Ingredients with product autocomplete */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-2">Ingrédients</label>
                <div className="space-y-2">
                  {form.ingredients.map((row, i) => (
                    <IngrInput
                      key={i}
                      row={row}
                      index={i}
                      products={products}
                      onChange={text => updateIngr(i, text)}
                      onSelectProduct={p => selectProduct(i, p)}
                      onUnlink={() => unlinkProduct(i)}
                      onRemove={() => removeIngr(i)}
                      canRemove={form.ingredients.length > 1}
                    />
                  ))}
                </div>
                <button type="button" onClick={addIngr} className="mt-2 text-xs font-bold text-brand-dark/40 hover:text-brand-dark transition-colors flex items-center gap-1">
                  <Plus size={12} weight="bold" /> Ajouter un ingrédient
                </button>
              </div>

              {/* Steps */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widests uppercase mb-2">Étapes</label>
                <div className="space-y-2">
                  {form.steps.map((step, i) => (
                    <div key={i} className="flex gap-2 items-center">
                      <span className="w-5 h-5 rounded-full bg-brand-dark text-brand-yellow text-[10px] font-bold flex items-center justify-center flex-shrink-0">{i + 1}</span>
                      <input value={step} onChange={e => setForm(f => { const arr = [...f.steps]; arr[i] = e.target.value; return { ...f, steps: arr }; })} placeholder={`Étape ${i + 1}`} 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 placeholder:text-brand-dark/25 transition-all" />
                      {form.steps.length > 1 && (
                        <button type="button" onClick={() => setForm(f => ({ ...f, steps: f.steps.filter((_, j) => j !== i) }))} className="text-brand-dark/25 hover:text-red-400 transition-colors flex-shrink-0">
                          <X size={14} weight="bold" />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
                <button type="button" onClick={() => setForm(f => ({ ...f, steps: [...f.steps, ""] }))} className="mt-2 text-xs font-bold text-brand-dark/40 hover:text-brand-dark transition-colors flex items-center gap-1">
                  <Plus size={12} weight="bold" /> Ajouter une étape
                </button>
              </div>

              {/* Astuces */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widests uppercase mb-2">
                  Astuces <span className="normal-case font-normal text-brand-dark/30">(optionnel)</span>
                </label>
                <div className="space-y-2">
                  {form.astuces.map((tip, i) => (
                    <div key={i} className="flex gap-2 items-center">
                      <span className="w-5 h-5 rounded-full bg-brand-yellow/30 text-brand-dark/60 text-[10px] font-bold flex items-center justify-center flex-shrink-0">💡</span>
                      <input value={tip} onChange={e => setForm(f => { const arr = [...f.astuces]; arr[i] = e.target.value; return { ...f, astuces: arr }; })} placeholder={`Astuce ${i + 1}`} 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 placeholder:text-brand-dark/25 transition-all" />
                      {form.astuces.length > 1 && (
                        <button type="button" onClick={() => setForm(f => ({ ...f, astuces: f.astuces.filter((_, j) => j !== i) }))} className="text-brand-dark/25 hover:text-red-400 transition-colors flex-shrink-0">
                          <X size={14} weight="bold" />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
                <button type="button" onClick={() => setForm(f => ({ ...f, astuces: [...f.astuces, ""] }))} className="mt-2 text-xs font-bold text-brand-dark/40 hover:text-brand-dark transition-colors flex items-center gap-1">
                  <Plus size={12} weight="bold" /> Ajouter une astuce
                </button>
              </div>

              {/* Bien fait */}
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widests uppercase mb-2">
                  Comment savoir si c'est bien fait <span className="normal-case font-normal text-brand-dark/30">(optionnel)</span>
                </label>
                <div className="space-y-2">
                  {form.bien_fait.map((tip, i) => (
                    <div key={i} className="flex gap-2 items-center">
                      <span className="w-5 h-5 rounded-full bg-green-100 text-green-600 text-[10px] font-bold flex items-center justify-center flex-shrink-0">✓</span>
                      <input value={tip} onChange={e => setForm(f => { const arr = [...f.bien_fait]; arr[i] = e.target.value; return { ...f, bien_fait: arr }; })} placeholder={`Indicateur ${i + 1}`} 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 placeholder:text-brand-dark/25 transition-all" />
                      {form.bien_fait.length > 1 && (
                        <button type="button" onClick={() => setForm(f => ({ ...f, bien_fait: f.bien_fait.filter((_, j) => j !== i) }))} className="text-brand-dark/25 hover:text-red-400 transition-colors flex-shrink-0">
                          <X size={14} weight="bold" />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
                <button type="button" onClick={() => setForm(f => ({ ...f, bien_fait: [...f.bien_fait, ""] }))} className="mt-2 text-xs font-bold text-brand-dark/40 hover:text-brand-dark transition-colors flex items-center gap-1">
                  <Plus size={12} weight="bold" /> Ajouter un indicateur
                </button>
              </div>

              {/* Published toggle */}
              <div className="flex items-center justify-between bg-brand-sand-light rounded-xl px-4 py-3">
                <div>
                  <div className="text-sm font-bold text-brand-dark">Publier</div>
                  <div className="text-[10px] text-brand-dark/40 mt-0.5">Visible sur le site public</div>
                </div>
                <button type="button" onClick={() => setForm(f => ({ ...f, published: !f.published }))} aria-checked={form.published} role="switch" className={`relative w-11 h-6 rounded-full transition-colors duration-300 flex-shrink-0 ${form.published ? "bg-brand-dark" : "bg-brand-dark/20"}`}>
                  <span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow-sm flex items-center justify-center transition-transform duration-300 ${form.published ? "translate-x-5" : "translate-x-0"}`}>
                    {form.published && <Check size={10} weight="bold" className="text-brand-dark" />}
                  </span>
                </button>
              </div>

              {/* Submit */}
              <div className="pb-safe">
                <button type="submit" disabled={savingRecette} className="w-full bg-brand-dark text-brand-yellow font-bold py-3.5 rounded-full text-sm tracking-wide flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] active:scale-[0.99] transition-transform duration-200 mt-1">
                  {savingRecette && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  {savingRecette ? "Enregistrement..." : recetteModal === "add" ? "Ajouter la recette" : "Enregistrer les modifications"}
                </button>
              </div>

            </form>
          </div>
        </div>
      )}

    </main>
  );
}

function LoadingSkeleton() {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      {Array.from({ length: 6 }).map((_, i) => (
        <div key={i} className="bg-white rounded-3xl overflow-hidden border border-brand-dark/8 animate-pulse">
          <div className="h-40 bg-brand-dark/5" />
          <div className="p-4 space-y-2.5">
            <div className="h-3.5 bg-brand-dark/8 rounded-full w-3/4" />
            <div className="h-3   bg-brand-dark/5 rounded-full w-1/2" />
            <div className="h-3   bg-brand-dark/5 rounded-full w-full" />
          </div>
        </div>
      ))}
    </div>
  );
}
