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

/** Which edge the Drawer slides from. */
export type DrawerSide = "top" | "bottom" | "left" | "right";

/** Internal context shared between all Drawer parts. */
export interface InternalDrawerContextValue {
  isOpen: Accessor<boolean>;
  setOpen: (open: boolean) => void;
  side: Accessor<DrawerSide>;
  contentId: Accessor<string>;
  titleId: Accessor<string | undefined>;
  setTitleId: (id: string | undefined) => void;
  descriptionId: Accessor<string | undefined>;
  setDescriptionId: (id: string | undefined) => void;
}

const InternalDrawerContext = createContext<InternalDrawerContextValue>();

/**
 * Returns the internal Drawer context. Throws if used outside <Drawer>.
 */
export function useInternalDrawerContext(): InternalDrawerContextValue {
  const ctx = useContext(InternalDrawerContext);
  if (!ctx) {
    throw new Error(
      "[PettyUI] Drawer parts must be used inside <Drawer>.\n" +
        "  Fix: Wrap Drawer.Content, Drawer.Trigger, etc. inside <Drawer>.",
    );
  }
  return ctx;
}

export const InternalDrawerContextProvider = InternalDrawerContext.Provider;

/** Public context exposed to consumers via Drawer.useContext(). */
export interface DrawerContextValue {
  /** Whether the drawer is currently open. */
  open: Accessor<boolean>;
  /** Which edge the drawer slides from. */
  side: Accessor<DrawerSide>;
}

const DrawerContext = createContext<DrawerContextValue>();

/**
 * Returns the public Drawer context. Throws if used outside <Drawer>.
 */
export function useDrawerContext(): DrawerContextValue {
  const ctx = useContext(DrawerContext);
  if (!ctx) {
    throw new Error("[PettyUI] Drawer.useContext() called outside of <Drawer>.");
  }
  return ctx;
}

export const DrawerContextProvider = DrawerContext.Provider;
