<script lang="ts">
    import CrinkledSection from "../CrinkledSection.svelte"
    import Input from "../widgets/Input.svelte"
    import { apiBaseURL } from "../../../config"
    import SectionTitle from "../widgets/SectionTitle.svelte"

    let firstName = ""
    let lastName = ""
    let message = ""
    let email = ""
    let submitting = false
    let responseMessage = ""
    let responseType: "success" | "error" | "" = ""

    const clearFeedback = () => {
        responseMessage = ""
        responseType = ""
    }

    const updateField = (setter: (value: string) => void) => (event: Event) => {
        const target = event.currentTarget as HTMLInputElement | HTMLTextAreaElement
        setter(target.value)
        if (responseMessage) {
            clearFeedback()
        }
    }

    const onFirstNameChange = updateField((value) => {
        firstName = value
    })

    const onLastNameChange = updateField((value) => {
        lastName = value
    })

    const onMessageChange = updateField((value) => {
        message = value
    })
    const onEmailChange = updateField((value) => {
        email = value
    })

    const submitContact = async () => {
        if (submitting) return

        clearFeedback()

        if (!firstName.trim() || !lastName.trim() || !message.trim()) {
            responseMessage = "Bitte füllen Sie alle Felder aus."
            responseType = "error"
            return
        }

        submitting = true

        try {
            const response = await fetch(`${apiBaseURL}contact`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Accept: "application/json",
                },
                body: JSON.stringify({
                    firstName: firstName.trim(),
                    lastName: lastName.trim(),
                    message: message.trim(),
                }),
            })

            if (!response.ok) {
                throw new Error(`Request failed with status ${response.status}`)
            }

            responseMessage = "Vielen Dank! Wir melden uns zeitnah bei Ihnen."
            responseType = "success"

            firstName = ""
            lastName = ""
            message = ""
        } catch (error) {
            console.error("Failed to submit contact request", error)
            responseMessage = "Leider konnte die Anfrage nicht gesendet werden. Bitte versuchen Sie es erneut."
            responseType = "error"
        } finally {
            submitting = false
        }
    }
</script>

<CrinkledSection>
    {#snippet contentSnippet()}
        <section
            class="small-wrapper contact-row"
            id="kontakt"
        >
            <div class="contact-wrapper">
                <SectionTitle
                    brightBackground={true}
                    title="Kontaktformular"
                    subtitle="Wir sind für Sie da"
                    description="Füllen Sie das Formular aus und wir melden uns zeitnah bei Ihnen."
                />
                <form
                    class="contact-form"
                    on:submit|preventDefault={submitContact}
                >
                    <div class="row">
                        <Input
                            id="contact-first-name"
                            name="firstName"
                            type="text"
                            placeholder="Vorname"
                            bind:value={firstName}
                            onChange={onFirstNameChange}
                            disabled={submitting}
                            classList="contact-input"
                        />
                    </div>
                    <div class="row">
                        <Input
                            id="contact-last-name"
                            name="lastName"
                            type="text"
                            placeholder="Nachname"
                            bind:value={lastName}
                            onChange={onLastNameChange}
                            disabled={submitting}
                            classList="contact-input"
                        />
                    </div>
                    <div class="row">
                        <Input
                            id="contact-email"
                            name="E-Mail"
                            type="text"
                            placeholder="E-Mail"
                            bind:value={email}
                            onChange={onEmailChange}
                            disabled={submitting}
                            classList="contact-input"
                        />
                    </div>
                    <div class="row">
                        <Input
                            id="contact-message"
                            name="message"
                            type="textarea"
                            placeholder="Nachricht"
                            bind:value={message}
                            onChange={onMessageChange}
                            disabled={submitting}
                            classList="contact-input"
                        />
                    </div>
                    {#if responseMessage}
                        <p
                            class={`status ${responseType}`}
                            role={responseType === "error" ? "alert" : "status"}
                            aria-live="polite"
                        >
                            {responseMessage}
                        </p>
                    {/if}
                    <button
                        class="cta primary"
                        type="submit"
                        disabled={submitting}
                    >
                        {submitting ? "Wird gesendet…" : "Absenden"}
                    </button>
                </form>
            </div>
        </section>
    {/snippet}
</CrinkledSection>

<style lang="less">
    @import "../../assets/css/variables.less";

    .contact-row {
        width: 100%;
        background-color: white;
        .contact-wrapper {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 2.4rem;
            width: 100%;
            overflow: visible;
        }

        .copy {
            display: flex;
            flex-direction: column;
            gap: 0.8rem;
            color: var(--text-invers-100);

            h2 {
                margin: 0;
                color: inherit;
            }

            p {
                margin: 0;
            }

            small {
                font-size: 0.875rem;
                letter-spacing: 0.08rem;
                text-transform: uppercase;
                font-weight: 600;
            }
        }

        .contact-form {
            display: flex;
            flex-direction: column;
            gap: 1rem;
            color: var(--text-invers-100);

            .row {
                display: flex;
                flex-direction: column;
                padding: 0px;
                gap: 0.4rem;
            }

            .status {
                margin: 0;
                font-weight: 600;

                &.success {
                    color: var(--text-200);
                }

                &.error {
                    color: var(--primary-100);
                }
            }

            button {
                align-self: flex-end;
            }
        }
    }

    :global(.contact-form label) {
        display: flex;
        flex-direction: column;
        gap: 0.4rem;
        color: var(--text-invers-100);
    }

    :global(.contact-form label > span:not(.underline)) {
        font-weight: 600;
    }

    :global(.contact-form .contact-input) {
        width: 100%;
        padding: 0.75rem 1rem;
        border-radius: 0.5rem;
        border: 1px solid var(--text-invers-100);
        background-color: transparent;
        color: var(--text-invers-100);
        font: inherit;
        transition: border-color 0.2s ease;
    }

    :global(.contact-form textarea.contact-input) {
        min-height: 8rem;
        resize: vertical;
    }

    :global(.contact-form .contact-input:focus) {
        outline: 2px solid var(--text-invers-150);
        outline-offset: 2px;
    }

    :global(.contact-form .contact-input:disabled) {
        cursor: not-allowed;
        opacity: 0.6;
    }

    :global(.contact-form .underline) {
        display: none;
    }

    @media @mobile {
        .contact-row {
            .contact-form {
                button {
                    width: 100%;
                }
            }
        }
    }
</style>
