/**
 * SearchableField Component
 * A wrapper that registers fields with the search index.
 */
import React, { useEffect, useContext, createContext } from "react";
import type { SearchableFieldData } from "./SearchResultsView";

interface SearchContextValue {
  registerField: (field: SearchableFieldData) => void;
  unregisterField: (id: string) => void;
  highlightedFieldId: string | null;
}

export const SearchContext = createContext<SearchContextValue | null>(null);

export interface SearchableFieldProps {
  /** Unique identifier for this field */
  id: string;
  /** Display label for the field */
  label: string;
  /** Optional description or help text */
  description?: string;
  /** Tab ID where this field is located */
  tabId: string;
  /** Human-readable tab label */
  tabLabel: string;
  /** Optional section/subsection name */
  section?: string;
  /** Child elements to render */
  children: React.ReactNode;
}

/**
 * Wrapper component that registers a field with the global search index
 * and applies highlight styling when the field is the target of a search result selection.
 */
export function SearchableField({
  id,
  label,
  description,
  tabId,
  tabLabel,
  section,
  children,
}: SearchableFieldProps) {
  const context = useContext(SearchContext);

  useEffect(() => {
    if (!context) return;

    context.registerField({
      id,
      label,
      description,
      tabId,
      tabLabel,
      section,
    });

    return () => {
      context.unregisterField(id);
    };
  }, [context, id, label, description, tabId, tabLabel, section]);

  const isHighlighted = context?.highlightedFieldId === id;

  return (
    <div
      id={id}
      data-searchable-field={id}
      className={`b3-wvs-transition-all b3-wvs-duration-500 ${
        isHighlighted
          ? "b3-wvs-ring-2 b3-wvs-ring-admin b3-wvs-ring-offset-4 b3-wvs-rounded-lg"
          : ""
      }`}
    >
      {children}
    </div>
  );
}
