import { useState, useCallback } from 'react';

/**
 * Server export pipeline wrapper.
 *
 * Posts the design payload to /api/export, receives back a URL to the
 * 4500×4500 PNG render, and (by default) triggers a browser download.
 *
 * `autoDownload` option
 * ─────────────────────
 * Save and the test-download button want auto-download. Print-preview
 * wants the URL but no download. Threading a flag through `exportDesign`
 * is cleaner than maintaining two parallel pipelines.
 */
export function useExport() {
  const [exporting, setExporting] = useState(false);
  const [progress, setProgress] = useState(0);
  const [exportUrl, setExportUrl] = useState(null);
  const [error, setError] = useState(null);

  const exportDesign = useCallback(async (
    elements,
    designName = 'design',
    template = null,
    { autoDownload = true } = {},
  ) => {
    setExporting(true); setProgress(0); setError(null); setExportUrl(null);

    let progressInterval = null;
    try {
      progressInterval = setInterval(() => { setProgress((prev) => Math.min(prev + 10, 90)); }, 200);

      const response = await fetch('/api/export', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ elements, designName, template }),
      });

      if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.error || 'Export failed'); }

      const data = await response.json();
      setProgress(100);
      setExportUrl(data.export.url);

      if (autoDownload) {
        const link = document.createElement('a');
        link.href = data.export.url;
        link.download = data.export.filename;
        link.click();
      }

      return data;
    } catch (err) {
      console.error('Export failed:', err);
      setError(err.message);
      throw err;
    } finally {
      if (progressInterval) clearInterval(progressInterval);
      setExporting(false);
    }
  }, []);

  const clearExport = useCallback(() => { setExportUrl(null); setError(null); }, []);

  return { exporting, progress, exportUrl, error, exportDesign, clearExport };
}
