(function () {
    const settingsForm = document.getElementById('matewa-settings-form');
    if (!settingsForm) return;

    const displayModeCheckboxes = Array.from(settingsForm.querySelectorAll('.matewa-display-mode-checkbox'));

    const dashboardShell = document.querySelector('.matewa-dashboard-shell');
    const dashboardPage = document.querySelector('.matewa-dashboard-page');
    const dashboardThemeButtons = Array.from(document.querySelectorAll('[data-matewa-dashboard-theme-option]'));
    const returnSectionInput = document.getElementById('matewa-return-section');

    /*
     * Phase 5-A-26 / 5-A-26A: Ready-to-save button state plus guided input haze.
     * UI state only. Does not alter the custom save handler, redirect target,
     * validation, chip logic, widget behaviour, licence logic or lead routing.
     */
    (function () {
        const saveButtons = Array.from(document.querySelectorAll('.matewa-admin-save-button[form="matewa-settings-form"]'));

        if (!saveButtons.length || !window.FormData) {
            return;
        }

        const ignoredFieldNames = new Set([
            '_wpnonce',
            '_wp_http_referer',
            'option_page',
            'action',
            'matewa_return_section'
        ]);

        const guidedFieldSelectors = [
            '#matewa_number',
            '#matewa_marketing_email',
            '#matewa_business_name',
            '#matewa_industry',
            '#matewa_leads_email'
        ];
        const guidedFields = guidedFieldSelectors
            .map(function (selector) { return settingsForm.querySelector(selector); })
            .filter(Boolean);

        let initialSnapshot = '';
        let pendingFrame = null;
        let submitted = false;
        let savedTimer = null;
        let guardTimer = null;
        let saveGuardHelper = null;

        function normaliseValue(value) {
            if (typeof File !== 'undefined' && value instanceof File) {
                return value.name + ':' + value.size + ':' + value.type;
            }

            return String(value == null ? '' : value);
        }

        function formSnapshot() {
            const entries = [];
            const data = new FormData(settingsForm);

            data.forEach(function (value, name) {
                if (ignoredFieldNames.has(String(name || ''))) {
                    return;
                }

                entries.push([String(name || ''), normaliseValue(value)]);
            });

            return JSON.stringify(entries);
        }

        function isFormDirty() {
            return formSnapshot() !== initialSnapshot;
        }

        function buttonLabel(button, key, fallback) {
            return button.getAttribute(key) || fallback;
        }

        function ensureSaveGuardHelper() {
            if (saveGuardHelper) {
                return saveGuardHelper;
            }

            const firstButton = saveButtons[0];
            const actionWrap = firstButton.closest('.matewa-admin-topbar-actions') || firstButton.parentNode;

            if (!actionWrap) {
                return null;
            }

            saveGuardHelper = actionWrap.querySelector('.matewa-save-guard-helper');

            if (!saveGuardHelper) {
                saveGuardHelper = document.createElement('span');
                saveGuardHelper.className = 'matewa-save-guard-helper';
                saveGuardHelper.setAttribute('role', 'status');
                saveGuardHelper.setAttribute('aria-live', 'polite');
                saveGuardHelper.hidden = true;
                actionWrap.appendChild(saveGuardHelper);
            }

            return saveGuardHelper;
        }

        function hideSaveGuardHelper() {
            if (guardTimer) {
                window.clearTimeout(guardTimer);
                guardTimer = null;
            }

            const helper = ensureSaveGuardHelper();

            if (!helper) {
                return;
            }

            helper.hidden = true;
            helper.classList.remove('is-visible');
            helper.textContent = '';
        }

        function showSaveGuardHelper(message) {
            const helper = ensureSaveGuardHelper();

            if (!helper) {
                return;
            }

            if (guardTimer) {
                window.clearTimeout(guardTimer);
                guardTimer = null;
            }

            helper.textContent = message;
            helper.hidden = false;
            helper.classList.add('is-visible');

            guardTimer = window.setTimeout(function () {
                hideSaveGuardHelper();
            }, 3600);
        }

        function fieldHasValue(field) {
            return String((field && field.value) || '').trim() !== '';
        }

        function getFieldLabel(field) {
            if (!field || !field.id) {
                return 'this field';
            }

            const label = settingsForm.querySelector('label[for="' + field.id + '"]');
            return label ? String(label.textContent || '').trim() || 'this field' : 'this field';
        }

        function getCurrentGuidedField() {
            for (let i = 0; i < guidedFields.length; i++) {
                if (!fieldHasValue(guidedFields[i])) {
                    return guidedFields[i];
                }
            }

            return null;
        }

        function isGuidedSetupComplete() {
            return guidedFields.every(fieldHasValue);
        }

        function isSetupPanelActive() {
            const page = document.querySelector('.matewa-dashboard-page');
            return page && page.getAttribute('data-matewa-active-panel') === 'setup';
        }

        function clearGuidedStepHelpers() {
            guidedFields.forEach(function (field) {
                const row = field ? field.closest('.matewa-field-row') : null;
                const helper = row ? row.querySelector('.matewa-guided-step-helper') : null;

                if (helper) {
                    helper.hidden = true;
                    helper.classList.remove('is-visible');
                    helper.textContent = '';
                }

                if (row) {
                    row.classList.remove('is-guided-blocked');
                }

                if (field) {
                    field.classList.remove('is-guided-blocked');
                }
            });
        }

        function showGuidedStepHelper(field, message) {
            if (!field) {
                return;
            }

            const row = field.closest('.matewa-field-row');
            const control = field.closest('.matewa-field-control');

            if (!row || !control) {
                return;
            }

            clearGuidedStepHelpers();

            let helper = control.querySelector('.matewa-guided-step-helper');

            if (!helper) {
                helper = document.createElement('span');
                helper.className = 'matewa-guided-step-helper';
                helper.setAttribute('role', 'status');
                helper.setAttribute('aria-live', 'polite');
                helper.hidden = true;
                control.appendChild(helper);
            }

            helper.textContent = message;
            helper.hidden = false;
            helper.classList.add('is-visible');
            row.classList.add('is-guided-blocked');
            field.classList.add('is-guided-blocked');

            window.setTimeout(function () {
                helper.hidden = true;
                helper.classList.remove('is-visible');
                row.classList.remove('is-guided-blocked');
                field.classList.remove('is-guided-blocked');
            }, 2600);
        }

        function updateGuidedField(field, currentField) {
            if (!field || field.disabled) {
                return;
            }

            const hasValue = fieldHasValue(field);
            const isCurrent = currentField && field === currentField;
            const isAhead = currentField && guidedFields.indexOf(field) > guidedFields.indexOf(currentField);
            const row = field.closest('.matewa-field-row');

            field.classList.add('matewa-guided-input');
            field.classList.toggle('is-awaiting-input', Boolean(isCurrent && !hasValue));
            field.classList.toggle('is-current-guided-step', Boolean(isCurrent));
            field.classList.toggle('is-guided-ahead', Boolean(isAhead));
            field.classList.toggle('has-guided-value', hasValue);

            if (row) {
                row.classList.add('matewa-guided-field-row');
                row.classList.toggle('is-awaiting-input', Boolean(isCurrent && !hasValue));
                row.classList.toggle('is-current-guided-step', Boolean(isCurrent));
                row.classList.toggle('is-guided-ahead', Boolean(isAhead));
                row.classList.toggle('has-guided-value', hasValue);
            }
        }

        function updateGuidedFields() {
            const currentField = getCurrentGuidedField();
            guidedFields.forEach(function (field) {
                updateGuidedField(field, currentField);
            });
        }

        function setSaveButtonState(state) {
            const isReady = state === 'ready';
            const isSaving = state === 'saving';
            const isSaved = state === 'saved';

            saveButtons.forEach(function (button) {
                const nextLabel = isSaving
                    ? buttonLabel(button, 'data-matewa-save-saving-label', 'Saving…')
                    : isSaved
                        ? buttonLabel(button, 'data-matewa-save-saved-label', 'Saved')
                        : isReady
                            ? buttonLabel(button, 'data-matewa-save-ready-label', 'Ready to save')
                            : buttonLabel(button, 'data-matewa-save-default-label', 'Save changes');

                button.textContent = nextLabel;
                button.setAttribute('data-matewa-save-state', state);
                button.classList.toggle('is-ready-to-save', isReady);
                button.classList.toggle('is-saving', isSaving);
                button.classList.toggle('is-saved', isSaved);
                button.setAttribute('aria-label', nextLabel);
            });
        }

        function refreshSaveButtonState() {
            pendingFrame = null;

            if (submitted) {
                return;
            }

            const dirty = isFormDirty();
            const setupIncomplete = isSetupPanelActive() && !isGuidedSetupComplete();
            setSaveButtonState(dirty && !setupIncomplete ? 'ready' : 'clean');
        }

        function scheduleRefresh() {
            if (submitted) {
                return;
            }

            updateGuidedFields();
            hideSaveGuardHelper();

            if (savedTimer) {
                window.clearTimeout(savedTimer);
                savedTimer = null;
            }

            if (pendingFrame) {
                if (window.cancelAnimationFrame) {
                    window.cancelAnimationFrame(pendingFrame);
                } else {
                    window.clearTimeout(pendingFrame);
                }
            }

            if (window.requestAnimationFrame) {
                pendingFrame = window.requestAnimationFrame(refreshSaveButtonState);
            } else {
                pendingFrame = window.setTimeout(refreshSaveButtonState, 0);
            }
        }

        initialSnapshot = formSnapshot();
        updateGuidedFields();
        const setupWasCompleteOnLoad = isGuidedSetupComplete();

        guidedFields.forEach(function (field) {
            field.addEventListener('focus', function () {
                const row = field.closest('.matewa-field-row');
                const currentField = getCurrentGuidedField();
                const currentIndex = currentField ? guidedFields.indexOf(currentField) : -1;
                const fieldIndex = guidedFields.indexOf(field);

                field.classList.add('is-guided-focus');

                if (row) {
                    row.classList.add('is-guided-focus');
                }

                if (currentField && fieldIndex > currentIndex) {
                    showGuidedStepHelper(field, '🚫 Complete ' + getFieldLabel(currentField) + ' first.');
                }
            });

            field.addEventListener('blur', function () {
                const row = field.closest('.matewa-field-row');
                field.classList.remove('is-guided-focus');

                if (row) {
                    row.classList.remove('is-guided-focus');
                }
            });
        });

        if (saveButtons.some(function (button) { return button.getAttribute('data-matewa-save-state') === 'saved'; })) {
            setSaveButtonState('saved');
            savedTimer = window.setTimeout(function () {
                savedTimer = null;
                setSaveButtonState('clean');
            }, 1900);
        } else {
            setSaveButtonState('clean');
        }

        settingsForm.addEventListener('input', function (event) {
            if (guidedFields.indexOf(event.target) !== -1) {
                updateGuidedFields();
            }

            scheduleRefresh();
        }, true);

        settingsForm.addEventListener('change', function (event) {
            if (guidedFields.indexOf(event.target) !== -1) {
                updateGuidedFields();
            }

            scheduleRefresh();
        }, true);

        settingsForm.addEventListener('submit', function (event) {
            updateGuidedFields();

            const submitter = event.submitter || document.activeElement;

            if (typeof window.matewaPreparePendingIndustrySuggestionForSubmit === 'function') {
                window.matewaPreparePendingIndustrySuggestionForSubmit(submitter);
            }

            const submitterName = submitter && submitter.name ? String(submitter.name) : '';
            const isSaveAndRefreshLicence = submitterName === 'matewa_save_and_refresh_license';
            const isAgencyClientPackSubmit = submitterName === 'matewa_agency_client_pack_delete_id' || submitterName === 'matewa_agency_client_pack_action';
            const isAgencyBundleSubmit = submitterName === 'matewa_agency_bundle_action';
            const isAgencySetupRequestSubmit = submitterName === 'matewa_agency_setup_request_action';
            const isAgencyRoutingSubmit = submitterName === 'matewa_agency_routing_action';
            const bypassDirtyAndGuidedSaveGuard = isSaveAndRefreshLicence || isAgencyClientPackSubmit || isAgencyBundleSubmit || isAgencySetupRequestSubmit || isAgencyRoutingSubmit;

            if (!bypassDirtyAndGuidedSaveGuard && !isFormDirty()) {
                event.preventDefault();
                submitted = false;
                setSaveButtonState('clean');
                showSaveGuardHelper('Make a change first — then the button will show Ready to save.');
                return;
            }

            if (!bypassDirtyAndGuidedSaveGuard && isSetupPanelActive() && !isGuidedSetupComplete()) {
                const currentField = getCurrentGuidedField();
                event.preventDefault();
                submitted = false;
                setSaveButtonState('clean');
                showSaveGuardHelper('🚫 Complete ' + getFieldLabel(currentField) + ' first — then Ready to save appears.');

                if (currentField && typeof currentField.focus === 'function') {
                    currentField.focus({ preventScroll: false });
                }

                return;
            }

            if (isSetupPanelActive() && !setupWasCompleteOnLoad && isGuidedSetupComplete() && returnSectionInput) {
                returnSectionInput.value = 'buttons';
            }

            hideSaveGuardHelper();
            submitted = true;
            setSaveButtonState('saving');
        });
    })();

    (function () {
        const panel = document.querySelector('[data-matewa-agency-setup-request]');
        if (!panel) {
            return;
        }

        const nameField = panel.querySelector('[data-matewa-setup-request-field="name"]');
        const emailField = panel.querySelector('[data-matewa-setup-request-field="email"]');
        const domainField = panel.querySelector('[data-matewa-setup-request-field="domain"]');
        const messageField = panel.querySelector('[data-matewa-setup-request-message]');
        const copyButton = panel.querySelector('[data-matewa-copy-setup-request]');
        const copyStatus = panel.querySelector('[data-matewa-copy-setup-request-status]');
        const agencyName = String(panel.getAttribute('data-matewa-agency-name') || 'your agency').trim() || 'your agency';

        if (!messageField) {
            return;
        }

        function fieldValue(field) {
            return String((field && field.value) || '').trim();
        }

        function buildMessage() {
            const clientName = fieldValue(nameField);
            const domain = fieldValue(domainField);
            let message = 'Hi' + (clientName ? ' ' + clientName : '') + ',\n\n';
            message += 'We are setting up your 247ChatMate WhatsApp lead capture on your website';
            if (domain) {
                message += ' for ' + domain;
            }
            message += '. Please reply with the details below so we can prepare your setup pack.\n\n';
            message += '1. Business name\n';
            message += '2. Website/domain\n';
            message += '3. WhatsApp mobile/cell number for customer enquiries\n';
            message += '4. Main admin email\n';
            message += '5. Leads email for enquiry alerts\n';
            message += '6. Pages where the widget should appear\n';
            message += '7. Business type/category\n';
            message += '8. Preferred visitor buttons or common customer questions\n';
            message += '9. Any Google Business Profile, Instagram or review links you want included later\n\n';
            message += 'Once we have this, we will create your client setup pack and confirm anything unclear before installation.\n\n';
            message += 'Thanks,\n' + agencyName;
            return message;
        }

        function refreshMessage() {
            messageField.value = buildMessage();
        }

        [nameField, emailField, domainField].forEach(function (field) {
            if (!field) {
                return;
            }
            field.addEventListener('input', refreshMessage);
            field.addEventListener('change', refreshMessage);
        });

        if (copyButton) {
            copyButton.addEventListener('click', function () {
                refreshMessage();
                const message = messageField.value;
                const done = function () {
                    if (copyStatus) {
                        copyStatus.textContent = 'Message copied.';
                        window.setTimeout(function () {
                            copyStatus.textContent = '';
                        }, 2200);
                    }
                };
                const failed = function () {
                    messageField.removeAttribute('readonly');
                    messageField.focus();
                    messageField.select();
                    try {
                        document.execCommand('copy');
                        done();
                    } catch (e) {
                        if (copyStatus) {
                            copyStatus.textContent = 'Select the message and copy manually.';
                        }
                    }
                    messageField.setAttribute('readonly', 'readonly');
                };

                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(message).then(done).catch(failed);
                } else {
                    failed();
                }
            });
        }

        refreshMessage();
    })();

    if (dashboardShell && dashboardThemeButtons.length) {
        const storageKey = 'matewaDashboardTheme';

        function applyDashboardTheme(theme) {
            const safeTheme = theme === 'dark' ? 'dark' : 'light';

            dashboardShell.setAttribute('data-matewa-dashboard-theme', safeTheme);
            dashboardShell.setAttribute('data-matewa-user-theme', '1');

            if (dashboardPage) {
                dashboardPage.setAttribute('data-matewa-dashboard-theme', safeTheme);
                dashboardPage.setAttribute('data-matewa-user-theme', '1');
            }

            dashboardThemeButtons.forEach(function (button) {
                const isActive = button.getAttribute('data-matewa-dashboard-theme-option') === safeTheme;
                button.classList.toggle('is-active', isActive);
                button.setAttribute('aria-pressed', isActive ? 'true' : 'false');
            });
        }

        // Default to the light dashboard every time the settings page opens.
        // Dark mode remains available as a manual view option for the current page view only.
        applyDashboardTheme('light');

        try {
            if (window.localStorage) {
                window.localStorage.removeItem(storageKey);
            }
        } catch (e) {
            // Keep the server-rendered light theme if browser storage is unavailable.
        }

        dashboardThemeButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                const requestedTheme = button.getAttribute('data-matewa-dashboard-theme-option') === 'dark' ? 'dark' : 'light';

                applyDashboardTheme(requestedTheme);

                // Do not persist the manual colour mode. The dashboard should reopen in light mode.
            });
        });
    }

    /*
     * Phase 5-A-14E/5-A-14F: Dashboard Leads/Status circle toggle.
     * View-only switching for circles and matching right rail.
     * Does not count leads, call remote services or alter frontend/widget behaviour.
     */
    (function () {
        const circlePanel = document.querySelector('[data-matewa-circle-view-default]');
        const circleToggles = Array.from(document.querySelectorAll('[data-matewa-circle-view-toggle]'));
        const circleViews = Array.from(document.querySelectorAll('[data-matewa-circle-view]'));
        const circleHeading = document.querySelector('[data-matewa-circle-heading]');
        const sidebarViews = Array.from(document.querySelectorAll('[data-matewa-circle-sidebar-view]'));
        const heroStatusPills = document.querySelector('[data-matewa-hero-status-pills]');

        if (!circlePanel || !circleToggles.length || !circleViews.length) {
            return;
        }

        function normaliseCircleView(view) {
            const requestedView = String(view || '');
            const allowedViews = circleViews
                .map(function (item) { return item.getAttribute('data-matewa-circle-view') || ''; })
                .filter(Boolean);

            if (allowedViews.indexOf(requestedView) !== -1) {
                return requestedView;
            }

            if (allowedViews.indexOf('leads') !== -1) {
                return 'leads';
            }

            return allowedViews[0] || 'leads';
        }

        function applyCircleView(view) {
            const activeView = normaliseCircleView(view);
            circlePanel.setAttribute('data-matewa-active-circle-view', activeView);

            circleViews.forEach(function (item) {
                const isActive = item.getAttribute('data-matewa-circle-view') === activeView;
                item.classList.toggle('is-active', isActive);

                if (isActive) {
                    item.removeAttribute('hidden');
                    item.setAttribute('aria-hidden', 'false');

                    if (circleHeading) {
                        circleHeading.textContent = item.getAttribute('data-matewa-circle-heading') || (activeView === 'status' ? 'Setup health' : 'Lead activity');
                    }
                } else {
                    item.setAttribute('hidden', 'hidden');
                    item.setAttribute('aria-hidden', 'true');
                }
            });

            circleToggles.forEach(function (button) {
                const isActive = button.getAttribute('data-matewa-circle-view-toggle') === activeView;
                button.classList.toggle('is-active', isActive);
                button.setAttribute('aria-pressed', isActive ? 'true' : 'false');
            });

            sidebarViews.forEach(function (item) {
                const isActive = item.getAttribute('data-matewa-circle-sidebar-view') === activeView;
                item.classList.toggle('is-active', isActive);

                if (isActive) {
                    item.removeAttribute('hidden');
                    item.setAttribute('aria-hidden', 'false');
                } else {
                    item.setAttribute('hidden', 'hidden');
                    item.setAttribute('aria-hidden', 'true');
                }
            });

            if (heroStatusPills) {
                if (activeView === 'status') {
                    heroStatusPills.setAttribute('hidden', 'hidden');
                    heroStatusPills.setAttribute('aria-hidden', 'true');
                } else {
                    heroStatusPills.removeAttribute('hidden');
                    heroStatusPills.setAttribute('aria-hidden', 'false');
                }
            }
        }

        applyCircleView(circlePanel.getAttribute('data-matewa-circle-view-default') || 'leads');

        circleToggles.forEach(function (button) {
            button.addEventListener('click', function () {
                applyCircleView(button.getAttribute('data-matewa-circle-view-toggle') || 'leads');
            });
        });
    })();

    /*
     * Phase 5-A-13: Admin page split navigation.
     * Visual/page-state only. Does not change settings fields, save handling,
     * vertical JSON, chip logic, licence logic, widget behaviour or WhatsApp handoff.
     */
    (function () {
        const page = document.querySelector('.matewa-dashboard-page');
        const tabs = Array.from(document.querySelectorAll('[data-matewa-admin-tab]'));
        const titleEl = document.querySelector('[data-matewa-admin-page-title]');
        const descriptionEl = document.querySelector('[data-matewa-admin-page-description]');
        const saveConfirmation = document.querySelector('[data-matewa-save-confirmation]');
        let saveConfirmationDismissed = false;
        let saveConfirmationTimer = null;
        let panelTransitionTimer = null;
        let panelTransitionFrame = null;
        let panelNavigationLocked = false;
        let panelNavigationLockTimer = null;

        if (!page || !tabs.length) {
            return;
        }

        const copy = {
            dashboard: {
                title: 'Dashboard',
                description: ''
            },
            setup: {
                title: 'Setup',
                description: ''
            },
            agency: {
                title: 'Agency Hub',
                description: 'Manage agency access, client seats and setup packs.'
            },
            display: {
                title: 'Appearance & pages',
                description: ''
            },
            buttons: {
                title: 'Visitor buttons',
                description: ''
            },
        };

        const hashToPanel = {
            '#matewa-dashboard-top': 'dashboard',
            '#matewa-admin-panel-dashboard': 'dashboard',
            '#matewa-core-settings-section': 'setup',
            '#matewa-settings-form': 'setup',
            '#matewa_number': 'setup',
            '#matewa_business_name': 'setup',
            '#matewa_leads_email': 'setup',
            '#matewa_marketing_email': 'setup',
            '#matewa-setup-lead-tools': 'setup',
            '#matewa-client-mail-delivery-options': 'setup',
            '#matewa-setup-support-diagnostics-heading': 'setup',
            '#matewa-agency-client-setup-key-panel': 'setup',
            '#matewa-agency-client-setup-key-agency-panel': 'agency',
            '#matewa-agency-client-import-panel': 'agency',
            '#matewa-agency-client-import-fallback': 'agency',
            '#matewa-agency-client-pdf-upload-panel': 'agency',
            '#matewa_license_key': 'setup',
            '#matewa-agency-hub-section': 'agency',
            '#matewa-admin-panel-agency': 'agency',
            '#matewa-agency-remote-push-panel': 'agency',
            '#matewa-agency-remote-push-test-panel': 'agency',
            '#matewa-display-settings-section': 'display',
            '#matewa-chip-labels-section': 'buttons'
        };

        const panelToHash = {
            dashboard: '#matewa-dashboard-top',
            setup: '#matewa-core-settings-section',
            agency: '#matewa-agency-hub-section',
            display: '#matewa-display-settings-section',
            buttons: '#matewa-chip-labels-section'
        };

        function normalisePanel(panel) {
            return copy[panel] ? panel : 'dashboard';
        }

        function currentPanelForTransition() {
            const panel = page.getAttribute('data-matewa-active-panel') || '';
            return copy[panel] ? panel : '';
        }

        function prefersReducedMotion() {
            return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
        }

        function clearPanelTransition() {
            if (panelTransitionFrame && window.cancelAnimationFrame) {
                window.cancelAnimationFrame(panelTransitionFrame);
            }

            panelTransitionFrame = null;

            if (panelTransitionTimer) {
                window.clearTimeout(panelTransitionTimer);
                panelTransitionTimer = null;
            }

            page.classList.remove('is-admin-panel-transitioning', 'is-admin-panel-entered');
            page.removeAttribute('data-matewa-transition-from');
            page.removeAttribute('data-matewa-transition-to');
        }

        function beginPanelTransition(previousPanel, nextPanel) {
            if (!previousPanel || previousPanel === nextPanel || prefersReducedMotion()) {
                return false;
            }

            clearPanelTransition();
            page.setAttribute('data-matewa-transition-from', previousPanel);
            page.setAttribute('data-matewa-transition-to', nextPanel);
            page.classList.add('is-admin-panel-transitioning');

            return true;
        }

        function commitPanelTransition() {
            const startTransition = function () {
                page.classList.add('is-admin-panel-entered');
            };

            if (window.requestAnimationFrame) {
                panelTransitionFrame = window.requestAnimationFrame(startTransition);
            } else {
                startTransition();
            }

            panelTransitionTimer = window.setTimeout(clearPanelTransition, 210);
        }

        function releasePanelNavigationLock() {
            panelNavigationLocked = false;

            if (panelNavigationLockTimer) {
                window.clearTimeout(panelNavigationLockTimer);
                panelNavigationLockTimer = null;
            }

            page.removeAttribute('data-matewa-panel-navigation-locked');
        }

        function schedulePanelNavigationUnlock(delay) {
            if (panelNavigationLockTimer) {
                window.clearTimeout(panelNavigationLockTimer);
            }

            panelNavigationLockTimer = window.setTimeout(releasePanelNavigationLock, delay);
        }

        function activatePanelSafely(panel, moveFocus, shouldScroll) {
            const requestedPanel = normalisePanel(panel);
            const currentPanel = normalisePanel(page.getAttribute('data-matewa-active-panel') || 'dashboard');

            if (panelNavigationLocked) {
                return false;
            }

            panelNavigationLocked = true;
            page.setAttribute('data-matewa-panel-navigation-locked', 'true');

            try {
                activatePanel(requestedPanel, moveFocus, shouldScroll);
            } catch (error) {
                releasePanelNavigationLock();
                throw error;
            }

            schedulePanelNavigationUnlock(requestedPanel === currentPanel || prefersReducedMotion() ? 90 : 260);
            return true;
        }

        function guardedScrollToShell() {
            const shell = document.querySelector('.matewa-dashboard-shell');
            if (!shell) {
                return;
            }

            const rect = shell.getBoundingClientRect();
            const shellAlreadyVisible = rect.top >= -24 && rect.top <= 72;

            if (shellAlreadyVisible) {
                return;
            }

            shell.scrollIntoView({ block: 'start', behavior: prefersReducedMotion() ? 'auto' : 'smooth' });
        }

        function setReturnSection(panel) {
            if (!returnSectionInput) {
                return;
            }

            returnSectionInput.value = normalisePanel(panel);
        }

        function dismissSaveConfirmation(immediate) {
            if (!saveConfirmation || saveConfirmationDismissed) {
                return;
            }

            saveConfirmationDismissed = true;

            if (saveConfirmationTimer) {
                window.clearTimeout(saveConfirmationTimer);
                saveConfirmationTimer = null;
            }

            if (immediate) {
                saveConfirmation.remove();
                return;
            }

            saveConfirmation.classList.add('is-dismissing');
            saveConfirmation.style.transition = 'opacity 180ms ease';
            saveConfirmation.style.opacity = '0';

            window.setTimeout(function () {
                if (saveConfirmation && saveConfirmation.parentNode) {
                    saveConfirmation.remove();
                }
            }, 220);
        }

        function cleanSaveNoticeFromUrl(activePanel) {
            try {
                const url = new URL(window.location.href);
                let changed = false;

                ['matewa_settings_saved', 'settings-updated', 'matewa_saved_section'].forEach(function (key) {
                    if (url.searchParams.has(key)) {
                        url.searchParams.delete(key);
                        changed = true;
                    }
                });

                if (url.hash) {
                    url.hash = '';
                    changed = true;
                }

                if (!changed) {
                    return;
                }

                window.history.replaceState(null, '', url.toString());
            } catch (e) {
                // URL cleanup is cosmetic only; the rendered panel state remains authoritative.
            }
        }

        function clearHashWithoutScrolling() {
            try {
                const url = new URL(window.location.href);

                if (!url.hash) {
                    return;
                }

                url.hash = '';
                window.history.replaceState(null, '', url.toString());
            } catch (e) {
                // Cosmetic only. The hidden return-section input controls save return state.
            }
        }

        function armSaveConfirmation(activePanel) {
            if (!saveConfirmation || saveConfirmationDismissed) {
                return;
            }

            const savedPanel = normalisePanel(saveConfirmation.getAttribute('data-matewa-save-panel') || activePanel || 'dashboard');
            const currentPanel = normalisePanel(activePanel || page.getAttribute('data-matewa-active-panel') || 'dashboard');

            if (savedPanel !== currentPanel) {
                dismissSaveConfirmation(true);
                return;
            }

            if (saveConfirmationTimer) {
                window.clearTimeout(saveConfirmationTimer);
            }

            saveConfirmationTimer = window.setTimeout(function () {
                dismissSaveConfirmation(false);
            }, 3200);
        }

        function activatePanel(panel, moveFocus, shouldScroll) {
            const activePanel = normalisePanel(panel);
            const activeCopy = copy[activePanel] || copy.dashboard;
            const previousPanel = currentPanelForTransition();
            const shouldTransition = beginPanelTransition(previousPanel, activePanel);

            page.setAttribute('data-matewa-active-panel', activePanel);
            setReturnSection(activePanel);

            if (activePanel === 'buttons') {
                window.setTimeout(function () {
                    try {
                        document.dispatchEvent(new CustomEvent('matewa:buttons-panel-visible'));
                    } catch (e) {
                        // Older browsers can ignore this visual refresh signal.
                    }
                }, 0);
            }

            tabs.forEach(function (tab) {
                const isActive = tab.getAttribute('data-matewa-admin-tab') === activePanel;
                tab.classList.toggle('is-active', isActive);

                if (isActive) {
                    tab.setAttribute('aria-current', 'page');
                } else {
                    tab.removeAttribute('aria-current');
                }
            });

            if (titleEl) {
                titleEl.textContent = activeCopy.title;
            }

            if (descriptionEl) {
                const activeDescription = activeCopy.description || '';
                descriptionEl.textContent = activeDescription;

                if (activeDescription) {
                    descriptionEl.removeAttribute('hidden');
                    descriptionEl.setAttribute('aria-hidden', 'false');
                } else {
                    descriptionEl.setAttribute('hidden', 'hidden');
                    descriptionEl.setAttribute('aria-hidden', 'true');
                }
            }

            if (moveFocus && titleEl) {
                titleEl.setAttribute('tabindex', '-1');
                titleEl.focus({ preventScroll: true });
            }

            if (shouldTransition) {
                commitPanelTransition();
            }

            if (shouldScroll) {
                guardedScrollToShell();
            }
        }

        function panelFromHash(hash) {
            return hashToPanel[String(hash || '')] || '';
        }

        tabs.forEach(function (tab) {
            tab.addEventListener('click', function (event) {
                const requestedPanel = tab.getAttribute('data-matewa-admin-tab');
                if (!requestedPanel) {
                    return;
                }

                event.preventDefault();
                if (!activatePanelSafely(requestedPanel, false, true)) {
                    return;
                }

                dismissSaveConfirmation(true);
                clearHashWithoutScrolling();
            });
        });

        document.addEventListener('click', function (event) {
            const link = event.target && event.target.closest ? event.target.closest('a[href^="#"]') : null;

            if (!link || link.hasAttribute('data-matewa-admin-tab')) {
                return;
            }

            const panel = panelFromHash(link.getAttribute('href'));
            if (!panel) {
                return;
            }

            event.preventDefault();
            if (!activatePanelSafely(panel, false, true)) {
                return;
            }

            dismissSaveConfirmation(true);
            clearHashWithoutScrolling();
        });

        let lastSettingsSubmitter = null;

        function inferReturnSectionFromElement(element) {
            if (!element || !element.closest) {
                return '';
            }

            if (element.closest('#matewa-chip-labels-section')) {
                return 'buttons';
            }

            if (element.closest('#matewa-display-settings-section')) {
                return 'display';
            }

            if (element.closest('#matewa-core-settings-section') || element.closest('#matewa-admin-panel-setup')) {
                return page.getAttribute('data-matewa-active-panel') === 'display' ? 'display' : 'setup';
            }

            return '';
        }

        Array.from(document.querySelectorAll('[type="submit"][form="matewa-settings-form"], #matewa-settings-form button[type="submit"], #matewa-settings-form input[type="submit"]')).forEach(function (button) {
            button.addEventListener('click', function () {
                lastSettingsSubmitter = button;
            });
        });

        settingsForm.addEventListener('submit', function (event) {
            const activePanel = normalisePanel(page.getAttribute('data-matewa-active-panel') || panelFromHash(window.location.hash) || 'setup');
            const submitter = event.submitter || lastSettingsSubmitter;
            const inferred = inferReturnSectionFromElement(submitter) || activePanel;

            setReturnSection(inferred);
            clearHashWithoutScrolling();

            // Do not set a panel hash during submit.
            // The hidden return section and server redirect are the authoritative save target.
            // Clearing any existing hash prevents browser anchor jump/judder on reload.
        });

        function panelFromQuery() {
            try {
                const params = new URLSearchParams(window.location.search || '');
                return normalisePanel(params.get('matewa_saved_section') || page.getAttribute('data-matewa-active-panel') || 'dashboard');
            } catch (e) {
                return normalisePanel(page.getAttribute('data-matewa-active-panel') || 'dashboard');
            }
        }

        const initialPanel = panelFromHash(window.location.hash) || panelFromQuery();
        activatePanel(initialPanel, false, false);
        armSaveConfirmation(initialPanel);

        try {
            const params = new URLSearchParams(window.location.search || '');
            if (params.get('matewa_scroll_target') === 'agency_remote_push') {
                window.setTimeout(function () {
                    const remotePanel = document.getElementById('matewa-agency-remote-push-panel');
                    if (remotePanel) {
                        remotePanel.open = true;
                        remotePanel.scrollIntoView({ block: 'center', behavior: prefersReducedMotion() ? 'auto' : 'smooth' });
                    }
                }, 260);
            }

            if (params.get('matewa_scroll_target') === 'setup_key' || params.has('matewa_setup_key_notice')) {
                window.setTimeout(function () {
                    const target = document.getElementById('matewa-setup-agency-key')
                        || document.getElementById('matewa-agency-client-setup-key-panel')
                        || document.getElementById('matewa-agency-client-setup-key-agency-panel');
                    if (!target) {
                        return;
                    }

                    const details = target.matches('details') ? target : target.querySelector('details');
                    if (details) {
                        details.open = true;
                    }

                    target.scrollIntoView({ block: 'center', behavior: prefersReducedMotion() ? 'auto' : 'smooth' });

                    const generatedKey = document.getElementById('matewa_agency_client_setup_key_plain');
                    if (generatedKey && typeof generatedKey.select === 'function') {
                        generatedKey.focus({ preventScroll: true });
                        generatedKey.select();
                    }
                }, 320);
            }


            if (params.get('matewa_scroll_target') === 'client_mail_delivery' || params.has('matewa_client_mail_notice')) {
                window.setTimeout(function () {
                    const target = document.getElementById('matewa-client-mail-delivery-options')
                        || document.getElementById('matewa-setup-lead-tools');
                    if (!target) {
                        return;
                    }

                    const details = target.matches('details') ? target : target.querySelector('details');
                    if (details) {
                        details.open = true;
                    }

                    target.scrollIntoView({ block: 'center', behavior: prefersReducedMotion() ? 'auto' : 'smooth' });
                }, 320);
            }

            if (params.get('matewa_scroll_target') === 'lead_tools' || params.has('matewa_weekly_summary_notice') || params.has('matewa_fallback_mail_notice')) {
                window.setTimeout(function () {
                    const target = document.getElementById('matewa-setup-lead-tools')
                        || document.getElementById('matewa-core-settings-section');
                    if (!target) {
                        return;
                    }

                    target.scrollIntoView({ block: 'center', behavior: prefersReducedMotion() ? 'auto' : 'smooth' });
                }, 320);
            }
        } catch (e) {
            // Scroll target is a convenience only; the Agency Hub panel still opens from query state.
        }

        cleanSaveNoticeFromUrl(initialPanel);
    })();

    /*
     * Phase 5-A-21O: Keep Plan & Licence calm by showing only one details
     * panel at a time. Browser-local UI state only; support diagnostics never
     * auto-open. Does not affect entitlement, trial, licence validation,
     * registry calls or saved plugin settings.
     */
    (function () {
        const planSections = Array.from(document.querySelectorAll('details[data-matewa-plan-section]'));

        if (!planSections.length) {
            return;
        }

        const storageKey = 'matewaPlanAccessOpenSectionV2';
        const oldStorageKey = 'matewaPlanAccessOpenSection';
        let isSyncing = false;

        function normaliseSection(section) {
            section = String(section || '');

            if ('advanced' === section) {
                return '';
            }

            return section;
        }

        function getStoredSection() {
            try {
                return window.localStorage ? normaliseSection(window.localStorage.getItem(storageKey) || '') : '';
            } catch (e) {
                return '';
            }
        }

        function setStoredSection(section) {
            try {
                if (!window.localStorage) return;

                section = normaliseSection(section);

                if (section && 'support' !== section) {
                    window.localStorage.setItem(storageKey, section);
                } else {
                    window.localStorage.removeItem(storageKey);
                }
            } catch (e) {
                // Details panels still work normally without browser storage.
            }
        }

        try {
            if (window.localStorage) {
                window.localStorage.removeItem(oldStorageKey);
            }
        } catch (e) {
            // Old visual state cleanup is optional.
        }

        const storedSection = getStoredSection();

        if (storedSection) {
            isSyncing = true;
            planSections.forEach(function (section) {
                section.open = section.getAttribute('data-matewa-plan-section') === storedSection;
            });
            isSyncing = false;
        } else {
            planSections.forEach(function (section) {
                section.open = false;
            });
        }

        planSections.forEach(function (section) {
            section.addEventListener('toggle', function () {
                if (isSyncing) {
                    return;
                }

                if (section.open) {
                    const activeSection = section.getAttribute('data-matewa-plan-section') || '';

                    isSyncing = true;
                    planSections.forEach(function (candidate) {
                        if (candidate !== section) {
                            candidate.open = false;
                        }
                    });
                    isSyncing = false;

                    setStoredSection(activeSection);
                } else if (!planSections.some(function (candidate) { return candidate.open; })) {
                    setStoredSection('');
                }
            });
        });
    })();

    /*
     * Phase 5-A-10: Licence checkout refresh nudge.
     * Browser-local visual guidance only. A checkout click is never treated as
     * proof of purchase and never changes entitlement or validation logic.
     */
    (function () {
        const storageKey = 'matewaLicenceCheckoutRefreshNudge';
        const triggers = Array.from(document.querySelectorAll('[data-matewa-checkout-nudge-trigger]'));
        const panels = Array.from(document.querySelectorAll('[data-matewa-checkout-nudge-panel], [data-matewa-checkout-nudge-card]'));
        const dismissButtons = Array.from(document.querySelectorAll('[data-matewa-checkout-nudge-dismiss]'));
        const licenceCheckCards = Array.from(document.querySelectorAll('[data-matewa-license-check-card]'));
        const licenceCheckForms = Array.from(document.querySelectorAll('[data-matewa-license-check-form]'));
        const focusLinks = Array.from(document.querySelectorAll('[data-matewa-licence-check-focus]'));

        if (!triggers.length && !panels.length && !licenceCheckCards.length) {
            return;
        }

        function setStoredActive(isActive) {
            try {
                if (!window.localStorage) return;

                if (isActive) {
                    window.localStorage.setItem(storageKey, '1');
                } else {
                    window.localStorage.removeItem(storageKey);
                }
            } catch (e) {
                // The nudge remains a current-page visual helper when storage is unavailable.
            }
        }

        function getStoredActive() {
            try {
                return !!window.localStorage && window.localStorage.getItem(storageKey) === '1';
            } catch (e) {
                return false;
            }
        }

        function setNudgeActive(isActive) {
            panels.forEach(function (panel) {
                panel.hidden = !isActive;
            });

            licenceCheckCards.forEach(function (card) {
                card.classList.toggle('is-checkout-nudge-active', isActive);
            });

            if (dashboardShell) {
                dashboardShell.classList.toggle('is-checkout-nudge-active', isActive);
            }
        }

        function clearNudge() {
            setStoredActive(false);
            setNudgeActive(false);
        }

        setNudgeActive(getStoredActive());

        triggers.forEach(function (trigger) {
            trigger.addEventListener('click', function () {
                setStoredActive(true);
                setNudgeActive(true);
            });
        });

        dismissButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                clearNudge();
            });
        });

        licenceCheckForms.forEach(function (form) {
            form.addEventListener('submit', function () {
                clearNudge();
            });
        });

        focusLinks.forEach(function (link) {
            link.addEventListener('click', function () {
                const target = document.getElementById('matewa-licence-check-card');

                if (!target) return;

                target.classList.add('is-checkout-nudge-active');
            });
        });
    })();

    if (displayModeCheckboxes.length > 1) {
        function ensureOneDisplayModeCheckbox(activeCheckbox) {
            if (!activeCheckbox) return;

            displayModeCheckboxes.forEach(function (checkbox) {
                checkbox.checked = checkbox === activeCheckbox;
            });
        }

        displayModeCheckboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                if (checkbox.checked) {
                    ensureOneDisplayModeCheckbox(checkbox);
                    return;
                }

                const anyChecked = displayModeCheckboxes.some(function (item) {
                    return item.checked;
                });

                if (!anyChecked) {
                    const fallback = displayModeCheckboxes.find(function (item) {
                        return item.value === 'all';
                    }) || displayModeCheckboxes[0];

                    ensureOneDisplayModeCheckbox(fallback);
                }
            });
        });
    }

    const categorySelect = document.getElementById('matewa_vertical_category_selected');
    const verticalSelect = document.getElementById('matewa_vertical_selected');
    const selectorDataEl = document.getElementById('matewa-vertical-selector-data');
    const previewGrid = document.getElementById('matewa-chip-preview-grid');
    const manualSelectorDataEl = document.getElementById('matewa-manual-vertical-selector-data');

    /*
     * Guard:
     * If the newer manual preview UI exists, do not let this older auto-preview
     * logic interfere with the manual preview/button selector flow.
     */
    if (!manualSelectorDataEl && categorySelect && verticalSelect && selectorDataEl) {
        let selectorData = {};
        const initialPreviewHtml = previewGrid ? previewGrid.innerHTML : '';

        try {
            selectorData = JSON.parse(selectorDataEl.textContent || '{}');
        } catch (e) {
            selectorData = {};
        }

        function renderPreviewForSelected() {
            if (!previewGrid) return;

            const loadedVertical = String(previewGrid.dataset.loadedVertical || '');
            const verticalKey = String(verticalSelect.value || '');

            if (verticalKey && loadedVertical && verticalKey === loadedVertical) {
                previewGrid.innerHTML = initialPreviewHtml;
                return;
            }

            previewGrid.innerHTML = '';

            const message = document.createElement('div');
            message.className = 'matewa-chip-preview-subtle';
            message.style.gridColumn = '1 / -1';
            message.textContent = 'Save settings to load this business type preview.';

            previewGrid.appendChild(message);
        }

        function rebuildVerticalOptions(preserveValue) {
            const categoryKey = String(categorySelect.value || '');
            const categoryData = selectorData[categoryKey] || null;
            const options = categoryData && Array.isArray(categoryData.options) ? categoryData.options : [];

            const currentValue = preserveValue ? String(verticalSelect.value || '') : '';
            verticalSelect.innerHTML = '';

            let firstKey = '';
            let matched = false;

            options.forEach(function (item, index) {
                if (!item || !item.key) return;

                const option = document.createElement('option');
                option.value = String(item.key);
                option.textContent = String(item.display_label || item.key);

                if (index === 0) {
                    firstKey = option.value;
                }

                if (preserveValue && currentValue && currentValue === option.value) {
                    option.selected = true;
                    matched = true;
                }

                verticalSelect.appendChild(option);
            });

            if (!matched && firstKey) {
                verticalSelect.value = firstKey;
            }

            renderPreviewForSelected();
        }

        categorySelect.addEventListener('change', function () {
            rebuildVerticalOptions(false);
        });

        verticalSelect.addEventListener('change', function () {
            renderPreviewForSelected();
        });

        rebuildVerticalOptions(true);
    }

    const form = settingsForm;
    const inputs = Array.from(form.querySelectorAll('.matewa-chip-label-input'));
    const livePreviewTargets = Array.from(form.querySelectorAll('[data-live-preview-for]'));
    const resetButton = document.getElementById('matewa-reset-chip-labels-trigger');
    const resetForm = document.getElementById('matewa-reset-chip-labels-form');
    const confirmActionButtons = Array.from(form.querySelectorAll('[data-matewa-confirm-action]'));
    const verticalField = form.querySelector('#matewa_vertical_selected');
    const categoryField = form.querySelector('#matewa_vertical_category_selected');
    const industryField = form.querySelector('#matewa_industry');
    const industryMatchHelper = form.querySelector('#matewa-industry-match-helper');
    const verticalSelectorDataEl = form.querySelector('#matewa-manual-vertical-selector-data');
    const initialChipValues = new Map();
    const initialChoiceValues = {
        vertical: verticalField ? String(verticalField.value || '') : '',
        category: categoryField ? String(categoryField.value || '') : ''
    };
    let dirtyTrackingReady = false;
    let industrySuggestionTimer = null;
    let industrySuggestionInProgress = false;
    let industrySuggestionAppliedVertical = '';
    let visitorBusinessTypeChangedByUser = false;
    let industryEditedInSession = false;
    let pendingIndustrySuggestion = null;
    const initialIndustryValue = industryField ? String(industryField.value || '').trim() : '';
    const industrySuggestionStorageKey = 'matewaIndustryBusinessTypeSuggestion';
    const smartVerticalSearch = form.querySelector('#matewa-vertical-smart-search');
    const smartVerticalResults = form.querySelector('#matewa-vertical-smart-results');
    let smartVerticalActiveIndex = -1;

    if (!inputs.length) {
        if (resetButton && resetForm) {
            resetButton.addEventListener('click', function () {
                resetForm.submit();
            });
        }
        return;
    }

    /*
     * 5-A-26D chip parity hardlock.
     * Keep these measurement constants aligned with the admin CSS hardlock
     * in chip-editor.php and the frontend CHIPS contract in
     * public/css/matewa-widget.css. Do not tune these during unrelated admin
     * spacing, dashboard, helper-copy or onboarding polish passes.
     */
    const SINGLE_LINE_HEIGHT = 15;
    const TWO_LINE_HEIGHT = 34;
    const HEIGHT_TOLERANCE = 2;
    const MAX_LINES = 2;
    const MAX_MEASURE_HEIGHT = 34;
    const MAX_TOTAL_CHARS = 34;
    const MAX_LINE_CHARS = 20;
    const CHIP_GRID_WIDTH = 292;
    const CHIP_GAP = 8;
    const CHIP_HORIZONTAL_PADDING = 16;
    const CHIP_FALLBACK_TEXT_WIDTH = Math.max(1, ((CHIP_GRID_WIDTH - (CHIP_GAP * 2)) / 3) - CHIP_HORIZONTAL_PADDING);

    function normaliseLineEndings(value) {
        return String(value || '')
            .replace(/\r\n/g, '\n')
            .replace(/\r/g, '\n')
            .replace(/\t/g, ' ');
    }

    function cleanLineForEditing(line) {
        return String(line || '')
            .replace(/\r/g, '')
            .replace(/\t/g, ' ');
    }

    function cleanLineForSave(line) {
        return cleanLineForEditing(line)
            .replace(/^[ ]+/g, '')
            .replace(/[ ]+$/g, '');
    }

    function trimLineToLength(line, maxChars) {
        const chars = Array.from(String(line || ''));
        if (chars.length <= maxChars) {
            return line;
        }
        return chars.slice(0, maxChars).join('');
    }

    function trimTotalToLength(value, maxChars) {
        const chars = Array.from(String(value || ''));
        if (chars.length <= maxChars) {
            return value;
        }
        return chars.slice(0, maxChars).join('');
    }

    function sanitiseForSave(value) {
        const lines = normaliseLineEndings(value).split('\n');
        const out = [];

        lines.forEach(function (line) {
            if (out.length >= MAX_LINES) return;

            const clean = trimLineToLength(cleanLineForSave(line), MAX_LINE_CHARS);

            if (clean === '') return;

            out.push(clean);
        });

        return trimTotalToLength(out.join('\n'), MAX_TOTAL_CHARS);
    }

    function sanitiseForEditing(value) {
        const raw = normaliseLineEndings(value);
        const hasTrailingNewline = raw.endsWith('\n');
        const rawLines = raw.split('\n').slice(0, MAX_LINES);
        const out = [];

        rawLines.forEach(function (line, index) {
            const clean = trimLineToLength(cleanLineForEditing(line), MAX_LINE_CHARS);

            if (clean !== '') {
                out.push(clean);
                return;
            }

            if (index === 1 && hasTrailingNewline && out.length === 1) {
                out.push('');
            }
        });

        return trimTotalToLength(out.join('\n'), MAX_TOTAL_CHARS);
    }

    function getMeasureEl(input) {
        const wrap = input.closest('.matewa-chip-editor-chip');
        return wrap ? wrap.querySelector('.matewa-chip-editor-measure') : null;
    }

    function getChipTextMeasureWidth(input) {
        if (!input) return CHIP_FALLBACK_TEXT_WIDTH;

        if (input.clientWidth && input.clientWidth > 1) {
            return Math.max(1, input.clientWidth);
        }

        const wrap = input.closest ? input.closest('.matewa-chip-editor-chip') : null;
        if (wrap && wrap.clientWidth && wrap.clientWidth > 1) {
            return Math.max(1, wrap.clientWidth - CHIP_HORIZONTAL_PADDING);
        }

        return CHIP_FALLBACK_TEXT_WIDTH;
    }

    function getMeasuredHeight(input, value) {
        const measure = getMeasureEl(input);
        if (!measure) return SINGLE_LINE_HEIGHT;

        /*
         * 5-A-21E locked frontend widget contract:
         * measure against the real chip text area. If the browser has not laid
         * the textarea out yet, fall back to the locked 292px / 3-column
         * frontend chip contract so wrapped defaults are never treated as one-line labels.
         */
        const measureWidth = getChipTextMeasureWidth(input);
        measure.style.width = measureWidth + 'px';
        measure.style.maxWidth = measureWidth + 'px';

        const renderValue = String(value || '');
        measure.textContent = renderValue === '' ? ' ' : renderValue;

        return measure.scrollHeight;
    }

    function getSingleLineTextWidth(input, value) {
        const text = normaliseLineEndings(value).replace(/\n+/g, ' ').replace(/\s+/g, ' ').trim();
        if (!input || !text) return 0;

        const canvas = getSingleLineTextWidth.canvas || (getSingleLineTextWidth.canvas = document.createElement('canvas'));
        const context = canvas.getContext && canvas.getContext('2d');
        if (!context) return 0;

        const style = window.getComputedStyle ? window.getComputedStyle(input) : null;
        const fontWeight = style && style.fontWeight ? style.fontWeight : '600';
        const fontSize = style && style.fontSize ? style.fontSize : '12px';
        const fontFamily = style && style.fontFamily ? style.fontFamily : 'system-ui, sans-serif';
        context.font = fontWeight + ' ' + fontSize + ' ' + fontFamily;

        return context.measureText(text).width;
    }

    function textNeedsWrappedLine(input, value) {
        if (!input) return false;

        const clean = normaliseLineEndings(value);
        if (clean.indexOf('\n') !== -1) return true;

        const text = clean.replace(/\s+/g, ' ').trim();
        if (!text) return false;

        const availableWidth = getChipTextMeasureWidth(input);
        if (availableWidth <= 0) return false;

        /*
         * Borderline chip labels such as “Something else” can measure a few
         * pixels differently before web fonts/layout have fully settled. Use a
         * small safety buffer so labels that are close to the real chip width
         * keep the two-line frontend-style render instead of clipping line two.
         */
        return getSingleLineTextWidth(input, text) > Math.max(1, availableWidth - 4);
    }

    function inputScrollNeedsTwoRenderedLines(input) {
        if (!input) return false;

        const previousHeight = input.style.getPropertyValue('height');
        const previousMinHeight = input.style.getPropertyValue('min-height');
        const previousMaxHeight = input.style.getPropertyValue('max-height');

        input.style.setProperty('height', SINGLE_LINE_HEIGHT + 'px', 'important');
        input.style.setProperty('min-height', SINGLE_LINE_HEIGHT + 'px', 'important');
        input.style.setProperty('max-height', TWO_LINE_HEIGHT + 'px', 'important');

        const needsTwoLines = input.scrollHeight > (SINGLE_LINE_HEIGHT + HEIGHT_TOLERANCE);

        if (previousHeight) {
            input.style.setProperty('height', previousHeight, 'important');
        } else {
            input.style.removeProperty('height');
        }

        if (previousMinHeight) {
            input.style.setProperty('min-height', previousMinHeight, 'important');
        } else {
            input.style.removeProperty('min-height');
        }

        if (previousMaxHeight) {
            input.style.setProperty('max-height', previousMaxHeight, 'important');
        } else {
            input.style.removeProperty('max-height');
        }

        return needsTwoLines;
    }

    function normaliseComparableChipLabel(value) {
        return String(value || '')
            .replace(/\r\n/g, '\n')
            .replace(/\r/g, '\n')
            .replace(/\n/g, ' ')
            .replace(/\t/g, ' ')
            .replace(/\s+/g, ' ')
            .trim()
            .toLowerCase();
    }

    function recoverClippedDefaultOnce(input) {
        if (!input || !input.dataset || input.dataset.matewaRecoveredClippedDefault === '1') {
            return;
        }

        input.dataset.matewaRecoveredClippedDefault = '1';

        const currentValue = sanitiseForSave(input.value);
        const defaultValue = sanitiseForSave(input.dataset.defaultLabel || '');
        const currentComparable = normaliseComparableChipLabel(currentValue);
        const defaultComparable = normaliseComparableChipLabel(defaultValue);

        if (!currentComparable || !defaultComparable || currentComparable === defaultComparable) {
            return;
        }

        if (
            currentComparable.length >= 4 &&
            defaultComparable.length - currentComparable.length >= 2 &&
            defaultComparable.indexOf(currentComparable) === 0
        ) {
            input.value = defaultValue;
        }
    }

    function measureFits(input, value) {
        return getMeasuredHeight(input, value) <= MAX_MEASURE_HEIGHT;
    }

    function needsTwoRenderedLines(input, value) {
        const clean = normaliseLineEndings(value);
        if (clean.indexOf('\n') !== -1) return true;

        return textNeedsWrappedLine(input, clean) || getMeasuredHeight(input, clean) > (SINGLE_LINE_HEIGHT + HEIGHT_TOLERANCE);
    }

    function getLogicalLineCount(value) {
        const clean = normaliseLineEndings(value);
        if (!clean) return 0;
        return clean.split('\n').length;
    }

    function isDefaultLabelValue(input, value) {
        const defaultValue = sanitiseForSave(input && input.dataset ? (input.dataset.defaultLabel || '') : '');
        const currentValue = sanitiseForSave(value);

        return defaultValue !== '' && currentValue === defaultValue;
    }

    function shrinkToFit(input, value, preserveEditingSecondLine) {
        let working = String(value || '');
        let guard = 0;

        if (isDefaultLabelValue(input, working)) {
            return sanitiseForSave(working);
        }

        while (working && !measureFits(input, working) && guard < 200) {
            const lines = working.split('\n');

            if (lines.length > 1) {
                if (lines[1].length > 0) {
                    lines[1] = Array.from(lines[1]).slice(0, -1).join('');
                } else if (!preserveEditingSecondLine) {
                    lines.pop();
                } else {
                    break;
                }
            } else {
                lines[0] = Array.from(lines[0]).slice(0, -1).join('');
            }

            working = lines.join('\n');
            working = preserveEditingSecondLine
                ? sanitiseForEditing(working)
                : sanitiseForSave(working);

            guard++;
        }

        return working;
    }

    function getComparableSaveValue(input, value) {
        let working = sanitiseForSave(value);

        if (isDefaultLabelValue(input, working)) {
            return working;
        }

        return shrinkToFit(input, working, false);
    }

    function getConfirmButtonLabel(button, key, fallback) {
        return button ? (button.getAttribute(key) || fallback) : fallback;
    }

    function setConfirmButtonState(button, state) {
        if (!button) {
            return;
        }

        const isReady = state === 'ready';
        const isSaved = state === 'saved';
        const isBlocked = state === 'blocked';
        const label = isSaved
            ? getConfirmButtonLabel(button, 'data-matewa-confirm-saved-label', 'Saved')
            : isBlocked
                ? getConfirmButtonLabel(button, 'data-matewa-confirm-blocked-label', 'Choose first')
                : getConfirmButtonLabel(button, 'data-matewa-confirm-ready-label', button.textContent || 'Confirm');

        button.textContent = label;
        button.setAttribute('data-matewa-confirm-state', state);
        button.classList.toggle('is-attention', isReady);
        button.classList.toggle('is-confirm-ready', isReady);
        button.classList.toggle('is-confirm-saved', isSaved);
        button.classList.toggle('is-confirm-blocked', isBlocked);
        button.classList.remove('is-confirm-saving');
    }

    function hasUnsavedChipLabelChanges() {
        if (!dirtyTrackingReady) {
            return false;
        }

        for (let i = 0; i < inputs.length; i++) {
            const input = inputs[i];

            if (!input || !input.id) {
                continue;
            }

            const initialValue = initialChipValues.has(input.id) ? initialChipValues.get(input.id) : '';
            const currentValue = getComparableSaveValue(input, input.value);

            if (currentValue !== initialValue) {
                return true;
            }
        }

        return false;
    }

    function setConfirmAttention(hasChanges) {
        if (!confirmActionButtons.length) {
            return;
        }

        confirmActionButtons.forEach(function (button) {
            const action = String(button.getAttribute('data-matewa-confirm-action') || '');

            if (action === 'business-type-save') {
                const businessChanged = Boolean(
                    (verticalField && String(verticalField.value || '') !== initialChoiceValues.vertical) ||
                    (categoryField && String(categoryField.value || '') !== initialChoiceValues.category)
                );
                setConfirmButtonState(button, businessChanged ? 'ready' : 'saved');
                return;
            }

            if (action === 'chip-save') {
                setConfirmButtonState(button, hasUnsavedChipLabelChanges() ? 'ready' : 'saved');
                return;
            }

            button.classList.toggle('is-attention', Boolean(hasChanges));
        });
    }

    function captureInitialDirtyState() {
        inputs.forEach(function (input) {
            if (!input || !input.id) {
                return;
            }

            initialChipValues.set(input.id, getComparableSaveValue(input, input.value));
        });

        if (verticalField) {
            initialChoiceValues.vertical = String(verticalField.value || '');
        }

        if (categoryField) {
            initialChoiceValues.category = String(categoryField.value || '');
        }

        dirtyTrackingReady = true;
        setConfirmAttention(false);
    }

    function hasUnsavedChipStudioChanges() {
        if (!dirtyTrackingReady) {
            return false;
        }

        if (verticalField && String(verticalField.value || '') !== initialChoiceValues.vertical) {
            return true;
        }

        if (categoryField && String(categoryField.value || '') !== initialChoiceValues.category) {
            return true;
        }

        for (let i = 0; i < inputs.length; i++) {
            const input = inputs[i];

            if (!input || !input.id) {
                continue;
            }

            const initialValue = initialChipValues.has(input.id) ? initialChipValues.get(input.id) : '';
            const currentValue = getComparableSaveValue(input, input.value);

            if (currentValue !== initialValue) {
                return true;
            }
        }

        return false;
    }

    function updateConfirmAttention() {
        setConfirmAttention(hasUnsavedChipStudioChanges());
        updateVisitorButtonGuidance();
    }

    function showVisitorGuideHelper(anchor, message) {
        if (!anchor) {
            return;
        }

        const wrap = anchor.closest('.matewa-selector-field') || anchor.closest('.matewa-chip-studio-panel') || anchor.parentNode;

        if (!wrap) {
            return;
        }

        let helper = wrap.querySelector('.matewa-visitor-guide-helper');

        if (!helper) {
            helper = document.createElement('span');
            helper.className = 'matewa-visitor-guide-helper';
            helper.setAttribute('role', 'status');
            helper.setAttribute('aria-live', 'polite');
            helper.hidden = true;
            wrap.appendChild(helper);
        }

        helper.textContent = message;
        helper.hidden = false;
        helper.classList.add('is-visible');
        wrap.classList.add('is-visitor-guide-blocked');

        window.setTimeout(function () {
            helper.hidden = true;
            helper.classList.remove('is-visible');
            wrap.classList.remove('is-visitor-guide-blocked');
        }, 2400);
    }

    function getSelectorField(field) {
        return field ? field.closest('.matewa-selector-field') : null;
    }

    function updateVisitorButtonGuidance() {
        const categoryWrap = getSelectorField(categoryField);
        const verticalWrap = getSelectorField(verticalField);
        const businessChanged = Boolean(
            (verticalField && String(verticalField.value || '') !== initialChoiceValues.vertical) ||
            (categoryField && String(categoryField.value || '') !== initialChoiceValues.category)
        );

        [categoryWrap, verticalWrap].forEach(function (wrap) {
            if (!wrap) {
                return;
            }

            wrap.classList.remove('is-current-guided-step', 'has-guided-value', 'is-guided-ahead');
        });

        if (!categoryField || !verticalField) {
            return;
        }

        if (!businessChanged) {
            if (categoryWrap) {
                categoryWrap.classList.add('is-current-guided-step');
            }
            if (verticalWrap) {
                verticalWrap.classList.add('has-guided-value');
            }
            return;
        }

        if (categoryField && String(categoryField.value || '') === '') {
            if (categoryWrap) {
                categoryWrap.classList.add('is-current-guided-step');
            }
            if (verticalWrap) {
                verticalWrap.classList.add('is-guided-ahead');
            }
            return;
        }

        if (categoryWrap) {
            categoryWrap.classList.add('has-guided-value');
        }
        if (verticalWrap) {
            verticalWrap.classList.add('is-current-guided-step');
        }
    }

    function parseVerticalSelectorData() {
        if (!verticalSelectorDataEl) {
            return {};
        }

        try {
            return JSON.parse(verticalSelectorDataEl.textContent || '{}') || {};
        } catch (error) {
            return {};
        }
    }

    function getAllBusinessTypeOptions() {
        const selectorData = parseVerticalSelectorData();
        const all = [];

        Object.keys(selectorData || {}).forEach(function (categoryKey) {
            const category = selectorData[categoryKey] || {};
            const options = Array.isArray(category.options) ? category.options : [];

            options.forEach(function (option) {
                if (!option || !option.key) {
                    return;
                }

                all.push(Object.assign({}, option, {
                    category_key: categoryKey,
                    category_label: String(category.label || 'General')
                }));
            });
        });

        return all;
    }

    function normaliseIndustryMatchText(value) {
        return String(value || '')
            .toLowerCase()
            .replace(/&/g, ' and ')
            .replace(/[^a-z0-9]+/g, ' ')
            .replace(/\s+/g, ' ')
            .trim();
    }

    function rootIndustryToken(token) {
        const aliases = {
            plumber: 'plumb', plumbers: 'plumb', plumbing: 'plumb', plumb: 'plumb',
            electrician: 'electric', electricians: 'electric', electrical: 'electric', electrics: 'electric', electric: 'electric',
            roofer: 'roof', roofers: 'roof', roofing: 'roof', roof: 'roof',
            builder: 'build', builders: 'build', building: 'build',
            carpenter: 'carpent', carpenters: 'carpent', carpentry: 'carpent',
            decorator: 'decorat', decorators: 'decorat', decorating: 'decorat',
            painter: 'paint', painters: 'paint', painting: 'paint',
            plasterer: 'plaster', plasterers: 'plaster', plastering: 'plaster',
            gardener: 'garden', gardeners: 'garden', gardening: 'garden',
            landscaper: 'landscap', landscapers: 'landscap', landscaping: 'landscap',
            cleaner: 'clean', cleaners: 'clean', cleaning: 'clean',
            locksmith: 'locksmith', locksmiths: 'locksmith',
            glazier: 'glaz', glaziers: 'glaz', glazing: 'glaz',
            dentist: 'dental', dentists: 'dental', dental: 'dental',
            solicitor: 'law', solicitors: 'law', lawyer: 'law', lawyers: 'law', legal: 'law', law: 'law',
            accountant: 'account', accountants: 'account', accounting: 'account', accountancy: 'account',
            agency: 'agency', agencies: 'agency', marketing: 'market', marketer: 'market', marketers: 'market',
            designer: 'design', designers: 'design', design: 'design', graphics: 'graphic', graphic: 'graphic',
            developer: 'develop', developers: 'develop', development: 'develop', web: 'web', website: 'web', websites: 'web',
            aerial: 'aerial', aerials: 'aerial', antenna: 'aerial', antennas: 'aerial', satellite: 'satellite',
            network: 'network', networking: 'network', wifi: 'wifi', 'wi fi': 'wifi', it: 'it', av: 'av',
            pest: 'pest', control: 'control', estate: 'estate', agent: 'agent', agents: 'agent', lettings: 'letting', letting: 'letting',
            gym: 'gym', fitness: 'fitness', dog: 'dog', groomer: 'groom', groomers: 'groom', grooming: 'groom',
            childcare: 'childcare', childminder: 'childcare', childminders: 'childcare', nursery: 'nursery', nurseries: 'nursery', preschool: 'preschool', pre: 'pre', school: 'school', nanny: 'nanny', nannies: 'nanny', wraparound: 'wraparound'
        };

        let working = normaliseIndustryMatchText(token);

        if (aliases[working]) {
            return aliases[working];
        }

        if (working.length > 5 && /ing$/.test(working)) {
            working = working.slice(0, -3);
        } else if (working.length > 4 && /ers$/.test(working)) {
            working = working.slice(0, -3);
        } else if (working.length > 4 && /er$/.test(working)) {
            working = working.slice(0, -2);
        } else if (working.length > 4 && /s$/.test(working)) {
            working = working.slice(0, -1);
        }

        return aliases[working] || working;
    }

    function getIndustryTokens(value) {
        const stopWords = new Set(['a', 'an', 'and', 'the', 'for', 'of', 'to', 'in', 'on', 'my', 'our', 'business', 'company', 'service', 'services', 'trade', 'trades', 'industry']);

        return normaliseIndustryMatchText(value)
            .split(' ')
            .map(function (token) { return token.trim(); })
            .filter(function (token) { return token.length >= 2 && !stopWords.has(token); });
    }

    function getOptionSearchText(option) {
        return normaliseIndustryMatchText([
            option && option.display_label,
            option && option.key,
            option && option.category_label,
            option && Array.isArray(option.search_terms) ? option.search_terms.join(' ') : ''
        ].join(' '));
    }

    function getOptionRootTokens(option) {
        return getIndustryTokens(getOptionSearchText(option)).map(rootIndustryToken).filter(Boolean);
    }

    function scoreIndustryMatch(industryValue, option) {
        const industry = normaliseIndustryMatchText(industryValue);
        const optionText = getOptionSearchText(option);
        const rawTokens = getIndustryTokens(industryValue);
        const industryRoots = rawTokens.map(rootIndustryToken).filter(Boolean);
        const optionRoots = getOptionRootTokens(option);

        if (!industry || !option || !option.key || !industryRoots.length) {
            return 0;
        }

        if (industry === normaliseIndustryMatchText(option.display_label) || industry === normaliseIndustryMatchText(option.key)) {
            return 100;
        }

        if (optionText.indexOf(industry) !== -1 && industry.length >= 4) {
            return 94;
        }

        if (rawTokens.length > 1 && rawTokens.every(function (token) { return optionText.indexOf(token) !== -1; })) {
            return 92;
        }

        if (industryRoots.length > 1 && industryRoots.every(function (root) { return optionRoots.indexOf(root) !== -1; })) {
            return 89;
        }

        if (industryRoots.length === 1) {
            const root = industryRoots[0];

            if (root.length >= 4 && optionRoots.some(function (candidate) { return candidate.indexOf(root) === 0 || root.indexOf(candidate) === 0; })) {
                return 87;
            }

            if (root.length >= 5 && optionText.indexOf(root) !== -1) {
                return 86;
            }
        }

        return 0;
    }

    function findGeneralBusinessTypeOption() {
        const options = getAllBusinessTypeOptions();

        for (let i = 0; i < options.length; i++) {
            if (String(options[i].key || '') === 'general') {
                return options[i];
            }
        }

        return options.length ? options[0] : null;
    }

    function findOptionByVerticalKey(verticalKey) {
        const wanted = String(verticalKey || '');
        const options = getAllBusinessTypeOptions();

        for (let i = 0; i < options.length; i++) {
            if (String(options[i].key || '') === wanted) {
                return options[i];
            }
        }

        return null;
    }

    function getCategoryOptionsFromSelectorData(categoryKey) {
        const selectorData = parseVerticalSelectorData();
        const categoryData = selectorData[String(categoryKey || '')] || {};
        return Array.isArray(categoryData.options) ? categoryData.options : [];
    }

    function ensureVerticalOptionAvailable(categoryKey, verticalKey) {
        if (!verticalField || !categoryField) {
            return;
        }

        const wanted = String(verticalKey || '');

        if (!wanted) {
            return;
        }

        const existing = Array.from(verticalField.options || []).some(function (option) {
            return String(option.value || '') === wanted;
        });

        if (existing) {
            return;
        }

        const options = getCategoryOptionsFromSelectorData(categoryKey);

        if (!options.length) {
            return;
        }

        verticalField.innerHTML = '';

        options.forEach(function (item) {
            if (!item || !item.key) {
                return;
            }

            const optionEl = document.createElement('option');
            optionEl.value = String(item.key || '');
            optionEl.textContent = String(item.display_label || item.key || '');
            verticalField.appendChild(optionEl);
        });
    }

    function storePendingIndustrySuggestion(option, confident, industryValue) {
        if (!option || !option.key || !window.sessionStorage) {
            return;
        }

        pendingIndustrySuggestion = {
            category: String(option.category_key || 'general'),
            vertical: String(option.key || 'general'),
            label: String(option.display_label || option.key || 'General'),
            confident: Boolean(confident),
            industry: String(industryValue || '')
        };

        try {
            window.sessionStorage.setItem(industrySuggestionStorageKey, JSON.stringify(pendingIndustrySuggestion));
        } catch (error) {}
    }

    function readPendingIndustrySuggestion() {
        if (pendingIndustrySuggestion) {
            return pendingIndustrySuggestion;
        }

        if (!window.sessionStorage) {
            return null;
        }

        try {
            const raw = window.sessionStorage.getItem(industrySuggestionStorageKey);
            const parsed = raw ? JSON.parse(raw) : null;

            if (parsed && parsed.vertical) {
                pendingIndustrySuggestion = parsed;
                return pendingIndustrySuggestion;
            }
        } catch (error) {}

        return null;
    }

    function clearPendingIndustrySuggestion() {
        pendingIndustrySuggestion = null;

        if (!window.sessionStorage) {
            return;
        }

        try {
            window.sessionStorage.removeItem(industrySuggestionStorageKey);
        } catch (error) {}
    }

    function setBusinessTypeSelection(option) {
        if (!option || !option.key || !categoryField || !verticalField) {
            return false;
        }

        const nextCategory = String(option.category_key || 'general');
        const nextVertical = String(option.key || 'general');

        industrySuggestionInProgress = true;

        if (nextCategory && categoryField.value !== nextCategory) {
            categoryField.value = nextCategory;
            categoryField.dispatchEvent(new Event('change', { bubbles: true }));
        }

        ensureVerticalOptionAvailable(nextCategory, nextVertical);

        if (verticalField.value !== nextVertical) {
            verticalField.value = nextVertical;
            verticalField.dispatchEvent(new Event('change', { bubbles: true }));
        } else {
            verticalField.dispatchEvent(new Event('change', { bubbles: true }));
        }

        industrySuggestionAppliedVertical = nextVertical;
        industrySuggestionInProgress = false;

        return true;
    }

    function setBusinessTypeBackToGeneralForUnconfirmedSubmit() {
        const general = findGeneralBusinessTypeOption();

        if (!general || !general.key) {
            return;
        }

        setBusinessTypeSelection(general);
    }

    function findIndustryBusinessTypeMatch(industryValue) {
        const options = getAllBusinessTypeOptions();
        let best = null;
        let bestScore = 0;

        options.forEach(function (option) {
            const score = scoreIndustryMatch(industryValue, option);

            if (score > bestScore) {
                best = option;
                bestScore = score;
            }
        });

        if (best && bestScore >= 86) {
            return {
                option: best,
                score: bestScore,
                confident: true
            };
        }

        return {
            option: findGeneralBusinessTypeOption(),
            score: bestScore,
            confident: false
        };
    }

    function isGeneralBusinessType(value) {
        const normalised = String(value || '').toLowerCase().trim();
        return normalised === '' || normalised === 'general';
    }

    function showIndustryMatchHelper(message, state) {
        if (!industryMatchHelper) {
            return;
        }

        industryMatchHelper.textContent = message;
        industryMatchHelper.hidden = false;
        industryMatchHelper.classList.add('is-visible');
        industryMatchHelper.setAttribute('data-match-state', state || 'suggested');
    }

    function shouldApplyIndustrySuggestion() {
        if (!industryField || !categoryField || !verticalField || !verticalSelectorDataEl) {
            return false;
        }

        if (visitorBusinessTypeChangedByUser) {
            return false;
        }

        if (industryEditedInSession) {
            return true;
        }

        const currentVertical = String(verticalField.value || '');

        return isGeneralBusinessType(initialChoiceValues.vertical) || isGeneralBusinessType(currentVertical) || (industrySuggestionAppliedVertical && currentVertical === industrySuggestionAppliedVertical);
    }

    function applyIndustryBusinessTypeSuggestion() {
        if (!shouldApplyIndustrySuggestion()) {
            return;
        }

        const industryValue = String(industryField.value || '').trim();

        if (industryValue.length < 3) {
            return;
        }

        const match = findIndustryBusinessTypeMatch(industryValue);
        const option = match && match.option ? match.option : null;

        if (!option || !option.key) {
            return;
        }

        const nextVertical = String(option.key || 'general');
        const label = String(option.display_label || nextVertical || 'General');

        if (!setBusinessTypeSelection(option)) {
            return;
        }

        storePendingIndustrySuggestion(option, match.confident, industryValue);

        if (match.confident) {
            showIndustryMatchHelper('Suggested from Setup: ' + label + '. Confirm this business type to load these starter buttons into the editor.', 'suggested');
        } else {
            showIndustryMatchHelper('No exact match found, so General is selected. You can choose a closer business type before confirming.', 'fallback');
        }

        updateConfirmAttention();
    }

    function queueIndustryBusinessTypeSuggestion(delay) {
        if (industrySuggestionTimer) {
            window.clearTimeout(industrySuggestionTimer);
        }

        industrySuggestionTimer = window.setTimeout(applyIndustryBusinessTypeSuggestion, typeof delay === 'number' ? delay : 400);
    }

    function applyPendingIndustrySuggestionFromStorage() {
        const pending = readPendingIndustrySuggestion();

        if (!pending || !pending.vertical || visitorBusinessTypeChangedByUser) {
            return;
        }

        const option = findOptionByVerticalKey(pending.vertical);

        if (!option || !option.key) {
            clearPendingIndustrySuggestion();
            return;
        }

        setBusinessTypeSelection(option);

        const label = String(option.display_label || pending.label || option.key || 'General');

        if (pending.confident) {
            showIndustryMatchHelper('Suggested from Setup: ' + label + '. Confirm this business type to load these starter buttons into the editor.', 'suggested');
        } else {
            showIndustryMatchHelper('No exact match found, so General is selected. You can choose a closer business type before confirming.', 'fallback');
        }

        updateConfirmAttention();
    }

    function renderSmartVerticalResults(query) {
        if (!smartVerticalResults) {
            return;
        }

        const value = String(query || '').trim();
        smartVerticalResults.innerHTML = '';

        if (value.length < 2) {
            smartVerticalResults.hidden = true;
            return;
        }

        const options = getAllBusinessTypeOptions()
            .map(function (option) {
                return { option: option, score: scoreIndustryMatch(value, option) };
            })
            .filter(function (item) {
                const haystack = getOptionSearchText(item.option);
                const needle = normaliseIndustryMatchText(value);
                return item.score > 0 || (needle.length >= 2 && haystack.indexOf(needle) !== -1);
            })
            .sort(function (a, b) {
                if (b.score !== a.score) return b.score - a.score;
                return String(a.option.display_label || '').localeCompare(String(b.option.display_label || ''));
            })
            .slice(0, 8);

        if (!options.length) {
            const empty = document.createElement('div');
            empty.className = 'matewa-smart-vertical-result';
            empty.setAttribute('aria-disabled', 'true');
            empty.innerHTML = '<span><strong>No close match</strong><br><small>Try another term or browse alphabetically below.</small></span>';
            smartVerticalResults.appendChild(empty);
            smartVerticalResults.hidden = false;
            return;
        }

        options.forEach(function (item) {
            const option = item.option;
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'matewa-smart-vertical-result';
            button.setAttribute('role', 'option');

            const text = document.createElement('span');
            const strong = document.createElement('strong');
            const small = document.createElement('small');
            strong.textContent = String(option.display_label || option.key || '');
            small.textContent = String(option.category_label || '');
            text.appendChild(strong);
            text.appendChild(document.createElement('br'));
            text.appendChild(small);
            button.appendChild(text);

            button.addEventListener('click', function () {
                visitorBusinessTypeChangedByUser = true;
                setBusinessTypeSelection(option);
                smartVerticalSearch.value = String(option.display_label || option.key || '');
                smartVerticalResults.hidden = true;
                clearPendingIndustrySuggestion();
                updateConfirmAttention();
                if (industryMatchHelper) {
                    showIndustryMatchHelper('Selected: ' + String(option.display_label || option.key || '') + '. Confirm this business type to load these starter buttons into the editor.', 'suggested');
                }
            });

            smartVerticalResults.appendChild(button);
        });

        smartVerticalResults.hidden = false;
    }

    if (smartVerticalSearch && smartVerticalResults) {
        
    function smartVerticalResultButtons() {
        if (!smartVerticalResults) return [];
        return Array.from(smartVerticalResults.querySelectorAll('.matewa-smart-vertical-result[role="option"]'));
    }

    function setSmartVerticalActiveIndex(nextIndex) {
        const buttons = smartVerticalResultButtons();

        if (!buttons.length) {
            smartVerticalActiveIndex = -1;
            return;
        }

        if (nextIndex < 0) nextIndex = buttons.length - 1;
        if (nextIndex >= buttons.length) nextIndex = 0;

        smartVerticalActiveIndex = nextIndex;

        buttons.forEach((button, index) => {
            const active = index === smartVerticalActiveIndex;
            button.classList.toggle('is-active', active);
            button.setAttribute('aria-selected', active ? 'true' : 'false');

            if (active) {
                button.scrollIntoView({ block: 'nearest' });
            }
        });
    }

smartVerticalSearch.addEventListener('input', function () {
            renderSmartVerticalResults(smartVerticalSearch.value);
        });

        smartVerticalSearch.addEventListener('focus', function () {
            if (String(smartVerticalSearch.value || '').trim().length >= 2) {
                renderSmartVerticalResults(smartVerticalSearch.value);
            }
        });

        document.addEventListener('click', function (event) {
            if (!event.target.closest('[data-matewa-smart-vertical-search-wrap]')) {
                smartVerticalResults.hidden = true;
            }
        });

        smartVerticalSearch.addEventListener('keydown', function (event) {
            if (event.key === 'ArrowDown') {
                event.preventDefault();

                if (smartVerticalResults.hidden) {
                    smartVerticalSearch.dispatchEvent(new Event('input', { bubbles: true }));
                }

                setSmartVerticalActiveIndex(smartVerticalActiveIndex + 1);
                return;
            }

            if (event.key === 'ArrowUp') {
                event.preventDefault();

                if (smartVerticalResults.hidden) {
                    smartVerticalSearch.dispatchEvent(new Event('input', { bubbles: true }));
                }

                setSmartVerticalActiveIndex(smartVerticalActiveIndex - 1);
                return;
            }

            if (event.key === 'Enter') {
                const buttons = smartVerticalResultButtons();

                if (!smartVerticalResults.hidden && smartVerticalActiveIndex >= 0 && buttons[smartVerticalActiveIndex]) {
                    event.preventDefault();
                    buttons[smartVerticalActiveIndex].click();
                }
                return;
            }

            if (event.key === 'Escape') {
                event.preventDefault();
                smartVerticalResults.hidden = true;
                smartVerticalActiveIndex = -1;
                smartVerticalSearch.blur();
            }
        });
    }

    window.matewaPreparePendingIndustrySuggestionForSubmit = function (submitter) {
        const action = submitter && submitter.matches && submitter.matches('[data-matewa-confirm-action]')
            ? String(submitter.getAttribute('data-matewa-confirm-action') || '')
            : '';

        if (action === 'business-type-save') {
            clearPendingIndustrySuggestion();
            return;
        }

        const pending = readPendingIndustrySuggestion();

        if (!pending || !pending.vertical) {
            return;
        }

        /*
         * 5-A-26D repair:
         * A Setup-page industry suggestion is allowed to preselect the Visitor
         * Buttons dropdowns, but it must not silently save as the active
         * business type. Revert the posted values to General unless the user
         * presses Confirm business type.
         */
        setBusinessTypeBackToGeneralForUnconfirmedSubmit();
    };

    function applyConstraints(input, mode) {
        const preserveEditingSecondLine = mode === 'editing';

        let value = preserveEditingSecondLine
            ? sanitiseForEditing(input.value)
            : sanitiseForSave(input.value);

        /*
         * Two-line lock:
         * Shrink custom edits while preserving valid default labels.
         * The default labels are already proven in the frontend chip contract;
         * do not re-trim them on page load or the right editor chips can lose
         * words after an earlier broken save.
         */
        if (!isDefaultLabelValue(input, value)) {
            value = shrinkToFit(input, value, preserveEditingSecondLine);
        }

        input.value = value;

        const twoLineDisplay = needsTwoRenderedLines(input, value) || value.indexOf('\n') !== -1;

        const chipInputHeight = twoLineDisplay
            ? (TWO_LINE_HEIGHT + 'px')
            : (SINGLE_LINE_HEIGHT + 'px');

        /*
         * 5-A-20F-4 visual recovery:
         * Do not use textarea scrollHeight to decide one-line vs two-line
         * display here. The editor textareas are rendered with rows=2, so
         * scrollHeight can report a two-line box even when the label is a
         * genuine one-line value. That made single-line editable buttons sit
         * high inside the chip instead of vertically matching the suggested
         * buttons. Use the hidden measure/newline test only.
         */
        input.style.setProperty('height', chipInputHeight, 'important');
        input.style.setProperty('min-height', chipInputHeight, 'important');
        input.style.setProperty('max-height', chipInputHeight, 'important');

        return input.value;
    }

    function updateLivePreviewForInput(input) {
        if (!livePreviewTargets.length || !input || !input.id) return;

        const previewText = String(input.value || input.dataset.defaultLabel || '').trim();

        livePreviewTargets.forEach(function (target) {
            if (String(target.getAttribute('data-live-preview-for') || '') !== String(input.id || '')) {
                return;
            }

            target.textContent = previewText || String(input.dataset.defaultLabel || '');
        });
    }

    function setChipState(input, mode) {
        const wrap = form.querySelector('[data-chip-wrap-for="' + input.id + '"]');
        if (!wrap) return true;

        applyConstraints(input, mode || 'editing');
        updateLivePreviewForInput(input);

        const value = getComparableSaveValue(input, input.value);
        const defaultLabel = getComparableSaveValue(input, input.dataset.defaultLabel || '');
        const isChanged = value !== '' && value !== defaultLabel;

        wrap.classList.remove('is-changed');

        if (isChanged) {
            wrap.classList.add('is-changed');
        }

        return true;
    }

    function canInsertLineBreak(input) {
        const currentValue = normaliseLineEndings(input.value);
        const start = typeof input.selectionStart === 'number' ? input.selectionStart : currentValue.length;
        const end = typeof input.selectionEnd === 'number' ? input.selectionEnd : currentValue.length;

        /*
         * If it already visually renders as two lines, do not allow another line break.
         */
        if (needsTwoRenderedLines(input, currentValue)) {
            return false;
        }

        const currentLineCount = getLogicalLineCount(currentValue);
        if (currentLineCount >= MAX_LINES) {
            return false;
        }

        const proposed =
            currentValue.slice(0, start) +
            '\n' +
            currentValue.slice(end);

        if (getLogicalLineCount(proposed) > MAX_LINES) {
            return false;
        }

        const candidate = sanitiseForEditing(proposed);

        if (getLogicalLineCount(candidate) > MAX_LINES) {
            return false;
        }

        return measureFits(input, candidate);
    }

    inputs.forEach(function (input) {
        input.addEventListener('beforeinput', function (event) {
            if (
                event.inputType === 'insertLineBreak' ||
                event.inputType === 'insertParagraph'
            ) {
                if (!canInsertLineBreak(input)) {
                    event.preventDefault();
                }
            }
        });

        input.addEventListener('keydown', function (event) {
            if (event.key === 'Enter') {
                if (!canInsertLineBreak(input)) {
                    event.preventDefault();
                }
                return;
            }

            /*
             * Prevent normal typing from creating a visual third line.
             */
            if (
                event.key.length === 1 &&
                !event.ctrlKey &&
                !event.metaKey &&
                !event.altKey
            ) {
                const start = typeof input.selectionStart === 'number' ? input.selectionStart : input.value.length;
                const end = typeof input.selectionEnd === 'number' ? input.selectionEnd : input.value.length;
                const currentValue = normaliseLineEndings(input.value);

                const proposed =
                    currentValue.slice(0, start) +
                    event.key +
                    currentValue.slice(end);

                const candidate = sanitiseForEditing(proposed);
                const fitted = shrinkToFit(input, candidate, true);

                if (candidate !== fitted || !measureFits(input, candidate)) {
                    event.preventDefault();
                }
            }
        });

        input.addEventListener('input', function () {
            setChipState(input, 'editing');
        });

        input.addEventListener('paste', function () {
            window.setTimeout(function () {
                setChipState(input, 'editing');
            }, 0);
        });

        input.addEventListener('blur', function () {
            setChipState(input, 'save');
        });

        recoverClippedDefaultOnce(input);
        setChipState(input, 'save');
    });

    function refreshChipEditorFit() {
        inputs.forEach(function (input) {
            setChipState(input, 'save');
        });
        updateConfirmAttention();
    }

    function scheduleChipEditorFitRefresh(delay) {
        window.setTimeout(refreshChipEditorFit, delay);
    }

    if (window.requestAnimationFrame) {
        window.requestAnimationFrame(function () {
            refreshChipEditorFit();
            window.requestAnimationFrame(refreshChipEditorFit);
        });
    }

    scheduleChipEditorFitRefresh(80);
    scheduleChipEditorFitRefresh(220);
    scheduleChipEditorFitRefresh(520);

    if (document.fonts && document.fonts.ready && typeof document.fonts.ready.then === 'function') {
        document.fonts.ready.then(refreshChipEditorFit).catch(function () {});
    }

    window.addEventListener('load', refreshChipEditorFit);
    document.addEventListener('matewa:buttons-panel-visible', function () {
        scheduleChipEditorFitRefresh(0);
        scheduleChipEditorFitRefresh(120);
        window.setTimeout(applyPendingIndustrySuggestionFromStorage, 0);
    });

    let chipResizeTimer = null;
    window.addEventListener('resize', function () {
        if (chipResizeTimer) {
            window.clearTimeout(chipResizeTimer);
        }
        chipResizeTimer = window.setTimeout(refreshChipEditorFit, 120);
    });

    captureInitialDirtyState();
    updateVisitorButtonGuidance();
    applyPendingIndustrySuggestionFromStorage();
    queueIndustryBusinessTypeSuggestion(250);

    inputs.forEach(function (input) {
        input.addEventListener('input', updateConfirmAttention);
        input.addEventListener('blur', updateConfirmAttention);
        input.addEventListener('paste', function () {
            window.setTimeout(updateConfirmAttention, 0);
        });
    });

    [verticalField, categoryField].forEach(function (field) {
        if (!field) {
            return;
        }

        field.addEventListener('change', function (event) {
            if (!industrySuggestionInProgress && event && event.isTrusted) {
                visitorBusinessTypeChangedByUser = true;
            }

            updateConfirmAttention();
        });
    });

    if (industryField) {
        industryField.addEventListener('input', function () {
            industryEditedInSession = String(industryField.value || '').trim() !== initialIndustryValue;
            queueIndustryBusinessTypeSuggestion(500);
        });

        industryField.addEventListener('blur', function () {
            industryEditedInSession = String(industryField.value || '').trim() !== initialIndustryValue;
            queueIndustryBusinessTypeSuggestion(0);
        });
    }

    if (verticalField && categoryField) {
        verticalField.addEventListener('focus', function () {
            if (!String(categoryField.value || '')) {
                showVisitorGuideHelper(verticalField, '🚫 Choose a category first.');
            }
        });
    }

    form.addEventListener('submit', function (event) {
        const submitter = event.submitter || document.activeElement;

        if (event.defaultPrevented || !submitter || !submitter.matches || !submitter.matches('[data-matewa-confirm-action]')) {
            return;
        }

        submitter.textContent = getConfirmButtonLabel(submitter, 'data-matewa-confirm-saving-label', 'Saving…');
        submitter.setAttribute('data-matewa-confirm-state', 'saving');
        submitter.classList.remove('is-attention', 'is-confirm-ready', 'is-confirm-saved', 'is-confirm-blocked');
        submitter.classList.add('is-confirm-saving');
    });

    if (resetButton && resetForm) {
        resetButton.addEventListener('click', function () {
            resetForm.submit();
        });
    }
})();
/* AGENCYREMOTEPUSHINLINECLIENTFLOW1 — keep remote push URL tied to the selected client pack/domain. */
(function () {
    'use strict';

    function cleanClientDomain(value) {
        return String(value || '')
            .trim()
            .replace(/^https?:\/\//i, '')
            .replace(/^www\./i, 'www.')
            .replace(/\s+/g, '')
            .replace(/\/.*$/, '')
            .toLowerCase();
    }

    function initAgencyRemotePushInlineUrl() {
        const packSelect = document.querySelector('[data-agency-remote-pack-select]');
        const remoteUrlInput = document.querySelector('[data-agency-remote-url-input]');
        const clientDomainInput = document.querySelector('input[name="matewa_agency_client_domain"]');

        if (!remoteUrlInput) {
            return;
        }

        function setRemoteUrlFromSelectedPack(force) {
            if (!packSelect) {
                return;
            }

            const option = packSelect.options && packSelect.selectedIndex >= 0 ? packSelect.options[packSelect.selectedIndex] : null;
            const domain = option && option.dataset ? cleanClientDomain(option.dataset.clientDomain || '') : '';

            if (domain && (force || !remoteUrlInput.value.trim())) {
                remoteUrlInput.value = domain;
            }
        }

        if (packSelect) {
            packSelect.addEventListener('change', function () {
                setRemoteUrlFromSelectedPack(true);
            });
            setRemoteUrlFromSelectedPack(false);
        }

        if (clientDomainInput) {
            clientDomainInput.addEventListener('input', function () {
                if (packSelect && packSelect.value) {
                    return;
                }

                remoteUrlInput.value = cleanClientDomain(clientDomainInput.value);
            });
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initAgencyRemotePushInlineUrl);
    } else {
        initAgencyRemotePushInlineUrl();
    }
}());

/* AGENCYHELPERADVISORYHIGHLIGHTLOCK — advisory-only Agency Hub helper/highlight. */
(function () {
    'use strict';

    const agencyPanel = document.getElementById('matewa-agency-hub-section');
    const dashboardPage = document.querySelector('.matewa-dashboard-page');

    if (!agencyPanel || !dashboardPage) {
        return;
    }

    const actionableSelector = [
        'input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"])',
        'textarea',
        'select',
        'summary',
        'button',
        'a.button',
        '[role="button"]'
    ].join(',');

    let currentTarget = null;
    let clearTimer = null;

    function isAgencyActive() {
        return dashboardPage.getAttribute('data-matewa-active-panel') === 'agency';
    }

    function isInsideVisitorChips(node) {
        return Boolean(node && node.closest && node.closest('.matewa-agency-client-chip-grid, #matewa-chip-labels-section'));
    }

    function isRelevantControl(node) {
        if (!node || !node.matches || !node.matches(actionableSelector)) {
            return false;
        }
        if (isInsideVisitorChips(node)) {
            return false;
        }
        if (node.disabled || node.getAttribute('aria-disabled') === 'true') {
            return false;
        }
        if (node.closest('[hidden], .hidden, .matewa-admin-hidden-action-form')) {
            return false;
        }

        const name = String(node.getAttribute('name') || '').toLowerCase();
        const text = String(node.textContent || node.value || '').toLowerCase();
        const className = String(node.className || '').toLowerCase();

        if (name.indexOf('delete') !== -1 || text.indexOf('delete') !== -1 || className.indexOf('danger') !== -1) {
            return false;
        }

        return true;
    }

    function getHighlightTarget(control) {
        if (!control || !control.closest) {
            return null;
        }

        return control.closest([
            '.matewa-agency-remote-sending-scope',
            '.matewa-agency-remote-push-card',
            '.matewa-agency-client-pack-form',
            '.matewa-agency-client-import-card',
            '.matewa-agency-email-proxy-card',
            '.matewa-agency-bundle-panel',
            '.matewa-agency-client-pack-row',
            '.matewa-agency-hub-card',
            'details',
            'label',
            '.matewa-field-row'
        ].join(','));
    }

    function clearHighlight() {
        if (clearTimer) {
            window.clearTimeout(clearTimer);
            clearTimer = null;
        }

        if (currentTarget) {
            currentTarget.classList.remove('is-agency-helper-current');
            currentTarget = null;
        }
    }

    function setHighlight(control) {
        if (!isAgencyActive() || !isRelevantControl(control)) {
            return;
        }

        const target = getHighlightTarget(control);
        if (!target || isInsideVisitorChips(target)) {
            return;
        }

        if (clearTimer) {
            window.clearTimeout(clearTimer);
            clearTimer = null;
        }

        if (currentTarget && currentTarget !== target) {
            currentTarget.classList.remove('is-agency-helper-current');
        }

        currentTarget = target;
        currentTarget.classList.add('is-agency-helper-current');
    }

    agencyPanel.addEventListener('focusin', function (event) {
        setHighlight(event.target);
    }, true);

    agencyPanel.addEventListener('click', function (event) {
        setHighlight(event.target);
    }, true);

    agencyPanel.addEventListener('input', function (event) {
        setHighlight(event.target);
    }, true);

    agencyPanel.addEventListener('change', function (event) {
        setHighlight(event.target);
    }, true);

    agencyPanel.addEventListener('focusout', function () {
        if (clearTimer) {
            window.clearTimeout(clearTimer);
        }
        clearTimer = window.setTimeout(function () {
            if (agencyPanel.contains(document.activeElement)) {
                return;
            }
            clearHighlight();
        }, 2600);
    }, true);
}());

(function () {
    'use strict';

    const cards = document.querySelectorAll('[data-matewa-client-mail-card]');
    if (!cards.length) {
        return;
    }

    function setDisabled(nodes, disabled) {
        nodes.forEach(function (node) {
            const controls = node.querySelectorAll('input, select, textarea');
            controls.forEach(function (control) {
                if (disabled) {
                    control.setAttribute('disabled', 'disabled');
                } else {
                    control.removeAttribute('disabled');
                }
            });
        });
    }

    function sync(card) {
        const routeSelect = card.querySelector('[data-matewa-client-mail-route]');
        if (!routeSelect) {
            return;
        }

        const route = routeSelect.value || 'site_mail';
        card.setAttribute('data-matewa-client-mail-route-current', route);

        const smtpFields = Array.prototype.slice.call(card.querySelectorAll('.matewa-client-mail-smtp-field'));
        const relayFields = Array.prototype.slice.call(card.querySelectorAll('.matewa-client-mail-relay-field'));
        const managedNotes = Array.prototype.slice.call(card.querySelectorAll('[data-matewa-client-mail-managed-note]'));

        smtpFields.forEach(function (field) {
            field.hidden = route !== 'client_smtp';
        });
        relayFields.forEach(function (field) {
            field.hidden = route !== 'managed_relay';
        });
        managedNotes.forEach(function (note) {
            note.hidden = route !== 'managed_relay';
        });

        setDisabled(smtpFields, route !== 'client_smtp');
        setDisabled(relayFields, route !== 'managed_relay');
    }

    cards.forEach(function (card) {
        sync(card);
        const routeSelect = card.querySelector('[data-matewa-client-mail-route]');
        if (routeSelect) {
            routeSelect.addEventListener('change', function () {
                sync(card);
            });
        }
    });
}());


/* AGENCYPDFCREATENEWPACK1LOCK — simple Agency Hub PDF upload dropzones. */
(function () {
    'use strict';

    const dropzones = Array.from(document.querySelectorAll('[data-matewa-agency-pdf-dropzone]'));

    if (!dropzones.length) {
        return;
    }

    function isPdf(file) {
        if (!file) {
            return false;
        }

        const name = String(file.name || '').toLowerCase();
        const type = String(file.type || '').toLowerCase();

        return name.endsWith('.pdf') && (type === '' || type === 'application/pdf');
    }

    dropzones.forEach(function (dropzone) {
        const fileInput = dropzone.querySelector('[data-matewa-agency-pdf-file]');
        const fileLabel = dropzone.querySelector('[data-matewa-agency-pdf-file-name]');

        if (!fileInput || !fileLabel) {
            return;
        }

        function setMessage(message, isError) {
            fileLabel.textContent = message;
            dropzone.classList.toggle('is-error', Boolean(isError));
            dropzone.classList.toggle('has-file', Boolean(message && !isError && message !== 'No PDF selected yet.'));
        }

        function assignFile(file) {
            if (!isPdf(file)) {
                fileInput.value = '';
                setMessage('Please upload a PDF file only.', true);
                return;
            }

            try {
                const transfer = new DataTransfer();
                transfer.items.add(file);
                fileInput.files = transfer.files;
            } catch (error) {
                // Very old browsers may not allow assignment. The Browse Files route still works.
            }

            setMessage(file.name || 'PDF selected.', false);
        }

        ['dragenter', 'dragover'].forEach(function (eventName) {
            dropzone.addEventListener(eventName, function (event) {
                event.preventDefault();
                event.stopPropagation();
                if (fileInput.disabled) {
                    return;
                }
                dropzone.classList.add('is-dragging');
            });
        });

        ['dragleave', 'dragend'].forEach(function (eventName) {
            dropzone.addEventListener(eventName, function (event) {
                event.preventDefault();
                event.stopPropagation();
                dropzone.classList.remove('is-dragging');
            });
        });

        dropzone.addEventListener('drop', function (event) {
            event.preventDefault();
            event.stopPropagation();
            dropzone.classList.remove('is-dragging');

            if (fileInput.disabled) {
                setMessage('No active client seats are available for a new PDF setup pack.', true);
                return;
            }

            const files = event.dataTransfer && event.dataTransfer.files ? event.dataTransfer.files : [];
            if (!files.length) {
                return;
            }

            assignFile(files[0]);
        });

        fileInput.addEventListener('change', function () {
            if (!fileInput.files || !fileInput.files.length) {
                setMessage('No PDF selected yet.', false);
                return;
            }

            assignFile(fileInput.files[0]);
        });
    });
}());

/* AGENCYPDFCREATENEWPACK1LOCK — open the PDF upload details when linked. */
(function () {
    'use strict';

    const panelId = 'matewa-agency-client-pdf-upload-panel';

    function openPanel() {
        const panel = document.getElementById(panelId);
        if (panel && panel.tagName && panel.tagName.toLowerCase() === 'details') {
            panel.open = true;
        }
    }

    if (window.location.hash === '#' + panelId) {
        openPanel();
    }

    document.querySelectorAll('a[href="#' + panelId + '"]').forEach(function (link) {
        link.addEventListener('click', openPanel);
    });
}());

/* 1.1.60 Free preview modal: never leaves wp-admin. */
(function () {
    const modal = document.querySelector('[data-matewa-free-preview-modal]');
    const openers = Array.from(document.querySelectorAll('[data-matewa-free-preview-open]'));
    if (!modal || !openers.length) return;
    const closers = Array.from(modal.querySelectorAll('[data-matewa-free-preview-close]'));

    function openPreview() {
        modal.hidden = false;
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('matewa-free-preview-is-open');
    }
    function closePreview() {
        modal.hidden = true;
        modal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('matewa-free-preview-is-open');
    }
    openers.forEach(btn => btn.addEventListener('click', e => { e.preventDefault(); openPreview(); }));
    closers.forEach(btn => btn.addEventListener('click', e => { e.preventDefault(); closePreview(); }));
    document.addEventListener('keydown', e => { if (e.key === 'Escape' && !modal.hidden) closePreview(); });
})();
