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

// Widget controller
function renesse_widget_plugin_add_widget() {
    // Fetch saved events and activities
    $events = get_option('renesse_widget_events', []);
    $activities = get_option('renesse_widget_activities', []);

    // Colors array for cycling through colors
    $colors = ['renesse-yellow', 'renesse-green', 'renesse-blue'];

    // Decide widget position, default to left
    $position = get_option('renesse_widget_plugin_position', 'left'); 
    $position_class = $position === 'right' ? 'widget-right' : 'widget-left';

    // Convert PHP data to JSON for JavaScript
    $events_json = json_encode($events);
    $activities_json = json_encode($activities);
    $colors_json = json_encode($colors);

    // Generate event carousel HTML in PHP (before JavaScript)
    $event_html = '';
    if (!empty($events)) {
        foreach ($events as $index => $event) {
            $active_class = $index === 0 ? ' active' : '';
            $color_class = $colors[$index % count($colors)];
            $event_content = wp_trim_words(wp_strip_all_tags($event['content']), 12, '...');
            
            $event_html .= 
            '<div class="carousel-item' . esc_html($active_class) . '">
                <div class="card">
                    <div class="date-overlay">
                        <span class="date-text">
                            <h3 class="text-white pb-0">' . esc_attr(date_i18n('M', strtotime($event['date']))) . '</h3>' 
                            . esc_attr(date_i18n('d', strtotime($event['date']))) . '
                        </span>
                    </div>
                    <img src="' . (esc_url($event['thumbnail']) ? esc_url($event['thumbnail']) : 'https://placehold.co/248x150?text=Renesse+Aan+Zee') . '" 
                        class="card-img-top img-fluid" 
                        alt="' . esc_attr($event['title']) . '">
                    <div class="card-body ' . esc_attr($color_class) . '">
                        <h2 class="card-title text-white mt-1 mb-0" style"color:#fff;">' . esc_html($event['title']) . '</h2>
                        <p class="card-text text-white mb-2" style"color:#fff;">' . esc_html($event_content) . '</p>
                        <a target="_blank" href="' . esc_url($event['url']) . '" class="btn btn-primary widget-button">Bekijk activiteit</a>
                    </div>
                </div>
            </div>';
        }
    } else {
        $event_html = '<div class="carousel-item active"><p class="m-2">Geen evenementen beschikbaar.</p></div>';
    }

    // Generate activities carousel HTML in PHP
    $activity_html = '';
    if (!empty($activities)) {
        foreach ($activities as $index => $activity) {
            $active_class = $index === 0 ? ' active' : '';
            $color_class = $colors[$index % count($colors)];
            $activity_content = wp_trim_words(wp_strip_all_tags($activity['content']), 12, '...');
            
            $activity_html .= 
            '<div class="carousel-item' . esc_html($active_class) . '">
                <div class="card">
                    <div class="date-overlay">
                        <span class="date-text">
                            <h3 class="text-white pb-0">' . esc_attr(date_i18n('M', strtotime($activity['date']))) . '</h3>' 
                            . esc_attr(date_i18n('d', strtotime($activity['date']))) . '
                        </span>
                    </div>
                    <img src="' . (esc_url($activity['thumbnail']) ? esc_url($activity['thumbnail']) : 'https://placehold.co/248x150?text=Renesse+Aan+Zee') . '" 
                        class="card-img-top img-fluid" 
                        alt="' . esc_attr($activity['title']) . '">
                    <div class="card-body ' . esc_attr($color_class) . '">
                        <h2 class="card-title text-white mt-1 mb-0" style"color: #fff;">' . esc_html($activity['title']) . '</h2>
                        <p class="card-text text-white mb-2" style"color: #fff;">' . esc_html($activity_content) . '</p>
                        <a target="_blank" href="' . esc_url($activity['url']) . '" class="btn btn-primary widget-button">Bekijk activiteit</a>
                    </div>
                </div>
            </div>';
        }
    } else {
        $activity_html = '<div class="carousel-item active"><p class="m-2">Geen activiteiten beschikbaar.</p></div>';
    }

    // Escape the PHP-generated HTML for safe JavaScript insertion
    $event_html = addslashes($event_html);
    $activity_html = addslashes($activity_html);

    echo '<div id="renesse-widget-container"></div>';

    echo "<script>
    document.addEventListener('DOMContentLoaded', function () {
        let widgetContainer = document.getElementById('renesse-widget-container');

        if (!widgetContainer) return;

        // Create a Shadow DOM
        let shadow = widgetContainer.attachShadow({ mode: 'open' });

        // Load Bootstrap 5 CSS inside Shadow DOM
        let bootstrapCSS = document.createElement('link');
        bootstrapCSS.rel = 'stylesheet';
        bootstrapCSS.href = 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css';

        // Load Bootstrap 5 JavaScript inside Shadow DOM
        let bootstrapJS = document.createElement('script');
        bootstrapJS.src = 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js';
        bootstrapJS.defer = true;

        // Load jQuery inside Shadow DOM
        let jQueryScript = document.createElement('script');
        jQueryScript.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
        jQueryScript.defer = true;

        // Custom Styles for Widget
        let widgetStyles = document.createElement('style');
        widgetStyles.textContent = `
            h2 {
                font-size: 22px;
            }
            h3 {
                font-size: 18px;
            }
            p {
                font-size: 16px;
            }
            .widget-left {
                bottom: 20px!important;
                left: 15px!important;
                position: fixed!important;
                z-index: 1000!important;
                text-align: left!important;
            }
            .widget-right {
                bottom: 20px!important;
                right: 15px!important;
                position: fixed!important;
                z-index: 1000!important;
                text-align: right!important;
            }
            #renesse-button {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background: url('/wp-content/plugins/renesse-aan-zee/assets/img/renesse-aan-zee-plugin-icon.png') no-repeat center center;
                background-size: cover;
                color: #fff;
                border: none;
                font-size: 24px!important;
                cursor: pointer;
                transition: all .3s ease-out;
                line-height: 50px;
                padding: 0;

                &:hover {
                    scale: 1.1;
                }
            }
            .btn:hover, .btn:active {
                background-color: #ec671a !important;
                color: #fff !important;
                border-color: #ec671a !important;
                transform: scale(1.05)!important;
            }
            #widget-content {
                display: none; 
                margin-bottom: 10px;
                padding: 10px;
                background-color: #fff;
                border: 1px solid #ccc;
                border-radius: 10px;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                width: 300px;
                position: relative;
                text-align: left!important;
            }
                #widget-buttons {
                display: none; 
                margin-bottom: 10px;
                border-radius: 5px;
                width: 300px;
                position: relative;
            }

            .widget-button {
                margin-bottom: 10px;
                margin-left: 5px;
                padding: 10px;
                background-color: #fff;
                border: none;
                border-radius: 10px;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                width: auto;
                position: relative;
                color: #fff;
                background-color: #ec671a;
                cursor: pointer;
                font-size: 14px!important;
                transition: all .3s ease-out;
                font-family: 'Open Sans', system-ui, -apple-system,'Helvetica Neue', sans-serif;
                text-decoration: none;

                &:hover {
                    scale: 1.1!important;
                }
            }
            #renesse-button.active {
                background-color: #ec671a;
                background-image: none;
                color: #fff;
            }
            #widget-container {
                position: fixed;
                bottom: 20px;
                //left: 15px;
                z-index: 1000;
                text-align: left;
            }
            .container-fluid, .row, .col, .carousel {
                all: initial;
                font-family: inherit;
            }
            .renesse-yellow { background-color: #fbba00; }
            .renesse-blue { background-color: #158db4; }
            .renesse-green { background-color: #199975; }
            .widget-button {
                padding: 10px;
                background-color: #ec671a;
                color: white;
                border: none;
                border-radius: 10px;
                cursor: pointer;
                font-size: 14px !important;
                transition: all .3s ease-out;
                text-decoration: none;
            }
            .widget-button:hover { scale: 1.1 !important; background-color: #ea580c; }
            .card {
                margin: 10px 0;
                border-radius: 10px;
                height: 100%;

                .card-img-top {
                    max-height: 150px;
                    border-top-left-radius: 10px;
                    border-top-right-radius: 10px;
                    border-bottom: none;
                }

                .card-body {
                    flex-grow: 1;
                    border-bottom-left-radius: 10px;
                    border-bottom-right-radius: 10px;

                    a {
                        margin-left: 0!important;
                    }
                }
            }

            .date-overlay {
                position: absolute;
                top: 0;
                left: 0;
                background-color: black;
                color: white;
                padding: 5px;
                font-size: 14px;
                text-align: center;
                width: 60px;
                height: 60px;
                display: flex;
                align-items: center;
                justify-content: center;
                line-height: 1.2;
                border-top-left-radius: 10px;
                border-bottom-right-radius: 10px;
            }
            .carousel-inner {
                margin: 0 auto;
                width: 90%;
                img {
                    width: 100%;
                }            
            }
            .carousel-control-prev, .carousel-control-next {
                width: 5%; 
                height: 85%;
                top: 15%;
            }
            .carousel-control-prev-icon {
                background-color: #ec671a;
                border-top-right-radius: 5px;
                border-bottom-right-radius: 5px;
            } 
            .carousel-control-next-icon {
                background-color: #ec671a;
                border-top-left-radius: 5px;
                border-bottom-left-radius: 5px;
            }

            .close-events {
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                transition: all 0.3s ease;
                padding: 0.5rem;
            }
            .close-events:hover {
                background-color:rgba(0, 0, 0, 0.10);
                border-radius: 20%;
                transform: scale(1.3);
            }
            .close-events svg {
                display: block;
            }


            .widget-hidden { display: none; }
        `;

        // Convert PHP variables into JavaScript
        let events = $events_json;
        let activities = $activities_json;
        let colors = $colors_json;

        // Widget HTML (same structure as requested)
        let widgetHTML = `
            <div id='widget-container' class='$position_class'>
                <div id='widget-content' style='display: none;'>
                    <p class='widget-text mb-0' style='font-size:14px'>Welkom in Renesse Aan Zee, bekijk de actuele evenementen en activiteiten.</p>
                    <div id='events-content' class='widget-hidden'>
                        <div class='container-fluid'>
                            <div class='d-flex align-content-center flex-wrap'>
                                <div class='p-2 flex-grow-1'><h2 class='my-0'>Evenementen</h2></div>
                                <div class='p-2 close-events'>
                                    <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">
                                        <path d=\"M18 6L6 18M6 6L18 18\" stroke=\"#000000\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>
                                    </svg>
                                </div>
                            </div>
                        </div>
                        <div id='events-carousel' class='carousel slide' data-bs-ride='carousel' data-bs-interval='3000'>
                            <div class='carousel-inner'>$event_html</div>
                            <button class='carousel-control-prev bg-white' type='button' data-bs-target='#events-carousel' data-bs-slide='prev'>
                                <span class='carousel-control-prev-icon' aria-hidden='true'></span>
                                <span class='visually-hidden'>Previous</span>
                            </button>
                            <button class='carousel-control-next bg-white' type='button' data-bs-target='#events-carousel' data-bs-slide='next'>
                                <span class='carousel-control-next-icon' aria-hidden='true'></span>
                                <span class='visually-hidden'>Next</span>
                            </button>
                        </div>
                    </div>
                    <div id='activities-content' class='widget-hidden'>
                        <div class='container-fluid'>
                            <div class='d-flex align-content-center flex-wrap'>
                                <div class='p-2 flex-grow-1'><h2 class='my-0'>Activiteiten</h2></div>
                                <div class='p-2 close-events'>
                                    <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">
                                        <path d=\"M18 6L6 18M6 6L18 18\" stroke=\"#000000\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>
                                    </svg>
                                </div>
                            </div>
                        </div>
                        <div id='activities-carousel' class='carousel slide' data-bs-ride='carousel' data-bs-interval='3000'>
                            <div class='carousel-inner'>$activity_html</div>
                            <button class='carousel-control-prev bg-white' type='button' data-bs-target='#activities-carousel' data-bs-slide='prev'>
                                <span class='carousel-control-prev-icon' aria-hidden='true'></span>
                                <span class='visually-hidden'>Previous</span>
                            </button>
                            <button class='carousel-control-next bg-white' type='button' data-bs-target='#activities-carousel' data-bs-slide='next'>
                                <span class='carousel-control-next-icon' aria-hidden='true'></span>
                                <span class='visually-hidden'>Next</span>
                            </button>
                        </div>
                    </div>
                </div>
                <div id='widget-buttons'>
                    <button id='show-events-button' class='widget-button'>" . esc_attr(__('Evenementen', 'renesse-aan-zee')) . "</button>
                    <button id='show-activities-button' class='widget-button'> " . esc_attr(__('Activiteiten', 'renesse-aan-zee')) . "</button>
                    <a target='_blank' href='https://renesseaanzee.nl/'><button class='widget-button'>" . esc_attr(__('Renesse Aan Zee', 'renesse-aan-zee')) . "</button></a>
                </div>
                <button id='renesse-button' class='inactive'></button>
            </div>
        `;

        // Append Everything
        shadow.appendChild(bootstrapCSS);
        shadow.appendChild(widgetStyles);
        let widgetDiv = document.createElement('div');
        widgetDiv.innerHTML = widgetHTML;
        shadow.appendChild(widgetDiv);
        shadow.appendChild(bootstrapJS);
        shadow.appendChild(jQueryScript);

        // jQuery Code inside Shadow DOM
        jQueryScript.onload = function () {
            let script = document.createElement('script');
            script.textContent = `
                jQuery(document).ready(function($) {
                    let shadow = document.querySelector('#renesse-widget-container').shadowRoot;

                    $(shadow).find('#renesse-button').click(function() {
                        $(shadow).find('#widget-content').slideToggle();
                        $(shadow).find('#widget-buttons').slideToggle();

                        if ($(this).hasClass('active')) {
                            $(this).removeClass('active').text('').css({
                                'background': 'url(\"/wp-content/plugins/renesse-aan-zee/assets/img/renesse-aan-zee-plugin-icon.png\") no-repeat center center',
                                'background-size': 'cover'
                            });
                        } else {
                            $(this).addClass('active')
                            .html('<div class=\"svg-wrapper\"><svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M18 6L6 18M6 6L18 18\" stroke=\"white\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></div>')
                            .css({
                                'background-color': '#ec671a',
                                'background-image': 'none',
                                'position': 'relative'
                            })
                            .find('.svg-wrapper').css({
                                'display': 'flex',
                                'justify-content': 'center',
                                'align-items': 'center',
                                'height': '100%',
                                'width': '100%'
                            });
                        }
                    });

                    // Show events
                    $(shadow).find('#show-events-button').click(function() {
                        $(shadow).find('#events-content').slideDown();
                        $(shadow).find('#activities-content').slideUp();
                        $(shadow).find('.widget-text').hide();
                    });

                    // Hide events
                    $(shadow).find('.close-events').click(function() {
                        $(shadow).find('#events-content').slideUp();
                        $(shadow).find('#activities-content').slideUp();
                        $(shadow).find('.widget-text').show();
                    });

                    // Show activities
                    $(shadow).find('#show-activities-button').click(function() {
                        $(shadow).find('#events-content').slideUp();
                        $(shadow).find('#activities-content').slideDown();
                        $(shadow).find('.widget-text').hide();
                    });

                    // Hide activities
                    $(shadow).find('.close-activities').click(function() {
                        $(shadow).find('#events-content').slideUp();
                        $(shadow).find('#activities-content').slideUp();
                        $(shadow).find('.widget-text').show();
                    });

                    function waitForBootstrap(callback) {
                        if (typeof bootstrap !== 'undefined') {
                            callback();
                        } else {
                            setTimeout(() => waitForBootstrap(callback), 100);
                        }
                    }

                    waitForBootstrap(() => {
                        // Events Carousel
                        let eventsCarouselElement = $(shadow).find('#events-carousel');
                        if (eventsCarouselElement.length > 0) {
                            let eventsCarousel = new bootstrap.Carousel(eventsCarouselElement[0], {
                                ride: 'carousel',
                                pause: false
                            });
                            $(shadow).find('#events-carousel .carousel-control-prev').click(function() {
                                eventsCarousel.prev();
                            });
                            $(shadow).find('#events-carousel .carousel-control-next').click(function() {
                                eventsCarousel.next();
                            });
                        }

                        // Activities Carousel
                        let activitiesCarouselElement = $(shadow).find('#activities-carousel');
                        if (activitiesCarouselElement.length > 0) {
                            let activitiesCarousel = new bootstrap.Carousel(activitiesCarouselElement[0], {
                                ride: 'carousel',
                                pause: false
                            });
                            $(shadow).find('#activities-carousel .carousel-control-prev').click(function() {
                                activitiesCarousel.prev();
                            });
                            $(shadow).find('#activities-carousel .carousel-control-next').click(function() {
                                activitiesCarousel.next();
                            });
                        }
                    });

                });
            `;
            shadow.appendChild(script);
        };
    });
    </script>";
}
add_action('wp_footer', 'renesse_widget_plugin_add_widget');