'use client';

import { useEffect, type ReactNode } from 'react';
import { cn } from '@/lib/utils';

/** Stable scroll target for command-palette deep links (`#field-…`). */
export function FieldAnchor({
  id,
  children,
  className
}: {
  id: string;
  children: ReactNode;
  className?: string;
}) {
  return (
    <div id={id} className={cn('scroll-mt-24', className)}>
      {children}
    </div>
  );
}

/** Scrolls to `location.hash` after navigation from the command palette. */
export function HashScroll() {
  useEffect(() => {
    function scrollToHash() {
      const hash = window.location.hash.replace(/^#/, '');
      if (!hash) {
        return;
      }
      const el = document.getElementById(hash);
      if (el) {
        el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }

    scrollToHash();
    window.addEventListener('hashchange', scrollToHash);
    const timer = window.setTimeout(scrollToHash, 120);
    return () => {
      window.removeEventListener('hashchange', scrollToHash);
      window.clearTimeout(timer);
    };
  }, []);

  return null;
}
