<?php
// asana-form-builder/admin/menu.php

require_once plugin_dir_path(__FILE__) . 'task-comms-admin.php';
require_once plugin_dir_path(__FILE__) . 'asana-accounts.php';
require_once plugin_dir_path(__FILE__) . 'global-field-map-helpers.php';

/**
 * Canonical list of Asana Form Builder admin pages.
 */
function afb_admin_shell_pages() {
    static $pages = null;

    if ($pages !== null) {
        return $pages;
    }

    $pages = [
        'asana-form-builder' => [
            'menu_title'   => 'Asana Forms',
            'page_title'   => 'Asana Forms',
            'icon'         => 'grid',
            'show_sidebar' => true,
        ],
        'asana-accounts' => [
            'menu_title'   => 'Asana Accounts',
            'page_title'   => 'Asana Accounts',
            'icon'         => 'lock',
            'show_sidebar' => true,
        ],
        'asana-project-selector' => [
            'menu_title'   => 'Project Selector',
            'page_title'   => 'Project Selector',
            'icon'         => 'list',
            'show_sidebar' => true,
        ],
        'asana-field-flow' => [
            'menu_title'   => 'Field Flow Config',
            'page_title'   => 'Field Flow Config',
            'icon'         => 'sliders',
            'show_sidebar' => true,
        ],
        'asana-task-prefixes' => [
            'menu_title'   => 'Task Prefixes',
            'page_title'   => 'Task Prefixes',
            'icon'         => 'tag',
            'show_sidebar' => true,
        ],
        'multi-home-settings' => [
            'menu_title'   => 'Multi-Home Settings',
            'page_title'   => 'Multi-Home Settings',
            'icon'         => 'building',
            'show_sidebar' => true,
        ],
        'afb-form-urls' => [
            'menu_title'   => 'Form URLs',
            'page_title'   => 'Form URLs',
            'icon'         => 'link',
            'show_sidebar' => true,
        ],
        'asana-email-settings' => [
            'menu_title'   => 'Email Notifications',
            'page_title'   => 'Email Notifications',
            'icon'         => 'mail',
            'show_sidebar' => true,
        ],
        'afb-global-field-map' => [
            'menu_title'   => 'Global Field Map',
            'page_title'   => 'Global Field Map',
            'icon'         => 'table',
            'show_sidebar' => true,
        ],
        'afb-global-field-map-edit' => [
            'menu_title'   => 'Global Field Map Editor',
            'page_title'   => 'Global Field Map Editor',
            'icon'         => 'pencil',
            'show_sidebar' => false,
            'active_slug'  => 'afb-global-field-map',
        ],
        'afb-client-gateway-settings' => [
            'menu_title'   => 'Client Gateway Settings',
            'page_title'   => 'Client Gateway Settings',
            'icon'         => 'globe',
            'show_sidebar' => true,
        ],
        'afb-live-client-gateways' => [
            'menu_title'   => 'Live Client Gateways',
            'page_title'   => 'Live Client Gateways',
            'icon'         => 'link',
            'show_sidebar' => true,
        ],
        'afb-feedback-settings' => [
            'menu_title'   => 'Client Feedback Settings',
            'page_title'   => 'Client Feedback Settings',
            'icon'         => 'chat',
            'show_sidebar' => true,
        ],
        'asana-automator' => [
            'menu_title'   => 'Automator',
            'page_title'   => 'Asana Automator',
            'icon'         => 'sliders',
            'show_sidebar' => true,
        ],
        'asana-automator-rules' => [
            'menu_title'   => 'Automation Rules',
            'page_title'   => 'Automation Rules',
            'icon'         => 'sliders',
            'show_sidebar' => true,
        ],
        'asana-automator-mappings' => [
            'menu_title'   => 'Mapping Profiles',
            'page_title'   => 'Mapping Profiles',
            'icon'         => 'table',
            'show_sidebar' => true,
        ],
        'asana-automator-webhooks' => [
            'menu_title'   => 'Webhooks',
            'page_title'   => 'Webhooks',
            'icon'         => 'link',
            'show_sidebar' => true,
        ],
        'asana-automator-diagnostics' => [
            'menu_title'   => 'Automator Diagnostics',
            'page_title'   => 'Automator Diagnostics',
            'icon'         => 'chat',
            'show_sidebar' => true,
        ],
    ];

    return $pages;
}

function afb_get_current_admin_page_slug() {
    if (!isset($_GET['page'])) {
        return '';
    }

    return sanitize_key(wp_unslash($_GET['page']));
}

function afb_is_admin_shell_page($page = null) {
    if ($page === null) {
        $page = afb_get_current_admin_page_slug();
    }

    if ($page === '') {
        return false;
    }

    $pages = afb_admin_shell_pages();

    return isset($pages[$page]);
}

function afb_admin_shell_active_slug($page_slug) {
    $pages = afb_admin_shell_pages();

    if (!isset($pages[$page_slug])) {
        return $page_slug;
    }

    if (!empty($pages[$page_slug]['active_slug'])) {
        return (string) $pages[$page_slug]['active_slug'];
    }

    return $page_slug;
}

function afb_admin_shell_title($page_slug, $fallback = 'Asana Forms') {
    $pages = afb_admin_shell_pages();

    if (isset($pages[$page_slug]['page_title'])) {
        return (string) $pages[$page_slug]['page_title'];
    }

    return $fallback;
}

function afb_admin_shell_sidebar_items() {
    $pages = afb_admin_shell_pages();
    $items = [];

    foreach ($pages as $slug => $item) {
        if (!empty($item['show_sidebar'])) {
            $items[$slug] = $item;
        }
    }

    return $items;
}

/**
 * Return an inline SVG icon by name.
 */
function afb_svg_icon( string $name, string $class = 'h-5 w-5' ): string {
    $a = 'class="' . esc_attr( $class ) . '" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"';

    $icons = [
        'grid'          => '<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/>',
        'lock'          => '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
        'list'          => '<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="3" cy="6" r="0.8" fill="currentColor" stroke="none"/><circle cx="3" cy="12" r="0.8" fill="currentColor" stroke="none"/><circle cx="3" cy="18" r="0.8" fill="currentColor" stroke="none"/>',
        'sliders'       => '<line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/>',
        'tag'           => '<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/>',
        'building'      => '<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>',
        'link'          => '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',
        'mail'          => '<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/>',
        'table'         => '<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/>',
        'pencil'        => '<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>',
        'globe'         => '<circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>',
        'chat'          => '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
        'home'          => '<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>',
        'chevron_left'  => '<polyline points="15 18 9 12 15 6"/>',
        'chevron_right' => '<polyline points="9 18 15 12 9 6"/>',
        'arrow_left'    => '<line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/>',
    ];

    $paths = isset( $icons[ $name ] ) ? $icons[ $name ] : '<circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/>';
    return '<svg ' . $a . '>' . $paths . '</svg>';
}

/**
 * Shared Tailwind v4 UI token strings for the admin shell.
 */
function afb_shell_ui(): array {
    $focus = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400 focus-visible:ring-offset-2';
    $base  = 'inline-flex items-center justify-center gap-2 font-medium transition duration-150 ease-in-out ' . $focus;

    return [
        'btn'           => $base . ' h-9 px-4 rounded-lg text-sm border border-slate-300 bg-white text-slate-700 hover:bg-slate-50',
        'btnPrimary'    => $base . ' h-9 px-4 rounded-lg text-sm bg-slate-900 text-white hover:bg-slate-800',
        'iconBtn'       => $base . ' h-9 w-9 rounded-lg border border-slate-200 bg-white text-slate-500 hover:bg-slate-50 hover:text-slate-700',
        'navItem'       => 'afb-nav-link group flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition duration-150 ease-in-out ' . $focus,
        'navItemActive' => 'afb-nav-link group flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-semibold text-slate-900 bg-slate-50 ' . $focus,
        'card'          => 'rounded-xl border border-slate-200 bg-white shadow-sm',
        'cardPad'       => 'p-6',
    ];
}

function afb_render_admin_shell( $title, $content_callback ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html( 'You do not have permission to access this page.' ) );
    }

    $ui          = afb_shell_ui();
    $cur         = afb_get_current_admin_page_slug();
    $active_slug = afb_admin_shell_active_slug( $cur );

    // Scoping wrapper
    echo '<div class="afb">';

    // FOUC prevention: restore collapsed state before first paint
    echo '<script>(function(){';
    echo 'try{if(localStorage.getItem("afb_sidebar_collapsed")==="1")';
    echo '{document.documentElement.classList.add("afb-collapsed");}}';
    echo 'catch(e){}})();</script>';

    echo '<div id="afb-admin-app" class="bg-slate-50 min-h-[calc(100vh-32px)]">';

    // Transfer collapsed class to #afb-admin-app
    echo '<script>(function(){';
    echo 'try{';
    echo 'var r=document.getElementById("afb-admin-app");';
    echo 'if(r&&document.documentElement.classList.contains("afb-collapsed")){r.classList.add("afb-collapsed");}';
    echo '}catch(e){}})();</script>';

    // ── Sidebar ──────────────────────────────────────────────────────────
    echo '<aside class="afb-sidebar fixed inset-y-0 left-0 bg-white border-r border-slate-200 shadow-sm transition-[width] duration-200 ease-out z-10 overflow-hidden">';
    echo '  <div class="h-full flex flex-col">';

    // Brand header
    echo '    <div class="afb-sidebar-header px-5 py-4 border-b border-slate-200">';
    echo '      <div class="afb-sidebar-header-inner flex items-center justify-between gap-3">';
    echo '        <div class="afb-brand flex items-center gap-2 min-w-0">';
    echo '          <div class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-slate-900 text-white text-sm font-semibold">AF</div>';
    echo '          <div class="afb-brand-text min-w-0">';
    echo '            <div class="text-sm font-semibold text-slate-900 truncate">Asana Forms</div>';
    echo '            <div class="text-xs text-slate-500 truncate">Form Builder</div>';
    echo '          </div>';
    echo '        </div>';
    echo '        <button id="afb-sidebar-toggle" type="button" class="' . esc_attr( $ui['iconBtn'] ) . ' shrink-0" aria-label="Toggle sidebar" aria-pressed="false">';
    echo            afb_svg_icon( 'chevron_left', 'h-5 w-5' );
    echo '        </button>';
    echo '      </div>';
    echo '    </div>';

    // Nav
    echo '    <nav class="flex-1 overflow-y-auto p-2 space-y-1" aria-label="Main navigation">';
    foreach ( afb_admin_shell_sidebar_items() as $slug => $item ) {
        $is_active = ( $active_slug === $slug );
        $cls       = $is_active ? $ui['navItemActive'] : $ui['navItem'];
        $label     = (string) $item['menu_title'];
        $icon      = (string) ( $item['icon'] ?? 'dot' );
        $icon_color = $is_active ? ' text-slate-700' : '';

        echo '      <a class="' . esc_attr( $cls ) . '" href="' . esc_url( admin_url( 'admin.php?page=' . $slug ) ) . '" title="' . esc_attr( $label ) . '">';
        echo '        <span class="flex h-5 w-5 shrink-0 items-center justify-center text-slate-400 group-hover:text-slate-600' . $icon_color . '">';
        echo            afb_svg_icon( $icon, 'h-5 w-5' );
        echo '        </span>';
        echo '        <span class="afb-nav-label">' . esc_html( $label ) . '</span>';
        echo '      </a>';
    }
    echo '    </nav>';

    // Footer — back to dashboard
    echo '    <div class="p-2 border-t border-slate-200 afb-sidebar-footer-inner">';
    echo '      <a class="' . esc_attr( $ui['navItem'] ) . '" href="' . esc_url( admin_url( 'index.php' ) ) . '" title="Back to WordPress Dashboard">';
    echo '        <span class="flex h-5 w-5 shrink-0 items-center justify-center text-slate-400 group-hover:text-slate-600">';
    echo            afb_svg_icon( 'arrow_left', 'h-5 w-5' );
    echo '        </span>';
    echo '        <span class="afb-nav-label">Dashboard</span>';
    echo '      </a>';
    echo '    </div>';

    echo '  </div>';
    echo '</aside>';

    // ── Main content ─────────────────────────────────────────────────────
    echo '<main class="afb-main transition-[padding-left] duration-200 ease-out">';
    echo '  <div class="min-h-[calc(100vh-32px)] p-6 space-y-6">';

    // Page heading row
    echo '    <div class="flex items-center justify-between gap-4 flex-wrap">';
    echo '      <h1 class="text-xl font-semibold text-slate-900 m-0 leading-tight">' . esc_html( $title ) . '</h1>';
    echo '      <a class="' . esc_attr( $ui['btn'] ) . '" href="' . esc_url( admin_url( 'index.php' ) ) . '">Back to Dashboard</a>';
    echo '    </div>';

    if ( is_callable( $content_callback ) ) {
        call_user_func( $content_callback );
    }

    echo '  </div>';
    echo '</main>';

    // ── Inline sidebar toggle script ──────────────────────────────────────
    $icon_collapse = wp_json_encode( afb_svg_icon( 'chevron_left',  'h-5 w-5' ) );
    $icon_expand   = wp_json_encode( afb_svg_icon( 'chevron_right', 'h-5 w-5' ) );

    echo '<script>(function(){';
    echo   'var root=document.getElementById("afb-admin-app");';
    echo   'var btn=document.getElementById("afb-sidebar-toggle");';
    echo   'if(!root||!btn)return;';
    echo   'var k="afb_sidebar_collapsed";';
    echo   'function apply(v){';
    echo     'root.classList.toggle("afb-collapsed",v);';
    echo     'document.documentElement.classList.toggle("afb-collapsed",v);';
    echo     'btn.innerHTML=v?' . $icon_expand . ':' . $icon_collapse . ';';
    echo     'btn.setAttribute("aria-pressed",v?"true":"false");';
    echo     'try{localStorage.setItem(k,v?"1":"0");}catch(e){}';
    echo   '}';
    echo   'var init=root.classList.contains("afb-collapsed")||document.documentElement.classList.contains("afb-collapsed");';
    echo   'apply(init);';
    echo   'btn.addEventListener("click",function(){apply(!root.classList.contains("afb-collapsed"));});';
    echo '})();</script>';

    echo '</div>'; // #afb-admin-app
    echo '</div>'; // .afb
}

function afb_render_admin_shell_include_page($title, $relative_path) {
    afb_render_admin_shell($title, function () use ($relative_path) {
        include_once plugin_dir_path(__FILE__) . $relative_path;
    });
}

function afb_render_asana_home_page() {
    afb_render_admin_shell('Asana Forms', function () {
        echo '<div class="wrap">';
        echo '  <p class="description">Select a section from the sidebar to manage Asana Form Builder settings.</p>';
        echo '</div>';
    });
}

function afb_render_asana_accounts_page_shell() {
    afb_render_admin_shell('Asana Accounts', 'afb_render_asana_accounts_page');
}

function afb_render_project_selector_page_shell() {
    afb_render_admin_shell_include_page('Project Selector', 'pages/project-selector.php');
}

function afb_render_field_flow_page_shell() {
    afb_render_admin_shell_include_page('Field Flow Config', 'pages/field-flow-config.php');
}

function afb_render_task_prefixes_page_shell() {
    afb_render_admin_shell_include_page('Task Prefixes', 'pages/task-prefixes.php');
}

function afb_render_multi_home_settings_page_shell() {
    afb_render_admin_shell_include_page('Multi-Home Settings', 'pages/multi-home-settings.php');
}

function afb_render_form_urls_page() {
    afb_render_admin_shell_include_page('Form URLs', 'pages/form-urls-page.php');
}

function afb_render_email_settings_page_shell() {
    afb_render_admin_shell_include_page('Email Notifications', 'pages/email-settings.php');
}

function afb_render_global_field_map_page_shell() {
    afb_render_admin_shell_include_page('Global Field Map', 'pages/global-field-map-index.php');
}

function afb_render_global_field_map_editor_page_shell() {
    afb_render_admin_shell_include_page('Global Field Map Editor', 'pages/global-field-map-editor.php');
}

function afb_render_client_gateway_settings_page_shell() {
    afb_render_admin_shell_include_page('Client Gateway Settings', 'pages/client-gateway-settings.php');
}

function afb_render_live_client_gateways_page_shell() {
    afb_render_admin_shell_include_page('Live Client Gateways', 'pages/live-client-gateways.php');
}

function afb_render_feedback_settings_page_shell() {
    afb_render_admin_shell_include_page('Client Feedback Settings', 'pages/feedback-settings.php');
}

function afb_render_automator_page_shell($title, $callback) {
    afb_render_admin_shell($title, function () use ($callback) {
        call_user_func($callback);
    });
}

function afb_render_automator_settings_page_shell() {
    afb_render_automator_page_shell('Asana Automator', 'asana_automator_main_settings_page');
}

function afb_render_automator_rules_page_shell() {
    afb_render_automator_page_shell('Automation Rules', 'asana_automator_rules_page');
}

function afb_render_automator_mappings_page_shell() {
    afb_render_automator_page_shell('Mapping Profiles', 'asana_automator_mapping_profiles_page');
}

function afb_render_automator_webhooks_page_shell() {
    afb_render_automator_page_shell('Webhooks', 'asana_automator_webhooks_page');
}

function afb_render_automator_diagnostics_page_shell() {
    afb_render_automator_page_shell('Automator Diagnostics', 'asana_automator_diagnostic_report');
}

function afb_register_admin_menu() {
    add_menu_page(
        'Asana Form Builder',
        'Asana Forms',
        'manage_options',
        'asana-form-builder',
        'afb_render_asana_home_page',
        'dashicons-forms',
        80
    );

    add_submenu_page(
        'asana-form-builder',
        'Asana Accounts',
        'Asana Accounts',
        'manage_options',
        'asana-accounts',
        'afb_render_asana_accounts_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Project Selector',
        'Project Selector',
        'manage_options',
        'asana-project-selector',
        'afb_render_project_selector_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Field Flow Config',
        'Field Flow Config',
        'manage_options',
        'asana-field-flow',
        'afb_render_field_flow_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Task Prefixes',
        'Task Prefixes',
        'manage_options',
        'asana-task-prefixes',
        'afb_render_task_prefixes_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Multi-Home Settings',
        'Multi-Home Settings',
        'manage_options',
        'multi-home-settings',
        'afb_render_multi_home_settings_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Form URLs',
        'Form URLs',
        'manage_options',
        'afb-form-urls',
        'afb_render_form_urls_page'
    );

    add_submenu_page(
        'asana-form-builder',
        'Email Notifications',
        'Email Notifications',
        'manage_options',
        'asana-email-settings',
        'afb_render_email_settings_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Global Field Map',
        'Global Field Map',
        'manage_options',
        'afb-global-field-map',
        'afb_render_global_field_map_page_shell'
    );

    add_submenu_page(
        null,
        'Global Field Map Editor',
        'Global Field Map Editor',
        'manage_options',
        'afb-global-field-map-edit',
        'afb_render_global_field_map_editor_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Client Gateway Settings',
        'Client Gateway Settings',
        'manage_options',
        'afb-client-gateway-settings',
        'afb_render_client_gateway_settings_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Live Client Gateways',
        'Live Client Gateways',
        'manage_options',
        'afb-live-client-gateways',
        'afb_render_live_client_gateways_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Client Feedback Settings',
        'Client Feedback Settings',
        'manage_options',
        'afb-feedback-settings',
        'afb_render_feedback_settings_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Asana Automator',
        'Automator',
        'manage_options',
        'asana-automator',
        'afb_render_automator_settings_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Automation Rules',
        'Automation Rules',
        'manage_options',
        'asana-automator-rules',
        'afb_render_automator_rules_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Mapping Profiles',
        'Mapping Profiles',
        'manage_options',
        'asana-automator-mappings',
        'afb_render_automator_mappings_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Webhooks',
        'Webhooks',
        'manage_options',
        'asana-automator-webhooks',
        'afb_render_automator_webhooks_page_shell'
    );

    add_submenu_page(
        'asana-form-builder',
        'Automator Diagnostics',
        'Automator Diagnostics',
        'manage_options',
        'asana-automator-diagnostics',
        'afb_render_automator_diagnostics_page_shell'
    );
}
add_action('admin_menu', 'afb_register_admin_menu');

add_filter('admin_body_class', function ($classes) {
    if (afb_is_admin_shell_page()) {
        $classes .= ' afb-app';
    }

    return $classes;
}, 20);

function afb_enqueue_admin_assets($hook) {
    if ( afb_is_admin_shell_page() ) {
        $shell_css_path = AFB_PLUGIN_DIR . 'assets/build/admin-shell.css';

        wp_enqueue_style(
            'afb-admin-shell',
            plugins_url( 'assets/build/admin-shell.css', AFB_PLUGIN_DIR . 'asana-form-builder.php' ),
            [],
            file_exists( $shell_css_path ) ? filemtime( $shell_css_path ) : null
        );
    }

    if (strpos((string) $hook, 'asana-field-flow') !== false) {
        $admin_css_path = plugin_dir_path(__DIR__) . 'assets/build/admin-field-flow.css';

        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_script('jquery-ui-draggable');

        wp_enqueue_style(
            'afb-field-flow-admin',
            plugin_dir_url(__DIR__) . 'assets/build/admin-field-flow.css',
            [],
            file_exists($admin_css_path) ? filemtime($admin_css_path) : null
        );

        wp_enqueue_script(
            'afb-field-flow-admin-js',
            plugin_dir_url(__DIR__) . 'assets/field-flow-admin.js',
            ['jquery', 'jquery-ui-sortable', 'jquery-ui-draggable'],
            file_exists(plugin_dir_path(__DIR__) . 'assets/field-flow-admin.js') ? filemtime(plugin_dir_path(__DIR__) . 'assets/field-flow-admin.js') : null,
            true
        );

        wp_localize_script('afb-field-flow-admin-js', 'afbFieldFlowAdmin', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'saveAction' => 'afb_save_field_flow_config',
        ]);
    }

    if (afb_get_current_admin_page_slug() === 'afb-global-field-map-edit') {
        $asset_path = plugin_dir_path(__DIR__) . 'assets/admin-global-field-map.js';

        wp_enqueue_script(
            'afb-global-field-map-admin',
            plugin_dir_url(__DIR__) . 'assets/admin-global-field-map.js',
            ['jquery'],
            file_exists($asset_path) ? filemtime($asset_path) : null,
            true
        );

        wp_localize_script('afb-global-field-map-admin', 'afbGlobalFieldMapCfg', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('afb_gf_editor_nonce'),
            'patId' => isset($_GET['pat_id']) ? (int) $_GET['pat_id'] : 0,
        ]);
    }
}
add_action('admin_enqueue_scripts', 'afb_enqueue_admin_assets');
