<script>
    import ChannelLayout from "../../layouts/ChannelLayout.svelte";
    import { onMount } from "svelte";

    import LocaleChooser from "./LocaleChooser.svelte";
    import RecordForm from "./RecordForm.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);
    let showPublished = $state(false);

    function handleLocaleChange() {
        selectedLocales = getSelectedLocales();
    }
    function toggleLiveData() {
        if (!showPublished) {
            // to avoid state sync
            Turbo.visit(window.location.href);
        }
    }
</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>
        {#if record.publishedBy}
            <label>
                <input
                    bind:checked={showPublished}
                    onchange={toggleLiveData}
                    type="checkbox"
                    role="switch"
                />
                Show Live Data
            </label>
        {/if}
        <PublishingOptions {record} status={data.recordStatus}
        ></PublishingOptions>
    </div>
    {#if !showPublished}
        <fieldset disabled={data.recordStatus === "trashed"}>
            <RecordForm
                {channel}
                fields={data.fields}
                edgeRecordPreviews={data.edgeRecordPreviewsDraft}
                filesPreviews={data.filesPreviewsDraft}
                {record}
                {selectedLocales}
                validationErrors={data.validationErrors}
                fieldData={data.draftData}
            ></RecordForm>
        </fieldset>
    {:else}
        <fieldset disabled={true}>
            <RecordForm
                {channel}
                fields={data.fields}
                edgeRecordPreviews={data.edgeRecordPreviewsLive}
                filesPreviews={data.filesPreviewsLive}
                {record}
                {selectedLocales}
                validationErrors={data.validationErrors}
                fieldData={data.liveData}
            ></RecordForm>
        </fieldset>
    {/if}
{/snippet}
