<?php
defined( 'ABSPATH' ) || exit;

class SITECL_Admin_Menu {

    public function __construct() {
        add_action( 'admin_menu',            [ $this, 'register_menus' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
    }

    public function register_menus(): void {
        add_menu_page(
            __( 'Site CliniQ', 'site-cliniq' ),
            __( 'Site CliniQ', 'site-cliniq' ),
            'manage_options',
            'sitecl',
            [ $this, 'render_app' ],
            'dashicons-heart',
            81
        );
    }

    public function enqueue_assets( string $hook ): void {
        if ( 'toplevel_page_sitecl' !== $hook ) {
            return;
        }

        $asset_file = SITECL_PLUGIN_DIR . 'assets/build/index.asset.php';
        $asset      = file_exists( $asset_file ) ? require $asset_file : [ 'dependencies' => [], 'version' => SITECL_VERSION ];

        wp_enqueue_style( 'dashicons' );

        wp_enqueue_script(
            'sitecl-app',
            SITECL_PLUGIN_URL . 'assets/build/index.js',
            $asset['dependencies'],
            $asset['version'],
            true
        );

        wp_enqueue_style(
            'sitecl-app',
            SITECL_PLUGIN_URL . 'assets/build/style-index.css',
            [ 'dashicons' ],
            $asset['version']
        );

        wp_localize_script( 'sitecl-app', 'siteclData', [
            'apiRoot'    => esc_url_raw( rest_url( 'site-cliniq/v1' ) ),
            'nonce'      => wp_create_nonce( 'wp_rest' ),
            'adminUrl'   => admin_url(),
            'siteUrl'    => site_url(),
            'adminEmail' => get_bloginfo( 'admin_email' ),
            'version'    => SITECL_VERSION,
            'isPro'      => class_exists( 'SITECL_License' ) && SITECL_License::is_active(),
            'hasApiKey'  => ! empty( get_option( 'sitecl_claude_api_key', '' ) ),
        ] );
    }

    public function render_app(): void {
        ?>
        <div id="sitecl-root"></div>
        <?php
    }
}
