import { useLoaderData, Form, useActionData, useNavigation } from "react-router";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";
import { syncToShopify, youtubeIdFromUrl } from "../utils/shopifySync.server";
import { ensurePurchaseProducts, getPurchaseProductsStatus } from "../utils/purchaseProducts.server";
import { getVariantStats, runVariantPurge } from "../utils/variantPurge.server";

export const loader = async ({ request }) => {
  const { admin, session } = await authenticate.admin(request);
  const config = await prisma.appConfig.findUnique({ where: { shop: session.shop } });
  const [purchaseProducts, variantStats] = await Promise.all([
    getPurchaseProductsStatus(admin, config),
    getVariantStats(session.shop),
  ]);
  return {
    shopHandle: session.shop.replace(/\.myshopify\.com$/, ""),
    purchaseProducts,
    variantStats,
    purge: {
      enabled:       config?.purgeEnabled       ?? true,
      deliveredDays: config?.purgeDeliveredDays ?? 30,
      abandonedDays: config?.purgeAbandonedDays ?? 7,
      intervalHours: config?.purgeIntervalHours ?? 6,
      lastRunAt:     config?.purgeLastRunAt ? config.purgeLastRunAt.toISOString() : null,
      lastReport:    config?.purgeLastReport ?? "",
    },
    variantIdGravure: config?.variantIdGravure ?? "",
    variantIdRelief:  config?.variantIdRelief  ?? "",
    variantIdDecoupe: config?.variantIdDecoupe ?? "",
    priceElementText:  config?.priceElementText  ?? 0,
    priceElementImage: config?.priceElementImage ?? 0,
    textSizeMinMm:     config?.textSizeMinMm     ?? 3,
    textSizeMaxMm:     config?.textSizeMaxMm     ?? 100,
    elementSizeMinMm:  config?.elementSizeMinMm  ?? 5,
    elementSizeMaxMm:  config?.elementSizeMaxMm  ?? 300,
    workAreaMinMm:     config?.workAreaMinMm     ?? 50,
    workAreaMaxMm:     config?.workAreaMaxMm     ?? 600,
    workAreaMinHeightMm: config?.workAreaMinHeightMm ?? 50,
    workAreaMaxHeightMm: config?.workAreaMaxHeightMm ?? 600,
    tutoVideoUrl:      config?.tutoVideoUrl      ?? "",
  };
};

/* Lit une paire min/max en mm : valeurs positives, et min ≤ max (inversées
   si saisies à l'envers). */
function readSizeRange(formData, minKey, maxKey, defMin, defMax) {
  const num = (k, d) => {
    const v = parseFloat(String(formData.get(k) ?? "").replace(",", "."));
    return Number.isFinite(v) && v > 0 ? v : d;
  };
  const a = num(minKey, defMin);
  const b = num(maxKey, defMax);
  return [Math.min(a, b), Math.max(a, b)];
}

async function activateCartTransform(admin, { reset = false } = {}) {
  try {
    return await doActivateCartTransform(admin, { reset });
  } catch (error) {
    return {
      cartTransform: {
        success: false,
        message: "Erreur lors de l'activation : " + (error?.message || String(error)),
      },
    };
  }
}

async function doActivateCartTransform(admin, { reset = false } = {}) {
  const functionsRes = await admin.graphql(`#graphql
    query {
      shopifyFunctions(first: 25) {
        nodes { id apiType title }
      }
    }
  `);
  const { data: functionsData, errors: functionsErrors } = await functionsRes.json();

  if (functionsErrors?.length || !functionsData?.shopifyFunctions) {
    return {
      cartTransform: {
        success: false,
        message:
          "Erreur lors de la recherche de la fonction : " +
          (functionsErrors?.map((e) => e.message).join(" ") || "réponse inattendue de l'API Shopify."),
      },
    };
  }

  const fn = functionsData.shopifyFunctions.nodes.find(
    (n) => n.apiType.toLowerCase() === "cart_transform" && n.title === "cart-image-transform",
  );

  if (!fn) {
    return {
      cartTransform: {
        success: false,
        message:
          "Fonction 'cart-image-transform' introuvable. Vérifiez qu'elle a bien été déployée (shopify app deploy) avant d'activer.",
      },
    };
  }

  /* Cart Transform déjà enregistrées sur la boutique (par cette app). Si l'une
     pointe vers une autre fonction que celle déployée, elle continue de
     s'exécuter à la place de la nouvelle — le panier garde alors le prix de
     base de la variante. Le bouton « Réinitialiser » les supprime puis
     recrée l'enregistrement avec la fonction actuelle. */
  let previousInfo = "";
  if (reset) {
    const listRes = await admin.graphql(`#graphql
      query { cartTransforms(first: 10) { nodes { id functionId } } }
    `);
    const { data: listData, errors: listErrors } = await listRes.json();
    if (listErrors?.length) {
      return { cartTransform: { success: false, message: "Lecture des Cart Transform impossible : " + listErrors.map((e) => e.message).join(" ") } };
    }
    const existing = listData?.cartTransforms?.nodes ?? [];
    previousInfo = ` (fonction déployée : ${fn.id} ; enregistrées avant : ${existing.map((n) => n.functionId).join(", ") || "aucune"})`;
    for (const node of existing) {
      const delRes = await admin.graphql(`#graphql
        mutation DeleteCartTransform($id: ID!) {
          cartTransformDelete(id: $id) { deletedId userErrors { field message } }
        }`, { variables: { id: node.id } });
      const { data: delData, errors: delErrors } = await delRes.json();
      const delUserErrors = delData?.cartTransformDelete?.userErrors ?? [];
      if (delErrors?.length || delUserErrors.length) {
        return { cartTransform: { success: false, message: "Suppression impossible : " + [...(delErrors ?? []), ...delUserErrors].map((e) => e.message).join(" ") + previousInfo } };
      }
    }
  }

  const createRes = await admin.graphql(
    `#graphql
    mutation ActivateCartTransform($functionId: String!) {
      cartTransformCreate(functionId: $functionId, blockOnFailure: false) {
        cartTransform { id }
        userErrors { field message }
      }
    }`,
    { variables: { functionId: fn.id } },
  );
  const { data, errors: createErrors } = await createRes.json();

  if (createErrors?.length || !data?.cartTransformCreate) {
    return {
      cartTransform: {
        success: false,
        message:
          "Erreur lors de l'activation : " +
          (createErrors?.map((e) => e.message).join(" ") || "réponse inattendue de l'API Shopify."),
      },
    };
  }

  const userErrors = data.cartTransformCreate.userErrors;

  if (userErrors.length > 0) {
    return {
      cartTransform: {
        success: false,
        message: userErrors.map((e) => e.message).join(" "),
      },
    };
  }

  return {
    cartTransform: {
      success: true,
      message: (reset ? "Cart Transform réinitialisée" : "Cart Transform activée") + " — l'image et le prix personnalisés s'appliqueront au panier." + previousInfo,
    },
  };
}

export const action = async ({ request }) => {
  const { admin, session } = await authenticate.admin(request);
  const formData = await request.formData();

  if (formData.get("intent") === "activate-cart-transform") {
    return activateCartTransform(admin);
  }
  if (formData.get("intent") === "reset-cart-transform") {
    return activateCartTransform(admin, { reset: true });
  }
  if (formData.get("intent") === "create-purchase-products") {
    try {
      return { purchase: await ensurePurchaseProducts(admin, session.shop) };
    } catch (e) {
      return { purchase: { success: false, message: "Erreur : " + (e?.message || String(e)) } };
    }
  }
  if (formData.get("intent") === "save-purge") {
    const int = (k, d, min, max) => {
      const v = parseInt(String(formData.get(k) ?? ""), 10);
      return Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : d;
    };
    const data = {
      purgeEnabled:       formData.get("purgeEnabled") === "on",
      purgeDeliveredDays: int("purgeDeliveredDays", 30, 0, 3650),
      purgeAbandonedDays: int("purgeAbandonedDays", 7, 1, 3650),
      purgeIntervalHours: int("purgeIntervalHours", 6, 1, 168),
    };
    await prisma.appConfig.upsert({ where: { shop: session.shop }, update: data, create: { shop: session.shop, ...data } });
    return { purge: { success: true, message: "Réglages du nettoyage enregistrés." } };
  }
  if (formData.get("intent") === "run-purge") {
    const report = await runVariantPurge(admin, session.shop);
    return { purge: { success: !report.includes("ERREUR"), message: "Nettoyage terminé : " + report } };
  }

  const priceElementText  = parseFloat(formData.get("priceElementText"))  || 0;
  const priceElementImage = parseFloat(formData.get("priceElementImage")) || 0;
  const [textSizeMinMm, textSizeMaxMm] =
    readSizeRange(formData, "textSizeMinMm", "textSizeMaxMm", 3, 100);
  const [elementSizeMinMm, elementSizeMaxMm] =
    readSizeRange(formData, "elementSizeMinMm", "elementSizeMaxMm", 5, 300);
  const [workAreaMinMm, workAreaMaxMm] =
    readSizeRange(formData, "workAreaMinMm", "workAreaMaxMm", 50, 600);
  const [workAreaMinHeightMm, workAreaMaxHeightMm] =
    readSizeRange(formData, "workAreaMinHeightMm", "workAreaMaxHeightMm", 50, 600);
  const tutoVideoUrl   = String(formData.get("tutoVideoUrl") ?? "").trim();

  if (tutoVideoUrl && !youtubeIdFromUrl(tutoVideoUrl)) {
    return { error: "URL de la vidéo tuto non reconnue : collez un lien YouTube (ex: https://www.youtube.com/watch?v=…)." };
  }

  await prisma.appConfig.upsert({
    where:  { shop: session.shop },
    update: {
      variantIdGravure: formData.get("variantIdGravure") ?? "",
      variantIdRelief:  formData.get("variantIdRelief")  ?? "",
      variantIdDecoupe: formData.get("variantIdDecoupe") ?? "",
      priceElementText,
      priceElementImage,
      textSizeMinMm,
      textSizeMaxMm,
      elementSizeMinMm,
      elementSizeMaxMm,
      workAreaMinMm,
      workAreaMaxMm,
      workAreaMinHeightMm,
      workAreaMaxHeightMm,
      tutoVideoUrl,
    },
    create: {
      shop:             session.shop,
      variantIdGravure: formData.get("variantIdGravure") ?? "",
      variantIdRelief:  formData.get("variantIdRelief")  ?? "",
      variantIdDecoupe: formData.get("variantIdDecoupe") ?? "",
      priceElementText,
      priceElementImage,
      textSizeMinMm,
      textSizeMaxMm,
      elementSizeMinMm,
      elementSizeMaxMm,
      workAreaMinMm,
      workAreaMaxMm,
      workAreaMinHeightMm,
      workAreaMaxHeightMm,
      tutoVideoUrl,
    },
  });

  await syncToShopify(admin, session.shop);
  return { success: true };
};

const fieldStyle = {
  width: "100%",
  padding: "8px 12px",
  border: "1px solid #c9cccf",
  borderRadius: "6px",
  fontSize: "14px",
  fontFamily: "inherit",
};

const labelStyle = {
  display: "block",
  marginBottom: "6px",
  fontWeight: 600,
  fontSize: "14px",
};

const hintStyle = {
  fontSize: "12px",
  color: "#6d7175",
  marginTop: "4px",
};

function banner(result) {
  if (!result) return null;
  return (
    <div
      style={{
        background: result.success ? "#f1f8f5" : "#fdf3f1",
        border: `1px solid ${result.success ? "#aee9c8" : "#f0b9ab"}`,
        borderRadius: "6px",
        padding: "10px 14px",
        marginBottom: "16px",
        color: result.success ? "#1a6b3c" : "#a02f1a",
        fontSize: "14px",
      }}
    >
      {result.message}
    </div>
  );
}

const formatDate = (iso) => (iso ? new Date(iso).toLocaleString("fr-FR", { dateStyle: "short", timeStyle: "short" }) : "jamais");

export default function Configuration() {
  const data       = useLoaderData();
  const actionData = useActionData();
  const navigation = useNavigation();
  const saving     = navigation.state === "submitting";

  return (
    <s-page heading="Configuration — Variants produit" inlineSize="large">
      <s-section heading="Variant IDs Shopify">
        <p style={{ marginBottom: "16px", color: "#6d7175", fontSize: "14px" }}>
          Collez ici les IDs de variantes de votre produit principal. Vous les trouvez dans{" "}
          <strong>Admin → Produits → [votre produit] → [variante]</strong> — l'ID est le numéro
          dans l'URL (ex: .../variants/<strong>12345678901</strong>).
        </p>

        {actionData?.success && (
          <div style={{ background: "#f1f8f5", border: "1px solid #aee9c8", borderRadius: "6px", padding: "10px 14px", marginBottom: "16px", color: "#1a6b3c", fontSize: "14px" }}>
            Configuration sauvegardée.
          </div>
        )}

        {actionData?.error && (
          <div style={{ background: "#fdf3f1", border: "1px solid #f0b9ab", borderRadius: "6px", padding: "10px 14px", marginBottom: "16px", color: "#a02f1a", fontSize: "14px" }}>
            {actionData.error}
          </div>
        )}

        <Form method="post">
          <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>

            <div>
              <label style={labelStyle} htmlFor="variantIdGravure">Variant ID — Gravure</label>
              <input
                id="variantIdGravure"
                name="variantIdGravure"
                type="text"
                defaultValue={data.variantIdGravure}
                placeholder="ex: 12345678901234"
                style={fieldStyle}
              />
              <p style={hintStyle}>Variante correspondant au type de travail "Gravure laser"</p>
            </div>

            <div>
              <label style={labelStyle} htmlFor="variantIdRelief">Variant ID — Relief</label>
              <input
                id="variantIdRelief"
                name="variantIdRelief"
                type="text"
                defaultValue={data.variantIdRelief}
                placeholder="ex: 12345678901234"
                style={fieldStyle}
              />
              <p style={hintStyle}>Variante correspondant au type de travail "Relief collé"</p>
            </div>

            <div>
              <label style={labelStyle} htmlFor="variantIdDecoupe">Variant ID — Découpe</label>
              <input
                id="variantIdDecoupe"
                name="variantIdDecoupe"
                type="text"
                defaultValue={data.variantIdDecoupe}
                placeholder="ex: 12345678901234"
                style={fieldStyle}
              />
              <p style={hintStyle}>Variante correspondant au type de travail "Découpe sur mesure"</p>
            </div>

            <div style={{ fontWeight: 700, fontSize: "14px", marginTop: "8px", borderTop: "1px solid #e3e5e7", paddingTop: "16px" }}>
              Tarification
            </div>

            <div>
              <label style={labelStyle} htmlFor="priceElementText">Prix par texte ajouté (€)</label>
              <input
                id="priceElementText"
                name="priceElementText"
                type="number"
                step="0.01"
                min="0"
                defaultValue={data.priceElementText}
                placeholder="ex: 2.5"
                style={fieldStyle}
              />
              <p style={hintStyle}>Prix ajouté pour chaque texte placé sur le design.</p>
            </div>

            <div>
              <label style={labelStyle} htmlFor="priceElementImage">Prix par image ajoutée (€)</label>
              <input
                id="priceElementImage"
                name="priceElementImage"
                type="number"
                step="0.01"
                min="0"
                defaultValue={data.priceElementImage}
                placeholder="ex: 2.5"
                style={fieldStyle}
              />
              <p style={hintStyle}>Prix ajouté pour chaque image/photo importée sur le design. Les icônes ont leur propre prix, défini dans la section Symboles.</p>
            </div>

            <div style={{ fontWeight: 700, fontSize: "14px", marginTop: "8px", borderTop: "1px solid #e3e5e7", paddingTop: "16px" }}>
              Tailles des éléments
            </div>

            <div>
              <span style={labelStyle}>Taille des textes (mm)</span>
              <div style={{ display: "flex", gap: "12px" }}>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="textSizeMinMm">Minimum</label>
                  <input id="textSizeMinMm" name="textSizeMinMm" type="number" step="0.5" min="0.5" defaultValue={data.textSizeMinMm} style={fieldStyle} />
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="textSizeMaxMm">Maximum</label>
                  <input id="textSizeMaxMm" name="textSizeMaxMm" type="number" step="0.5" min="0.5" defaultValue={data.textSizeMaxMm} style={fieldStyle} />
                </div>
              </div>
              <p style={hintStyle}>Hauteur des lettres majuscules, en mm réels sur la planche, que le client peut choisir.</p>
            </div>

            <div>
              <span style={labelStyle}>Taille des symboles et images (mm)</span>
              <div style={{ display: "flex", gap: "12px" }}>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="elementSizeMinMm">Minimum</label>
                  <input id="elementSizeMinMm" name="elementSizeMinMm" type="number" step="0.5" min="0.5" defaultValue={data.elementSizeMinMm} style={fieldStyle} />
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="elementSizeMaxMm">Maximum</label>
                  <input id="elementSizeMaxMm" name="elementSizeMaxMm" type="number" step="0.5" min="0.5" defaultValue={data.elementSizeMaxMm} style={fieldStyle} />
                </div>
              </div>
              <p style={hintStyle}>{"Plus grand côté (largeur ou hauteur) d'un symbole ou d'une image importée, en mm réels sur la planche."}</p>
            </div>

            <div>
              <span style={labelStyle}>Longueur de la plaque (mm)</span>
              <div style={{ display: "flex", gap: "12px" }}>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="workAreaMinHeightMm">Minimum</label>
                  <input id="workAreaMinHeightMm" name="workAreaMinHeightMm" type="number" step="1" min="1" defaultValue={data.workAreaMinHeightMm} style={fieldStyle} />
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="workAreaMaxHeightMm">Maximum</label>
                  <input id="workAreaMaxHeightMm" name="workAreaMaxHeightMm" type="number" step="1" min="1" defaultValue={data.workAreaMaxHeightMm} style={fieldStyle} />
                </div>
              </div>
              <p style={hintStyle}>{"Hauteur de la plaque à l'écran (champ « Longueur » du personnalisateur)."}</p>
            </div>

            <div>
              <span style={labelStyle}>Largeur de la plaque (mm)</span>
              <div style={{ display: "flex", gap: "12px" }}>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="workAreaMinMm">Minimum</label>
                  <input id="workAreaMinMm" name="workAreaMinMm" type="number" step="1" min="1" defaultValue={data.workAreaMinMm} style={fieldStyle} />
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ ...hintStyle, display: "block", marginTop: 0, marginBottom: "4px" }} htmlFor="workAreaMaxMm">Maximum</label>
                  <input id="workAreaMaxMm" name="workAreaMaxMm" type="number" step="1" min="1" defaultValue={data.workAreaMaxMm} style={fieldStyle} />
                </div>
              </div>
              <p style={hintStyle}>{"Quel que soit le format choisi, le client peut réduire la plaque jusqu'au minimum ou l'agrandir jusqu'au maximum, pour chaque côté."}</p>
            </div>

            <div style={{ fontWeight: 700, fontSize: "14px", marginTop: "8px", borderTop: "1px solid #e3e5e7", paddingTop: "16px" }}>
              Tutoriel vidéo
            </div>

            <div>
              <label style={labelStyle} htmlFor="tutoVideoUrl">Vidéo tuto (YouTube)</label>
              <input
                id="tutoVideoUrl"
                name="tutoVideoUrl"
                type="url"
                defaultValue={data.tutoVideoUrl}
                placeholder="ex: https://www.youtube.com/watch?v=…"
                style={fieldStyle}
              />
              <p style={hintStyle}>Vidéo affichée dans la barre latérale du personnalisateur. Laissez vide pour masquer la section.</p>
            </div>

            <div>
              <button
                type="submit"
                disabled={saving}
                style={{ background: "#008060", color: "#fff", border: "none", borderRadius: "6px", padding: "10px 20px", fontSize: "14px", fontWeight: 600, cursor: saving ? "not-allowed" : "pointer", opacity: saving ? 0.7 : 1 }}
              >
                {saving ? "Sauvegarde…" : "Sauvegarder"}
              </button>
            </div>
          </div>
        </Form>
      </s-section>

      <s-section heading="Produits d'achat (variantes au prix exact)">
        <p style={{ marginBottom: "16px", color: "#6d7175", fontSize: "14px" }}>
          {"À chaque ajout au panier, une variante au prix exact de la plaque est créée dans le produit d'achat de son type. Shopify limite un produit à 2048 variantes : les trois produits en accueillent 6144 en circulation. Le produit personnalisable n'est plus modifié."}
        </p>
        {banner(actionData?.purchase)}
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "14px", marginBottom: "16px" }}>
          <thead>
            <tr style={{ textAlign: "left", borderBottom: "1px solid #e3e5e7" }}>
              <th style={{ padding: "6px 4px" }}>Type</th>
              <th style={{ padding: "6px 4px" }}>Produit</th>
              <th style={{ padding: "6px 4px" }}>Variantes</th>
            </tr>
          </thead>
          <tbody>
            {data.purchaseProducts.map((p) => (
              <tr key={p.type} style={{ borderBottom: "1px solid #f1f2f3" }}>
                <td style={{ padding: "6px 4px" }}>{p.label}</td>
                <td style={{ padding: "6px 4px" }}>
                  {p.exists ? (
                    <a href={`https://admin.shopify.com/store/${data.shopHandle}/products/${p.productId.split("/").pop()}`} target="_top">
                      {p.title}
                    </a>
                  ) : (
                    <span style={{ color: "#a02f1a" }}>{p.productId ? "introuvable (supprimé ?)" : "non créé"}</span>
                  )}
                  {p.exists && p.status !== "UNLISTED" && <span style={{ color: "#a02f1a" }}> — statut {p.status} : doit être Non répertorié</span>}
                </td>
                <td style={{ padding: "6px 4px", color: p.variantsCount > p.max * 0.9 ? "#a02f1a" : undefined }}>
                  {p.exists ? `${p.variantsCount} / ${p.max}` : "—"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {data.purchaseProducts.some((p) => !p.exists || p.status !== "UNLISTED") && (
          <Form method="post">
            <input type="hidden" name="intent" value="create-purchase-products" />
            <button
              type="submit"
              disabled={saving}
              style={{ background: "#008060", color: "#fff", border: "none", borderRadius: "6px", padding: "10px 20px", fontSize: "14px", fontWeight: 600, cursor: saving ? "not-allowed" : "pointer", opacity: saving ? 0.7 : 1 }}
            >
              {saving ? "…" : data.purchaseProducts.some((p) => !p.exists) ? "Créer les produits d'achat manquants" : "Passer les produits d'achat en non répertorié"}
            </button>
          </Form>
        )}
        <p style={hintStyle}>
          {"Les produits sont créés en statut « Non répertorié » et publiés sur la boutique en ligne : achetables, mais absents des collections, de la recherche et des recommandations. Vous pouvez les renommer ou leur ajouter une image ; ne supprimez pas leurs variantes à la main."}
        </p>
      </s-section>

      <s-section heading="Nettoyage automatique des variantes">
        <p style={{ marginBottom: "16px", color: "#6d7175", fontSize: "14px" }}>
          {"Le serveur rapproche régulièrement les variantes créées des commandes, puis supprime celles des commandes livrées (ou expédiées, si la livraison n'est pas remontée) et annulées après le délai choisi, ainsi que celles jamais commandées (paniers abandonnés). Les commandes gardent leur prix, leur libellé et leurs fichiers."}
        </p>
        {banner(actionData?.purge)}
        <p style={{ fontSize: "14px", marginBottom: "16px" }}>
          <strong>{data.variantStats.total}</strong> variante(s) suivie(s) : {data.variantStats.pending} pas encore commandée(s),{" "}
          {data.variantStats.ordered} en commande non expédiée, {data.variantStats.done} livrée(s) ou annulée(s) en attente de suppression.
          <br />
          <span style={{ color: "#6d7175" }}>
            Dernier passage : {formatDate(data.purge.lastRunAt)}{data.purge.lastReport ? ` — ${data.purge.lastReport}` : ""}
          </span>
        </p>
        <Form method="post">
          <input type="hidden" name="intent" value="save-purge" />
          <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
            <label style={{ display: "flex", gap: "8px", alignItems: "center", fontSize: "14px", fontWeight: 600 }}>
              <input type="checkbox" name="purgeEnabled" defaultChecked={data.purge.enabled} />
              Nettoyage automatique activé
            </label>
            <div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
              <div style={{ flex: "1 1 180px" }}>
                <label style={labelStyle} htmlFor="purgeDeliveredDays">Délai après livraison (jours)</label>
                <input id="purgeDeliveredDays" name="purgeDeliveredDays" type="number" min="0" step="1" defaultValue={data.purge.deliveredDays} style={fieldStyle} />
                <p style={hintStyle}>Variante supprimée ce nombre de jours après la livraison ou l’annulation de la commande.</p>
              </div>
              <div style={{ flex: "1 1 180px" }}>
                <label style={labelStyle} htmlFor="purgeAbandonedDays">Paniers abandonnés (jours)</label>
                <input id="purgeAbandonedDays" name="purgeAbandonedDays" type="number" min="1" step="1" defaultValue={data.purge.abandonedDays} style={fieldStyle} />
                <p style={hintStyle}>Variante jamais commandée supprimée après ce délai (elle disparaît alors du panier du client).</p>
              </div>
              <div style={{ flex: "1 1 180px" }}>
                <label style={labelStyle} htmlFor="purgeIntervalHours">Fréquence (heures)</label>
                <input id="purgeIntervalHours" name="purgeIntervalHours" type="number" min="1" max="168" step="1" defaultValue={data.purge.intervalHours} style={fieldStyle} />
                <p style={hintStyle}>Intervalle entre deux passages automatiques.</p>
              </div>
            </div>
            <div>
              <button
                type="submit"
                disabled={saving}
                style={{ background: "#008060", color: "#fff", border: "none", borderRadius: "6px", padding: "10px 20px", fontSize: "14px", fontWeight: 600, cursor: saving ? "not-allowed" : "pointer", opacity: saving ? 0.7 : 1 }}
              >
                {saving ? "Sauvegarde…" : "Enregistrer les réglages"}
              </button>
            </div>
          </div>
        </Form>
        <Form method="post" style={{ marginTop: "12px" }}>
          <input type="hidden" name="intent" value="run-purge" />
          <button
            type="submit"
            disabled={saving}
            style={{ background: "#fff", color: "#202223", border: "1px solid #8c9196", borderRadius: "6px", padding: "10px 20px", fontSize: "14px", fontWeight: 600, cursor: saving ? "not-allowed" : "pointer", opacity: saving ? 0.7 : 1 }}
          >
            {saving ? "…" : "Lancer le nettoyage maintenant"}
          </button>
        </Form>
      </s-section>

      <s-section heading="Image du produit dans le panier">
        <p style={{ marginBottom: "16px", color: "#6d7175", fontSize: "14px" }}>
          Active la Cart Transform Function qui remplace l'image de la ligne de panier par le
          rendu 2D généré dans le personnalisateur. À faire une seule fois, après avoir déployé
          l'extension <strong>cart-image-transform</strong> (<code>shopify app deploy</code>).
        </p>

        {actionData?.cartTransform && (
          <div
            style={{
              background: actionData.cartTransform.success ? "#f1f8f5" : "#fdf3f1",
              border: `1px solid ${actionData.cartTransform.success ? "#aee9c8" : "#f0b9ab"}`,
              borderRadius: "6px",
              padding: "10px 14px",
              marginBottom: "16px",
              color: actionData.cartTransform.success ? "#1a6b3c" : "#a02f1a",
              fontSize: "14px",
            }}
          >
            {actionData.cartTransform.message}
          </div>
        )}

        <Form method="post">
          <input type="hidden" name="intent" value="activate-cart-transform" />
          <button
            type="submit"
            disabled={saving}
            style={{ background: "#202223", color: "#fff", border: "none", borderRadius: "6px", padding: "10px 20px", fontSize: "14px", fontWeight: 600, cursor: saving ? "not-allowed" : "pointer", opacity: saving ? 0.7 : 1 }}
          >
            {saving ? "…" : "Activer l'image personnalisée dans le panier"}
          </button>
        </Form>
        <p style={{ margin: "20px 0 8px", color: "#6d7175", fontSize: "14px" }}>
          Le panier garde le prix de base de la variante alors que la fonction est déployée ?
          Supprime l'enregistrement actuel de la Cart Transform puis le recrée avec la fonction
          déployée en dernier.
        </p>
        <Form method="post">
          <input type="hidden" name="intent" value="reset-cart-transform" />
          <button
            type="submit"
            disabled={saving}
            style={{ background: "#fff", color: "#202223", border: "1px solid #8c9196", borderRadius: "6px", padding: "10px 20px", fontSize: "14px", fontWeight: 600, cursor: saving ? "not-allowed" : "pointer", opacity: saving ? 0.7 : 1 }}
          >
            {saving ? "…" : "Réinitialiser la Cart Transform"}
          </button>
        </Form>
      </s-section>
    </s-page>
  );
}
