<script>
    import ChannelLayout from "../../layouts/ChannelLayout.svelte";
    import { onMount } from "svelte";
    import TextField from "./fields/TextField.svelte";
    import LocaleChooser from "./LocaleChooser.svelte";
    import RecordStatus from "./RecordStatus.svelte";
    import PublishingOptions from "./PublishingOptions.svelte";
    import { getSelectedLocales } from "./locale.svelte.js";
    let { channel, user, data } = $props();
    let selectedLocales = $state(getSelectedLocales());
    let record = $state(data.record);

    function handleLocaleChange() {
        selectedLocales = getSelectedLocales();
    }
</script>

<!-- <svelte:window on:beforeunload={beforeUnload} /> -->
<ChannelLayout {body} {channel} schemas={data.schemas} {user}></ChannelLayout>
{#snippet body()}
    <RecordStatus {channel} {record} status={data.recordStatus}></RecordStatus>
    <div style="display:flex;gap:20px;justify-content: space-between;">
        <LocaleChooser {channel} onLocaleChange={handleLocaleChange}
        ></LocaleChooser>
        <PublishingOptions {record} status={data.recordStatus}
        ></PublishingOptions>
    </div>
    <fieldset disabled={data.recordStatus === "trashed"}>
        {#each data.fields as field}
            <div style="display:flex;gap:20px;">
                {#if field.type === "text"}
                    <TextField
                        {channel}
                        {record}
                        validationError={data.validationErrors.find(
                            (f) =>
                                f.fieldId === field.id && f.locale === "main",
                        )}
                        schemaField={field}
                        locale="main"
                        dataField={data.draftData.find(
                            (f) => f.id === field.id && f.locale === "main",
                        )}
                    ></TextField>
                    {#if field.translatable}
                        {#each selectedLocales as locale (locale)}
                            <TextField
                                {channel}
                                {record}
                                validationError={data.validationErrors.find(
                                    (f) =>
                                        f.fieldId === field.id &&
                                        f.locale === locale,
                                )}
                                schemaField={field}
                                {locale}
                                dataField={data.draftData.find(
                                    (f) =>
                                        f.id === field.id &&
                                        f.locale === locale,
                                )}
                            ></TextField>
                        {/each}
                    {/if}
                {/if}
            </div>
        {/each}
    </fieldset>
{/snippet}
