import { useState, useEffect } from 'react';
import type { MetaField } from '@/components/MetaFields';

interface MetaFieldsRegistry {
  orders: MetaField[];
  products: MetaField[];
}

// Global registry exposed by PHP via wp_localize_script
declare global {
  interface Window {
    WooNooWMetaFields?: MetaFieldsRegistry;
  }
}

/**
 * useMetaFields Hook
 * 
 * Retrieves registered meta fields from global registry (set by PHP).
 * Part of Level 1 compatibility - allows plugins to register their fields
 * via PHP filters, which are then exposed to the frontend.
 * 
 * Zero coupling with specific plugins - just reads the registry.
 * 
 * @param type - 'orders' or 'products'
 * @returns Array of registered meta fields
 * 
 * @example
 * ```tsx
 * const metaFields = useMetaFields('orders');
 * 
 * return (
 *   <MetaFields
 *     meta={order.meta}
 *     fields={metaFields}
 *     onChange={handleMetaChange}
 *   />
 * );
 * ```
 */
export function useMetaFields(type: 'orders' | 'products'): MetaField[] {
  const [fields, setFields] = useState<MetaField[]>([]);

  useEffect(() => {
    // Get fields from global registry (set by PHP via wp_localize_script)
    const registry = window.WooNooWMetaFields || { orders: [], products: [] };
    setFields(registry[type] || []);

    // Listen for dynamic field registration (for future extensibility)
    const handleFieldsUpdated = (e: CustomEvent) => {
      if (e.detail.type === type) {
        setFields(e.detail.fields);
      }
    };

    window.addEventListener(
      'woonoow:meta_fields_updated',
      handleFieldsUpdated as EventListener
    );

    return () => {
      window.removeEventListener(
        'woonoow:meta_fields_updated',
        handleFieldsUpdated as EventListener
      );
    };
  }, [type]);

  return fields;
}
