document.addEventListener('DOMContentLoaded', function () {

    const input = document.getElementById('party_name');
    const box = document.getElementById('partySuggestions');

    if (!input || !box) {
        return;
    }

    let timer = null;

    input.addEventListener('input', function () {

        const term = this.value.trim();

        clearTimeout(timer);

        if (term.length < 2) {
            box.innerHTML = '';
            box.style.display = 'none';
            return;
        }

        timer = setTimeout(function () {

            fetch(
                `/case-search/party-suggestions?term=${encodeURIComponent(term)}`,
                {
                    headers: {
                        'Accept': 'application/json'
                    }
                }
            )
            .then(response => response.json())
            .then(data => {

                box.innerHTML = '';

                if (!data.length) {

                    box.innerHTML = `
                        <div class="party-suggestion-empty">
                            No matching party found
                        </div>
                    `;

                    box.style.display = 'block';

                    return;
                }


                data.forEach(function (item) {

                    // Petitioner
                    if (item.pet_name) {

                        addSuggestion(
                            item.pet_name,
                            'Petitioner',
                            item,
                            term
                        );

                    }


                    // Respondent
                    if (
                        item.res_name &&
                        item.res_name.toLowerCase() !==
                        (item.pet_name || '').toLowerCase()
                    ) {

                        addSuggestion(
                            item.res_name,
                            'Respondent',
                            item,
                            term
                        );

                    }

                });


                if (box.children.length > 0) {
                    box.style.display = 'block';
                } else {
                    box.style.display = 'none';
                }

            })
            .catch(error => {

                console.error(
                    'Party suggestion error:',
                    error
                );

                box.innerHTML = '';
                box.style.display = 'none';

            });

        }, 250);

    });


    function addSuggestion(name, type, item, term) {

        const div = document.createElement('div');

        div.className = 'party-suggestion-item';

        div.innerHTML = `

            <div class="party-suggestion-main">

                <i class="bi bi-person"></i>

                <span>
                    ${highlight(name, term)}
                </span>

            </div>

            <div class="party-suggestion-info">

                <span class="party-type">
                    ${type}
                </span>

                <span>
                    ${item.caseno || ''}
                    ${item.caseyear ? '-' + item.caseyear : ''}
                </span>

            </div>

        `;


        div.addEventListener('click', function () {

            input.value = name;

            box.innerHTML = '';
            box.style.display = 'none';

            input.focus();

        });


        box.appendChild(div);

    }


    function highlight(text, term) {

        const escaped = term.replace(
            /[.*+?^${}()|[\]\\]/g,
            '\\$&'
        );

        const regex = new RegExp(
            `(${escaped})`,
            'gi'
        );

        return text.replace(
            regex,
            '<strong>$1</strong>'
        );

    }


    // बाहर click करने पर suggestions बंद

    document.addEventListener('click', function (event) {

        if (
            !input.contains(event.target) &&
            !box.contains(event.target)
        ) {

            box.innerHTML = '';
            box.style.display = 'none';

        }

    });

});

