<script lang="ts">
    export let row: Row
    export let rows: Row[]
    import IconBoard from "./iconBoard.svelte"
    import Image from "./image.svelte"
    import InfoBoard from "./infoBoard.svelte"
    import MainPicture from "./mainPicture.svelte"
    import TextContent from "./textContent.svelte"
    import Table from "./table.svelte"
    import Form from "./form/form.svelte"
    import MobileForm from "./form/mobileForm.svelte"
    import { writable } from "svelte/store"
    import { validateFields } from "../../functions/validateFields"
    import { sendForm } from "../../functions/sendForm"
    import GoogleMaps from "../googleMaps.svelte"
    import { navigate } from "svelte-routing"
    import IconInfoBoard from "./iconInfoBoard.svelte"
    import Boxlist from "./boxlist.svelte"
    import ProductPreview from "./productPreview.svelte"

    export let siteId: string
    export let rowNr: number
    let formSend = false

    let formValues = writable<FormValues>({})
    function getRowClass(row: Row) {
        if (row.maxWidth || row.column.some((col) => col.iconBackgroundImage)) return "max-width"
        return row.column.some((col) => col.contentType === "mainPicture") ? "max-width" : "small-max-width"
    }

    function submitForm() {
        const values = Object.entries($formValues).map((entry) => {
            return [
                entry[0],
                !entry[0].includes("numberLabel")
                    ? [entry[1].checked || entry[1].value, entry[1].required]
                    : [entry[1].value, entry[1], entry[1].getAttribute("name"), entry[1].required],
            ]
        })

        const fields = values.filter((entry) => !entry[0].includes("label"))
        const validation = validateFields([...fields])
        if (validation.length) {
            validation.forEach((error) => {
                // @ts-ignore
                if (error[0].includes("block")) {
                    // @ts-ignore
                    error[1]()
                } else {
                    // @ts-ignore
                    $formValues[error[1]].classList.add("invalid")
                    const label = $formValues[`${error[1]}_label`]
                    const errorElement = document.createElement("div")
                    errorElement.className = "error-message"
                    errorElement.textContent = error[0] as string
                    label?.appendChild(errorElement)
                }
            })
        } else {
            const formObj: any = {}
            fields.forEach((entry) => {
                if (Array.isArray(entry[1]) && entry[1].length == 4) {
                    // @ts-ignore
                    if (entry[1][0]) formObj[entry[0]] = entry[1]
                } else {
                    if (!entry[1][0] && !entry[1][1]) return
                    // @ts-ignore
                    formObj[entry[0]] = entry[1][0]
                }
            })
            let form: any
            row.column.forEach((col) => {
                if (col.contentType == "form") form = col
            })
            if (!form) return
            formObj["formRows"] = form.formRows.map((r: FormRow) => r.rowName)
            formObj["formTitle"] = form.formEmailTitle
            formSend = true
            const hny = document.getElementById("hny") as HTMLInputElement
            if (hny) formObj["honey"] = hny.checked
            sendForm(formObj)
        }
    }
    let innerWidth = window.innerWidth
</script>

<main class="row" name="{row.title}" class:max-width="{getRowClass(row) === 'max-width'}" id="{`RowNr` + rowNr}">
    {#if row.title}
        <h3 class="row-title" class:no-margin="{rowNr == 0}">{row?.title || ""}</h3>
    {/if}
    <div class:no-gap="{row.noGap}" class:wrapAfterTwo="{row.column.length >= 4}">
        {#each row.column || [] as col, i}
            {#if col.contentType == "mainPicture"}
                <MainPicture col="{col}" siteId="{siteId}" />
            {:else if col.contentType == "text"}
                <TextContent rows="{rows}" col="{col}" />
            {:else if col.contentType == "infoBoard"}
                <InfoBoard siteId="{siteId}" col="{col}" i="{i}" />
            {:else if col.contentType == "iconInfoBoard"}
                <IconInfoBoard pageId="{siteId}" col="{col}" i="{i}" />
            {:else if col.contentType == "boxlist"}
                <Boxlist col="{col}" />
            {:else if col.contentType == "iconBoard"}
                <IconBoard col="{col}" siteId="{siteId}" />
            {:else if col.contentType == "image"}
                <Image siteImages="{col.imageSlider}" siteId="{siteId}" />
            {:else if col.contentType == "table"}
                <Table col="{col}" rows="{rows}" />
            {:else if col.contentType == "productPreview"}
                <ProductPreview col="{col}" siteId="{siteId}" />
            {:else if col.contentType == "googleMaps"}{#if col.showGoogleMaps}
                    <GoogleMaps />
                {/if}
            {:else if col.contentType == "form"}
                {#if formSend}
                    <div class="success-message">
                        <h1>Formular erfolgreich gesendet!</h1>
                        <p>Vielen Dank für Ihre Anfrage. Wir werden uns in Kürze bei Ihnen melden.</p>
                    </div>
                {:else}
                    <form
                        class="form-rows"
                        on:submit="{(e) => {
                            e.preventDefault()
                            submitForm()
                        }}"
                    >
                        {#each col.formRows ?? [] as formRow, i}
                            {#if innerWidth < 768}
                                <MobileForm formRow="{formRow}" formValues="{formValues}" index="{i}" />
                            {:else}
                                <Form formRow="{formRow}" formValues="{formValues}" index="{i}" />
                            {/if}
                        {/each}
                        <div class="row additional">
                            <div class="data-protection">
                                <label bind:this="{$formValues[`agreement_label`]}">
                                    <input
                                        required="{true}"
                                        class="checkit"
                                        type="checkbox"
                                        on:change="{(e) => {
                                            let element = e.currentTarget
                                            element.classList.remove('invalid')
                                        }}"
                                        bind:this="{$formValues['agreement']}"
                                    />
                                    <span class="checkit-span"></span>
                                </label>

                                <div class="datasec">
                                    <button on:click|preventDefault="{() => navigate('/datenschutz')}" class="link">
                                        Datenschutz
                                    </button>
                                    akzeptieren
                                </div>
                            </div>

                            <input
                                type="checkbox"
                                name="contact_me_by_fax_only"
                                id="hny"
                                value="1"
                                style="display:none !important"
                                tabindex="-1"
                                autocomplete="off"
                            />
                            <button class="submit-request" type="submit">Anfrage absenden</button>
                        </div>
                    </form>
                {/if}
            {/if}
        {/each}
    </div>
</main>

<style lang="less" global>
    @import "../../assets/css/variables.less";
    .wave-placeholder {
        height: 10px;
    }

    input,
    select,
    textarea,
    .data-protection {
        margin: 5px 0px;
        box-shadow: 0 0 25px 10px var(--opposite-bg-color-5);
    }

    .success-message {
        h1 {
            color: var(--heading-font-color);
            font-size: 36px;
            margin-top: 50px;
        }

        p {
            font-size: 20px;
            margin-top: 20px;
        }
    }
    .invalidBlocks {
        border: 2px solid rgb(255, 0, 0) !important;
        position: relative;
        &::after {
            font-size: 0.9rem !important;
            color: red !important;
            position: absolute;
            bottom: 2px;
            content: "Bitte wähle entweder eine Kartenanzahl oder einen Wunschbetrag aus.";
        }
    }

    .border-red {
        border-color: red !important;
    }

    .row-title {
        font-size: 1.6rem;
        font-weight: bold;
        line-height: normal;
        width: 100%;
        color: var(--heading-font-color);
        @media @mobile {
            margin: 3.2rem 1.5vw 1.6rem;
        }

        @media @desktop {
            margin: 6rem 0vw 1.6rem 0vw;
        }
    }
    .no-margin {
        margin-top: 15px !important;
    }

    .invalid {
        border-bottom: 2px solid red !important;
    }
    .error-message {
        font-size: 0.9rem !important;
        color: red !important;
        position: absolute;
    }

    .row {
        width: 100%;
        padding: 0px 0px 15px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        max-width: @body-small-maxwidth;

        input[type="number"]::-webkit-inner-spin-button,
        input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
            height: 100%;
        }

        input[type="number"] {
            -moz-appearance: textfield;
            appearance: textfield;
        }

        ul {
            list-style-type: none; /* Remove default bullet points */
            padding: 0;

            li {
                padding-left: 1.5em; /* Add padding to the left of the list items */
                position: relative;
            }

            li::before {
                content: ""; /* Add an empty content */
                background-image: url("../../../../media/arrow-right.svg");
                background-size: contain;
                background-repeat: no-repeat;
                position: absolute;
                left: 0; /* Position the SVG at the beginning of the list item */
                width: 1em; /* Adjust the width of the SVG */
                height: 1em; /* Adjust the height of the SVG */
                top: 0.2em; /* Adjust the vertical alignment of the SVG */
            }
        }
        & > div {
            width: 100%;
        }
        & > h3 {
            width: 100%;
        }
        .checkit {
            display: none;
        }

        .checkit-span {
            height: 20px;
            width: 20px;
            border: 1px solid grey;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        [type="checkbox"]:checked + span:before {
            content: "\2714";
            position: absolute;
            transform-origin: bottom;
        }
        &.additional {
            display: flex;

            @media @mobile {
                flex-direction: column;
            }
            @media @tablet {
                flex-direction: row;
            }
            gap: 2.5rem;
            div {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: start;
            }
            .submit-request {
                flex: 1;
                box-shadow: 0 0 25px 10px var(--opposite-bg-color-5);
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: start;
                background-color: var(--heading-font-color);
                color: var(--background-color);
                padding: 10px 20px;
            }
        }
        .form-rows {
            display: flex;
            flex-direction: column;

            gap: 1.5rem;
            width: 100%;
            h3 {
                font-weight: bold !important;
            }

            .form-row {
                display: flex;
                flex-direction: column;
                width: 100%;
                gap: 1.5rem;

                .date {
                    max-width: 100%;
                    box-sizing: border-box;
                }
                label {
                    width: 100% !important;
                    font-size: inherit;
                    input,
                    select,
                    textarea {
                        width: 100%;
                        font-size: inherit;
                    }
                }
                .form-cols {
                    display: flex;
                    gap: 1.5rem;
                    width: 100%;
                }
            }

            .form-column {
                display: flex;
                flex: 1;
                flex-direction: column;
                justify-content: flex-end;
                gap: 1rem;
                border-radius: 4px;
            }

            h3 {
                margin-bottom: 0.5rem;
                font-size: 1.2rem;
                font-weight: bold;
            }

            p {
                margin-bottom: 0.5rem;
                color: var(--hover-color);
            }

            input,
            select,
            textarea,
            .data-protection {
                padding: 10px 20px;
                border: 0px solid var(--opposite-bg-color);
                border-bottom: 3px solid var(--heading-font-color);
                outline: 0px solid var(--opposite-bg-color);
                color: var(--opposite-bg-color);
                background-color: var(--background-color);
                resize: none;
            }

            .data-protection {
                display: flex;

                flex-wrap: nowrap;
                gap: 5px !important;
                justify-content: start;
                flex-direction: row !important;
            }

            input[type="date"] {
                font-family: inherit;
                width: 100% !important;
                position: relative;
            }

            select {
                padding: 10px 20px;
                border: 0;
                border-bottom: 3px solid var(--heading-font-color);
                outline: none;
            }

            select:focus {
                border-bottom-color: var(--heading-font-color);
            }

            #time-select {
                appearance: none;
                background-image: url("../../../../media/clock.svg");
                background-repeat: no-repeat;
                background-position: right 20px center;
                background-size: 18px;

                option {
                    padding: 10px 20px;
                    background-color: var(--background-color);
                }
            }
            @media @mobile {
                .date {
                    width: 100vw !important;
                }
            }
            @media @tablet {
                .date {
                    width: 100% !important;
                }
                .form-cols {
                    flex-direction: row;
                }
            }
        }

        @media @mobile {
            .no-gap {
                gap: 0px !important;
            }

            & > div {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: start;

                gap: 20px;

                & > div {
                    flex: 1;
                }
            }
        }

        @media @tablet {
            & > div {
                gap: 40px;
            }
            & > div.wrapAfterTwo {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
            }
        }
        @media @desktop {
            .no-gap {
                gap: 40px !important;
            }
            .row-title {
                font-size: 2.5rem !important;
            }
            & > div,
            & > div.wrapAfterTwo {
                display: flex;
                flex-direction: row;
                align-items: start;
                justify-content: center;
            }
        }
    }
    .max-width {
        max-width: @body-maxwidth !important;
    }

    .datasec {
        display: flex;
        align-items: center !important;
        .link {
            height: 100%;
            display: flex;
            align-items: flex-end !important;
            text-decoration: underline;
            margin-right: 3px;
            color: rgb(14, 91, 146);
        }
    }
</style>
