/* global jQuery, etnEgrAdminUi, ajaxurl, window, document, navigator */

(function ($) {
    'use strict';

    var l10n = (etnEgrAdminUi && etnEgrAdminUi.l10n) ? etnEgrAdminUi.l10n : {};
    var manualNonce = (etnEgrAdminUi && etnEgrAdminUi.manualNonce) ? etnEgrAdminUi.manualNonce : '';

    var tabs = document.querySelectorAll('.etn-egr-admin-tabs .etn-egr-tab');
    var panes = document.querySelectorAll('.etn-egr-pane');

    function showPane(id) {
        panes.forEach(function (p) {
            var isActive = p.id === id;
            p.classList.toggle('etn-egr-pane-active', isActive);
            p.hidden = !isActive;
        });
        tabs.forEach(function (t) {
            var isActive = t.getAttribute('data-tab') === id;
            t.classList.toggle('active', isActive);
            t.setAttribute('aria-selected', isActive ? 'true' : 'false');
        });
    }

    if (tabs.length) {
        tabs.forEach(function (btn) {
            btn.addEventListener('click', function () {
                var tabId = this.getAttribute('data-tab');
                showPane(tabId);
                if (tabId === 'etn-egr-tab-layout' && window.etnEgrRefreshPreviews) {
                    setTimeout(window.etnEgrRefreshPreviews, 80);
                }
            });
        });
    }

    $('#etn-egr-sync-btn').on('click', function () {
        var btn = $(this);
        btn.prop('disabled', true).text('⏳ ' + (l10n.syncing || 'Syncing...'));
        $.post(ajaxurl, { action: 'etn_egr_sync_reviews' }, function (res) {
            alert(res.data);
            window.location.reload();
        }).fail(function () {
            alert(l10n.syncError || 'Unknown error while syncing.');
            window.location.reload();
        });
    });

    $('#etn-egr-reset-google-btn').on('click', function () {
        if (!confirm(l10n.confirmReset || 'Delete all stored Google reviews?')) {
            return;
        }
        var btn = $(this);
        btn.prop('disabled', true).text('⏳ ' + (l10n.resetting || 'Deleting...'));
        $.post(ajaxurl, {
            action: 'etn_egr_reset_google_reviews',
            nonce: manualNonce
        }, function (res) {
            if (res.success) {
                alert(res.data);
                window.location.reload();
            } else {
                alert(res.data || (l10n.resetError || 'Error'));
                btn.prop('disabled', false).text(l10n.resetBtn || 'Delete Google reviews and re-sync');
            }
        }).fail(function () {
            alert(l10n.resetError || 'Connection error.');
            btn.prop('disabled', false).text(l10n.resetBtn || 'Delete Google reviews and re-sync');
        });
    });

    (function () {
        var frame = null;
        function openMedia(target) {
            if (frame) {
                frame.dispose();
            }
            frame = wp.media({ library: { type: 'image' }, multiple: false });
            frame.on('select', function () {
                var att = frame.state().get('selection').first().toJSON();
                var id = att.id;
                var url = att.sizes && att.sizes.thumbnail ? att.sizes.thumbnail.url : att.url;
                if (target === 'add') {
                    $('#etn-egr-manual-photo-id').val(id || '');
                    $('#etn-egr-manual-photo-preview').attr('src', url || '');
                    $('#etn-egr-manual-photo-preview-wrap').toggle(!!url);
                    $('#etn-egr-clear-photo-add').toggle(!!id);
                } else {
                    $('#etn-egr-edit-photo-id').val(id || '');
                    $('#etn-egr-edit-photo-url').val('');
                    $('#etn-egr-edit-photo-preview').attr('src', url || '');
                    $('#etn-egr-edit-photo-preview-wrap').toggle(!!url);
                    $('#etn-egr-clear-photo-edit').toggle(!!id);
                }
            });
            frame.open();
        }
        $('#etn-egr-select-photo-add').on('click', function () { openMedia('add'); });
        $('#etn-egr-select-photo-edit').on('click', function () { openMedia('edit'); });
        $('#etn-egr-clear-photo-add').on('click', function () {
            $('#etn-egr-manual-photo-id').val('');
            $('#etn-egr-manual-photo-preview').attr('src', '');
            $('#etn-egr-manual-photo-preview-wrap').hide();
            $(this).hide();
        });
        $('#etn-egr-clear-photo-edit').on('click', function () {
            $('#etn-egr-edit-photo-id').val('');
            $('#etn-egr-edit-photo-url').val('');
            $('#etn-egr-edit-photo-preview').attr('src', '');
            $('#etn-egr-edit-photo-preview-wrap').hide();
            $(this).hide();
        });
    })();

    $('#etn-egr-add-manual-btn').on('click', function () {
        var btn = $(this);
        var author = $('#etn-egr-manual-author').val().trim();
        var text = $('#etn-egr-manual-text').val().trim();
        var rating = $('#etn-egr-manual-rating').val();
        var photoId = $('#etn-egr-manual-photo-id').val().trim();
        var date = $('#etn-egr-manual-date').val().trim();
        if (!author || !text) {
            alert(l10n.required || 'Author name and review text are required.');
            return;
        }
        btn.prop('disabled', true).text(l10n.adding || 'Adding...');
        var payload = {
            action: 'etn_egr_add_manual_review',
            nonce: manualNonce,
            author_name: author,
            text: text,
            rating: rating,
            relative_time_description: date
        };
        if (photoId) {
            payload.profile_photo_id = photoId;
        }
        $.post(ajaxurl, payload).done(function (res) {
            if (res.success) {
                window.location.reload();
            } else {
                alert(res.data || (l10n.errorAdd || 'Could not add review.'));
                btn.prop('disabled', false).text(l10n.addReview || 'Add review');
            }
        }).fail(function () {
            alert(l10n.errorConn || 'Connection error.');
            btn.prop('disabled', false).text(l10n.addReview || 'Add review');
        });
    });

    $(document).on('click', '.etn-egr-edit-manual', function () {
        var tr = $(this).closest('tr');
        var dataStr = tr.attr('data-review');
        if (!dataStr) {
            return;
        }
        var r = JSON.parse(dataStr);
        $('#etn-egr-edit-id').val(r.id || '');
        $('#etn-egr-edit-author').val(r.author_name || '');
        $('#etn-egr-edit-text').val(r.text || '');
        $('#etn-egr-edit-rating').val(String(r.rating || 5));
        var photoId = r.profile_photo_id ? String(r.profile_photo_id) : '';
        var photoUrl = r.profile_photo_url || '';
        $('#etn-egr-edit-photo-id').val(photoId);
        $('#etn-egr-edit-photo-url').val(photoUrl);
        $('#etn-egr-edit-photo-preview').attr('src', photoUrl);
        $('#etn-egr-edit-photo-preview-wrap').toggle(!!photoUrl);
        $('#etn-egr-clear-photo-edit').toggle(!!photoId || !!photoUrl);
        $('#etn-egr-edit-visible').prop('checked', r.visible !== false);
        $('#etn-egr-edit-date').val(r.relative_time_description || '');
        $('#etn-egr-edit-modal').css('display', 'flex');
    });

    $('.etn-egr-edit-cancel').on('click', function () {
        $('#etn-egr-edit-modal').hide();
    });

    $('#etn-egr-edit-modal').on('click', function (e) {
        if (e.target === this) {
            $(this).hide();
        }
    });

    $(document).on('change', '.etn-egr-visible-checkbox', function () {
        var cb = $(this);
        var etnEgrKey = cb.data('etn-egr-key');
        var visible = cb.prop('checked') ? 1 : 0;
        $.post(ajaxurl, {
            action: 'etn_egr_set_review_visibility',
            nonce: manualNonce,
            etn_egr_key: etnEgrKey,
            visible: visible
        }).done(function (res) {
            if (!res.success) {
                cb.prop('checked', !cb.prop('checked'));
                if (res.data) {
                    alert(res.data);
                }
            }
        }).fail(function () {
            cb.prop('checked', !cb.prop('checked'));
        });
    });

    $('#etn-egr-select-all-manual').on('change', function () {
        $('.etn-egr-row-checkbox').prop('checked', this.checked);
    });

    $('#etn-egr-bulk-delete-btn').on('click', function () {
        var ids = $('.etn-egr-row-checkbox:checked').map(function () { return $(this).val(); }).get();
        if (ids.length === 0) {
            alert(l10n.noSelected || 'Select at least one manual review.');
            return;
        }
        if (!window.confirm(l10n.confirmBulk || 'Delete the selected reviews?')) {
            return;
        }
        var btn = $(this);
        btn.prop('disabled', true);
        $.post(ajaxurl, { action: 'etn_egr_bulk_delete_manual_reviews', nonce: manualNonce, ids: ids }).done(function (res) {
            if (res.success) {
                alert(res.data);
                window.location.reload();
            } else {
                alert(res.data || (l10n.errorDel || 'Could not delete.'));
            }
        }).fail(function () {
            alert(l10n.errorConn || 'Connection error.');
        }).always(function () {
            btn.prop('disabled', false);
        });
    });

    $('#etn-egr-edit-form').on('submit', function (e) {
        e.preventDefault();
        var btn = $('#etn-egr-edit-submit');
        var author = $('#etn-egr-edit-author').val().trim();
        var text = $('#etn-egr-edit-text').val().trim();
        if (!author || !text) {
            alert(l10n.required || 'Author name and review text are required.');
            return;
        }
        btn.prop('disabled', true).text(l10n.saving || 'Saving...');
        var photoId = $('#etn-egr-edit-photo-id').val().trim();
        var payload = {
            action: 'etn_egr_update_manual_review',
            nonce: manualNonce,
            id: $('#etn-egr-edit-id').val(),
            author_name: author,
            text: text,
            rating: $('#etn-egr-edit-rating').val(),
            relative_time_description: $('#etn-egr-edit-date').val().trim(),
            visible: $('#etn-egr-edit-visible').prop('checked') ? 1 : 0
        };
        if (photoId) {
            payload.profile_photo_id = photoId;
        } else {
            payload.profile_photo_url = $('#etn-egr-edit-photo-url').val().trim();
        }
        $.post(ajaxurl, payload).done(function (res) {
            if (res.success) {
                alert(l10n.saved || 'Review updated successfully.');
                window.location.reload();
            } else {
                alert(res.data || (l10n.errorUpdate || 'Could not update.'));
                btn.prop('disabled', false).text(l10n.saveBtn || 'Save changes');
            }
        }).fail(function () {
            alert(l10n.errorConn || 'Connection error.');
            btn.prop('disabled', false).text(l10n.saveBtn || 'Save changes');
        });
    });

    $(document).on('click', '.etn-egr-delete-manual', function () {
        var id = $(this).data('id');
        if (!id || !window.confirm(l10n.confirmDel || 'Delete this manual review?')) {
            return;
        }
        $.post(ajaxurl, { action: 'etn_egr_delete_manual_review', nonce: manualNonce, id: id }).done(function (res) {
            if (res.success) {
                $('tr[data-id="' + id + '"]').fadeOut(200, function () { $(this).remove(); });
            } else {
                alert(res.data || (l10n.errorDel || 'Could not delete.'));
            }
        });
    });

    $('#etn-egr-copy-shortcode').on('click', function () {
        var code = $('#etn-egr-shortcode-text').text();
        var feedback = $('#etn-egr-copy-feedback');
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(code).then(function () {
                feedback.show();
                setTimeout(function () { feedback.hide(); }, 2000);
            });
        } else {
            var ta = document.createElement('textarea');
            ta.value = code;
            ta.setAttribute('readonly', '');
            ta.style.position = 'absolute';
            ta.style.left = '-9999px';
            document.body.appendChild(ta);
            ta.select();
            try {
                document.execCommand('copy');
                feedback.show();
                setTimeout(function () { feedback.hide(); }, 2000);
            } catch (err) {
                // no-op fallback
            }
            document.body.removeChild(ta);
        }
    });

    (function () {
        function getOpt(name) {
            var el = document.querySelector('[name="etn_egr_style_options[' + name + ']"]');
            if (!el) {
                return '';
            }
            if (el.type === 'checkbox') {
                return el.checked ? '1' : '';
            }
            return el.value || '';
        }
        function num(v, def) {
            var n = parseInt(v, 10);
            return isNaN(n) ? (def || 0) : n;
        }
        function refreshPreviews() {
            var cardBg = getOpt('bg_card') || '#ffffff';
            var cName = getOpt('c_name') || '#333';
            var cText = getOpt('c_text') || '#555';
            var cStar = getOpt('c_star') || '#ffc107';
            var radius = num(getOpt('border_radius'), 8);
            var cardPad = num(getOpt('card_padding'), 16);
            var cardGap = num(getOpt('card_gap'), 12);
            var columns = Math.max(1, Math.min(6, num(getOpt('columns'), 3)));
            var equalHeight = getOpt('equal_height') === '1';
            var badgePad = num(getOpt('badge_padding'), 15);
            var sideBg = getOpt('sidebar_bg') || 'rgba(6,30,70,0.66)';
            var sidePad = num(getOpt('sidebar_padding'), 20);
            var sideRadius = num(getOpt('sidebar_border_radius'), 0);
            var sideShadow = getOpt('sidebar_shadow') || '0 4px 20px rgba(0,0,0,0.3)';
            var sideWidth = num(getOpt('sidebar_width'), 360);
            var sideCardBg = getOpt('sidebar_card_bg') || 'rgba(255,255,255,0.1)';
            var sideCardPad = num(getOpt('sidebar_card_padding'), 15);
            var sideCardMargin = num(getOpt('sidebar_card_margin'), 10);
            var sideCardRadius = num(getOpt('sidebar_card_border_radius'), 8);
            var writeUrl = getOpt('write_review_url') || '';

            var layoutRow = document.querySelector('#etn-egr-preview-layout .etn-egr-preview-cards-row');
            if (layoutRow) {
                layoutRow.style.gap = cardGap + 'px';
                layoutRow.style.alignItems = equalHeight ? 'stretch' : 'flex-start';
                layoutRow.style.flexWrap = 'nowrap';
                var gapTotal = (columns - 1) * cardGap;
                var flexBasis = 'calc((100% - ' + gapTotal + 'px - 1px) / ' + columns + ')';
                layoutRow.querySelectorAll('.etn-egr-preview-card').forEach(function (card, index) {
                    if (index >= columns) {
                        card.style.display = 'none';
                        return;
                    }
                    card.style.display = '';
                    card.style.background = cardBg;
                    card.style.padding = cardPad + 'px';
                    card.style.borderRadius = radius + 'px';
                    card.style.flex = '0 0 ' + flexBasis;
                    card.style.width = flexBasis;
                    card.style.minWidth = '0';
                    card.style.maxWidth = flexBasis;
                    card.style.boxSizing = 'border-box';
                    if (equalHeight) {
                        card.style.minHeight = '70px';
                    } else {
                        card.style.minHeight = '';
                    }
                    var cols = card.querySelectorAll('div');
                    if (cols[0]) {
                        cols[0].style.color = cName;
                    }
                    if (cols[1]) {
                        cols[1].style.color = cStar;
                    }
                    if (cols[2]) {
                        cols[2].style.color = cText;
                    }
                });
            }
            var estCard = document.querySelector('#etn-egr-preview-estetica .etn-egr-preview-card-single');
            if (estCard) {
                estCard.style.background = cardBg;
                estCard.style.padding = cardPad + 'px';
                estCard.style.borderRadius = radius + 'px';
                var ch = estCard.children;
                if (ch[0] && ch[0].children[1]) {
                    ch[0].children[1].style.color = cName;
                }
                if (ch[1]) {
                    ch[1].style.color = cStar;
                }
                if (ch[2]) {
                    ch[2].style.color = cText;
                }
            }
            var badgeInner = document.querySelector('#etn-egr-preview-badge .etn-egr-preview-badge-inner');
            if (badgeInner) {
                badgeInner.style.padding = badgePad + 'px';
                badgeInner.style.borderRadius = radius + 'px';
                var starEl = badgeInner.querySelector('.etn-egr-preview-badge-stars');
                if (starEl) {
                    starEl.style.color = cStar;
                }
                var plusSpan = badgeInner.querySelector('.etn-egr-preview-badge-plus');
                if (plusSpan) {
                    plusSpan.style.display = writeUrl ? '' : 'none';
                    plusSpan.style.background = cStar;
                }
            }
            var panelInner = document.querySelector('#etn-egr-preview-panel .etn-egr-preview-panel-inner');
            if (panelInner) {
                panelInner.style.background = sideBg;
                panelInner.style.padding = sidePad + 'px';
                panelInner.style.borderRadius = '0 ' + sideRadius + 'px ' + sideRadius + 'px 0';
                panelInner.style.boxShadow = sideShadow;
                panelInner.style.maxWidth = Math.min(Math.max(sideWidth, 200), 400) + 'px';
            }
            var panelCard = document.querySelector('#etn-egr-preview-panel .etn-egr-preview-panel-card');
            if (panelCard) {
                panelCard.style.background = sideCardBg;
                panelCard.style.padding = sideCardPad + 'px';
                panelCard.style.marginBottom = sideCardMargin + 'px';
                panelCard.style.borderRadius = sideCardRadius + 'px';
            }
        }
        var form = document.getElementById('etn-egr-settings-form');
        if (form) {
            form.addEventListener('input', refreshPreviews);
            form.addEventListener('change', refreshPreviews);
            window.etnEgrRefreshPreviews = refreshPreviews;
            refreshPreviews();
            jQuery(form).on('wpcolorpickerchange', function() {
                setTimeout(refreshPreviews, 30);
            });
        }
    })();

})(jQuery);

