<?php
/**
 * TAB: MAPS — Map Engine Selector
 *
 * @package ParcelSelector
 * @since   3.1.6
 */

if ( ! defined( 'ABSPATH' ) ) exit;

if ( ! function_exists( 'parcselect_tab_maps' ) ) {
function parcselect_tab_maps() {
    $t        = parcselect_admin_i18n();
    $engine   = get_option( 'parcselect_map_engine', 'classic' );
    $flag_url = PARCSELECT_PLUGIN_URL . 'assets/flags/20x15/';
    ?>

    <!-- ══════════ PICKUP POINTS — INPOST / POLAND ══════════ -->
    <div class="parcelselector-section">
        <h2><?php echo esc_html__( 'Pickup points', 'parcel-selector' ); ?></h2>
        <p class="description"><?php echo esc_html__( 'The free version shows InPost Paczkomaty pickup points in Poland on the checkout map.', 'parcel-selector' ); ?></p>
    </div>

    <div class="parcelselector-card" style="border-left:4px solid #22c55e;background:#f0fdf4;margin-bottom:24px;padding:16px 20px;">
        <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
            <img src="<?php echo esc_url( $flag_url . 'pl.png' ); ?>" width="40" height="30" alt="PL" style="border:1px solid #e5e7eb;border-radius:4px;flex-shrink:0;">
            <div>
                <h4 style="margin:0 0 4px;font-size:14px;font-weight:700;color:#166534;">
                    <?php echo esc_html__( 'InPost Paczkomaty — Poland', 'parcel-selector' ); ?>
                </h4>
                <p style="margin:0;font-size:13px;color:#15803d;line-height:1.5;">
                    <?php echo esc_html__( 'Domestic delivery within Poland. No special configuration needed.', 'parcel-selector' ); ?>
                </p>
            </div>
            <span style="margin-left:auto;font-size:11px;color:#22c55e;font-weight:700;background:#fff;padding:4px 10px;border-radius:6px;">&#x2713; <?php echo esc_html__( 'Active', 'parcel-selector' ); ?></span>
        </div>
    </div>

    <hr style="margin:32px 0; border:none; border-top:1px solid var(--ps-border);">

    <!-- ═══════════════ MAP ENGINE SELECTOR ═══════════════ -->
    <div class="parcelselector-section">
        <h2>🗺️ <?php echo esc_html( $t['map_engine_title'] ); ?></h2>
        <p class="description"><?php echo esc_html( $t['map_engine_desc'] ); ?></p>
    </div>

    <form method="post" action="options.php" id="ps-engine-form">
        <input type="hidden" name="ps_save_group" value="parcselect_settings_group">
        <?php settings_fields( 'parcselect_settings_group' ); ?>
        <input type="hidden" name="ps_map_engine" id="ps_map_engine_input" value="<?php echo esc_attr( $engine ); ?>">

        <div class="ps-engine-toggle">

            <!-- ANUNAKI -->
            <div class="ps-engine-card <?php echo $engine === 'anunaki' ? 'ps-engine-active' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static CSS class. ?>"
                 data-engine="anunaki" onclick="parcselectSelectEngine('anunaki')">
                <div class="ps-engine-logo">
                    <svg width="48" height="48" viewBox="0 0 38 38" fill="none">
                        <circle cx="19" cy="19" r="19" fill="<?php echo esc_attr( $engine === 'anunaki' ? 'var(--ps-primary)' : 'var(--ps-border)' ); ?>"/>
                        <path d="M10 27 L19 11 L28 27 Z" fill="#fff" stroke="none"/>
                        <circle cx="19" cy="20" r="3" fill="rgba(255,255,255,0.5)"/>
                    </svg>
                </div>
                <div class="ps-engine-info">
                    <div class="ps-engine-name">ANUNAKI</div>
                    <div class="ps-engine-desc"><?php echo esc_html__( 'Live data from carriers. Always up to date.', 'parcel-selector' ); ?></div>
                    <button type="button" class="ps-play-btn" onclick="event.stopPropagation(); parcselectMapPreview('anunaki')">
                        <span>▶️</span> <?php echo esc_html( $t['map_preview'] ); ?>
                    </button>
                </div>
                <div class="ps-engine-badge <?php echo $engine === 'anunaki' ? 'ps-engine-badge-active' : 'ps-engine-badge-inactive'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static CSS class. ?>">
                    <?php echo $engine === 'anunaki' ? '&#x2713; ' . esc_html( $t['map_active'] ) : esc_html( $t['map_select'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML entity + esc_html() values. ?>
                </div>
            </div>

            <!-- CLASSIC (JSON) -->
            <div class="ps-engine-card <?php echo $engine === 'classic' ? 'ps-engine-active' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static CSS class. ?>"
                 data-engine="classic" onclick="parcselectSelectEngine('classic')">
                <div class="ps-engine-logo">
                    <svg width="48" height="48" viewBox="0 0 38 38" fill="none">
                        <circle cx="19" cy="19" r="19" fill="<?php echo esc_attr( $engine === 'classic' ? 'var(--ps-primary)' : 'var(--ps-border)' ); ?>"/>
                        <rect x="10" y="12" width="18" height="14" rx="2" fill="#fff"/>
                        <circle cx="19" cy="19" r="3" fill="rgba(255,255,255,0.5)"/>
                    </svg>
                </div>
                <div class="ps-engine-info">
                    <div class="ps-engine-name">CLASSIC</div>
                    <div class="ps-engine-desc"><?php echo esc_html__( 'Lightweight map UI. Pickup points loaded from the ParcelSelector.com server.', 'parcel-selector' ); ?></div>
                    <button type="button" class="ps-play-btn" onclick="event.stopPropagation(); parcselectMapPreview('classic')">
                        <span>▶️</span> <?php echo esc_html( $t['map_preview_classic'] ); ?>
                    </button>
                </div>
                <div class="ps-engine-badge <?php echo $engine === 'classic' ? 'ps-engine-badge-active' : 'ps-engine-badge-inactive'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static CSS class. ?>">
                    <?php echo $engine === 'classic' ? '&#x2713; ' . esc_html( $t['map_active'] ) : esc_html( $t['map_select'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML entity + esc_html() values. ?>
                </div>
            </div>

        </div><!-- .ps-engine-toggle -->

        <p style="margin-top:24px;">
            <?php submit_button( $t['map_save_engine'], 'parcelselector-btn parcelselector-btn-primary', 'submit_engine', false ); ?>
            <span style="margin-left:16px; color:var(--ps-text-dim); font-size:14px;"><?php echo esc_html( $t['map_active'] ); ?>: <strong style="color:var(--ps-primary);"><?php echo esc_html( strtoupper( $engine ) ); ?></strong></span>
        </p>
    </form>

    <!-- MAP SCRIPTS — oba silniki (do przycisku PLAY) -->
    <?php
    // Admin preview fetches points through the same-origin admin-ajax proxy as the
    // front end (avoids a cross-origin/CORS fetch straight to the VPS API).
    $_ps_api = admin_url( 'admin-ajax.php' ) . '?action=parcselect_get_points&nonce=' . wp_create_nonce( 'parcselect_points_public' ) . '&country=';

    // ── Styles ──
    wp_enqueue_style( 'parcselect-leaflet-css', PARCSELECT_PLUGIN_URL . 'assets/vendor/leaflet/leaflet.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-markercluster-css', PARCSELECT_PLUGIN_URL . 'assets/vendor/markercluster/MarkerCluster.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-markercluster-default-css', PARCSELECT_PLUGIN_URL . 'assets/vendor/markercluster/MarkerCluster.Default.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-classic-intro-css', PARCSELECT_PLUGIN_URL . 'map/classic/css/intro-popup.css', array(), PARCSELECT_VERSION );
    wp_enqueue_style( 'parcselect-anunaki-popup-css', PARCSELECT_PLUGIN_URL . 'map/anunaki/css/anunaki-popup.css', array(), PARCSELECT_VERSION );

    // ── Vendor scripts ──
    wp_enqueue_script( 'parcselect-leaflet', PARCSELECT_PLUGIN_URL . 'assets/vendor/leaflet/leaflet.js', array(), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-markercluster', PARCSELECT_PLUGIN_URL . 'assets/vendor/markercluster/leaflet.markercluster.js', array( 'parcselect-leaflet' ), PARCSELECT_VERSION, true );

    // ── Config inline script (after markercluster) ──
    wp_add_inline_script( 'parcselect-markercluster', 'window.inpostPopupConfig = { initialPointsLimit: 1000, lazyLoadOnZoom: true, viewportCulling: false };
    window.parcselectCacheConfig = { enabled: false, baseUrl: ' . wp_json_encode( wp_upload_dir()['baseurl'] . '/inpost-cache/' ) . ', epicZoomEnabled: true,
        countryModes: { pl:"api" } };' );

    // ── Mobile detect + search libs ──
    wp_enqueue_script( 'parcselect-mobile-detect', PARCSELECT_PLUGIN_URL . 'map/Mobilki/ps-mobile-detect.js', array(), PARCSELECT_VERSION, true );
    // flexsearch.bundle.js intentionally NOT loaded: no script references the FlexSearch
    // global (search-engine.js is a self-contained IIFE) and the shipped vendor bundle has
    // a syntax error — loading it only emitted a console SyntaxError with no functional use.
    wp_enqueue_script( 'parcselect-classic-search', PARCSELECT_PLUGIN_URL . 'map/classic/js/search-engine.js', array(), PARCSELECT_VERSION, true );
    // CLASSIC countries — defines window.IPS_COUNTRIES and (via parcselectClassicConfig)
    // routes each country's point API through the same-origin admin-ajax proxy, exactly
    // like the front end. Without this the preview falls back to embedded country URLs
    // pointing straight at the VPS API → cross-origin fetch blocked by CORS.
    wp_enqueue_script( 'parcselect-classic-countries', PARCSELECT_PLUGIN_URL . 'map/classic/js/countries.js', array(), PARCSELECT_VERSION, true );
    wp_localize_script( 'parcselect-classic-countries', 'parcselectClassicConfig', array( 'apiBase' => $_ps_api ) );
    wp_enqueue_script( 'parcselect-classic-intro', PARCSELECT_PLUGIN_URL . 'map/classic/js/intro-popup.js', array( 'parcselect-leaflet', 'parcselect-markercluster', 'parcselect-classic-countries' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-classic-selector', PARCSELECT_PLUGIN_URL . 'map/classic/js/parcel-locker-selector.js', array( 'parcselect-classic-intro' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-fuse', PARCSELECT_PLUGIN_URL . 'assets/vendor/fuse/fuse.min.js', array(), PARCSELECT_VERSION, true );

    // ── ANUNAKI engine ──
    wp_enqueue_script( 'parcselect-anunaki-countries', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-countries.js', array(), PARCSELECT_VERSION, true );
    wp_localize_script( 'parcselect-anunaki-countries', 'parcselectAnunakiConfig', array(
        'flagBaseW20' => PARCSELECT_PLUGIN_URL . 'assets/flags/20x15/',
        'flagBaseW40' => PARCSELECT_PLUGIN_URL . 'assets/flags/w40/',
        'mascotUrl'   => PARCSELECT_PLUGIN_URL . 'assets/images/Parcel_Selector_Com.jpg',
    ) );
    wp_add_inline_script( 'parcselect-anunaki-countries', '(function(){ var c=window.ANUNAKI_COUNTRIES||{}; var b=' . wp_json_encode( $_ps_api ) . '; Object.keys(c).forEach(function(cc){c[cc].api=b+cc;}); })();' );
    wp_enqueue_script( 'parcselect-anunaki-translations', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-translations.js', array( 'parcselect-anunaki-countries' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-anunaki-search', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-search.js', array( 'parcselect-anunaki-translations' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-anunaki-cluster-rules', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-cluster-rules.js', array( 'parcselect-anunaki-search' ), PARCSELECT_VERSION, true );
    wp_enqueue_script( 'parcselect-anunaki-popup', PARCSELECT_PLUGIN_URL . 'map/anunaki/js/anunaki-popup.js', array( 'parcselect-anunaki-cluster-rules', 'parcselect-leaflet', 'parcselect-markercluster' ), PARCSELECT_VERSION, true );
    // ── Map preview function ──
    wp_add_inline_script( 'parcselect-anunaki-popup', 'window.parcselectEngineANUNAKI = window.AnunakiPopup || null;
    window.parcselectMapPreview = function(type) {
        var eng;
        if (type === "anunaki") { eng = window.parcselectEngineANUNAKI || window.AnunakiPopup; }
        if (eng && typeof eng.open === "function") { eng.open("pl"); }
        else if (type === "classic") { document.dispatchEvent(new CustomEvent("inpost-open-map", { detail: { country: "pl" } })); }
        else { console.error("[PS] Engine not loaded for type: " + type); }
    };' );
    ?>

    <!-- Cross-tab navigation -->
    <div style="margin-top:32px;padding:16px 20px;background:#f5f3ff;border:1px solid #e9d5ff;border-radius:10px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
        <span style="font-size:13px;color:#6b21a8;font-weight:600;">
            <?php echo esc_html__( 'Next step: review your carrier settings', 'parcel-selector' ); ?>
        </span>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=parcelselector-settings&tab=carriers' ) ); ?>"
           style="display:inline-flex;align-items:center;gap:6px;padding:8px 20px;background:#7c3aed;color:#fff;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;">
            <?php echo esc_html__( 'Carriers', 'parcel-selector' ); ?> &rarr;
        </a>
    </div>
    <?php
}
}
