<?php

namespace ModernFields\WordPress\Hooks;

use ModernFields\Settings\Hooks\AdminSettings;
use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\WordPress\Services\ScriptDataService;

defined('ABSPATH') || exit;

/**
 * Registers the single Modern Fields admin page and its React shell.
 *
 * Every section (field groups, post types, taxonomies, blocks, import/export,
 * settings, licence) is a tab inside one React app mounted on the
 * `modern-fields` page. The submenu items all link to this page and only switch
 * the `tab` query arg; the app navigates between tabs client-side, without a
 * full reload. The default tab (groups) uses the bare parent slug so it matches
 * the auto-generated parent submenu item.
 *
 * @since 1.0.5
 */
class AdminPageHooks implements Hooks
{
  public const PAGE_SLUG = 'modern-fields';

  /**
   * @since 1.0.5
   */
  public function __construct(protected AdminSettings $settings)
  {
  }

  /**
   * @since 1.0.5
   */
  public function registerHooks(): void
  {
    add_action('admin_menu', [$this, 'removeDefaultMenuItems']);
    add_action('admin_menu', [$this, 'registerMenu'], 10);
    add_filter('submenu_file', [$this, 'highlightCurrentTab']);
    add_action('admin_enqueue_scripts', [$this, 'enqueueAdminPagesReset']);
    add_action('admin_enqueue_scripts', [$this, 'enqueueAppAssets']);
  }

  /**
   * Hides the auto-generated CPT menu item; field groups live in the React app.
   *
   * @since 1.0.5
   */
  public function removeDefaultMenuItems(): void
  {
    remove_menu_page('edit.php?post_type=' . MODERN_FIELDS_CPT_SLUG);
  }

  /**
   * Registers the top-level page and one submenu item per tab.
   *
   * @since 1.0.5
   */
  public function registerMenu(): void
  {
    add_menu_page(
      __('Modern Fields', 'modern-fields'),
      __('Modern Fields', 'modern-fields'),
      'manage_options',
      self::PAGE_SLUG,
      [$this, 'renderApp'],
      'dashicons-superhero',
      99
    );

    # [tab, label]. An empty tab reuses the parent slug (default = field groups).
    # Premium injects its own tabs (e.g. Licence) through this filter.
    $tabs = apply_filters('modern-fields/admin/menu_tabs', [
      ['', __('Field Groups', 'modern-fields')],
      ['post-types', __('Post Types', 'modern-fields')],
      ['taxonomies', __('Taxonomies', 'modern-fields')],
      ['blocks', __('Blocks', 'modern-fields')],
      ['import-export', __('Import/Export', 'modern-fields')],
      ['settings', __('Settings', 'modern-fields')],
    ]);

    foreach ($tabs as [$tab, $label]) {
      add_submenu_page(
        self::PAGE_SLUG,
        $label,
        $label,
        'manage_options',
        $tab === '' ? self::PAGE_SLUG : self::PAGE_SLUG . '&tab=' . $tab,
        $tab === '' ? [$this, 'renderApp'] : '__return_null'
      );
    }
  }

  /**
   * Highlights the submenu item matching the current `tab` query arg.
   *
   * All submenu links share `page=modern-fields`, so WordPress would otherwise
   * always highlight the first item.
   *
   * @since 1.0.5
   */
  public function highlightCurrentTab(?string $submenu_file): ?string
  {
    if (($_GET['page'] ?? '') !== self::PAGE_SLUG) {
      return $submenu_file;
    }

    $tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : '';

    if ($tab === '' || $tab === 'groups') {
      return self::PAGE_SLUG;
    }

    return self::PAGE_SLUG . '&tab=' . $tab;
  }

  /**
   * @since 1.0.5
   */
  public function renderApp(): void
  {
    echo '<div id="mf-admin-root"></div>';
  }

  /**
   * Enqueues the layout reset styles shared by all Modern Fields admin screens.
   *
   * @since 1.0.5
   */
  public function enqueueAdminPagesReset(string $hook): void
  {
    if (!str_contains($hook, 'modern-fields')) {
      return;
    }

    wp_enqueue_style(
      'modern-fields-admin-pages',
      MODERN_FIELDS_PLUGIN_URL . 'assets/css/admin-pages.css',
      [],
      MODERN_FIELDS_VERSION
    );
  }

  /**
   * Enqueues the single admin React app on the Modern Fields page.
   *
   * @since 1.0.5
   */
  public function enqueueAppAssets(string $hook): void
  {
    if ($hook !== 'toplevel_page_' . self::PAGE_SLUG) {
      return;
    }

    $file_path = MODERN_FIELDS_PLUGIN_DIR . 'build/admin/index.asset.php';

    if (!file_exists($file_path)) {
      return;
    }

    $asset_file = include $file_path;

    wp_enqueue_script(
      'modern-fields-admin',
      MODERN_FIELDS_PLUGIN_URL . 'build/admin/index.js',
      $asset_file['dependencies'],
      $asset_file['version'],
      ['in_footer' => true]
    );

    wp_set_script_translations('modern-fields-admin', 'modern-fields');

    wp_enqueue_style(
      'modern-fields-admin',
      MODERN_FIELDS_PLUGIN_URL . 'build/admin/index.css',
      ['wp-components'],
      MODERN_FIELDS_VERSION
    );

    # All tabs load together, so every section's script data is exposed here.
    ScriptDataService::enqueue($this->settings->getScriptData());
  }
}
