// Rôle : copie des données filtrées au format compatible avec l'import checklist.
import { useState } from "react";
import { Icon } from "../../components/Icon.jsx";

async function copyText(value) {
  try {
    await navigator.clipboard.writeText(value);
    return true;
  } catch {
    return false;
  }
}

function notify(message) {
  window.dispatchEvent(new CustomEvent("sokkog:notify", { detail: { message } }));
}

export function formatChecklistImportItems(labels) {
  return labels
    .map((entry) => {
      if (typeof entry === "object" && entry !== null) {
        const label = String(entry.label || entry.name || "").trim();
        const quantity = Number.parseInt(entry.quantity ?? entry.quantite ?? 1, 10);
        return label ? { label, quantity: Number.isFinite(quantity) ? quantity : 1 } : null;
      }
      const label = String(entry || "").trim();
      return label ? { label, quantity: 1 } : null;
    })
    .filter(Boolean)
    .map((entry) => `${entry.label}:${entry.quantity}`)
    .join("\n");
}

export function formatChecklistImportSections(sections = []) {
  return sections
    .map((section) => {
      const title = String(section?.title || "").trim();
      const items = formatChecklistImportItems(section?.items || []);
      if (!items) return "";
      return title ? `# ${title}\n${items}` : items;
    })
    .filter(Boolean)
    .join("\n\n");
}

export function CopyChecklistItemsButton({ labels, sections, title = "Copier pour checklist" }) {
  const [copied, setCopied] = useState(false);
  const text = sections ? formatChecklistImportSections(sections) : formatChecklistImportItems(labels);

  async function copyItems() {
    if (!text || !await copyText(text)) return;
    setCopied(true);
    notify("Copié dans le presse-papiers.");
    window.setTimeout(() => setCopied(false), 1400);
  }

  return (
    <button
      className="filter-reset-button results-copy-button"
      type="button"
      onClick={copyItems}
      disabled={!text}
      aria-label={title}
      title={copied ? "Copié" : title}
    >
      <Icon name="copy" />
    </button>
  );
}
