import { createContext, useContext } from 'react';

export type SettingsFocus = {
  /** Stable anchor id for a setting tile (from settingAnchorId). */
  anchorId?: string;
  setAnchorId: (anchorId: string | undefined) => void;
};

const SettingsFocusContext = createContext<SettingsFocus | null>(null);

export const SettingsFocusProvider = SettingsFocusContext.Provider;

export const useSettingsFocus = (): SettingsFocus => {
  const ctx = useContext(SettingsFocusContext);
  if (!ctx) {
    return {
      anchorId: undefined,
      setAnchorId: () => undefined,
    };
  }
  return ctx;
};

/** Stable DOM id for a settings tile title. */
export function settingAnchorId(title: string): string {
  const slug = title
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '');
  return `settings-item-${slug || 'untitled'}`;
}
