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

    let groupSelectElement = document.getElementById("election-group"),
        areaSelectElement = document.getElementById("election-area"),
        formContainer = document.querySelector(".election-form--form");

// STEP 1: LOAD SEARCH ITEMS

    // Load all groups and areas
    if (formContainer) {
        fetch("https://ihk-wahl.info/selects?ihk_id=M6uOiDGzTD7SlhF1")
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Fill in groups
                // Remove old entries
                while (groupSelectElement.firstChild) {
                    groupSelectElement.removeChild(groupSelectElement.firstChild);
                }

                // Sort groups alphabetically by name
                let sortedGroups = data.groups.slice().sort(function (a, b) {
                    return a.number.localeCompare(b.number);
                });

                // Populate with sorted options
                let groupsOptionElement = document.createElement("option");
                groupsOptionElement.value = "-";
                groupsOptionElement.textContent = "Wahlgruppe (Alle)";
                groupsOptionElement.setAttribute("data-number", "");
                groupsOptionElement.setAttribute("data-title", "Alle");
                groupSelectElement.appendChild(groupsOptionElement);
                sortedGroups.forEach(function (group) {
                    let groupsOptionElement = document.createElement("option");
                    groupsOptionElement.value = group.id;
                    groupsOptionElement.textContent = group.number + " " + group.title;
                    groupsOptionElement.setAttribute("data-number", group.number);
                    groupsOptionElement.setAttribute("data-title", group.title);
                    groupSelectElement.appendChild(groupsOptionElement);
                });

                // Fill in areas
                // Remove old entries
                while (areaSelectElement.firstChild) {
                    areaSelectElement.removeChild(areaSelectElement.firstChild);
                }

                // Sort groups alphabetically by name
                let sortedAreas = data.districts.slice().sort(function (a, b) {
                    return a.number.localeCompare(b.number);
                });

                // Populate with sorted options
                let areasOptionElement = document.createElement("option");
                areasOptionElement.value = "-";
                areasOptionElement.textContent = "Wahlbezirk (Alle)";
                areasOptionElement.setAttribute("data-number", "");
                areasOptionElement.setAttribute("data-title", "Alle");
                areaSelectElement.appendChild(areasOptionElement);
                sortedAreas.forEach(function (district) {
                    let areasOptionElement = document.createElement("option");
                    areasOptionElement.value = district.id;
                    areasOptionElement.textContent = district.number + " " + district.title;
                    areasOptionElement.setAttribute("data-number", district.number);
                    areasOptionElement.setAttribute("data-title", district.title);
                    areaSelectElement.appendChild(areasOptionElement);
                });
            })
            .catch(error => {
                // Handle errors here
                console.error('Fetch error:', error);
            });

// STEP 2: CLICK SEARCH

        // Click on search
        const hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = 'ihk_id';
        hiddenInput.value = 'M6uOiDGzTD7SlhF1';
        formContainer.appendChild(hiddenInput);

        formContainer.onsubmit = function (e) {
            e.preventDefault();

            submitForm(e);

        };
        let selectElements = formContainer.querySelectorAll("select");
        selectElements.forEach(select => {
            select.addEventListener("change", function (e) {
                submitForm();
            });
        });

        document.addEventListener("click", function (event) {
            // click one of the search again links
            if (event.target && (event.target.getAttribute("data-search") === "group" || event.target.getAttribute("data-search") === "area")) {
                let id = event.target.getAttribute("data-id");
                document.getElementById("election-searchstring").value = "";
                if (event.target.getAttribute("data-search") === "group") {
                    document.getElementById("election-group").value = id;
                    document.getElementById("election-area").value = "-";
                } else if (event.target.getAttribute("data-search") === "area") {
                    document.getElementById("election-group").value = "-";
                    document.getElementById("election-area").value = id;
                }
                submitForm();
            }

            // click the detail page link
            const topBoxElement = event.target.closest(".top-box");
            if (topBoxElement) {
                let ihkId = topBoxElement.getAttribute("data-ihk_id"),
                    candidate = topBoxElement.getAttribute("data-c");
                showDetailPage(event, ihkId, candidate);
            }

            // click the back button
            if (event.target.closest(".election-detail--back a")) {
                event.preventDefault();
                hideDetailPage();
            }
        });
    }

// STEP 3 NEW: SET LINK AND LOAD DETAIL PAGE


});

function submitForm(e) {
    let formData,
        groupSelectElement = document.getElementById("election-group"),
        areaSelectElement = document.getElementById("election-area"),
        xhr = new XMLHttpRequest();

    if(e) {
        formData = new FormData(e.target);
    } else {
        formData = new FormData(document.querySelector(".election-form--form"));
    }

    xhr.open("POST", "https://ihk-wahl.info/search", true);

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                console.log("Form data sent successfully!");
                let data = JSON.parse(xhr.responseText); // Assuming the backend sends JSON response

                // Add badge with result (group and area)
                let badgeGroupsAreas = document.querySelector(".election-result-list--header-left"),
                    selectedGroupOption = groupSelectElement.options[groupSelectElement.selectedIndex],
                    groupNumber = selectedGroupOption.getAttribute("data-number"),
                    groupTitle = selectedGroupOption.getAttribute("data-title"),
                    selectedAreaOption = areaSelectElement.options[areaSelectElement.selectedIndex],
                    areaNumber = selectedAreaOption.getAttribute("data-number"),
                    areaTitle = selectedAreaOption.getAttribute("data-title"),
                    searchContent = document.getElementById("election-searchstring");

                let badgeHtml = "";

                badgeHtml += (groupNumber !== "" || groupTitle !== "") && (groupTitle !== "Alle") ? `
                            <div class="election-result-list-badge inverted closable" data-name="group">
                                <div class="badge-inner">
                                  <p>Wahlgruppe ${groupNumber}: <span>${groupTitle}</span></p>
                                </div>
                            </div>
                        ` : '';

                badgeHtml += (areaNumber !== "" || areaTitle !== "") && (areaTitle !== "Alle") ? `
                            <div class="election-result-list-badge inverted closable" data-name="area">
                                <div class="badge-inner">
                                    <p>Wahlbezirk ${areaNumber}: <span>${areaTitle}</span></p>
                                </div>
                            </div>
                        ` : '';

                badgeHtml += searchContent.value !== "" ? `
                            <div class="election-result-list-badge inverted closable" data-name="searchstring">
                                <div class="badge-inner">
                                    <p>Suchbegriff: <span>${searchContent.value}</span></p>
                                </div>
                            </div>
                        ` : '';

                badgeGroupsAreas.innerHTML = badgeHtml;
                let badgeElements = badgeGroupsAreas.querySelectorAll(".election-result-list-badge");
                badgeElements.forEach(badgeElement => {
                    badgeElement.addEventListener("click", badgeClick);
                });

                // Add badge with index of results
                let badgeResultsContainer = document.querySelector(".election-result-list--header"),
                    badgeResults = null,
                    resultsIndex = "";

                // Iterate through the direct children of headerElement
                for (let i = 0; i < badgeResultsContainer.children.length; i++) {
                    let child = badgeResultsContainer.children[i];
                    if (child.classList.contains("election-result-list-badge")) {
                        badgeResults = child;
                        break;
                    }
                }
                resultsIndex = data.res.length;

                // Insert Badge with resultsIndex
                badgeResults.innerHTML = `
                          <div class="badge-inner">
                            <p>${resultsIndex}<span>Kanditat:innen</span></p>
                          </div>
                        `;

                // Add candidates to list
                let candidatesContainer = document.querySelector(".election-result-list--inner");
                candidatesContainer.innerHTML = "";

                // Sort groups alphabetically by name
                let sortedCandidates = data.res.slice().sort(function (a, b) {
                    return a.last_name.localeCompare(b.last_name);
                });

                sortedCandidates.forEach(function (candidate) {
                    let html = `
                                <div class="election-result-list-item">
                                    <span class="top-box" data-ihk_id="${data.ihk_id}" data-c="${candidate.candidate_id}">
                                        <div class="image-box">
                                            <img src="${candidate.img_path}" loading="lazy" class="loading" width="310" height="310">
                                        </div>
                                        <h3>${candidate.first_name} ${candidate.last_name}</h3>
                                    </span>
                                    <div class="text-box">
                                        <div class="job-box">
                                            <span class="icon-small-election-group" data-search="group" data-id="${candidate.candidate_election_group_id}">${candidate.candidate_election_group_name}</span>
                                        </div>
                                        <div class="city-box">
                                            <span class="icon-small-icon-election-location" data-search="area" data-id="${candidate.candidate_election_district_id}">${candidate.candidate_election_district_name}</span>
                                        </div>
                                    </div>
                                </div>
                            `;

                    candidatesContainer.innerHTML += html;
                });

            } else {
                console.error("Error sending form data.");
            }
        }
    };

    xhr.send(formData);
}

// Return phone number to call
function formatNumberLink(phoneNo) {
    const phoneNoStripped = phoneNo.replace(/\D/g, '');
    if (phoneNoStripped !== "") {
        let formatedNo = phoneNoStripped;
        if (phoneNoStripped.startsWith('49')) {
            // has leading 49 - countrycode
            formatedNo = `00${phoneNoStripped}`;
        } else if (phoneNoStripped.startsWith('0')) {
            if (phoneNoStripped.startsWith('000')) {
                // has three leading zeros - countrycode with error?
                formatedNo = phoneNoStripped.substr(1);
            } else if (phoneNoStripped.startsWith('00')) {
                // has two leading zeros - countrycode
                // Do nothing
            } else {
                // has leading zero
                formatedNo = `0049${phoneNoStripped.substr(1)}`;
            }
        }
        return formatedNo;
    }
    return phoneNo;
}

// Return phone number to show on website
function formatNumberOutput(phoneNo) {
    const allowedChars = /[0-9\-\/\s]/g;
    if (phoneNo.match(allowedChars) !== null) {
        const phoneNoStripped = phoneNo.match(allowedChars).join('');
        let formatedNo = phoneNoStripped;

        if (phoneNoStripped.startsWith('49')) {
            // has leading 49 - countrycode
            formatedNo = `+${phoneNoStripped}`;
        } else if (phoneNoStripped.startsWith('0')) {
            if (phoneNoStripped.startsWith('000')) {
                // has three leading zeros - countrycode with error?
                formatedNo = `+${phoneNoStripped.substr(3)}`;
            } else if (phoneNoStripped.startsWith('00')) {
                // has two leading zeros - countrycode
                formatedNo = `+${phoneNoStripped.substr(2, 2)} ${phoneNoStripped.substr(4)}`;

            } else {
                // has leading zero
                formatedNo = `+49 ${phoneNoStripped.substr(1)}`;
            }
        }

        // Überprüfe, ob nach "+49" ein Leerzeichen folgt, falls nicht, füge es hinzu
        if (formatedNo.startsWith('+49') && !formatedNo.includes(' ', 3)) {
            formatedNo = `${formatedNo.slice(0, 3)} ${formatedNo.slice(3)}`;
        }

        return formatedNo;
    }
    return phoneNo;
}

// STEP 2B: CLICK BADGE (RELOAD SEARCH)
function badgeClick(e) {
    const clickedBadge = e.target.closest(".election-result-list-badge"),
          dataName = clickedBadge.getAttribute("data-name");

    if (dataName === "group") {
        let groupSelectElement = document.getElementById("election-group");
        groupSelectElement.value = "-";
    } else if (dataName === "area") {
        let areaSelectElement = document.getElementById("election-area");
        areaSelectElement.value = "-";
    } else if (dataName === "searchstring") {
        let searchElement = document.getElementById("election-searchstring");
        searchElement.value = "";
    }
    submitForm();
}

// STEP 3: LOAD DETAIL PAGE
function showDetailPage(e, ihkIdValue, cValue) {
    let electionDetail = document.querySelector(".election-detail"),
        electionDetailText = electionDetail.querySelector('.election-detail--text'),
        electionDetailVideo = electionDetail.querySelector('.election-detail--video'),
        electionDetailInfo = electionDetail.querySelector('.election-detail--info'),
        htmlText = '',
        htmlVideo = '',
        htmlInfo = '',
        staticElectionOverviewElement = document.getElementById("static-election-overview"),
        staticElectionDetailElement = document.getElementById("static-election-detail");

    fetch("https://ihk-wahl.info/candidate?ihk_id=" + ihkIdValue + "&candidate=" + cValue)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log(data);
            // Build the detail page for the candidate

            htmlText += data.img_path ? `
                <img src="${data.img_path}" loading="lazy" class="loading" width="545" height="526">
            ` : '';

            htmlText += '<div class="text-box">';

            htmlText += (data.first_name && data.last_name) ? `
                <h1>${data.first_name} ${data.last_name}</h1>
            ` : '';

            htmlText += data.position ? `
                <p class="subheadline">${data.position}</p>
            ` : '';

            htmlText += data.election_statement ? `
                <h2>Was möchten Sie bewegen?</h2>
                <p>${data.election_statement}</p>
            ` : '';

            if (data.twitter_link || data.facebook_link || data.xing_link ||
                data.whatsapp_link || data.linkedin_link || data.threema_link ||
                data.telegram_link) {
                htmlText += `
                    <div class="social-media">
                        <p>Meine Kanäle</p>
                        <ul class="social-icons">
                `;
            }

            htmlText += data.twitter_link ? `
                <li><a class="social-share twitter" href="${data.twitter_link}"></a></li>
            ` : '';

            htmlText += data.facebook_link ? `
                <li><a class="social-share facebook" href="${data.facebook_link}"></a></li>
            ` : '';

            htmlText += data.xing_link ? `
                <li><a class="social-share xing" href="${data.xing_link}"></a></li>
            ` : '';

            htmlText += data.whatsapp_link ? `
                <li><a class="social-share whatsapp" href="${data.whatsapp_link}"></a></li>
            ` : '';

            htmlText += data.linkedin_link ? `
                <li><a class="social-share linkedin" href="${data.linkedin_link}"></a></li>
            ` : '';

            htmlText += data.threema_link ? `
                <li><a class="social-share threema" href="${data.threema_link}"></a></li>
            ` : '';

            htmlText += data.telegram_link ? `
                <li><a class="social-share telegram" href="${data.telegram_link}"></a></li>
            ` : '';

            if (data.twitter_link || data.facebook_link || data.xing_link ||
                data.whatsapp_link || data.linkedin_link || data.threema_link ||
                data.telegram_link) {
                htmlText += `
                        </ul>
                    </div>
                `;
            }

            htmlText += '</div>';

            electionDetailText.innerHTML = htmlText;

            htmlVideo += data.video_path ? `
                <div className="video-container">
                    <figure className="video">
                        <div className="video-box">
            ` : '';

            if (data.video_path && data.video_img_path) {
                htmlVideo += `
                    <video src="${data.video_path}" controls="" poster="${data.video_img_path}"></video>
                `;
            } else if (data.video_path) {
                htmlVideo += `
                    <video src="${data.video_path}" controls=""></video>
                `;
            }

            htmlVideo += data.video_path ? `                                
                        </div>
                    </figure>
                </div>
            ` : '';

            electionDetailVideo.innerHTML = htmlVideo;

            htmlInfo += (data.candidate_election_group_id && data.candidate_election_group_name) ? `
                <div class="info-box info-box-01">
                    <p class="info-headline">Wahlgruppe 02</p>
                    <p class="info-box--content info-box--text">
                        <a href="${data.candidate_election_group_id}">${data.candidate_election_group_name}</a>
                    </p>
                </div>
            ` : '';
            htmlInfo += (data.candidate_election_district_id && data.candidate_election_district_name) ? `
                <div class="info-box info-box-02">
                    <p class="info-headline">Wahlbezirk 05</p>
                    <p class="info-box--content info-box--text">
                        <a href="${data.candidate_election_district_id}">${data.candidate_election_district_name}</a>
                    </p>
                </div>                    
            ` : '';

            htmlInfo += '<div class="info-box info-box-03">';

            htmlInfo += data.company ? `
                <p class="info-headline">Unternehmen</p>
                <div class="info-box--content">
                    <p class="headline">${data.company}</p>
            ` : '';

            htmlInfo += data.company_address ? `
                <p className="address">${data.company_address}</p>
            ` : '';

            htmlInfo += data.website ? `
                <p>
                    <a href="${data.website}" target="_blank">Unternehmenswebseite</a>
                </p>
            ` : '';

            htmlInfo += data.email ? `
                <p>
                    <a href="mailto:${data.email}">E-Mail</a>
                </p>
            ` : '';

            if (data.phone) {

                htmlInfo += `
                    <p>
                        <a href="tel:${formatNumberLink(data.phone)}">${formatNumberOutput(data.phone)}</a>                            
                    </p>
                `;
                console.log(data);
            }

            if (data.phone2) {

                htmlInfo += `
                    <p>
                        <a href="tel:${formatNumberLink(data.phone2)}">${formatNumberOutput(data.phone2)}</a>
                    </p>
                `;
            }

            htmlInfo += data.company ? `
                </div>
            ` : '';

            htmlInfo += '</div>';

            electionDetailInfo.innerHTML = htmlInfo;

            staticElectionOverviewElement.style.display = "none";
            staticElectionDetailElement.style.display = "block";

            if (staticElectionDetailElement) {
                staticElectionDetailElement.scrollIntoView({
                    behavior: "smooth",
                    block: "start",
                });
            }
        })
        .catch(error => {
            // Handle errors here
            console.error('Fetch error:', error);
        });
}

function hideDetailPage(e) {
    let staticElectionOverviewElement = document.getElementById("static-election-overview"),
        staticElectionDetailElement = document.getElementById("static-election-detail");

    staticElectionOverviewElement.style.display = "block";
    staticElectionDetailElement.style.display = "none";

    if (staticElectionOverviewElement) {
        staticElectionOverviewElement.scrollIntoView({
            behavior: "smooth",
            block: "start",
        });
    }
}
