(function($) {
    'use strict';

    // -- Shared notify-method popup ------------------------------------------
    // Square-style choice, asked fresh each time an admin action might reach the
    // customer: "Don't notify / Email / Text message / Email & Text". Text-message
    // options are hidden automatically when Twilio SMS isn't configured.
    // Usage: yatoonPromptNotifyMethod({title, message}, function(method){ ... });
    // `method` is one of 'none' | 'email' | 'sms' | 'both'. The callback is never
    // invoked if the admin dismisses the popup (Cancel / click-away) - callers
    // should treat that as "don't proceed with the action at all".
    window.yatoonPromptNotifyMethod = function(options, callback) {
        options = options || {};
        var title      = options.title || 'Notify the customer?';
        var message    = options.message || '';
        var smsEnabled = !!(window.sbsAdmin && sbsAdmin.sms_enabled);

        $('#yatoon-notify-method-modal').remove();

        var buttons = '';
        buttons += '<button type="button" class="button yatoon-notify-btn" data-method="none">Don&rsquo;t notify</button>';
        buttons += '<button type="button" class="button button-primary yatoon-notify-btn" data-method="email">Email</button>';
        if (smsEnabled) {
            buttons += '<button type="button" class="button button-primary yatoon-notify-btn" data-method="sms">Text message</button>';
            buttons += '<button type="button" class="button button-primary yatoon-notify-btn" data-method="both">Email &amp; Text</button>';
        }

        var html = '<div id="yatoon-notify-method-modal" style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:100000;display:flex;align-items:center;justify-content:center;padding:20px;">' +
            '<div style="background:#fff;border-radius:10px;max-width:360px;width:100%;box-shadow:0 12px 30px rgba(0,0,0,.25);padding:24px;">' +
            '<h3 style="margin:0 0 8px;font-size:17px;">' + title + '</h3>' +
            (message ? '<p style="margin:0 0 16px;color:#555;font-size:13px;">' + message + '</p>' : '') +
            '<div style="display:flex;flex-direction:column;gap:8px;margin-top:10px;">' + buttons + '</div>' +
            '<div style="text-align:right;margin-top:16px;">' +
            '<button type="button" class="button" id="yatoon-notify-cancel">Cancel</button>' +
            '</div></div></div>';

        var $modal = $(html);
        $('body').append($modal);

        $modal.on('click', function(e) { if (e.target === this) { $modal.remove(); } });
        $modal.find('#yatoon-notify-cancel').on('click', function() { $modal.remove(); });
        $modal.find('.yatoon-notify-btn').on('click', function() {
            var method = $(this).data('method');
            $modal.remove();
            callback(method);
        });
    };

    $(document).ready(function() {
        
        // Test Connection
        $('#sbs-test-connection').on('click', function() {
            const $button = $(this);
            const $status = $('#sbs-connection-status');
            
            // Check if token is entered
            const token = $('#yatoon_square_access_token').val();
            if (!token || token.trim() === '') {
                $status.removeClass('loading success').addClass('error').html('No Please enter an Access Token first!');
                return;
            }
            
            // Check if location ID is entered
            const locationId = $('#yatoon_square_location_id').val();
            if (!locationId || locationId.trim() === '') {
                $status.removeClass('loading success').addClass('error').html('No Please enter a Location ID first!');
                return;
            }
            
            // Warn if settings might not be saved
            if ($('#yatoon_square_access_token').is(':visible') && !$('#yatoon_square_access_token').prop('readonly')) {
                const confirmTest = confirm('Have you saved your settings? Click OK to test, or Cancel to save settings first.');
                if (!confirmTest) {
                    return;
                }
            }
            
            $button.prop('disabled', true).text('Testing...');
            $status.removeClass('success error').addClass('loading').html('<span class="sbs-spinner"></span> Testing connection...');
            
            $.ajax({
                url: sbsAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'yatoon_test_connection',
                    nonce: sbsAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        let message = 'Yes ' + response.data.message;
                        if (response.data.locations && response.data.locations.length > 0) {
                            message += '<br><small>Locations found: ';
                            response.data.locations.forEach(function(loc, index) {
                                if (index > 0) message += ', ';
                                message += loc.name + ' (' + loc.id + ')';
                            });
                            message += '</small>';
                        }
                        $status.removeClass('loading error').addClass('success').html(message);
                    } else {
                        let errorMsg = 'No ' + response.data.message;
                        if (response.data.details) {
                            errorMsg += '<br><small>Error code: ' + response.data.details + '</small>';
                        }
                        $status.removeClass('loading success').addClass('error').html(errorMsg);
                    }
                },
                error: function(xhr, status, error) {
                    let errorMsg = 'No Connection test failed';
                    if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        errorMsg = 'No ' + xhr.responseJSON.data.message;
                    }
                    $status.removeClass('loading success').addClass('error').html(errorMsg + '<br><small>Network error: ' + error + '</small>');
                },
                complete: function() {
                    $button.prop('disabled', false).text('Test Connection');
                }
            });
        });
        
        // Sync Now
        $('#sbs-sync-now, #sbs-sync-services, #sbs-sync-staff').on('click', function() {
            const $button = $(this);
            const $status = $('#sbs-sync-status');
            const $icon   = $button.find('#sbs-sync-icon');
            const $label  = $button.find('#sbs-sync-label');
            const hasStructure = $label.length > 0;

            $button.prop('disabled', true);
            if (hasStructure) {
                $icon.text('⏳');
                $label.text('Syncing...');
            } else {
                $button.text('Syncing...');
            }

            $status.removeClass('success error')
                   .html('<span style="color:#6b7280;">⏳ Pulling data from Square...</span>');

            $.ajax({
                url: sbsAdmin.ajax_url,
                type: 'POST',
                timeout: 120000,
                data: { action: 'yatoon_sync_now', nonce: sbsAdmin.nonce },
                success: function(response) {
                    if (response.success) {
                        const now = new Date().toLocaleString('en-US', {month:'short',day:'numeric',year:'numeric',hour:'numeric',minute:'2-digit'});
                        $status.html('<span style="color:#10b981;font-weight:600;">OK Sync complete! ' + (response.data.message || '') + '</span>'
                            + ' <span style="color:#9ca3af;font-size:12px;">· Just now</span>');
                        showNotice('success', sbsAdmin.strings.sync_success);
                        setTimeout(function() { location.reload(); }, 2000);
                    } else {
                        $status.html('<span style="color:#ef4444;">❌ ' + (response.data.message || 'Sync failed') + '</span>');
                        showNotice('error', response.data.message || sbsAdmin.strings.sync_error);
                    }
                },
                error: function() {
                    $status.html('<span style="color:#ef4444;">❌ Sync request timed out or PHP fatal error - check WP error log (wp-content/debug.log)</span>');
                    showNotice('error', sbsAdmin.strings.sync_error);
                },
                complete: function() {
                    $button.prop('disabled', false);
                    if (hasStructure) {
                        $icon.text('🔄');
                        $label.text('Sync Now');
                    } else {
                        $button.text('Sync Now');
                    }
                }
            });
        });
        
        // Delete Service
        $(document).on('click', '.sbs-delete-service', function() {
            if (!confirm(sbsAdmin.strings.confirm_delete)) {
                return;
            }
            
            const $button = $(this);
            const serviceId = $button.data('id');
            const $row = $button.closest('tr');
            
            $button.prop('disabled', true).text('Deleting...');
            
            $.ajax({
                url: sbsAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'yatoon_delete_service',
                    nonce: sbsAdmin.nonce,
                    service_id: serviceId
                },
                success: function(response) {
                    if (response.success) {
                        $row.fadeOut(300, function() {
                            $(this).remove();
                        });
                        showNotice('success', response.data.message);
                    } else {
                        showNotice('error', response.data.message);
                        $button.prop('disabled', false).text('Delete');
                    }
                },
                error: function() {
                    showNotice('error', 'Failed to delete service');
                    $button.prop('disabled', false).text('Delete');
                }
            });
        });

        enhanceResizableTables();
        $(window).on('resize', function() {
            $('.sbs-admin-page table.yatoon-resizable-table').each(function() {
                syncResizableTableWidth($(this));
            });
        });

        function enhanceResizableTables() {
            $('.sbs-admin-page table.wp-list-table, .sbs-admin-page table.widefat').not('.form-table').each(function(tableIndex) {
                const $table = $(this);
                if ($table.attr('id') === 'sbs-services-table') {
                    return;
                }
                if ($table.data('yatoonResizableReady') || !$table.find('thead th').length) {
                    return;
                }

                $table.data('yatoonResizableReady', true).addClass('yatoon-resizable-table');
                if (!$table.parent().hasClass('yatoon-admin-table-scroll') && !$table.parent().hasClass('sbs-admin-table-wrap')) {
                    $table.wrap('<div class="yatoon-admin-table-scroll"></div>');
                }

                const storageKey = 'yatoon-admin-table-widths:' + location.pathname + ':' + (new URLSearchParams(location.search).get('page') || 'page') + ':' + ($table.attr('id') || tableIndex);
                let savedWidths = {};
                try {
                    savedWidths = JSON.parse(localStorage.getItem(storageKey) || '{}');
                } catch (err) {
                    savedWidths = {};
                }

                $table.find('thead th').each(function(colIndex) {
                    const $th = $(this);
                    if ($th.attr('colspan')) {
                        return;
                    }
                    const minWidth = getColumnMinWidth($table, colIndex);
                    const saved = parseInt(savedWidths[colIndex], 10);
                    const defaultWidth = getColumnDefaultWidth($table, colIndex);
                    const current = Math.max(minWidth, saved || defaultWidth || Math.round($th.outerWidth()));
                    setColumnWidth($table, colIndex, current);
                    $('<span class="yatoon-col-resizer" aria-hidden="true"></span>').appendTo($th).on('mousedown touchstart', function(e) {
                        const point = e.originalEvent.touches ? e.originalEvent.touches[0] : e;
                        const startX = point.pageX;
                        const startWidth = $th.outerWidth();
                        const $handle = $(this).addClass('is-dragging');
                        $('body').addClass('yatoon-table-resizing');
                        e.preventDefault();

                        $(document).on('mousemove.yatoonResize touchmove.yatoonResize', function(moveEvent) {
                            const movePoint = moveEvent.originalEvent.touches ? moveEvent.originalEvent.touches[0] : moveEvent;
                            const nextWidth = Math.max(getColumnMinWidth($table, colIndex), Math.round(startWidth + movePoint.pageX - startX));
                            setColumnWidth($table, colIndex, nextWidth);
                            savedWidths[colIndex] = nextWidth;
                            syncResizableTableWidth($table);
                        });

                        $(document).on('mouseup.yatoonResize touchend.yatoonResize touchcancel.yatoonResize', function() {
                            localStorage.setItem(storageKey, JSON.stringify(savedWidths));
                            $handle.removeClass('is-dragging');
                            $('body').removeClass('yatoon-table-resizing');
                            $(document).off('.yatoonResize');
                        });
                    });
                });

                $table.find('tbody td').each(function() {
                    const $cell = $(this);
                    const text = $.trim($cell.text());
                    if (text && !$cell.attr('title')) {
                        $cell.attr('title', text);
                    }
                });
                attachTableScrollbar($table);
                syncResizableTableWidth($table);
            });
        }

        function setColumnWidth($table, colIndex, width) {
            width = Math.max(getColumnMinWidth($table, colIndex), width);
            $table.find('tr').each(function() {
                $(this).children('th,td').eq(colIndex).css({
                    width: width + 'px',
                    minWidth: width + 'px',
                    maxWidth: width + 'px'
                });
            });
        }

        function syncResizableTableWidth($table) {
            let total = 0;
            $table.find('thead th').each(function() {
                total += Math.max(44, Math.round($(this).outerWidth()));
            });
            if (total > 0) {
                $table.css('min-width', Math.max(total, 1180) + 'px');
            }
            syncTableScrollbar($table);
        }

        function attachTableScrollbar($table) {
            const $wrap = $table.closest('.sbs-admin-table-wrap, .yatoon-admin-table-scroll');
            if ($table.attr('id') === 'sbs-staff-table') {
                // The Staff table already has the wrapper's native horizontal
                // scrollbar. Do not append a second synchronized scrollbar.
                $wrap.children('.yatoon-table-x-scrollbar').remove();
                return;
            }
            if (!$wrap.length || $wrap.children('.yatoon-table-x-scrollbar').length) {
                return;
            }

            const $bar = $('<div class="yatoon-table-x-scrollbar" aria-hidden="true"><div class="yatoon-table-x-scrollbar-inner"></div></div>');
            $wrap.append($bar);

            let syncing = false;
            $wrap.on('scroll.yatoonTableX', function() {
                if (syncing) {
                    return;
                }
                syncing = true;
                $bar.scrollLeft($wrap.scrollLeft());
                syncing = false;
            });
            $bar.on('scroll.yatoonTableX', function() {
                if (syncing) {
                    return;
                }
                syncing = true;
                $wrap.scrollLeft($bar.scrollLeft());
                syncing = false;
            });
            syncTableScrollbar($table);
        }

        function syncTableScrollbar($table) {
            const $wrap = $table.closest('.sbs-admin-table-wrap, .yatoon-admin-table-scroll');
            const $bar = $wrap.children('.yatoon-table-x-scrollbar');
            if (!$wrap.length || !$bar.length) {
                return;
            }

            const scrollWidth = Math.max($table.outerWidth(), $table[0] ? $table[0].scrollWidth : 0, $wrap[0] ? $wrap[0].scrollWidth : 0);
            $bar.children('.yatoon-table-x-scrollbar-inner').width(scrollWidth);
            $bar.toggle(scrollWidth > Math.ceil($wrap.innerWidth()) + 2);
            $bar.scrollLeft($wrap.scrollLeft());
        }

        function getColumnDefaultWidth($table, colIndex) {
            if ($table.attr('id') === 'sbs-services-table') {
                const defaults = [44, 34, 76, 0, 520, 90, 88, 0, 0, 86, 0];
                return defaults[colIndex] || 0;
            }
            return 0;
        }

        function getColumnMinWidth($table, colIndex) {
            if ($table.attr('id') === 'sbs-services-table') {
                const mins = [44, 30, 64, 0, 240, 72, 70, 0, 0, 70, 0];
                return mins[colIndex] || 56;
            }
            return 56;
        }
        
        // Helper function to show admin notices
        function showNotice(type, message) {
            const noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
            const $notice = $('<div class="notice ' + noticeClass + ' is-dismissible sbs-notice"><p>' + message + '</p></div>');
            
            $('.wrap h1').after($notice);
            
            // Auto-dismiss after 5 seconds
            setTimeout(function() {
                $notice.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 5000);
            
            // Handle dismiss button
            $notice.on('click', '.notice-dismiss', function() {
                $notice.fadeOut(300, function() {
                    $(this).remove();
                });
            });
        }
    });

})(jQuery);
