<?php

function enqueue_theme_scripts() {
    wp_enqueue_script(
        'modals-js',
        get_template_directory_uri() . '/template-parts/la-components/js/modals.js',
        array('jquery'),
        '2.0.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_theme_scripts');

function modal_system_container() {
    $modals_dir = get_template_directory() . '/template-parts/la-components/modals/';
    $modals = array();

    if (is_dir($modals_dir)) {
        $files = scandir($modals_dir);
        foreach ($files as $file) {
            if (preg_match('/^modal-(.+)\.php$/', $file, $matches)) {
                $modals[] = $matches[1];
            }
        }
    }

    ?>
    <div id="modal-overlay" class="fixed inset-0 bg-[rgba(0,0,0,0.5)] backdrop-blur-sm z-50 flex items-center justify-center p-4 opacity-0 invisible transition-all ">
        <div id="modal-container" class="bg-[#f9f9f9] rounded-[20px] w-full max-h-[90vh] relative transform transition-transform overflow-hidden" style="max-width: 970px;">
            <button id="modal-close" class="absolute top-4 right-4 z-10 w-8 h-8 flex items-center cursor-pointer justify-center rounded-full hover:bg-gray-100 transition-colors text-black outline-none hover:text-gray-700">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
            <div id="modal-content" class="overflow-y-auto max-h-[90vh]"></div>
        </div>
    </div>

    <div id="modal-templates" class="hidden">
        <?php foreach ($modals as $modal_name): ?>
            <div id="modal-template-<?php echo esc_attr($modal_name); ?>" class="modal-template">
                <?php get_template_part('template-parts/la-components/modals/modal', $modal_name); ?>
            </div>
        <?php endforeach; ?>
    </div>
    <?php
}
add_action('wp_footer', 'modal_system_container');
?>