<?php
if (!defined('ABSPATH')) exit;

/**
 * Script-Module-Registrierung (view/editor) + script_module_data_ce-pd-editor-Filter (Icons, XLSX, i18n).
 */

/**
 * Registriert Editor- und Viewer-JS als Script Modules (WP 6.5+).
 * - ce-pd-view: lädt die Frontend-Runtime (Three.js per absolute URLs aus __CE_PD_THREE_IMPORTS__).
 * - ce-pd-editor: lädt die Gutenberg-Edit-Komponente als natives ES-Modul.
 */
add_action('init', function () {
    if (!function_exists('wp_register_script_module')) return;
    wp_register_script_module(
        'ce-pd-view',
        CE_PD_URL . 'blocks/pop3d-diagram/view.js',
        [],
        ce_pd_asset_ver()
    );
    wp_register_script_module(
        'ce-pd-editor',
        CE_PD_URL . 'blocks/pop3d-diagram/edit.js',
        [],
        ce_pd_asset_ver()
    );
});

/** Editor: view-Modul für die Live-Preview + edit-Modul für die Sidebar. (Frontend-Ladung läuft automatisch über viewScriptModule in block.json.) */
add_action('enqueue_block_editor_assets', function () {
    if (!function_exists('wp_enqueue_script_module')) return;
    wp_enqueue_script_module('ce-pd-view');
    wp_enqueue_script_module('ce-pd-editor');
});

/**
 * Script-Module-Data für ce-pd-editor (WP 6.7+ `script_module_data_{$id}`-Filter).
 *
 * Liefert:
 * - icons: Toolbar-Icon-URLs (mit Cache-Busting).
 * - xlsxScriptUrl: SheetJS-URL für den Import-Modal.
 * - i18n: Jed-locale_data für wp.i18n.setLocaleData() — ersetzt wp_set_script_translations,
 *   da es für Script Modules noch kein offizielles Translations-API gibt (Trac #60234).
 *
 * Die i18n-JSON-Dateien liegen unter languages/pop3d-charts-{locale}-3dfcabd35eae28d56d07f0f1657e8177.json.
 * Bei Änderungen an __()-Strings in edit.js: .po anpassen und JSON-Dateien im Repo
 * aktualisieren (siehe .cursor/rules/pop3d-i18n-editor-json.mdc).
 */
add_filter('script_module_data_ce-pd-editor', function ($data) {
    if (!is_array($data)) $data = [];
    $data['icons'] = [
        'legendToggle'    => ce_pd_asset_url('ce-diagram-legend-toggle-icon.svg'),
        'dataTable'       => ce_pd_asset_url('ce-diagram-data-table-icon.svg'),
        'fullscreenEnter' => ce_pd_asset_url('ce-diagram-fullscreen-enter-icon.svg'),
        'fullscreenExit'  => ce_pd_asset_url('ce-diagram-fullscreen-exit-icon.svg'),
        'pngDownload'     => ce_pd_asset_url('ce-diagram-png-download-icon.svg'),
        'projectionTo2d'  => ce_pd_asset_url('ce-diagram-projection-2d-icon.svg'),
        'projectionTo3d'  => ce_pd_asset_url('ce-diagram-projection-3d-icon.svg'),
        'interactionHint' => ce_pd_asset_url('ce-diagram-interaction-hint-icon.svg'),
        'viewerSort'      => ce_pd_asset_url('ce-diagram-viewer-sort-icon.svg'),
        'layouts'         => [
            'straight'  => ce_pd_asset_url('ce-diagram-layout-straight-icon.svg'),
            'stacked'   => ce_pd_asset_url('ce-diagram-layout-stacked-icon.svg'),
            'pie'       => ce_pd_asset_url('ce-diagram-layout-pie-icon.svg'),
            'pieStairs' => ce_pd_asset_url('ce-diagram-layout-pie-stairs-icon.svg'),
            'wave'      => ce_pd_asset_url('ce-diagram-layout-wave-icon.svg'),
            'pyramid'   => ce_pd_asset_url('ce-diagram-layout-pyramid-icon.svg'),
        ],
    ];
    $data['xlsxScriptUrl'] = CE_PD_URL . 'vendor/sheetjs/xlsx.full.min.js?ver=' . ce_pd_asset_ver();

    /* "Theme colors"-Palette: gleiche Quelle/Reihenfolge wie im Frontend (render.php),
     * damit Editor-Preview und Website identische Farben zeigen. */
    $data['themePalette'] = ce_pd_get_theme_palette_hex();

    /** Inserter-/Pattern-Vorschau: Standbilder (Schlüssel = defaultLayout des Blocks). */
    $preview_rel = [
        'straight' => 'pattern-previews/straight.jpg',
        'stacked'  => 'pattern-previews/stacked.jpg',
        'pie'      => 'pattern-previews/donut.jpg',
    ];
    $data['patternPreviews'] = [];
    foreach ($preview_rel as $lid => $rel) {
        $path = CE_PD_DIR . 'assets/' . $rel;
        if (!is_readable($path)) {
            continue;
        }
        $data['patternPreviews'][ $lid ] = ce_pd_asset_url($rel);
    }

    $locale = determine_locale();
    $hash = md5('blocks/pop3d-diagram/edit.js');
    $json_file = CE_PD_DIR . "languages/pop3d-charts-{$locale}-{$hash}.json";
    if (is_readable($json_file)) {
        $raw = file_get_contents($json_file);
        $translations = $raw !== false ? json_decode($raw, true) : null;
        if (is_array($translations) && isset($translations['locale_data']['messages'])) {
            $data['i18n'] = $translations['locale_data']['messages'];
        }
    }
    return $data;
});
