<?php

defined( 'ABSPATH' ) or die( 'Forbidden' );

/**
 * Handles front-end script and style enqueuing.
 */
class SCPWOO_Scripts {

    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'load_scripts' ) );
        // Add no-js class to <html> — removed by JS when it loads (progressive enhancement)
        add_filter( 'language_attributes', array( $this, 'add_nojs_class' ) );
    }

    /**
     * Add no-js class to <html> for progressive enhancement fallback.
     *
     * Appends to an existing class="…" attribute when the theme already sets one,
     * instead of adding a duplicate attribute (invalid HTML).
     *
     * @param string $output
     * @return string
     */
    public function add_nojs_class( string $output ): string {
        if ( is_cart() || is_checkout() || is_wc_endpoint_url( 'edit-address' ) ) {
            if ( preg_match( '/\bclass="([^"]*)"/i', $output ) ) {
                $output = preg_replace( '/\bclass="([^"]*)"/i', 'class="$1 no-js"', $output );
            } else {
                $output .= ' class="no-js"';
            }
        }
        return $output;
    }

    public function load_scripts() {
        if ( is_cart() || is_checkout() || is_wc_endpoint_url( 'edit-address' ) ) {

            wp_enqueue_script(
                'scpwoo-fuse',
                plugin_dir_url( SCPWOO_PLUGIN_FILE ) . 'js/fuse.min.js',
                array(),
                '7.3.0',
                true
            );

            wp_enqueue_script(
                'scpwoo-city-select',
                plugin_dir_url( SCPWOO_PLUGIN_FILE ) . 'js/place-select.js',
                array( 'jquery', 'woocommerce', 'scpwoo-fuse' ),
                SCPWOO_States_Places::VERSION,
                true
            );

            wp_localize_script( 'scpwoo-city-select', 'scpwoo_city_select_params', array(
                'ajax_url'                      => admin_url( 'admin-ajax.php' ),
                'nonce'                         => wp_create_nonce( 'scpwoo_front_nonce' ),
                'i18n_select_city_text'         => esc_attr__( 'Select an option&hellip;', 'afriregions-city-neighborhood-for-woocommerce' ),
                'i18n_select_neighborhood_text' => esc_attr__( 'Select an option&hellip;', 'afriregions-city-neighborhood-for-woocommerce' ),
                'supported_countries'           => SCPWOO_States_Places::instance() ? SCPWOO_States_Places::instance()->get_supported_countries() : array(),
                'single_country'               => self::get_single_active_country(),
                'i18n_load_error'              => esc_attr__( 'Could not load options. You can type your address manually.', 'afriregions-city-neighborhood-for-woocommerce' ),
            ) );

            wp_enqueue_style(
                'scpwoo-front-css',
                plugin_dir_url( SCPWOO_PLUGIN_FILE ) . 'css/scpwoo-front.css',
                array(),
                SCPWOO_States_Places::VERSION
            );

            // Remove no-js class when JS is available — enables progressive enhancement
            wp_add_inline_script( 'scpwoo-city-select', 'document.documentElement.classList.remove("no-js");', 'before' );
        }
    }

    /**
     * Returns the single active supported country code, or empty string if multiple.
     * Used to auto-hide the country field in JS after WC initialises the cascade.
     */
    private static function get_single_active_country(): string {
        $plugin = SCPWOO_States_Places::instance();
        if ( ! $plugin || ! function_exists( 'WC' ) || ! WC()->countries ) {
            return '';
        }
        $supported = $plugin->get_supported_countries();
        $sell_to   = get_option( 'woocommerce_allowed_countries', 'all' );

        if ( 'specific' === $sell_to ) {
            $specific = (array) get_option( 'woocommerce_specific_allowed_countries', array() );
            $active   = array_intersect( $supported, array_map( 'strtoupper', $specific ) );
            return 1 === count( $active ) ? (string) reset( $active ) : '';
        }

        $base = $plugin->get_store_country();
        return in_array( $base, $supported, true ) ? $base : '';
    }
}
