// Rôle : centralise le flux import/export texte des outils compatibles.
import { useCallback, useMemo, useState } from "react";
import { exportModuleText, hasTextExchangeContent, importModuleText } from "./textImport.js";

export function useTextExchange({ type, data, context, onImport, textContent = {} }) {
  const [mode, setMode] = useState("");
  const [draft, setDraft] = useState("");
  const [error, setError] = useState("");
  const exportText = useMemo(() => mode === "export" ? exportModuleText(type, data) : "", [data, mode, type]);
  const canExport = hasTextExchangeContent(type, data);

  const closeModal = useCallback(() => {
    setMode("");
    setDraft("");
    setError("");
  }, []);

  function openImport() {
    setDraft("");
    setError("");
    setMode("import");
  }

  function openExport() {
    setError("");
    setMode("export");
  }

  function updateDraft(value) {
    setDraft(value);
    if (error) setError("");
  }

  function submitImport(event) {
    event.preventDefault();
    const result = importModuleText(type, draft, context);
    if (!result.ok) {
      setError(result.error || textContent.importError || "Format invalide.");
      return;
    }
    onImport(result.data);
    context.notify?.(textContent.importSuccess || "Import texte terminé.");
    closeModal();
  }

  async function copyExport() {
    if (!await context.copyText(exportText)) return;
    context.notify?.(textContent.exportSuccess || "Export texte copié.");
  }

  return {
    canExport,
    closeModal,
    copyExport,
    draft,
    error,
    exportText,
    mode,
    openExport,
    openImport,
    submitImport,
    updateDraft
  };
}
