<?php
/**
 * 247ChatMate — Agency Hub partial.
 * Checkpoint: AGENCYHUBRESPONSIBILITYSPLIT1
 *
 * Display-only split from admin/views/partials/agency-hub.php.
 * Expects parent Agency Hub variables to be prepared before include.
 */

defined('ABSPATH') || exit;
?>
    <script type="application/json" id="matewa-agency-client-selector-data">
        <?php echo wp_json_encode($matewa_agency_client_selector_categories, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>
    </script>
    <script>
    (function () {
        const root = document.querySelector('[data-matewa-agency-client-selector]');
        const dataEl = document.getElementById('matewa-agency-client-selector-data');
        if (!root || !dataEl) {
            return;
        }

        const categorySelect = root.querySelector('[data-agency-client-category]');
        const businessSelect = root.querySelector('[data-agency-client-business-type]');
        const industryLabel = root.querySelector('[data-agency-client-industry-label]');
        const categoryLabel = root.querySelector('[data-agency-client-category-label]');
        const businessLabel = root.querySelector('[data-agency-client-business-label]');
        const chipTitle = root.querySelector('[data-agency-client-chip-title]');
        const chipGrid = root.querySelector('[data-agency-client-chip-grid]');
        let data = {};

        try {
            data = JSON.parse(dataEl.textContent || '{}');
        } catch (error) {
            data = {};
        }

        function optionLabel(select) {
            if (!select || !select.options || select.selectedIndex < 0) {
                return '';
            }
            return select.options[select.selectedIndex].textContent.trim();
        }

        function getCurrentOption() {
            const categoryKey = categorySelect ? categorySelect.value : '';
            const businessKey = businessSelect ? businessSelect.value : '';
            const category = data[categoryKey] || {};
            const options = category.options || {};
            return options[businessKey] || null;
        }

        function renderBusinessOptions() {
            if (!categorySelect || !businessSelect) {
                return;
            }

            const category = data[categorySelect.value] || {};
            const options = category.options || {};
            const previous = businessSelect.value;
            businessSelect.innerHTML = '';

            Object.keys(options).forEach(function (key) {
                const item = options[key] || {};
                const option = document.createElement('option');
                option.value = key;
                option.textContent = item.display_label || key;
                businessSelect.appendChild(option);
            });

            if (previous && options[previous]) {
                businessSelect.value = previous;
            }
        }

        const CHIP_MAX_LINES = 2;
        const CHIP_MAX_LINE_CHARS = 20;
        const CHIP_MAX_TOTAL_CHARS = 34;

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

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

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

        function normaliseChipLabelForEditing(value) {
            const raw = normaliseChipLineEndings(value);
            const hasTrailingNewline = raw.endsWith('\n');
            const rawLines = raw.split('\n').slice(0, CHIP_MAX_LINES);
            const out = [];

            rawLines.forEach(function (line, index) {
                const clean = trimLineToLength(String(line || '').replace(/ {2,}/g, ' '), CHIP_MAX_LINE_CHARS);

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

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

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

        function normaliseChipLabelForSave(value) {
            const rawLines = normaliseChipLineEndings(value).split('\n');
            const out = [];

            rawLines.forEach(function (line) {
                if (out.length >= CHIP_MAX_LINES) {
                    return;
                }

                const clean = trimLineToLength(String(line || '').replace(/ {2,}/g, ' ').trim(), CHIP_MAX_LINE_CHARS);
                if (clean !== '') {
                    out.push(clean);
                }
            });

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

        function isChipEditingSecondLine(input) {
            if (!input) {
                return false;
            }

            const value = normaliseChipLineEndings(input.value);
            return value.indexOf('\n') !== -1;
        }

        function keepChipCaretVisible(input) {
            if (!input) {
                return;
            }

            window.requestAnimationFrame(function () {
                input.scrollTop = 0;
            });
        }

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

            const canvas = getAgencyChipTextWidth.canvas || (getAgencyChipTextWidth.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 : '700';
            const fontSize = style && style.fontSize ? style.fontSize : '11.2px';
            const fontFamily = style && style.fontFamily ? style.fontFamily : 'Inter, system-ui, sans-serif';
            context.font = fontWeight + ' ' + fontSize + ' ' + fontFamily;

            return context.measureText(text).width;
        }

        function getAgencyChipTextSpace(input) {
            if (!input) {
                return 0;
            }

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

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

            return 0;
        }

        function agencyChipLabelFitsOneLine(input, label) {
            const clean = String(label || '').replace(/\n+/g, ' ').replace(/\s+/g, ' ').trim();
            if (!clean) {
                return false;
            }

            /*
             * Mirror the locked chip editor behaviour without adding separate
             * Agency Hub chip sizing rules. A short, explicit one-line label
             * such as “Fault Finding” should stay vertically centred even when
             * browser font measurement is a few pixels conservative. Longer
             * labels remain two-line unless they visibly fit.
             */
            if (clean.length <= 13) {
                return true;
            }

            const space = getAgencyChipTextSpace(input);
            if (space <= 0) {
                return false;
            }

            return getAgencyChipTextWidth(input, clean) <= Math.max(1, space - 4);
        }

        function applyChipVerticalClass(input) {
            if (!input) {
                return;
            }
            const shell = input.closest('.matewa-chip-editor-chip');
            if (!shell) {
                return;
            }

            const editingSecondLine = isChipEditingSecondLine(input);
            const label = normaliseChipLabelForSave(input.value);
            shell.classList.toggle('is-single-line', !editingSecondLine && label.indexOf('\n') === -1 && agencyChipLabelFitsOneLine(input, label));
            shell.classList.toggle('is-two-line-editing', editingSecondLine);
            keepChipCaretVisible(input);
        }

        function bindChipFitInputs() {
            if (!chipGrid) {
                return;
            }
            chipGrid.querySelectorAll('textarea[name="matewa_agency_client_chip_labels[]"]').forEach(function (input) {
                applyChipVerticalClass(input);
                if (input.dataset.matewaAgencyChipBound === '1') {
                    return;
                }
                input.dataset.matewaAgencyChipBound = '1';
                input.addEventListener('keydown', function (event) {
                    if (event.key !== 'Enter') {
                        return;
                    }

                    const value = normaliseChipLineEndings(input.value);
                    if (value.indexOf('\n') !== -1) {
                        event.preventDefault();
                        return;
                    }

                    event.preventDefault();
                    const start = input.selectionStart || value.length;
                    const end = input.selectionEnd || value.length;
                    const next = normaliseChipLabelForEditing(value.slice(0, start) + '\n' + value.slice(end));
                    input.value = next;
                    const caret = Math.min(start + 1, input.value.length);
                    input.setSelectionRange(caret, caret);
                    applyChipVerticalClass(input);
                });
                input.addEventListener('input', function () {
                    const clean = normaliseChipLabelForEditing(input.value);
                    if (input.value !== clean) {
                        input.value = clean;
                    }
                    applyChipVerticalClass(input);
                });
            });
        }

        function renderChips() {
            if (!chipGrid) {
                return;
            }

            const current = getCurrentOption();
            const labels = current && Array.isArray(current.chips) && current.chips.length ? current.chips.slice(0, 6) : ['Get a quote', 'Pricing', 'Availability', 'Ask a question', 'Book a job', 'Something else'];
            chipGrid.innerHTML = '';

            labels.forEach(function (label) {
                const item = document.createElement('div');
                const shell = document.createElement('div');
                const input = document.createElement('textarea');
                item.className = 'matewa-chip-editor-item';
                shell.className = 'matewa-chip-editor-chip';
                input.name = 'matewa_agency_client_chip_labels[]';
                input.value = normaliseChipLabelForSave(label || '');
                input.maxLength = 34;
                input.rows = 2;
                input.autocomplete = 'off';
                input.setAttribute('aria-label', 'Visitor button label, maximum 34 characters over two visual rows');
                input.addEventListener('keydown', function (event) {
                    if (event.key !== 'Enter') {
                        return;
                    }

                    const value = normaliseChipLineEndings(input.value);
                    if (value.indexOf('\n') !== -1) {
                        event.preventDefault();
                        return;
                    }

                    event.preventDefault();
                    const start = input.selectionStart || value.length;
                    const end = input.selectionEnd || value.length;
                    const next = normaliseChipLabelForEditing(value.slice(0, start) + '\n' + value.slice(end));
                    input.value = next;
                    const caret = Math.min(start + 1, input.value.length);
                    input.setSelectionRange(caret, caret);
                    applyChipVerticalClass(input);
                });
                input.addEventListener('input', function () {
                    const clean = normaliseChipLabelForEditing(input.value);
                    if (input.value !== clean) {
                        input.value = clean;
                    }
                    applyChipVerticalClass(input);
                });
                shell.appendChild(input);
                item.appendChild(shell);
                chipGrid.appendChild(item);
                applyChipVerticalClass(input);
            });
        }

        function syncHiddenLabels() {
            const categoryText = optionLabel(categorySelect) || 'General';
            const businessText = optionLabel(businessSelect) || 'General';
            if (industryLabel) {
                industryLabel.value = categoryText;
            }
            if (categoryLabel) {
                categoryLabel.value = categoryText;
            }
            if (businessLabel) {
                businessLabel.value = businessText;
            }
            if (chipTitle) {
                chipTitle.textContent = businessText;
            }
        }

        function refreshAll() {
            renderBusinessOptions();
            syncHiddenLabels();
            renderChips();
        }

        if (categorySelect) {
            categorySelect.addEventListener('change', refreshAll);
        }
        if (businessSelect) {
            businessSelect.addEventListener('change', function () {
                syncHiddenLabels();
                renderChips();
            });
        }

        syncHiddenLabels();
        bindChipFitInputs();
    }());
    </script>
