import type { Accessor, JSX } from "solid-js";
import { createContext, useContext } from "solid-js";

// --- Internal Context (used only by Tooltip parts) ---

/** Internal context shared between all Tooltip sub-components. */
export interface InternalTooltipContextValue {
  isOpen: Accessor<boolean>;
  open: () => void;
  close: () => void;
  triggerRef: Accessor<HTMLElement | null>;
  setTriggerRef: (el: HTMLElement | null) => void;
  contentRef: Accessor<HTMLElement | null>;
  setContentRef: (el: HTMLElement | null) => void;
  contentId: string;
  triggerId: string;
  floatingStyle: Accessor<JSX.CSSProperties>;
  openDelayed: () => void;
  closeDelayed: () => void;
  cancelTimers: () => void;
}

const InternalTooltipContext = createContext<InternalTooltipContextValue>();

/**
 * Returns the internal Tooltip context value.
 * Throws if used outside of a Tooltip root.
 */
export function useInternalTooltipContext(): InternalTooltipContextValue {
  const ctx = useContext(InternalTooltipContext);
  if (!ctx) {
    throw new Error(
      "[PettyUI] Tooltip parts must be used inside <Tooltip>.\n" +
        "  Fix: <Tooltip>\n" +
        "         <Tooltip.Trigger>...</Tooltip.Trigger>\n" +
        "         <Tooltip.Content>...</Tooltip.Content>\n" +
        "       </Tooltip>",
    );
  }
  return ctx;
}

/** Provider for the internal Tooltip context. */
export const InternalTooltipContextProvider = InternalTooltipContext.Provider;

// --- Public Context (exported via Tooltip.useContext) ---

/** Public context exposed via Tooltip.useContext(). */
export interface TooltipContextValue {
  /** Whether the tooltip is currently open. */
  open: Accessor<boolean>;
}

const TooltipContext = createContext<TooltipContextValue>();

/**
 * Returns the public Tooltip context value.
 * Throws if used outside of a Tooltip root.
 */
export function useTooltipContext(): TooltipContextValue {
  const ctx = useContext(TooltipContext);
  if (!ctx) {
    throw new Error(
      "[PettyUI] Tooltip.useContext() was called outside of a <Tooltip>.\n" +
        "  Fix: Call Tooltip.useContext() inside a component rendered within <Tooltip>.",
    );
  }
  return ctx;
}

/** Provider for the public Tooltip context. */
export const TooltipContextProvider = TooltipContext.Provider;
