/**
 * Block Registry System
 *
 * Centralized registry for managing WPUF User Directory blocks.
 * Provides priority-based registration and simplified block management.
 *
 * @since 4.2.0
 */

import { registerBlockType } from '@wordpress/blocks';

/**
 * Block Registry Configuration
 *
 * Defines all blocks with their metadata and registration priority.
 * Priority determines registration order (lower numbers = higher priority).
 */
export const BLOCK_REGISTRY = {
  // Container blocks (Priority 1-2)
  'directory': {
    name: 'wpuf-ud/directory',
    category: 'wpuf-ud',
    priority: 1,
    description: 'Main container for user directory listings'
  },
  'directory-item': {
    name: 'wpuf-ud/directory-item',
    category: 'wpuf-ud',
    priority: 2,
    description: 'Container for individual user items in directory'
  },
  'profile': {
    name: 'wpuf-ud/profile',
    category: 'wpuf-ud',
    priority: 1,
    description: 'Main container for user profile display'
  },

  // Individual blocks (Priority 3)
  'avatar': {
    name: 'wpuf-ud/avatar',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user avatar image'
  },
  'cover-photo': {
    name: 'wpuf-ud/cover-photo',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user cover photo with various sizing options'
  },
  'name': {
    name: 'wpuf-ud/name',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user name'
  },
  'bio': {
    name: 'wpuf-ud/bio',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user biography'
  },
  'contact': {
    name: 'wpuf-ud/contact',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user contact information'
  },
  'custom-field': {
    name: 'wpuf-ud/custom-field',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display custom user fields'
  },
  'posts': {
    name: 'wpuf-ud/posts',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user posts'
  },
  'comments': {
    name: 'wpuf-ud/comments',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user comments'
  },
  'files': {
    name: 'wpuf-ud/files',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user files'
  },
  'social': {
    name: 'wpuf-ud/social',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user social media links'
  },
  'tabs': {
    name: 'wpuf-ud/tabs',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Display user information in tabs'
  },
  'profile-button': {
    name: 'wpuf-ud/profile-button',
    category: 'wpuf-ud',
    priority: 3,
    description: 'Button that automatically links to user profile'
  },
  'message-button': {
    name: 'wpuf-ud/message-button',
    category: 'wpuf-ud',
    priority: 3,
    description: 'A message button inside User Profile block when Private Message module is enabled'
  },
  'unmatched-blocks': {
      name: 'wpuf-ud/unmatched-blocks',
      category: 'wpuf-ud',
      priority: 3,
      description: 'Container for unmatched blocks that don\'t have specific implementations'
  }
};

/**
 * Block Registry Class
 *
 * Handles block registration with priority-based ordering and error handling.
 */
export class BlockRegistry {
  /**
   * Register a single block by name
   *
   * @param {string} blockName - The block name from BLOCK_REGISTRY
   * @throws {Error} If block is not found in registry
   */
  static register(blockName) {
    const config = BLOCK_REGISTRY[blockName];
    if (!config) {
      throw new Error(`Block '${blockName}' not found in registry`);
    }

    try {
      // Dynamically import the block module using new simplified directory names
      const blockModule = require(`./${blockName}/index.js`);

      // Register the block with WordPress
      registerBlockType(config.name, blockModule.settings);
    } catch (error) {
      console.error(`❌ Failed to register block '${blockName}':`, error);
      throw error;
    }
  }

  /**
   * Register all blocks in priority order
   *
   * @param {string[]} blockNames - Optional array of specific blocks to register
   */
  static registerAll(blockNames = null) {
    const blocksToRegister = blockNames || Object.keys(BLOCK_REGISTRY);

    // Sort blocks by priority (lower number = higher priority)
    const sortedBlocks = blocksToRegister
      .filter(name => BLOCK_REGISTRY[name]) // Only include valid blocks
      .sort((a, b) => BLOCK_REGISTRY[a].priority - BLOCK_REGISTRY[b].priority);

    sortedBlocks.forEach(blockName => {
      try {
        this.register(blockName);
      } catch (error) {
        console.error(`Failed to register block '${blockName}':`, error);
        // Continue with other blocks even if one fails
      }
    });
  }

  /**
   * Get block configuration by name
   *
   * @param {string} blockName - The block name
   * @returns {Object|null} Block configuration or null if not found
   */
  static getBlockConfig(blockName) {
    return BLOCK_REGISTRY[blockName] || null;
  }

  /**
   * Get all registered block names
   *
   * @returns {string[]} Array of block names
   */
  static getBlockNames() {
    return Object.keys(BLOCK_REGISTRY);
  }

  /**
   * Get blocks by category
   *
   * @param {string} category - The category to filter by
   * @returns {string[]} Array of block names in the category
   */
  static getBlocksByCategory(category) {
    return Object.entries(BLOCK_REGISTRY)
      .filter(([, config]) => config.category === category)
      .map(([name]) => name);
  }

  /**
   * Get blocks by priority
   *
   * @param {number} priority - The priority to filter by
   * @returns {string[]} Array of block names with the specified priority
   */
  static getBlocksByPriority(priority) {
    return Object.entries(BLOCK_REGISTRY)
      .filter(([, config]) => config.priority === priority)
      .map(([name]) => name);
  }
}

export default BlockRegistry;
