"use client";

import { useCallback, useState } from "react";

export interface PastedImage {
  file: File;
  // Data URL for instant local preview. In Phase 4 we upload `file` to the
  // storage bucket and persist the returned public URL instead.
  dataUrl: string;
}

/**
 * Captures images pasted via CMD/CTRL+V. Attach `handlePaste` to the onPaste
 * of the note textarea (or any focusable region). The first image found in the
 * clipboard payload is read as a data URL for preview.
 */
export function useImagePaste() {
  const [image, setImage] = useState<PastedImage | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handlePaste = useCallback((e: React.ClipboardEvent) => {
    const items = e.clipboardData?.items;
    if (!items) return;

    for (const item of items) {
      if (item.kind === "file" && item.type.startsWith("image/")) {
        const file = item.getAsFile();
        if (!file) continue;

        // Stop the image bytes from also landing as garbage text in the textarea.
        e.preventDefault();

        const reader = new FileReader();
        reader.onload = () => {
          setImage({ file, dataUrl: reader.result as string });
          setError(null);
        };
        reader.onerror = () => setError("Could not read the pasted image.");
        reader.readAsDataURL(file);
        return;
      }
    }
  }, []);

  const clear = useCallback(() => {
    setImage(null);
    setError(null);
  }, []);

  return { image, error, handlePaste, clear };
}
