import { useState, useCallback, useRef } from 'react';
import { loadImageDimensions } from '../utils/imageLoading';

export function calculateAutoCrop(imageSize, slotSize) {
  const imageRatio = imageSize.width / imageSize.height;
  const slotRatio = slotSize.width / slotSize.height;
  let sx, sy, sWidth, sHeight;
  if (imageRatio > slotRatio) { sHeight = imageSize.height; sWidth = imageSize.height * slotRatio; sx = (imageSize.width - sWidth) / 2; sy = 0; }
  else { sWidth = imageSize.width; sHeight = imageSize.width / slotRatio; sx = 0; sy = (imageSize.height - sHeight) / 2; }
  return { sx, sy, sWidth, sHeight };
}

export function useTemplate(templates = []) {
  const [currentTemplateId, setCurrentTemplateId] = useState(null);
  const templateRef = useRef(null);

  const currentTemplate = templates.find(t => t.id === currentTemplateId) || null;
  const getSlots = useCallback(() => currentTemplate?.slots || [], [currentTemplate]);

  const loadTemplate = useCallback((templateId) => {
    const template = templates.find(t => t.id === templateId);
    if (template) { setCurrentTemplateId(templateId); templateRef.current = template; return true; }
    return false;
  }, [templates]);

  const clearTemplate = useCallback(() => { setCurrentTemplateId(null); templateRef.current = null; }, []);

  // Build the element data for an image dropped into a slot. Resolves only after
  // the image has loaded so the auto-crop reflects the image's real dimensions
  // (returning early with crop:null lets the caller create an element that never
  // gets its crop populated, since the mutation arrives after React already
  // captured the value). Caller is responsible for adding the returned element
  // to the editor state, which makes that state the single source of truth for
  // "is this slot filled" — see DesignCanvas, which derives slot occupancy from
  // the elements array.
  const assignImageToSlot = useCallback(async (slotId, imageData) => {
    const slots = getSlots();
    const slot = slots.find(s => s.id === slotId);
    if (!slot) return null;

    const dimensions = await loadImageDimensions(imageData);

    const crop = calculateAutoCrop(
      { width: dimensions.width, height: dimensions.height },
      { width: slot.bounds.width, height: slot.bounds.height },
    );

    return {
      type: 'image',
      src: imageData,
      x: slot.bounds.x,
      y: slot.bounds.y,
      width: slot.bounds.width,
      height: slot.bounds.height,
      slotId,
      crop,
    };
  }, [getSlots]);

  return { currentTemplateId, currentTemplate, loadTemplate, clearTemplate, getSlots, assignImageToSlot };
}
