/**
 * FRESH Manager — Admin JavaScript
 * Handles: Tabs, Image Uploader, Repeater, Color Picker, Sortable, Cards
 */
(function($) {
    'use strict';

    // ========== TABS ==========
    $(document).on('click', '.freshm-tab', function() {
        var tab = $(this).data('tab');
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        $(this).closest('.freshm-wrap').find('.freshm-tab-content').removeClass('active');
        $(this).closest('.freshm-wrap').find('.freshm-tab-content[data-tab="' + tab + '"]').addClass('active');

        // Update URL with tab parameter for persistence
        if (window.history && window.history.replaceState) {
            var url = new URL(window.location);
            url.searchParams.set('tab', tab);
            // Remove saved/reset notices from URL on tab switch
            url.searchParams.delete('freshm_saved');
            url.searchParams.delete('freshm_reset');
            url.searchParams.delete('freshm_migrated');
            window.history.replaceState({}, '', url);
        }

        // Inject tab value into forms within the active tab content for save redirect
        $(this).closest('.freshm-wrap').find('.freshm-tab-content form').each(function() {
            var $input = $(this).find('input[name="freshm_tab"]');
            if ($input.length) {
                $input.val(tab);
            } else {
                $(this).append('<input type="hidden" name="freshm_tab" value="' + tab + '">');
            }
        });
    });

    // ========== IMAGE UPLOADER ==========
    $(document).on('click', '.freshm-upload-btn', function(e) {
        e.preventDefault();
        var $field = $(this).closest('.freshm-image-field');
        var $input = $field.find('.freshm-image-input');
        var $preview = $field.find('.freshm-image-preview');
        var $remove = $field.find('.freshm-remove-btn');

        var frame = wp.media({
            title: (typeof freshmData !== 'undefined' && freshmData.uploadTitle) || 'בחרו תמונה',
            button: { text: (typeof freshmData !== 'undefined' && freshmData.uploadButton) || 'השתמש בתמונה זו' },
            multiple: false
        });

        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            var url = attachment.sizes && attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url;
            $input.val(attachment.url);
            $preview.html('<img src="' + url + '">');
            if ($remove.length) $remove.show();
        });

        frame.open();
    });

    $(document).on('click', '.freshm-remove-btn', function(e) {
        e.preventDefault();
        var $field = $(this).closest('.freshm-image-field');
        $field.find('.freshm-image-input').val('');
        $field.find('.freshm-image-preview').html('');
        $(this).hide();
    });

    // ========== REPEATER ==========
    $(document).on('click', '.freshm-repeater-add', function() {
        var $repeater = $(this).closest('.freshm-repeater');
        var $items = $repeater.find('.freshm-repeater-items');
        var template = $repeater.find('.freshm-repeater-template').html();
        var index = Date.now();
        template = template.replace(/__INDEX__/g, index);
        $items.append(template);
    });

    $(document).on('click', '.freshm-repeater-remove', function() {
        if (confirm('למחוק את הפריט?')) {
            $(this).closest('.freshm-repeater-item').fadeOut(200, function() { $(this).remove(); });
        }
    });

    // ========== COLOR PICKER ==========
    $(document).ready(function() {
        $('.freshm-color-picker').wpColorPicker();
    });

    // ========== SORTABLE REPEATER ==========
    $(document).ready(function() {
        if ($.fn.sortable) {
            $('.freshm-repeater-items').sortable({
                handle: '.freshm-repeater-handle',
                placeholder: 'freshm-sortable-placeholder',
                opacity: 0.7,
                update: function() {
                    $(this).find('.freshm-repeater-item').each(function(i) {
                        $(this).find('input, textarea, select').each(function() {
                            var name = $(this).attr('name');
                            if (name) {
                                name = name.replace(/\[\d+\]/, '[' + i + ']');
                                $(this).attr('name', name);
                            }
                        });
                    });
                }
            });
        }
    });

    // ========== COLLAPSIBLE CARDS ==========

    // Add new card (stories or services)
    $(document).on('click', '.freshm-add-card', function() {
        var target = $(this).data('target');
        var templateMap = { stories: '#freshm-story-template', services: '#freshm-service-template', team: '#freshm-team-template' };
        var listMap = { stories: '#freshm-stories-list', services: '#freshm-services-list', team: '#freshm-team-list' };
        var $template = $(templateMap[target] || '#freshm-' + target + '-template');
        if (!$template.length) return;

        var html = $template.html();
        var idx = Date.now();
        html = html.replace(/__IDX__/g, idx);

        var $list = $(listMap[target] || '#freshm-' + target + '-list');
        var $card = $(html);
        $card.addClass('open'); // Open new cards by default
        $list.append($card);

        // Init color pickers in new card
        $card.find('.freshm-color-picker').wpColorPicker();

        // Scroll to new card
        $('html, body').animate({ scrollTop: $card.offset().top - 100 }, 300);

        // Update count
        updateCardCount($list);
    });

    // Delete card
    $(document).on('click', '.freshm-delete-card', function(e) {
        e.stopPropagation();
        if (!confirm('למחוק את הפריט? פעולה זו לא ניתנת לביטול.')) return;
        var $card = $(this).closest('.freshm-card');
        var $list = $card.closest('.freshm-cards-list');
        $card.slideUp(300, function() {
            $(this).remove();
            updateCardCount($list);
        });
    });

    // Update card title in real-time
    $(document).on('input', '.freshm-card-name-input', function() {
        var val = $(this).val() || ($(this).closest('.freshm-card').data('type') === 'story' ? 'הצלחת לקוח חדשה' : 'שירות חדש');
        $(this).closest('.freshm-card').find('.freshm-card-title').text(val);
    });

    // Card count helper
    function updateCardCount($list) {
        var count = $list.find('.freshm-card').length;
        $list.closest('form').find('.freshm-cards-count').text(count + ' פריטים');
    }

    // Sortable cards
    $(document).ready(function() {
        if ($.fn.sortable) {
            $('.freshm-cards-list').sortable({
                handle: '.freshm-card-handle',
                placeholder: 'ui-sortable-placeholder',
                opacity: 0.8,
                tolerance: 'pointer',
                update: function() {
                    // Re-index card form names
                    reindexCards($(this));
                }
            });
        }
    });

    function reindexCards($list) {
        var id = $list.attr('id');
        var prefix = id === 'freshm-stories-list' ? 'freshm_stories' : id === 'freshm-team-list' ? 'freshm_team' : 'freshm_svcs';
        $list.find('.freshm-card').each(function(i) {
            $(this).find('input, textarea, select').each(function() {
                var name = $(this).attr('name');
                if (!name) return;
                // Replace the top-level index: prefix[OLD_IDX] -> prefix[NEW_IDX]
                var re = new RegExp('^' + prefix.replace(/[[\]]/g, '\\$&') + '\\[\\d+\\]');
                name = name.replace(re, prefix + '[' + i + ']');
                $(this).attr('name', name);
            });
        });
    }

    // ========== MINI REPEATER (metrics, benefits, process) ==========

    // Add metric row
    $(document).on('click', '.freshm-mini-add', function() {
        var nameNum = $(this).data('name-num');
        var nameLabel = $(this).data('name-label');
        var idx = Date.now();
        nameNum = nameNum.replace('__MI__', idx);
        nameLabel = nameLabel.replace('__MI__', idx);

        var html = '<div class="freshm-mini-item">' +
            '<input type="text" name="' + nameNum + '" placeholder="+85%" class="freshm-mini-num">' +
            '<input type="text" name="' + nameLabel + '" placeholder="תיאור" class="freshm-mini-label">' +
            '<button type="button" class="freshm-mini-remove" title="הסר">✕</button>' +
            '</div>';
        $(this).closest('.freshm-mini-repeater').find('.freshm-mini-items').append(html);
    });

    // Add benefit row
    $(document).on('click', '.freshm-mini-add-benefit', function() {
        var baseName = $(this).data('name');
        var idx = Date.now();
        var html = '<div class="freshm-mini-item freshm-benefit-item">' +
            '<select name="' + baseName + '[' + idx + '][icon]" class="freshm-mini-icon"><option value="">אייקון</option></select>' +
            '<input type="text" name="' + baseName + '[' + idx + '][title]" placeholder="כותרת">' +
            '<input type="text" name="' + baseName + '[' + idx + '][desc]" placeholder="תיאור">' +
            '<button type="button" class="freshm-mini-remove">✕</button>' +
            '</div>';
        $(this).closest('.freshm-mini-repeater').find('.freshm-mini-items').append(html);
    });

    // Add process step row (services/stories — category pages use inline JS)
    $(document).on('click', '.freshm-mini-add-process', function() {
        var baseName = $(this).data('name');
        if (!baseName) return; // category-page buttons use data-slug, handled by page-specific JS
        var idx = Date.now();
        var html = '<div class="freshm-mini-item">' +
            '<input type="text" name="' + baseName + '[' + idx + '][number]" placeholder="01" class="freshm-mini-num">' +
            '<input type="text" name="' + baseName + '[' + idx + '][title]" placeholder="כותרת">' +
            '<input type="text" name="' + baseName + '[' + idx + '][desc]" placeholder="תיאור">' +
            '<button type="button" class="freshm-mini-remove">✕</button>' +
            '</div>';
        $(this).closest('.freshm-mini-repeater').find('.freshm-mini-items').append(html);
    });

    // Add FAQ row
    $(document).on('click', '.freshm-mini-add-faq', function() {
        var baseName = $(this).data('name');
        if (!baseName) return;
        var idx = Date.now();
        var html = '<div class="freshm-mini-item freshm-faq-item" style="flex-wrap:wrap;gap:6px;">' +
            '<input type="text" name="' + baseName + '[' + idx + '][q]" placeholder="שאלה" style="flex:1;min-width:200px;">' +
            '<button type="button" class="freshm-mini-remove">✕</button>' +
            '<textarea name="' + baseName + '[' + idx + '][a]" rows="2" placeholder="תשובה" style="width:100%;margin-top:2px;"></textarea>' +
            '</div>';
        $(this).closest('.freshm-mini-repeater').find('.freshm-mini-items').append(html);
    });

    // Remove mini repeater item
    $(document).on('click', '.freshm-mini-remove', function() {
        $(this).closest('.freshm-mini-item, .freshm-cat-item').fadeOut(200, function() { $(this).remove(); });
    });

    // ========== CATEGORY MANAGEMENT ==========
    $(document).on('click', '.freshm-cat-add', function() {
        var idx = Date.now();
        var html = '<div class="freshm-cat-item">' +
            '<input type="text" name="freshm_svc_cats[' + idx + '][name]" placeholder="שם קטגוריה">' +
            '<input type="text" name="freshm_svc_cats[' + idx + '][slug]" placeholder="slug" dir="ltr" class="freshm-cat-slug">' +
            '<input type="number" name="freshm_svc_cats[' + idx + '][order]" placeholder="סדר" class="freshm-cat-order" value="0">' +
            '<button type="button" class="freshm-mini-remove" title="הסר">✕</button>' +
            '</div>';
        $(this).closest('.freshm-cats-list').find('.freshm-cats-items').append(html);
    });

    // ========== GALLERY REPEATER ==========
    $(document).on('click', '.freshm-gallery-add', function() {
        var baseName = $(this).data('name');
        var idx = Date.now();
        var html = '<div class="freshm-gallery-item">' +
            '<div class="freshm-image-field">' +
            '<input type="hidden" name="' + baseName + '[' + idx + ']" value="" class="freshm-image-input">' +
            '<div class="freshm-image-preview"></div>' +
            '<button type="button" class="freshm-btn freshm-upload-btn">📷</button>' +
            '<button type="button" class="freshm-btn freshm-gallery-remove">✕</button>' +
            '</div></div>';
        $(this).closest('.freshm-gallery-repeater').find('.freshm-gallery-items').append(html);
    });

    $(document).on('click', '.freshm-gallery-remove', function() {
        $(this).closest('.freshm-gallery-item').fadeOut(200, function() { $(this).remove(); });
    });

})(jQuery);
