/* Cryptoniq Options Framework — admin UI */
(function ($) {
    'use strict';

    $(function () {
        var $wrap = $('.cryptoniq-options-wrap');
        if (!$wrap.length) return;

        initTabs($wrap);
        initSwitches($wrap);
        initColorPickers($wrap);
        initMultiText($wrap);
        initConditional($wrap);
        initToast($wrap);
    });

    // ---------- Toast (auto-dismiss "settings saved" notice) ----------
    function initToast($wrap) {
        var $toast = $wrap.find('.cn-toast');
        if (!$toast.length) return;

        setTimeout(function () {
            $toast.addClass('is-hiding');
            setTimeout(function () { $toast.remove(); }, 260);
        }, 2400);
    }

    // ---------- Tabs ----------
    function initTabs($wrap) {
        var $tabs   = $wrap.find('.cn-tab');
        var $panels = $wrap.find('.cn-panel');
        var $activeInput = $wrap.find('.cn-active-tab-input');

        $tabs.on('click', function (e) {
            e.preventDefault();
            var id = $(this).data('tab');
            $tabs.removeClass('is-active');
            $(this).addClass('is-active');
            $panels.removeClass('is-active').filter('[data-tab="' + id + '"]').addClass('is-active');
            $activeInput.val(id);
            try { history.replaceState(null, '', addQueryArg(location.href, 'tab', id)); } catch (e) {}
        });
    }

    function addQueryArg(url, key, value) {
        var u = new URL(url, location.origin);
        u.searchParams.set(key, value);
        return u.toString();
    }

    // ---------- Switch ----------
    function initSwitches($wrap) {
        $wrap.on('change', '.cn-switch-input', function () {
            $(this).closest('.cn-switch').toggleClass('is-on', this.checked);
        });
    }

    // ---------- Color picker ----------
    function initColorPickers($wrap) {
        if (!$.fn.wpColorPicker) return;
        $wrap.find('.cn-input-color').wpColorPicker();
    }

    // ---------- Multi-text ----------
    function initMultiText($wrap) {
        $wrap.on('click', '.cn-multitext-add', function (e) {
            e.preventDefault();
            var $container = $(this).closest('.cn-multitext');
            var max = parseInt($container.data('max'), 10) || 0;
            var $rows = $container.find('.cn-multitext-row');
            if (max > 0 && $rows.length >= max) return;

            var nameBase = $container.data('name-base');
            var $row = $(
                '<div class="cn-multitext-row">' +
                    '<input type="text" name="' + nameBase + '[]" value="" class="cn-input cn-multitext-input" />' +
                    '<button type="button" class="cn-btn cn-btn-icon cn-btn-danger cn-multitext-remove" aria-label="Remove"></button>' +
                '</div>'
            );
            $container.find('.cn-multitext-rows').append($row);
            $row.find('input').trigger('focus');
        });

        // Live duplicate detection for fields marked data-unique="1".
        // Highlights any input whose value matches another input in the
        // same multitext container (case-insensitive). Server-side dedupe
        // is the source of truth — this is just instant visual feedback.
        $wrap.on('input change', '.cn-multitext[data-unique="1"] .cn-multitext-input', function () {
            highlightDuplicates($(this).closest('.cn-multitext'));
        });
        // Initial pass for pre-existing values
        $wrap.find('.cn-multitext[data-unique="1"]').each(function () {
            highlightDuplicates($(this));
        });

        $wrap.on('click', '.cn-multitext-remove', function (e) {
            e.preventDefault();
            var $container = $(this).closest('.cn-multitext');
            var $rows = $container.find('.cn-multitext-row');
            if ($rows.length <= 1) {
                $(this).siblings('input').val('');
            } else {
                $(this).closest('.cn-multitext-row').remove();
            }
            // After remove/clear, re-check for dupes in case removing
            // one duplicate de-flags the remaining ones.
            if ($container.attr('data-unique') === '1') {
                highlightDuplicates($container);
            }
        });
    }

    /**
     * Flag duplicate values within a single .cn-multitext container.
     * The FIRST occurrence of each value is left clean; subsequent ones
     * get .is-duplicate and the inline "Duplicate" tag via CSS.
     */
    function highlightDuplicates($container) {
        var seen = {};
        $container.find('.cn-multitext-row').each(function () {
            var $row = $(this);
            var $input = $row.find('.cn-multitext-input').first();
            var val = ($input.val() || '').trim().toLowerCase();

            if (val === '') {
                $row.removeClass('is-duplicate');
                return;
            }
            if (seen[val]) {
                $row.addClass('is-duplicate');
            } else {
                $row.removeClass('is-duplicate');
                seen[val] = true;
            }
        });
    }

    // ---------- Conditional `required` fields ----------
    // Field markup: data-required-target / data-required-op / data-required-value
    // Mirrors the Redux `required` syntax: ['target_id', '=', 'value']
    function initConditional($wrap) {
        var $conditional = $wrap.find('[data-required-target]');
        if (!$conditional.length) return;

        function valueOf(targetId) {
            var $field = $wrap.find('[data-field-id="' + targetId + '"]');
            if (!$field.length) return '';
            var $input = $field.find('input[type="checkbox"]:not(.cn-switch-input)');
            if ($input.length === 1) return $input.is(':checked') ? '1' : '';
            var $sw = $field.find('.cn-switch-input');
            if ($sw.length) return $sw.is(':checked') ? '1' : '';
            var $sel = $field.find('select');
            if ($sel.length) return $sel.val();
            var $txt = $field.find('input[type="text"], textarea').first();
            if ($txt.length) return $txt.val();
            return '';
        }

        function compare(left, op, right) {
            switch (op) {
                case '=':
                case '==':  return String(left) === String(right);
                case '!=':  return String(left) !== String(right);
                case '>':   return parseFloat(left) >   parseFloat(right);
                case '<':   return parseFloat(left) <   parseFloat(right);
                case '>=':  return parseFloat(left) >=  parseFloat(right);
                case '<=':  return parseFloat(left) <=  parseFloat(right);
                default:    return String(left) === String(right);
            }
        }

        function evaluate() {
            $conditional.each(function () {
                var $f     = $(this);
                var target = $f.data('required-target');
                var op     = $f.data('required-op');
                var want   = $f.data('required-value');
                var got    = valueOf(target);
                $f.toggleClass('is-hidden', !compare(got, op, want));
            });
        }

        // Re-evaluate when any potential target changes.
        $wrap.on('change input', 'input, select, textarea', evaluate);
        evaluate();
    }
})(jQuery);
