/**
 * Shared helpers for the original UI Stacks-compatible components.
 * MIT licensed. Written from the public API documentation at uistacks.dev.
 */
"use client";

import * as React from "react";

export function cn(...parts: Array<string | false | null | undefined>) {
  return parts.filter(Boolean).join(" ");
}

/** Controlled-or-uncontrolled state. */
export function useControllable<T>(
  controlled: T | undefined,
  defaultValue: T,
  onChange?: (value: T) => void,
) {
  const [uncontrolled, setUncontrolled] = React.useState<T>(defaultValue);
  const isControlled = controlled !== undefined;
  const value = isControlled ? (controlled as T) : uncontrolled;
  const setValue = React.useCallback(
    (next: T | ((prev: T) => T)) => {
      const resolved =
        typeof next === "function" ? (next as (prev: T) => T)(value) : next;
      if (!isControlled) setUncontrolled(resolved);
      onChange?.(resolved);
    },
    [isControlled, onChange, value],
  );
  return [value, setValue] as const;
}

/** Calls `handler` on pointerdown outside the ref. */
export function useOnClickOutside(
  ref: React.RefObject<HTMLElement | null>,
  handler: (event: MouseEvent | TouchEvent) => void,
  enabled = true,
) {
  React.useEffect(() => {
    if (!enabled) return;
    const listener = (event: MouseEvent | TouchEvent) => {
      const node = ref.current;
      // Shadow DOM events expose the host as their target at the document.
      if (!node || event.composedPath().includes(node)) return;
      handler(event);
    };
    document.addEventListener("mousedown", listener);
    document.addEventListener("touchstart", listener);
    return () => {
      document.removeEventListener("mousedown", listener);
      document.removeEventListener("touchstart", listener);
    };
  }, [ref, handler, enabled]);
}

/**
 * Keeps Tab focus inside `ref` while `active`, and restores focus to the
 * element that had it before opening.
 */
export function useFocusTrap(
  ref: React.RefObject<HTMLElement | null>,
  active: boolean,
  options: { initialFocus?: React.RefObject<HTMLElement | null>; autoFocus?: boolean } = {},
) {
  const { initialFocus, autoFocus = true } = options;
  const previous = React.useRef<HTMLElement | null>(null);

  React.useEffect(() => {
    if (!active) return;
    previous.current = document.activeElement as HTMLElement | null;
    const node = ref.current;
    if (node && autoFocus) {
      const target =
        initialFocus?.current ??
        node.querySelector<HTMLElement>(
          "[data-autofocus],[autofocus],input:not([type=hidden]),textarea,select,button,[href],[tabindex]:not([tabindex='-1'])",
        ) ??
        node;
      window.requestAnimationFrame(() => target.focus?.());
    }

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Tab" || !node) return;
      const focusables = Array.from(
        node.querySelectorAll<HTMLElement>(
          "input:not([type=hidden]),textarea,select,button,[href],[tabindex]:not([tabindex='-1'])",
        ),
      ).filter((el) => !el.hasAttribute("disabled") && el.offsetParent !== null);
      if (!focusables.length) return;
      const first = focusables[0];
      const last = focusables[focusables.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      previous.current?.focus?.();
    };
  }, [ref, active, initialFocus, autoFocus]);
}

const FOCUSABLE =
  "input:not([type=hidden]),textarea,select,button,[href],[tabindex]:not([tabindex='-1'])";

/** Moves focus to the next / previous element inside `container`. */
export function moveFocus(
  container: HTMLElement | null,
  direction: 1 | -1,
  current?: HTMLElement | null,
) {
  if (!container) return;
  const items = Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
    (el) => !el.hasAttribute("disabled") && el.offsetParent !== null,
  );
  if (!items.length) return;
  const active = current ?? (document.activeElement as HTMLElement | null);
  const index = active ? items.indexOf(active) : -1;
  const next =
    index === -1
      ? direction === 1
        ? 0
        : items.length - 1
      : (index + direction + items.length) % items.length;
  items[next].focus();
}

export const CONTROL_SIZES = {
  sm: "h-8 text-[13px]",
  md: "h-9 text-[14px]",
  lg: "h-10 text-[15px]",
} as const;

export type ControlSize = keyof typeof CONTROL_SIZES;
