<template>
    <div>
        <LicenseStatusBanner v-if="LicenseStatusBanner" />
        <div class="fmt-builder" v-if="!store.loading">
            <!-- Quick Start Tip - Only for new forms -->
            <div v-if="showNewFormTip" class="fmt-quick-start">
                <div class="fmt-quick-start__icon">
                    <span class="dashicons dashicons-lightbulb"></span>
                </div>
                <div class="fmt-quick-start__content">
                    <strong>{{ __("Quick Start:", "formatrica") }}</strong>
                    {{ __("Save time by applying a template! Click the", "formatrica") }}
                    <img
                        class="fmt-icon fmt-icon--inline"
                        :src="ICON_FILE_SPARK"
                        alt=""
                        aria-hidden="true"
                    />
                    {{ __("button below to choose from pre-built forms.", "formatrica") }}
                </div>
                <button
                    type="button"
                    class="fmt-quick-start__dismiss"
                    @click="dismissNewFormTip()"
                    :title="__('Dismiss')"
                >
                    <span class="dashicons dashicons-no-alt"></span>
                </button>
            </div>

            <header class="fmt-builder__top">
                <div class="fmt-builder__title">
                    <label for="fmt-form-title">{{ __("Form title") }}</label>
                    <input
                        id="fmt-form-title"
                        type="text"
                        :placeholder="__('Untitled form')"
                        v-model="formTitle"
                    />
                </div>
                <div class="fmt-builder__actions">
                    <button
                        type="button"
                        class="button button-secondary fmt-builder__template"
                        @click="toggleTemplates(true)"
                        :title="__('Apply template', 'formatrica')"
                    >
                        <img class="fmt-icon" :src="ICON_FILE_SPARK" alt="" aria-hidden="true" />
                    </button>
                    <button
                        v-if="showAiButton"
                        type="button"
                        class="button button-secondary fmt-builder__ai"
                        @click="showAi = true"
                        :title="__('AI Assistant', 'formatrica')"
                        :aria-label="__('AI Assistant', 'formatrica')"
                    >
                        <img class="fmt-icon" :src="ICON_WAND" alt="" aria-hidden="true" />
                        <span class="fmt-builder__ai-label">{{ __("AI", "formatrica") }}</span>
                    </button>
                    <button
                        type="button"
                        class="button button-secondary fmt-builder__preview"
                        @click="togglePreview(true)"
                        :title="__('Preview form', 'formatrica')"
                        :aria-label="__('Preview form', 'formatrica')"
                    >
                        <img class="fmt-icon" :src="ICON_EYE" alt="" aria-hidden="true" />
                    </button>
                    <button
                        v-if="supportsPinnedPreview || previewPinned"
                        type="button"
                        class="button button-secondary fmt-builder__preview-pin"
                        :class="{ 'fmt-builder__preview-pin--pinned': previewPinned }"
                        @click="previewPinned ? unpinPreview() : pinPreview()"
                        :title="previewPinned ? __('Unpin preview', 'formatrica') : __('Pin preview to the side', 'formatrica')"
                        :aria-label="previewPinned ? __('Unpin preview', 'formatrica') : __('Pin preview to the side', 'formatrica')"
                        :aria-pressed="previewPinned ? 'true' : 'false'"
                        aria-controls="fmt-preview-panel"
                    >
                        <img class="fmt-icon" :src="ICON_PIN" alt="" aria-hidden="true" />
                    </button>
                    <button
                        type="button"
                        class="button button-primary fmt-builder__save"
                        :disabled="store.saving"
                        @click="store.saveForm()"
                    >
                        <span v-if="store.saving">{{ __("Saving…") }}</span>
                        <span v-else>{{ __("Save form") }}</span>
                    </button>
                </div>
            </header>

            <div v-if="store.error" class="notice notice-error">
                <p>{{ store.error }}</p>
            </div>

            <div v-if="store.warning" class="notice notice-warning">
                <p>{{ store.warning }}</p>
            </div>

            <div v-if="store.notice" class="notice notice-success">
                <p>{{ store.notice }}</p>
                <button
                    type="button"
                    class="notice-dismiss"
                    @click="store.clearNotice()"
                >
                    <span class="screen-reader-text">{{ __("Dismiss") }}</span>
                </button>
            </div>

        <main
            ref="layoutRef"
            class="fmt-builder__layout"
            :class="{
                'fmt-builder__layout--palette-collapsed': effectivePaletteCollapsed,
                'fmt-builder__layout--preview-pinned': previewPinned,
            }"
        >
            <div class="fmt-builder__palette-desktop">
                <FieldPalette
                    :collapsed="effectivePaletteCollapsed"
                    @update:collapsed="setPaletteCollapsed"
                    @add-field="addField"
                />
            </div>
            <FormCanvas
                :fields="store.fields"
                :selected-id="selectedFieldId"
                @select="selectField"
                @remove="removeField"
                @duplicate="duplicateField"
                @reorder="handleReorder"
                @create-field="handleCreateFromPalette"
                @open-settings="toggleSettings(true)"
                @open-shortcode="toggleShortcode(true)"
            />
            <FormPreviewPanel
                v-if="previewPinned"
                :form-title="store.title"
                :fields="store.fields"
                :theme="store.options?.theme || null"
                :layout-mode="store.options?.layout?.mode || 'single'"
                @unpin="unpinPreview"
                @expand="expandPreview"
                @apply-theme="applyThemePreview"
            />

            <FieldEditorDrawer
                :placement="previewPinned ? 'pinned-canvas' : 'default'"
            :field="selectedField"
            :fields="store.fields"
            @update="updateField"
            @close="selectedFieldId = null"
        />
        </main>

        <!-- Mobile: the desktop palette is hidden; a FAB opens the palette as
             a bottom sheet. -->
        <button
            type="button"
            class="fmt-mobile-add-fab button button-primary"
            @click="showMobilePalette = true"
            :aria-label="__('Add field', 'formatrica')"
        >
            +
        </button>
        <div
            v-if="showMobilePalette"
            class="fmt-mobile-palette-overlay"
            @click.self="showMobilePalette = false"
        >
            <div class="fmt-mobile-palette-overlay__sheet">
                <div class="fmt-mobile-palette-overlay__bar">
                    <strong>{{ __("Add a field", "formatrica") }}</strong>
                    <button
                        type="button"
                        class="fmt-close-btn"
                        @click="showMobilePalette = false"
                        :aria-label="__('Close', 'formatrica')"
                    >
                        &times;
                    </button>
                </div>
                <FieldPalette
                    :collapsed="false"
                    @add-field="addFieldFromMobile"
                />
            </div>
        </div>

        <FormSettingsModal
            :visible="showSettings"
            :options="store.options"
            :fields="store.fields"
            @update="updateOptions"
            @close="toggleSettings(false)"
            @test-email="sendTestEmail"
        />

            <TemplateModal
                :is-open="showTemplates"
                @close="toggleTemplates(false)"
                @select="applyTemplate"
            />

            <AiAssistantDrawer
                v-if="AiAssistantDrawer && showAiButton"
                :is-open="showAi"
                :form-schema="aiFormSchema"
                @close="showAi = false"
                @apply-generate="applyAiProposal"
                @apply-notification="applyAiNotificationOp"
            />

            <ShortcodeGeneratorModal
                v-if="ShortcodeGeneratorModal"
                :visible="showShortcode"
                :form-id="Number(store.formId) || 0"
                :form-title="store.title"
                @close="toggleShortcode(false)"
            />
            <FormPreviewModal
                :visible="showPreview"
                :form-title="store.title"
                :fields="store.fields"
                :theme="store.options?.theme || null"
                :layout-mode="store.options?.layout?.mode || 'single'"
                :can-pin="supportsPinnedPreview"
                @close="togglePreview(false)"
                @pin="pinPreview"
                @apply-theme="applyThemePreview"
            />
        </div>
        <div v-else class="fmt-builder__loading">
            {{ __("Loading form…") }}
        </div>
    </div>
</template>

<script setup>
import { computed, onMounted, onBeforeUnmount, ref, watch } from "vue";
import { useFormStore } from "@/admin/stores/formStore";
import FieldPalette from "@/admin/components/FieldPalette.vue";
import FormCanvas from "@/admin/components/FormCanvas.vue";
import FieldEditorDrawer from "@/admin/components/FieldEditorDrawer.vue";
import FormSettingsModal from "@/admin/components/FormSettingsModal.vue";
import TemplateModal from "@/admin/components/TemplateModal.vue";
import FormPreviewModal from "@/admin/components/FormPreviewModal.vue";
import FormPreviewPanel from "@/admin/components/preview/FormPreviewPanel.vue";
import { usePreviewLayout } from "@/admin/composables/usePreviewLayout";
import ICON_PIN from "../../assets/icons/pin.svg";
import { __ } from "@/utils/i18n";
import ICON_FILE_SPARK from "../../assets/icons/file-spark.svg";
import ICON_WAND from "../../assets/icons/wand.svg";
import ICON_EYE from "../../assets/icons/eye.svg";
import { proUi } from "@/admin/pro-ui-registry";
import { useCapabilities } from "@/admin/composables/useCapabilities";

// Pro UI slots (Phase 7.2): filled by the Pro entrypoint, null in Free — the
// component code never enters the Free bundle.
const ShortcodeGeneratorModal = proUi("shortcodeGeneratorModal");
const LicenseStatusBanner = proUi("licenseStatusBanner");
const AiAssistantDrawer = proUi("aiAssistantDrawer");

const store = useFormStore();
const { has: hasCapability } = useCapabilities();
const hasAiCapability = hasCapability("ai.assistant");
// The AI toolbar button shows only when the admin has enabled AI in settings
// (capability + the enable toggle). The localized flag reflects the saved state.
const showAiButton = hasAiCapability && !!(window.formatrica?.builder?.ai?.enabled);
const selectedFieldId = ref(null);
const showSettings = ref(false);
const showTemplates = ref(false);
const showAi = ref(false);
const showPreview = ref(false);
const showShortcode = ref(false);
const showMobilePalette = ref(false);

// Light current-form context handed to the AI so it can extend/refine.
const aiFormSchema = computed(() => ({
    title: store.title,
    fields: (store.fields || []).map((f) => ({
        name: f.name,
        type: f.type,
        label: f.label,
    })),
}));
const applyAiProposal = (payload) => {
    store.applyAiProposal(payload.proposal, payload.replaceFields);
};
// Notification-template action: apply a single suggested subject / success message.
const applyAiNotificationOp = (op) => {
    if (op.op === "set_email_subject") {
        store.options = { ...store.options, email_subject: op.value };
    } else if (op.op === "set_success_message") {
        store.options = { ...store.options, success_message: op.value };
    }
    store.hasUnsavedChanges = true;
};
const addFieldFromMobile = (type) => {
    addField(type);
    showMobilePalette.value = false;
};

const toggleShortcode = (value) => {
    showShortcode.value = value;
};
const showNewFormTip = ref(false);
const layoutRef = ref(null);
// Docked preview: pin support tracks the layout width with
// hysteresis; pinning collapses the palette to its rail; single-surface rule
// (modal open unpins first, pinning closes the modal); pin state not persisted.
const { supportsPinnedPreview, previewPinned } = usePreviewLayout(layoutRef);
const effectivePaletteCollapsed = computed(() => paletteCollapsed.value || previewPinned.value);

const pinPreview = () => {
    showPreview.value = false;
    previewPinned.value = true;
};
const unpinPreview = () => {
    previewPinned.value = false;
};
const expandPreview = () => {
    previewPinned.value = false;
    showPreview.value = true;
};
// Apply from the theme popover: stage into the form options (same path as the
// Appearance tab). Toolbar Save still required to persist.
const applyThemePreview = (theme) => {
    store.updateOptions({ ...store.options, theme });
    store.hasUnsavedChanges = true;
};


// Fields-panel collapse (icon-rail mode). Persisted so it survives reloads.
const PALETTE_COLLAPSED_KEY = "fmt_palette_collapsed";
const readPaletteCollapsed = () => {
    try {
        return localStorage.getItem(PALETTE_COLLAPSED_KEY) === "1";
    } catch {
        return false;
    }
};
const paletteCollapsed = ref(readPaletteCollapsed());
const setPaletteCollapsed = (value) => {
    paletteCollapsed.value = value;
    try {
        localStorage.setItem(PALETTE_COLLAPSED_KEY, value ? "1" : "0");
    } catch {
        // ignore
    }
};

const formTitle = computed({
    get: () => store.title,
    set: (value) => {
        store.title = value;
        store.hasUnsavedChanges = true;
    },
});

const selectedField = computed(
    () =>
        store.fields.find((field) => field.id === selectedFieldId.value) ||
        null,
);

const handleBeforeUnload = (event) => {
    if (store.hasUnsavedChanges) {
        event.preventDefault();
        event.returnValue = __(
            "You have unsaved changes. If you leave now, your changes will be lost.",
            "formatrica"
        );
        return event.returnValue;
    }
};

onMounted(() => {
    store.bootstrap();
    window.addEventListener("beforeunload", handleBeforeUnload);

    // Show tip for new forms only
    if (store.formId === 0) {
        showNewFormTip.value = true;
    }

    const updateBottomSafe = () => {
        try {
            const bodyContent = document.getElementById('wpbody-content');
            const footer = document.getElementById('wpfooter');
            const paddingBottom = bodyContent ? parseInt(getComputedStyle(bodyContent).paddingBottom || '0', 10) : 0;
            const footerHeight = footer ? footer.offsetHeight : 0;
            const safe = Math.max(paddingBottom, footerHeight) + 12; // add small buffer
            if (layoutRef.value && Number.isFinite(safe)) {
                layoutRef.value.style.setProperty('--fmt-bottom-safe', `${safe}px`);
            }
        } catch (e) {
            // noop
        }
    };
    updateBottomSafe();
    window.addEventListener('resize', updateBottomSafe);
    // Also observe footer size changes if available
    if (window.ResizeObserver) {
        const ro = new ResizeObserver(updateBottomSafe);
        const footerEl = document.getElementById('wpfooter');
        if (footerEl) ro.observe(footerEl);
    }
});

onBeforeUnmount(() => {
    window.removeEventListener("beforeunload", handleBeforeUnload);
});

const dismissNewFormTip = () => {
    showNewFormTip.value = false;
};

watch(
    () => store.fields.length,
    () => {
        if (!selectedField.value) {
            selectedFieldId.value = null;
        }
    },
);

watch(
    () => store.formId,
    (newId) => {
        if (newId) {
            showNewFormTip.value = false;
        }
    },
);

const addField = (type) => {
    store.addField(type);
};

const handleCreateFromPalette = ({ type, index }) => {
    store.addField(type, index);
};

const selectField = (id) => {
    selectedFieldId.value = id;
};

const removeField = (id) => {
    store.removeField(id);
    if (selectedFieldId.value === id) {
        selectedFieldId.value = null;
    }
};

const duplicateField = (id) => {
    store.duplicateField(id);
};

const handleReorder = ({ oldIndex, newIndex }) => {
    store.updateFieldOrder(oldIndex, newIndex);
};

const updateField = (payload) => {
    store.updateField(payload.id, payload);
};

const updateOptions = (options) => {
    store.updateOptions(options);
    store.updateThrottle(options.throttle);
};

const toggleSettings = (value) => {
    showSettings.value = value;
};

const toggleTemplates = (value) => {
    showTemplates.value = value;
};

const togglePreview = (value) => {
    showPreview.value = value;
};

const applyTemplate = (template) => {
    store.applyTemplate(template);
};

const sendTestEmail = (payload) => {
  store.sendTestEmail({ ...payload, formId: store.formId });
};
</script>

<style scoped>
.fmt-builder {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.fmt-builder__top {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    gap: 24px;
    background: #fff;
    border: 1px solid #e2e4e7;
    border-radius: 10px;
    padding: 16px 20px;
}

.fmt-builder__title {
    flex: 1;
}

.fmt-builder__title label {
    display: block;
    font-weight: 600;
    font-size: 0.85rem;
    color: #757a82;
    margin-bottom: 5px;
}

.fmt-builder__title input {
    width: 100%;
    font-size: 1.05rem;
    padding: 9px 12px;
}

.fmt-builder__actions {
    display: flex;
    gap: 8px;
    align-items: stretch;
}

.fmt-builder__actions > button {
    min-height: 42px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
}

.fmt-builder__actions button.fmt-builder__template,
.fmt-builder__actions button.fmt-builder__preview {
    line-height: 1.3;
    width: 42px;
    padding: 0;
}

.fmt-builder__actions .fmt-builder__template .fmt-icon,
.fmt-builder__actions .fmt-builder__preview .fmt-icon {
    width: 20px;
    height: 20px;
}

/* AI toolbar button: wand + "AI" label */
.fmt-builder__actions button.fmt-builder__ai {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    line-height: 1.3;
}
.fmt-builder__actions .fmt-builder__ai .fmt-icon {
    width: 20px;
    height: 20px;
}
.fmt-builder__ai-label {
    font-weight: 600;
    font-size: 13px;
}

.fmt-icon {
    width: 18px;
    height: 18px;
    vertical-align: middle;
}

.fmt-icon--inline {
    width: 16px;
    height: 16px;
}

.fmt-builder__save {
    min-height: 44px;
    border: 1px solid transparent;
}

.fmt-builder__layout {
    display: grid;
    grid-template-columns: minmax(260px, 300px) 1fr;
    gap: 24px;
    align-items: start;
    transition: grid-template-columns 0.2s ease;
}

/* Collapsed fields panel → narrow icon rail. */
.fmt-builder__layout--palette-collapsed {
    grid-template-columns: 64px 1fr;
}

/* Docked preview: rail + canvas + preview, ~50/50 split
   position:relative = containing block for the pinned-canvas drawer;
   overflow:hidden clips the parked off-canvas drawer's shadow. */
.fmt-builder__layout--preview-pinned {
    grid-template-columns: 64px minmax(0, 1fr) minmax(0, 1fr);
    position: relative;
    overflow: hidden;
}

.fmt-builder__layout--preview-pinned > * {
    min-width: 0;
}

/* Comfortable touch targets on every builder action. */
.fmt-builder__actions button {
    min-height: 44px;
}

/* Mobile add-field FAB: hidden on desktop. */
.fmt-mobile-add-fab {
    display: none;
}

/* ---- Mobile builder ---- */
@media (max-width: 767.98px) {
    .fmt-builder__layout {
        grid-template-columns: 1fr;
        gap: 12px;
    }

    .fmt-builder__palette-desktop {
        display: none;
    }

    .fmt-builder__layout .fmt-panel {
        min-height: auto;
        max-height: none;
        overflow: visible;
    }

    .fmt-mobile-add-fab {
        position: fixed;
        right: 16px;
        bottom: calc(24px + env(safe-area-inset-bottom, 0px));
        z-index: 950;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 52px;
        height: 52px;
        border-radius: 999px;
        font-size: 26px;
        line-height: 1;
        box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);
    }
}

.fmt-mobile-palette-overlay {
    position: fixed;
    inset: 0;
    z-index: 1100;
    display: flex;
    flex-direction: column;
    background: rgba(0, 0, 0, 0.4);
}

.fmt-mobile-palette-overlay__sheet {
    margin-top: auto;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background: #fff;
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
}

.fmt-mobile-palette-overlay__bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border-bottom: 1px solid #dcdcde;
}

.fmt-mobile-palette-overlay__sheet .fmt-panel {
    flex: 1 1 auto;
    min-height: 0;
    overflow-y: auto;
    max-height: none;
    border: 0;
}

.fmt-builder__preview-pin--pinned {
    border-color: #2271b1 !important;
    background: #f0f6fc !important;
}

.fmt-builder__preview-pin--pinned .fmt-icon {
    transform: rotate(-45deg);
}

/* Ensure the main canvas column can scroll within the constrained layout */
.fmt-builder__layout .fmt-panel {
    /* Constrain height so side panels (like the field palette) can scroll internally */
    min-height: 520px;
    /* Tweak these offsets if WP admin bars/toolbars change
       Subtract the WP admin footer safe area (~65px) to avoid bottom cut-off */
    max-height: calc(100vh - 180px - 65px);
    overflow: hidden;
}

.fmt-builder__loading {
    padding: 60px;
    text-align: center;
    font-size: 1.2rem;
}

.notice {
    position: relative;
}

/* Quick Start notification */
.fmt-quick-start {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 16px 18px;
    background: #e7f5fe;
    border-left: 4px solid #2271b1;
    border-radius: 4px;
    margin-bottom: 20px;
    position: relative;
}

.fmt-quick-start__icon {
    flex-shrink: 0;
    color: #2271b1;
    font-size: 20px;
    line-height: 1;
    margin-top: 2px;
}

.fmt-quick-start__icon .dashicons {
    width: 20px;
    height: 20px;
    font-size: 20px;
}

.fmt-quick-start__content {
    flex: 1;
    line-height: 1.6;
    color: #1d2327;
}

.fmt-quick-start__content strong {
    color: #1d2327;
    font-weight: 600;
}

.fmt-quick-start__dismiss {
    flex-shrink: 0;
    background: transparent;
    border: none;
    padding: 0;
    cursor: pointer;
    color: #50575e;
    line-height: 1;
    transition: color 0.15s ease;
    margin-top: 2px;
}

.fmt-quick-start__dismiss:hover {
    color: #d63638;
}

.fmt-quick-start__dismiss .dashicons {
    width: 20px;
    height: 20px;
    font-size: 20px;
}
</style>
