'use client';

/**
 * LinkContext
 *
 * Adapter slot for the framework's native link component (e.g. `next/link`).
 * `<Link>` reads this context: when populated, it delegates rendering so
 * the host framework's prefetching / locale handling kicks in. When empty,
 * `<Link>` falls back to a pure `<a>` driven by `useNavigate`.
 *
 * Mount once near the root via the matching adapter
 * (e.g. `NextLinkProvider` from `@djangocfg/ui-core/adapters/nextjs`).
 */

import { createContext, useContext, type ComponentType, type ReactNode, type Ref } from 'react';

export interface LinkComponentProps {
  href: string;
  replace?: boolean;
  scroll?: boolean;
  prefetch?: boolean | null;
  className?: string;
  children?: ReactNode;
  target?: string;
  rel?: string;
  ref?: Ref<HTMLAnchorElement>;
  onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
  [dataAttr: `data-${string}`]: unknown;
  [ariaAttr: `aria-${string}`]: unknown;
}

export type LinkComponent = ComponentType<LinkComponentProps>;

export const LinkComponentContext = createContext<LinkComponent | null>(null);

export interface LinkProviderProps {
  value: LinkComponent;
  children: ReactNode;
}

export function LinkProvider({ value, children }: LinkProviderProps) {
  return (
    <LinkComponentContext.Provider value={value}>
      {children}
    </LinkComponentContext.Provider>
  );
}

/** Returns the host-framework Link if a provider is mounted, else `null`. */
export function useLinkComponent(): LinkComponent | null {
  return useContext(LinkComponentContext);
}
