import type { JSX } from "solid-js";
import { createUniqueId, splitProps } from "solid-js";
import { createControllableSignal } from "../../primitives/create-controllable-signal";
import { TabsContextProvider, type TabsContextValue } from "./tabs-context";

/** Props for the Tabs root component. */
export interface TabsRootProps extends JSX.HTMLAttributes<HTMLDivElement> {
  /** Controlled active tab value. */
  value?: string;
  /** Initial active tab value (uncontrolled). */
  defaultValue?: string;
  /** Called when the active tab changes. */
  onValueChange?: ((value: string) => void) | undefined;
  /** @default "horizontal" */
  orientation?: "horizontal" | "vertical";
  /** automatic: activates on focus; manual: activates on click/Enter/Space. @default "automatic" */
  activationMode?: "automatic" | "manual";
  children: JSX.Element;
}

/**
 * Root container for the Tabs component. Manages which tab is active.
 */
export function TabsRoot(props: TabsRootProps): JSX.Element {
  const [local, rest] = splitProps(props, [
    "value",
    "defaultValue",
    "onValueChange",
    "orientation",
    "activationMode",
    "children",
  ]);

  const baseId = createUniqueId();

  const [activeTab, setActiveTab] = createControllableSignal<string | undefined>({
    value: () => local.value,
    defaultValue: () => local.defaultValue,
    onChange: (v) => {
      if (v !== undefined) local.onValueChange?.(v);
    },
  });

  const ctx: TabsContextValue = {
    activeTab,
    setActiveTab: (v) => setActiveTab(v),
    baseId,
    orientation: () => local.orientation ?? "horizontal",
    activationMode: () => local.activationMode ?? "automatic",
  };

  return (
    <TabsContextProvider value={ctx}>
      <div data-orientation={local.orientation ?? "horizontal"} {...rest}>
        {local.children}
      </div>
    </TabsContextProvider>
  );
}
