(function ($) {
    "use strict";

    const initTimezoneClock = ($scope) => {
        const wrapper = $scope.find('.sifency-clock-wrapper')[0];
        if (!wrapper) return;

        const clockItems = wrapper.querySelectorAll('.sifency-clock-item');
        if (clockItems.length === 0) return;

        const is12Hr = wrapper.dataset['12hr'] === 'true';
        const showSec = wrapper.dataset.sec === 'true';

        // Function to format numbers with leading zero (e.g., 9 -> 09)
        const padZero = (num) => (num < 10 ? '0' + num : num);

        const updateClocks = () => {
            const now = new Date();

            clockItems.forEach((item) => {
                const tz = item.dataset.tz;
                if (!tz) return;

                try {
                    // Use Intl.DateTimeFormat to get the exact time in the requested timezone
                    const formatter = new Intl.DateTimeFormat('en-US', {
                        timeZone: tz,
                        hour12: is12Hr,
                        hour: 'numeric',
                        minute: '2-digit',
                        second: showSec ? '2-digit' : undefined,
                    });

                    // Format: "10:30:45 AM" or "22:30:45"
                    const parts = formatter.formatToParts(now);

                    let h = '00', m = '00', s = '00', ampm = '';

                    // Extract values from Intl parts
                    parts.forEach(part => {
                        if (part.type === 'hour') h = padZero(parseInt(part.value));
                        if (part.type === 'minute') m = part.value;
                        if (part.type === 'second') s = part.value;
                        if (part.type === 'dayPeriod') ampm = part.value;
                    });

                    // Update DOM elements efficiently
                    item.querySelector('.sifency-c-hour').textContent = h;
                    item.querySelector('.sifency-c-min').textContent = m;
                    
                    if (showSec) {
                        item.querySelector('.sifency-c-sec').textContent = s;
                    }
                    if (is12Hr && ampm) {
                        item.querySelector('.sifency-c-ampm').textContent = ampm.toUpperCase();
                    }

                } catch (error) {
                    console.error(`Sifency Clock Error: Invalid Timezone ID "${tz}"`);
                    item.querySelector('.sifency-clock-time').textContent = "Invalid TZ";
                }
            });
        };

        // Run immediately to avoid 1-second delay
        updateClocks();

        // Update every second
        // Save interval to wrapper to clear it if Elementor re-renders the widget
        if (wrapper.clockInterval) clearInterval(wrapper.clockInterval);
        wrapper.clockInterval = setInterval(updateClocks, 1000);
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-timezone-clock.default',
            initTimezoneClock
        );
    });

})(jQuery);