import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';

/**
 * Optional target for a Sitesmith chat session. When set, the modal renders a
 * "Editing X" banner and the chat input is biased toward modifying just that
 * subtree — the user's prompt is augmented server-side with the node's
 * serialized tree, and the AI is instructed to return a `patch` op (typically
 * `replace_node`) rather than a full-site replace.
 */
export interface SitesmithTarget {
  /** Craft.js node id, used to find the node when applying the patch. */
  nodeId: string;
  /** Human-readable component name, shown in the modal header. */
  displayName: string;
  /** The component's serialized subtree (used to build a usable AI prompt). */
  treeJson: string;
}

interface SitesmithContextValue {
  isOpen: boolean;
  target: SitesmithTarget | null;
  open: (target?: SitesmithTarget) => void;
  close: () => void;
}

const SitesmithCtx = createContext<SitesmithContextValue>({
  isOpen: false,
  target: null,
  open: () => {},
  close: () => {},
});

export const useSitesmithModal = () => useContext(SitesmithCtx);

export const SitesmithProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [target, setTarget] = useState<SitesmithTarget | null>(null);

  const open = useCallback((t?: SitesmithTarget) => {
    setTarget(t ?? null);
    setIsOpen(true);
  }, []);

  const close = useCallback(() => {
    setIsOpen(false);
    setTarget(null);
  }, []);

  const value = useMemo<SitesmithContextValue>(
    () => ({ isOpen, target, open, close }),
    [isOpen, target, open, close],
  );

  return <SitesmithCtx.Provider value={value}>{children}</SitesmithCtx.Provider>;
};
