<?php
/**
 * Structure Viewer — Asset Loader
 *
 * Enqueues all CSS and JS files for the plugin admin page.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit( 'Direct access denied.' );
}

final class SV_Loader {

    /** Admin hook suffix for the plugin page. */
    const PAGE_HOOK = 'tools_page_structure-viewer';

    public static function enqueue( $hook ) {
        if ( $hook !== self::PAGE_HOOK ) {
            return;
        }

        // ── External: jsPDF (client-side PDF export) ──────────────────
        // Bundled locally — WordPress.org does not allow loading from external CDNs.
        // File: assets/js/vendor/jspdf.umd.min.js (jsPDF v2.5.1, MIT licence)
        $jspdf_path = STRUCTUREVIEWER_PLUGIN_DIR . 'assets/js/vendor/jspdf.umd.min.js';
        if ( file_exists( $jspdf_path ) ) {
            wp_enqueue_script(
                'jspdf',
                STRUCTUREVIEWER_PLUGIN_URL . 'assets/js/vendor/jspdf.umd.min.js',
                [],
                '2.5.1',
                true
            );
        }

        // ── CSS ───────────────────────────────────────────────────────
        $css_files = [
            'structureviewer-styles'   => 'sv-styles.css',
            'structureviewer-controls' => 'sv-controls.css',
            'structureviewer-tree'     => 'sv-tree.css',
            'structureviewer-results'  => 'sv-results.css',
            'structureviewer-modal'    => 'sv-modal.css',
            'structureviewer-loading'  => 'sv-loading.css',
            'structureviewer-viewer'   => 'sv-viewer.css',
        ];

        foreach ( $css_files as $handle => $filename ) {
            $path = STRUCTUREVIEWER_PLUGIN_DIR . 'assets/css/' . $filename;
            wp_enqueue_style(
                $handle,
                STRUCTUREVIEWER_PLUGIN_URL . 'assets/css/' . $filename,
                $handle === 'structureviewer-styles' ? [] : [ 'structureviewer-styles' ],
                file_exists( $path ) ? filemtime( $path ) : STRUCTUREVIEWER_VERSION
            );
        }

        // ── Pro CSS & JS (premium only — stripped from free version) ─────────
        // This block is automatically removed by Freemius when generating the
        // free version. The file_exists() guards remain as a safety net for
        // manual installs where the pro/ folder might be absent.
        if ( class_exists( 'SV_Pro' ) && SV_Pro::is_active() ) {

            // Comparator
            $pro_css = STRUCTUREVIEWER_PLUGIN_DIR . 'pro/Comparator/sv-comparator.css';
            if ( file_exists( $pro_css ) ) {
                wp_enqueue_style(
                    'structureviewer-comparator',
                    STRUCTUREVIEWER_PLUGIN_URL . 'pro/Comparator/sv-comparator.css',
                    [ 'structureviewer-styles' ],
                    filemtime( $pro_css )
                );
            }

            // FlatPack — CSS + JS (FlatPack has its own interaction script)
            $fp_css = STRUCTUREVIEWER_PLUGIN_DIR . 'pro/FlatPack/sv-flatpack.css';
            $fp_js  = STRUCTUREVIEWER_PLUGIN_DIR . 'pro/FlatPack/sv-flatpack.js';
            if ( file_exists( $fp_css ) ) {
                wp_enqueue_style(
                    'structureviewer-flatpack',
                    STRUCTUREVIEWER_PLUGIN_URL . 'pro/FlatPack/sv-flatpack.css',
                    [ 'structureviewer-styles' ],
                    filemtime( $fp_css )
                );
            }
            if ( file_exists( $fp_js ) ) {
                wp_enqueue_script(
                    'structureviewer-flatpack',
                    STRUCTUREVIEWER_PLUGIN_URL . 'pro/FlatPack/sv-flatpack.js',
                    [ 'jquery' ],
                    filemtime( $fp_js ),
                    true
                );
                wp_localize_script( 'structureviewer-flatpack', 'svFlatpackData', [
                    'ajax_url'        => admin_url( 'admin-ajax.php' ),
                    'nonce'           => wp_create_nonce( STRUCTUREVIEWER_NONCE ),
                    'i18n_preparing'  => __( 'Preparing download…', 'structure-viewer' ),
                ] );
            }

        } // end premium-only enqueue

        // ── JS ────────────────────────────────────────────────────────
        // Dependency chain: utils → fileviewer → export → app.
        // jsPDF is listed as optional — sv-export.js guards internally with
        // `if (!window.jspdf)` so PDF export is simply disabled when the
        // vendor file is absent. All other functionality remains intact.
        $js_files = [
            'structureviewer-utils'      => [ 'sv-utils.js',      [ 'jquery' ] ],
            'structureviewer-fileviewer' => [ 'sv-fileviewer.js', [ 'jquery', 'structureviewer-utils' ] ],
            'structureviewer-export'     => [ 'sv-export.js',     [ 'jquery', 'structureviewer-utils' ] ], // jspdf intentionally not a hard dep
            'structureviewer-app'        => [ 'sv-app.js',        [ 'jquery', 'structureviewer-utils', 'structureviewer-fileviewer', 'structureviewer-export' ] ],
        ];

        foreach ( $js_files as $handle => [ $filename, $deps ] ) {
            $path = STRUCTUREVIEWER_PLUGIN_DIR . 'assets/js/' . $filename;
            wp_enqueue_script(
                $handle,
                STRUCTUREVIEWER_PLUGIN_URL . 'assets/js/' . $filename,
                $deps,
                file_exists( $path ) ? filemtime( $path ) : STRUCTUREVIEWER_VERSION,
                true
            );
        }

        // ── Localize (single source of truth for all JS) ──────────────
        $user_id              = get_current_user_id();
        $show_welcome         = (bool) get_transient( 'sv_welcome_modal_' . $user_id );
        // Consume the transient immediately so the modal only fires once.
        if ( $show_welcome ) {
            delete_transient( 'sv_welcome_modal_' . $user_id );
        }

        $account_url = ( function_exists( 'structureviewer_fs' ) ) ? structureviewer_fs()->get_account_url() : '';

        $data = [
            'ajaxurl'            => admin_url( 'admin-ajax.php' ),
            'nonce'              => wp_create_nonce( STRUCTUREVIEWER_NONCE ),
            'search_nonce'       => wp_create_nonce( 'structureviewer_search_nonce' ),
            'content_url'        => content_url(),
            'version'            => STRUCTUREVIEWER_VERSION,
            'show_welcome_modal' => $show_welcome,
            'account_url'        => $account_url,
        ];

        // Localized on utils (first script in the chain) — every subsequent
        // script has utils as a direct or transitive dependency, so the
        // variable is always available when they run.
        wp_localize_script( 'structureviewer-utils', 'structureviewerSettings', $data );
    }
}