<template>
    <Head :title="form ? `Edit ${form.name}` : 'Create Form'" />
    <AppLayout :no-padding="true">
        <div class="fb-main">

            <!-- Top bar -->
            <div class="fb-topbar">
                <div class="fb-topbar-left">
                    <Link :href="route('forms.index')" class="fb-back-link">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
                        </svg>
                        Forms
                    </Link>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width:14px;height:14px;color:#d1d5db">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
                    </svg>
                    <div class="fb-name-wrap">
                        <input type="text" class="fb-form-name" v-model="name" placeholder="Untitled Form">
                        <select v-model="status" class="fb-draft-badge" style="border:none;cursor:pointer">
                            <option value="draft">Draft</option>
                            <option value="active">Active</option>
                            <option value="paused">Paused</option>
                        </select>
                    </div>
                </div>

                <div class="fb-topbar-center">
                    <button type="button" class="fb-tab-btn" :class="{ 'is-active': topTab === 'editor' }" @click="topTab = 'editor'">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:13px;height:13px;display:inline;margin-right:4px;vertical-align:middle"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25z" /></svg>
                        Editor
                    </button>
                    <button type="button" class="fb-tab-btn" :class="{ 'is-active': topTab === 'settings' }" @click="topTab = 'settings'">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:13px;height:13px;display:inline;margin-right:4px;vertical-align:middle"><path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" /><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
                        Settings
                    </button>
                </div>

                <div class="fb-topbar-right">
                    <button type="button" class="btn btn-outline btn-sm" @click="preview">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:14px;height:14px"><path stroke-linecap="round" stroke-linejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" /><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
                        Preview
                    </button>
                    <button v-if="form" type="button" class="btn btn-outline btn-sm" @click="showEmbedModal = true">
                        Embed
                    </button>
                    <button type="button" class="btn btn-primary btn-sm" @click="save" :disabled="saving">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" /></svg>
                        {{ saving ? 'Saving…' : 'Save Form' }}
                    </button>
                </div>
            </div>

            <!-- Workspace -->
            <div v-show="topTab === 'editor'" class="fb-editor-body">
                <FormEditor ref="formEditorRef" v-model="state.blocks" />
            </div>
            <div v-show="topTab === 'settings'" class="fb-settings-standalone">
                <FormSettingsPanel />
            </div>
        </div>

        <EmbedCodeModal :open="showEmbedModal" :embed="form?.embed" @close="showEmbedModal = false" @activate="activateAndSave" />
    </AppLayout>
</template>

<script setup>
import { provide, reactive, ref } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import FormEditor from '@/Components/FormEditor/FormEditor.vue';
import FormSettingsPanel from '@/Components/FormBuilder/FormSettingsPanel.vue';
import EmbedCodeModal from '@/Components/Forms/EmbedCodeModal.vue';

const props = defineProps({
    type: { type: String, default: 'inline' },
    form: { type: Object, default: null },
    allLists: { type: Array, default: () => [] },
    allTags: { type: Array, default: () => [] },
    fieldRegistry: { type: Object, default: () => ({}) },
});

const name = ref(props.form?.name || 'Untitled Form');
const status = ref(props.form?.status || 'draft');
const saving = ref(false);
const showEmbedModal = ref(false);
const topTab = ref('editor');
const formEditorRef = ref(null);

const state = reactive({
    type: props.form?.type || props.type,
    blocks: props.form?.fields?.length ? props.form.fields : [],
    settings: {
        submit_button_text: 'Subscribe',
        after_submit_action: 'message',
        success_message: 'Thank you for subscribing!',
        redirect_url: '',
        popup_trigger: 'delay',
        popup_trigger_value: 5,
        popup_display_style: 'center_modal',
        popup_frequency: 'every_visit',
        ...(props.form?.settings || {}),
    },
    list_ids: props.form?.list_ids ? [...props.form.list_ids] : [],
    tag_ids: props.form?.tag_ids ? [...props.form.tag_ids] : [],
});

// FormBlockSettings (nested inside FormEditor) injects this same key to
// reach fieldRegistry/allLists/allTags - see its comment for why inject()
// reaching past FormEditor's own provide works.
provide('formBuilderState', {
    allLists: props.allLists,
    allTags: props.allTags,
    fieldRegistry: props.fieldRegistry,
    state,
});

function save(onSuccess) {
    // Force any pending debounced edit (a color pick, a padding tweak, etc.)
    // into state.blocks synchronously first - otherwise a Save click made
    // within the editor's 400ms flush window would persist stale data.
    formEditorRef.value?.flush();
    saving.value = true;

    const payload = {
        name: name.value || 'Untitled Form',
        type: state.type,
        status: status.value,
        fields: state.blocks,
        settings: state.settings,
        style: {},
        list_ids: state.list_ids,
        tag_ids: state.tag_ids,
    };

    const opts = {
        preserveScroll: true,
        onFinish: () => { saving.value = false; },
        onSuccess: () => { if (onSuccess) onSuccess(); },
    };

    if (props.form) {
        router.put(route('forms.update', props.form.id), payload, opts);
    } else {
        router.post(route('forms.store'), payload, opts);
    }
}

function activateAndSave() {
    status.value = 'active';
    showEmbedModal.value = false;
    save();
}

function preview() {
    if (!props.form) {
        window.alert('Save the form first to preview it.');
        return;
    }

    // Open the window synchronously (inside the click handler) so browsers
    // don't treat it as a blocked popup, then fill it in once the save
    // (always run first, so the preview never shows a stale version of the
    // form) resolves and props.form.embed is fresh.
    const w = window.open('', '_blank');
    if (w) w.document.write('<!doctype html><html><body style="font-family:sans-serif;padding:40px;color:#6b7280;">Saving…</body></html>');

    save(() => {
        if (!w || w.closed || !props.form?.embed) return;
        w.document.open();
        w.document.write(`<!doctype html><html><head><title>${name.value} - Preview</title></head><body style="font-family:sans-serif;padding:40px;max-width:700px;margin:0 auto;">${props.form.embed.preview_html}</body></html>`);
        w.document.close();
    });
}
</script>

<style scoped>
.fb-editor-body {
    flex: 1;
    min-height: 0;
    display: flex;
}
.fb-settings-standalone {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    max-width: 520px;
    width: 100%;
    margin: 0 auto;
    padding: 24px;
    box-sizing: border-box;
}
</style>
