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

/** Shared state provided by AccordionRoot to all descendant accordion parts. */
export interface AccordionRootContextValue {
  isExpanded: (value: string) => boolean;
  toggleItem: (value: string) => void;
  disabled: Accessor<boolean>;
}

/** Per-item state provided by AccordionItem to its trigger and content. */
export interface AccordionItemContextValue {
  value: string;
  isExpanded: Accessor<boolean>;
  triggerId: string;
  contentId: string;
  disabled: Accessor<boolean>;
}

const AccordionRootContext = createContext<AccordionRootContextValue>();
const AccordionItemContext = createContext<AccordionItemContextValue>();

/**
 * Returns the Accordion root context. Throws if used outside <Accordion>.
 */
export function useAccordionRootContext(): AccordionRootContextValue {
  const ctx = useContext(AccordionRootContext);
  if (!ctx) throw new Error("[PettyUI] Accordion parts must be used inside <Accordion>.");
  return ctx;
}

/**
 * Returns the AccordionItem context. Throws if used outside <Accordion.Item>.
 */
export function useAccordionItemContext(): AccordionItemContextValue {
  const ctx = useContext(AccordionItemContext);
  if (!ctx)
    throw new Error("[PettyUI] Accordion.Trigger/Content must be used inside <Accordion.Item>.");
  return ctx;
}

export const AccordionRootContextProvider = AccordionRootContext.Provider;
export const AccordionItemContextProvider = AccordionItemContext.Provider;
