(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        initInstructionsToggle();
        initCategoryToggle();
        initTypeToggle();
        initHoursToggle();
        initDayToggles();
        initSchemaPreview();
        initLogoUpload();
        initPhoneFormat();
    });

    /**
     * Toggle instructions panel visibility.
     */
    function initInstructionsToggle() {
        var toggle = document.getElementById('blm-instructions-toggle');
        var content = document.getElementById('blm-instructions-content');
        if (!toggle || !content) return;

        toggle.addEventListener('click', function () {
            var isVisible = content.style.display !== 'none';
            content.style.display = isVisible ? 'none' : 'block';
            toggle.classList.toggle('active', !isVisible);
        });
    }

    /**
     * Handle category dropdown change to filter business types.
     */
    function initCategoryToggle() {
        var categorySelect = document.getElementById('blm_business_category');
        var typeSelect = document.getElementById('blm_business_type');
        if (!categorySelect || !typeSelect || typeof blmTypesGrouped === 'undefined') return;

        categorySelect.addEventListener('change', function () {
            var category = this.value;
            var types = blmTypesGrouped[category] || {};

            // Clear current options
            typeSelect.innerHTML = '';

            // Add new options
            for (var key in types) {
                if (types.hasOwnProperty(key)) {
                    var option = document.createElement('option');
                    option.value = key;
                    option.textContent = types[key].label;
                    typeSelect.appendChild(option);
                }
            }

            // Trigger type change to update type-specific fields
            typeSelect.dispatchEvent(new Event('change'));
        });
    }

    /**
     * Show/hide type-specific field sections based on the Business Type dropdown.
     */
    function initTypeToggle() {
        var typeSelect = document.getElementById('blm_business_type');
        if (!typeSelect) return;

        typeSelect.addEventListener('change', function () {
            var sections = document.querySelectorAll('.blm-type-fields');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = (sections[i].getAttribute('data-type') === this.value) ? '' : 'none';
            }
            updateSchemaPreview();
        });
    }

    /**
     * Open 24/7 toggle: check all days as open, hide time pickers.
     */
    function initHoursToggle() {
        var toggle = document.getElementById('blm_open_247');
        if (!toggle) return;

        toggle.addEventListener('change', function () {
            var table = document.getElementById('blm-hours-table');
            if (!table) return;

            var dayCheckboxes = table.querySelectorAll('.blm-day-open');
            var timeFields = table.querySelectorAll('.blm-time-fields');

            if (this.checked) {
                for (var i = 0; i < dayCheckboxes.length; i++) {
                    dayCheckboxes[i].checked = true;
                }
                for (var j = 0; j < timeFields.length; j++) {
                    timeFields[j].style.display = 'none';
                }
            } else {
                for (var k = 0; k < timeFields.length; k++) {
                    var dayCheck = timeFields[k].parentNode.querySelector('.blm-day-open');
                    timeFields[k].style.display = (dayCheck && dayCheck.checked) ? 'flex' : 'none';
                }
            }
            updateSchemaPreview();
        });

        // Apply initial state
        if (toggle.checked) {
            toggle.dispatchEvent(new Event('change'));
        }
    }

    /**
     * Per-day open/closed checkbox: show/hide time pickers for that day.
     */
    function initDayToggles() {
        var dayCheckboxes = document.querySelectorAll('.blm-day-open');
        for (var i = 0; i < dayCheckboxes.length; i++) {
            dayCheckboxes[i].addEventListener('change', function () {
                var row = this.closest('.blm-hours-row');
                if (!row) return;
                var timeFields = row.querySelector('.blm-time-fields');
                if (!timeFields) return;

                var open247 = document.getElementById('blm_open_247');
                if (open247 && open247.checked) return;

                timeFields.style.display = this.checked ? 'flex' : 'none';
                updateSchemaPreview();
            });

            // Apply initial state
            var open247 = document.getElementById('blm_open_247');
            if (!open247 || !open247.checked) {
                var row = dayCheckboxes[i].closest('.blm-hours-row');
                if (row) {
                    var timeFields = row.querySelector('.blm-time-fields');
                    if (timeFields) {
                        timeFields.style.display = dayCheckboxes[i].checked ? 'flex' : 'none';
                    }
                }
            }
        }
    }

    /**
     * Live schema preview: collect all field values, build JSON-LD object, display in preview area.
     */
    function initSchemaPreview() {
        var toggleBtn = document.getElementById('blm-toggle-preview');
        var previewWrap = document.getElementById('blm-schema-preview');

        if (toggleBtn && previewWrap) {
            toggleBtn.addEventListener('click', function () {
                var isHidden = previewWrap.style.display === 'none';
                previewWrap.style.display = isHidden ? 'block' : 'none';
                if (isHidden) {
                    updateSchemaPreview();
                }
            });
        }

        // Listen for field changes
        var form = document.getElementById('blm-settings-form');
        if (form) {
            form.addEventListener('input', debounce(updateSchemaPreview, 300));
            form.addEventListener('change', updateSchemaPreview);
        }
    }

    function updateSchemaPreview() {
        var output = document.getElementById('blm-schema-output');
        if (!output) return;
        if (document.getElementById('blm-schema-preview').style.display === 'none') return;

        var typeSelect = document.getElementById('blm_business_type');
        var typeKey = typeSelect ? typeSelect.value : 'local_business';

        // Build schema type from blmTypesGrouped data
        var schemaType = 'LocalBusiness';
        if (typeof blmTypesGrouped !== 'undefined') {
            for (var cat in blmTypesGrouped) {
                if (blmTypesGrouped.hasOwnProperty(cat) && blmTypesGrouped[cat][typeKey]) {
                    schemaType = blmTypesGrouped[cat][typeKey].schema_type;
                    break;
                }
            }
        }

        var schema = {
            '@context': 'https://schema.org',
            '@type': schemaType
        };

        var name = getVal('blm_business_name');
        if (name) schema.name = name;

        var desc = getVal('blm_description');
        if (desc) schema.description = desc;

        var website = getVal('blm_website');
        if (website) schema.url = website;

        var phone = getVal('blm_phone');
        if (phone) schema.telephone = phone;

        var email = getVal('blm_email');
        if (email) schema.email = email;

        var logo = getVal('blm_logo');
        if (logo) {
            schema.logo = logo;
            schema.image = logo;
        }

        var priceRange = getVal('blm_price_range');
        if (priceRange) schema.priceRange = priceRange;

        // Address
        var address = {};
        var addr = getVal('blm_address'); if (addr) address.streetAddress = addr;
        var city = getVal('blm_city'); if (city) address.addressLocality = city;
        var state = getVal('blm_state'); if (state) address.addressRegion = state;
        var postal = getVal('blm_postal_code'); if (postal) address.postalCode = postal;
        var country = getVal('blm_country'); if (country) address.addressCountry = country;

        if (Object.keys(address).length) {
            address['@type'] = 'PostalAddress';
            schema.address = address;
        }

        // Hours
        var open247 = document.getElementById('blm_open_247');
        if (open247 && open247.checked) {
            schema.openingHoursSpecification = [{
                '@type': 'OpeningHoursSpecification',
                dayOfWeek: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                opens: '00:00',
                closes: '23:59'
            }];
        } else {
            var hours = [];
            var dayNames = {
                monday: 'Monday', tuesday: 'Tuesday', wednesday: 'Wednesday',
                thursday: 'Thursday', friday: 'Friday', saturday: 'Saturday', sunday: 'Sunday'
            };
            var days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            for (var d = 0; d < days.length; d++) {
                var dayOpen = document.querySelector('input[name="blm[hours][' + days[d] + '][open]"]');
                if (dayOpen && dayOpen.checked) {
                    var openTime = document.querySelector('input[name="blm[hours][' + days[d] + '][open_time]"]');
                    var closeTime = document.querySelector('input[name="blm[hours][' + days[d] + '][close_time]"]');
                    hours.push({
                        '@type': 'OpeningHoursSpecification',
                        dayOfWeek: dayNames[days[d]],
                        opens: openTime ? openTime.value : '09:00',
                        closes: closeTime ? closeTime.value : '17:00'
                    });
                }
            }
            if (hours.length) schema.openingHoursSpecification = hours;
        }

        // Social
        var sameAs = [];
        var socialKeys = ['facebook', 'twitter', 'instagram', 'linkedin', 'youtube', 'yelp'];
        for (var s = 0; s < socialKeys.length; s++) {
            var val = getVal('blm_social_' + socialKeys[s]);
            if (val) sameAs.push(val);
        }
        if (sameAs.length) schema.sameAs = sameAs;

        // Type-specific fields - generic handling for all types
        addTypeSpecificFields(schema, typeKey)

        output.textContent = JSON.stringify(schema, null, 2);
    }

    function getVal(id) {
        var el = document.getElementById(id);
        return el ? el.value.trim() : '';
    }

    /**
     * Add type-specific fields to schema based on field key mappings.
     */
    function addTypeSpecificFields(schema, typeKey) {
        // Field key to schema property mapping for single-value text fields
        var fieldMappings = {
            'menu_url': 'hasMenu',
            'checkin_time': 'checkinTime',
            'checkout_time': 'checkoutTime',
            'mission_statement': 'nonprofitMission',
            'nonprofit_status': 'nonprofitStatus',
            'capacity': 'maximumAttendeeCapacity',
            'screen_count': 'screenCount'
        };

        // Process single-value text fields
        for (var fieldKey in fieldMappings) {
            if (fieldMappings.hasOwnProperty(fieldKey)) {
                var val = getVal('blm_tf_' + fieldKey);
                if (val) {
                    schema[fieldMappings[fieldKey]] = val;
                }
            }
        }

        // Multi-line textarea fields that should become arrays
        var multilineMappings = {
            'known_for': 'knowsAbout',
            'available_services': 'availableService',
            'serves_cuisine': 'servesCuisine',
            'auto_brands': 'brand',
            'medical_specialty': 'medicalSpecialty',
            'currencies_accepted': 'currenciesAccepted',
            'sport': 'sport'
        };

        for (var mlKey in multilineMappings) {
            if (multilineMappings.hasOwnProperty(mlKey)) {
                var mlVal = getVal('blm_tf_' + mlKey);
                if (mlVal) {
                    var items = mlVal.split('\n').map(function (a) { return a.trim(); }).filter(function (a) { return a.length > 0; });
                    if (items.length === 1) {
                        schema[multilineMappings[mlKey]] = items[0];
                    } else if (items.length > 1) {
                        schema[multilineMappings[mlKey]] = items;
                    }
                }
            }
        }

        // Service area (textarea -> areaServed array)
        var serviceArea = getVal('blm_tf_service_area');
        if (serviceArea) {
            var areas = serviceArea.split('\n').map(function (a) { return a.trim(); }).filter(function (a) { return a.length > 0; });
            if (areas.length === 1) {
                schema.areaServed = { '@type': 'AdministrativeArea', name: areas[0] };
            } else if (areas.length > 1) {
                schema.areaServed = areas.map(function (a) {
                    return { '@type': 'AdministrativeArea', name: a };
                });
            }
        }

        // Star rating (select -> Rating object)
        var starRating = getVal('blm_tf_star_rating');
        if (starRating) {
            schema.starRating = { '@type': 'Rating', ratingValue: starRating };
        }

        // Checkbox fields
        var checkboxMappings = {
            'accepts_reservations': 'acceptsReservations',
            'has_drive_through': 'hasDriveThroughService',
            'accepting_patients': 'isAcceptingNewPatients'
        };
        for (var cbKey in checkboxMappings) {
            if (checkboxMappings.hasOwnProperty(cbKey)) {
                var cb = document.getElementById('blm_tf_' + cbKey);
                if (cb && cb.checked) {
                    schema[checkboxMappings[cbKey]] = 'True';
                }
            }
        }

        // Payment accepted (checkboxes -> comma-separated string)
        var paymentCheckboxes = document.querySelectorAll('input[name="blm[type_fields][payment_accepted][]"]:checked');
        if (paymentCheckboxes.length) {
            var payments = [];
            for (var p = 0; p < paymentCheckboxes.length; p++) {
                payments.push(paymentCheckboxes[p].value);
            }
            schema.paymentAccepted = payments.join(', ');
        }

        // Amenities (checkboxes -> amenityFeature array)
        var amenityCheckboxes = document.querySelectorAll('input[name="blm[type_fields][amenities][]"]:checked');
        if (amenityCheckboxes.length) {
            schema.amenityFeature = [];
            for (var am = 0; am < amenityCheckboxes.length; am++) {
                schema.amenityFeature.push({
                    '@type': 'LocationFeatureSpecification',
                    name: amenityCheckboxes[am].value,
                    value: true
                });
            }
        }
    }

    /**
     * WordPress media uploader for logo.
     */
    function initLogoUpload() {
        var btn = document.getElementById('blm-upload-logo-btn');
        if (!btn) return;

        btn.addEventListener('click', function (e) {
            e.preventDefault();

            if (typeof wp === 'undefined' || typeof wp.media === 'undefined') return;

            var frame = wp.media({
                title: 'Select Logo',
                button: { text: 'Use this image' },
                multiple: false
            });

            frame.on('select', function () {
                var attachment = frame.state().get('selection').first().toJSON();
                var logoField = document.getElementById('blm_logo');
                if (logoField) {
                    logoField.value = attachment.url;
                    updateSchemaPreview();
                }
            });

            frame.open();
        });
    }

    /**
     * Auto-format US phone numbers on blur. International numbers pass through untouched.
     */
    function initPhoneFormat() {
        var phoneInput = document.getElementById('blm_phone');
        if (!phoneInput) return;

        phoneInput.addEventListener('blur', function () {
            this.value = formatPhone(this.value);
        });
    }

    function formatPhone(value) {
        var digits = value.replace(/\D/g, '');
        if (digits.length === 10) {
            return '(' + digits.substring(0, 3) + ') ' + digits.substring(3, 6) + '-' + digits.substring(6);
        }
        if (digits.length === 11 && digits.charAt(0) === '1') {
            return '(' + digits.substring(1, 4) + ') ' + digits.substring(4, 7) + '-' + digits.substring(7);
        }
        return value;
    }

    function debounce(fn, delay) {
        var timer;
        return function () {
            clearTimeout(timer);
            timer = setTimeout(fn, delay);
        };
    }

    /**
     * Disable hidden panel fields before submit to prevent field name conflicts.
     * Multiple business types share the same field keys (e.g., 'known_for').
     */
    function initFormSubmitHandler() {
        var form = document.getElementById('blm-settings-form');
        if (!form) return;

        form.addEventListener('submit', function () {
            var hiddenPanels = document.querySelectorAll('.blm-type-fields[style*="display: none"], .blm-type-fields[style*="display:none"]');
            for (var i = 0; i < hiddenPanels.length; i++) {
                var inputs = hiddenPanels[i].querySelectorAll('input, select, textarea');
                for (var j = 0; j < inputs.length; j++) {
                    inputs[j].disabled = true;
                }
            }
        });
    }

    // Initialize form submit handler
    document.addEventListener('DOMContentLoaded', function () {
        initFormSubmitHandler();
    });
})();
