/**
 * Store global para captura de canvas 3D (M9.3)
 *
 * O componente 3DViewer registra seu canvas via `registerCanvas`.
 * O painel de captura usa `captureCanvas` para extrair uma imagem.
 *
 * Funciona com qualquer viewer 3D baseado em R3F (galpão, cilindro,
 * abóbada, cúpula, etc.) — basta chamar `registerCanvas(canvas)` quando
 * o canvas monta e `unregisterCanvas()` quando desmonta.
 */

import { create } from 'zustand';
import { captureCanvasImage, canvasToDataURL } from '../lib/canvas-capture';

interface CaptureState {
  /** Canvas 3D ativo registrado pelo viewer atual */
  canvas: HTMLCanvasElement | null;
  /** Imagem capturada em data URL (PNG). Limpa após uso. */
  capturedImage: string | null;
  /** Timestamp da última captura */
  capturedAt: number | null;
  /** Largura preferida do PNG exportado (px). 0 = original */
  targetWidth: number;
  /** Qualidade JPEG (0–1) se formato = jpeg */
  jpegQuality: number;
  /** Formato de saída */
  format: 'png' | 'jpeg';

  registerCanvas: (canvas: HTMLCanvasElement | null) => void;
  unregisterCanvas: () => void;
  setTargetWidth: (w: number) => void;
  setFormat: (f: 'png' | 'jpeg') => void;
  setJpegQuality: (q: number) => void;
  capture: () => Promise<string | null>;
  clearCaptured: () => void;
}

export const useCaptureStore = create<CaptureState>((set, get) => ({
  canvas: null,
  capturedImage: null,
  capturedAt: null,
  targetWidth: 1600,
  jpegQuality: 0.92,
  format: 'png',

  registerCanvas: (canvas) => set({ canvas }),
  unregisterCanvas: () => set({ canvas: null }),

  setTargetWidth: (w) => set({ targetWidth: Math.max(0, Math.floor(w)) }),
  setFormat: (f) => set({ format: f }),
  setJpegQuality: (q) => set({ jpegQuality: Math.max(0, Math.min(1, q)) }),

  capture: async () => {
    const { canvas, format, jpegQuality, targetWidth } = get();
    if (!canvas) return null;
    try {
      const dataUrl = canvasToDataURL(canvas, format, jpegQuality);
      const resized = targetWidth > 0
        ? await captureCanvasImage(canvas, { format, quality: jpegQuality, maxWidth: targetWidth })
        : dataUrl;
      set({ capturedImage: resized, capturedAt: Date.now() });
      return resized;
    } catch (err) {
      console.error('[capture] Falha ao capturar canvas:', err);
      return null;
    }
  },

  clearCaptured: () => set({ capturedImage: null, capturedAt: null }),
}));