<template>
    <div class="fmt-preview-container">
        <div class="fmt-preview-form" :style="zoomStyle">
            <!-- Real frontend classes + theme attrs so the ACTUAL overlay
                 stylesheet (frontend-themes.css, enqueued on the builder page)
                 paints the preview — no bespoke theme CSS copies. -->
            <form
                class="formatrica formatrica__form"
                :class="[themeModifierClass, gridClass]"
                :data-fmt-theme="themePreset"
                :data-fmt-mode="themeMode"
                :style="themeBrandStyle"
                @submit.prevent
            >
                <h2 v-if="formTitle" class="fmt-preview-form__title">
                    {{ formTitle }}
                </h2>

                <div
                    v-for="field in previewFields"
                    :key="field.id"
                    class="fmt-form-field formatrica__group"
                    :class="[`fmt-form-field--${field.type}`, `formatrica__group--${field.type}`, fieldWidthClass(field)]"
                >
                    <template v-if="field.type === 'text_block'">
                        <div class="fmt-form-text-block" v-html="field.content"></div>
                    </template>

                    <!-- WP's submit field type is 'button' (the palette's Submit
                         Inquiry); without this branch it fell through to the
                         generic text input and the preview had NO accent-colored
                         element — the picked accent looked like a no-op. -->
                    <template v-else-if="field.type === 'submit' || field.type === 'button'">
                        <button type="submit" class="fmt-form-submit formatrica__submit" disabled>
                            {{ field.label || __("Submit", "formatrica") }}
                        </button>
                    </template>

                    <template v-else>
                        <label v-if="field.label" class="fmt-form-label formatrica__label">
                            {{ field.label }}
                            <span v-if="field.required" class="fmt-form-required formatrica__required" :data-required-label="__('Required', 'formatrica')" aria-hidden="true">*</span>
                        </label>

                        <template v-if="field.type === 'textarea'">
                            <textarea
                                class="formatrica__textarea"
                                :placeholder="field.placeholder"
                                :rows="field.rows || 4"
                                disabled
                            ></textarea>
                        </template>

                        <template v-else-if="field.type === 'select'">
                            <select class="formatrica__select" disabled>
                                <option value="">
                                    {{ field.placeholder || __("Select an option", "formatrica") }}
                                </option>
                                <option
                                    v-for="(option, idx) in field.options"
                                    :key="idx"
                                    :value="option.value"
                                >
                                    {{ option.label }}
                                </option>
                            </select>
                        </template>

                        <template v-else-if="field.type === 'radio'">
                            <div class="fmt-form-radio-group formatrica__choices">
                                <label
                                    v-for="(option, idx) in field.options"
                                    :key="idx"
                                    class="fmt-form-radio"
                                >
                                    <input type="radio" :name="field.name" :value="option.value" disabled />
                                    <span>{{ option.label }}</span>
                                </label>
                            </div>
                        </template>

                        <template v-else-if="field.type === 'checkbox'">
                            <div class="fmt-form-checkbox-group formatrica__choices">
                                <label
                                    v-for="(option, idx) in field.options"
                                    :key="idx"
                                    class="fmt-form-checkbox"
                                >
                                    <input type="checkbox" :name="field.name + '[]'" :value="option.value" disabled />
                                    <span>{{ option.label }}</span>
                                </label>
                            </div>
                        </template>

                        <template v-else-if="field.type === 'file'">
                            <input type="file" class="formatrica__input" disabled />
                        </template>

                        <!-- Registry-provided preview partial (Pro types register
                             theirs under src/admin-pro/fields/previews). -->
                        <component
                            v-else-if="previewFor(field.type)"
                            :is="previewFor(field.type)"
                            :field="field"
                        />

                        <template v-else>
                            <input
                                class="formatrica__input"
                                :type="getInputType(field.type)"
                                :placeholder="field.placeholder"
                                disabled
                            />
                        </template>

                        <p v-if="field.description" class="fmt-form-description">
                            {{ field.description }}
                        </p>
                    </template>
                </div>
            </form>
        </div>
    </div>
</template>

<script setup>
import { computed } from "vue";
import { __ } from "@/utils/i18n";
import { isValidBrandColor } from "@/admin/utils/themeAppearance";
import { fieldTypeDef, typeFlag } from "@/admin/fields/type-registry";

const props = defineProps({
    fields: { type: Array, default: () => [] },
    formTitle: { type: String, default: "" },
    /** {preset, brand_color, mode} — the live preview theme (override or saved). */
    theme: { type: Object, default: null },
    /** single | two_column | three_column — the form's column layout mode. */
    layoutMode: { type: String, default: "single" },
    zoom: { type: Number, default: 100 },
});

// Mirror Form_Renderer: an advanced width on any field upgrades a 'single'
// form to the two-column grid so half/third fields just work. Grid
// participation comes from the registry's `grid` flag; 'submit'/'text_block'
// are preview-only pseudo types with no registry entry, handled literally.
const PREVIEW_NON_GRID_TYPES = ["submit", "text_block"];
const isGridField = (type) =>
    !PREVIEW_NON_GRID_TYPES.includes(type) && typeFlag(type, "grid", true);
const previewFor = (type) => fieldTypeDef(type)?.preview || null;
const effectiveLayoutMode = computed(() => {
    const mode = ["single", "two_column", "three_column"].includes(props.layoutMode)
        ? props.layoutMode
        : "single";
    if (mode !== "single") {
        return mode;
    }
    const hasAdvanced = props.fields.some(
        (f) => isGridField(f.type) && ["half", "third"].includes(f.layout?.width),
    );
    return hasAdvanced ? "two_column" : "single";
});
const gridClass = computed(() => ({
    "fmt-preview-grid--two-column": effectiveLayoutMode.value === "two_column",
    "fmt-preview-grid--three-column": effectiveLayoutMode.value === "three_column",
}));
const fieldWidthClass = (field) => {
    if (!isGridField(field.type)) {
        return "";
    }
    const width = field.layout?.width;
    if (width === "half") {
        return "fmt-preview-field--half";
    }
    if (width === "third") {
        return "fmt-preview-field--third";
    }
    return "";
};

const previewFields = computed(() => props.fields.filter((field) => field.type !== "hidden"));

const themePreset = computed(() => {
    const preset = props.theme?.preset;
    return typeof preset === "string" && preset !== "" ? preset : "classic";
});
const themeModifierClass = computed(() =>
    themePreset.value === "classic" ? "" : `formatrica__form--theme-${themePreset.value}`,
);
const themeMode = computed(() => props.theme?.mode || "inherit");
// Same variable contract as Theme_Overlay_Resolver::inline_attributes.
const themeBrandStyle = computed(() => {
    const brand = props.theme?.brand_color;
    if (!isValidBrandColor(brand)) {
        return null;
    }
    return {
        "--fmt-accent": brand,
        "--fmt-focus-ring": `color-mix(in srgb, ${brand} 22%, transparent)`,
    };
});

const zoomStyle = computed(() => ({
    transform: `scale(${(Number(props.zoom) || 100) / 100})`,
    transformOrigin: "top center",
}));

const getInputType = (fieldType) => {
    const typeMap = {
        text: "text",
        email: "email",
        tel: "tel",
        password: "password",
        date: "date",
        number: "number",
        url: "url",
        range: "range",
        color: "color",
        datetime: "datetime-local",
    };
    return typeMap[fieldType] || "text";
};
</script>

<style scoped>
.fmt-preview-container {
    flex: 1;
    display: flex;
    justify-content: center;
    padding: 20px;
    background: #f5f5f5;
    border-radius: 4px;
    overflow: visible;
}

.fmt-preview-form {
    width: 100%;
    max-width: 600px;
    background: #fff;
    padding: 32px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease;
    max-height: none !important;
    overflow: visible;
}

.fmt-preview-form__title {
    margin: 0 0 24px;
    font-size: 24px;
    font-weight: 600;
    color: #1d2327;
}

.formatrica {
    display: flex;
    flex-direction: column;
    gap: 20px;
    /* Radios/checkboxes tint with the picked accent in every preset. */
    accent-color: var(--fmt-accent, #2271b1);
}

/* Column layout preview: same 12-track model as the frontend renderer so
   half (6/12) and third (4/12) match the live page. */
.formatrica.fmt-preview-grid--two-column,
.formatrica.fmt-preview-grid--three-column {
    display: grid;
    grid-template-columns: repeat(12, minmax(0, 1fr));
    align-items: start;
}

.fmt-preview-grid--two-column > *,
.fmt-preview-grid--three-column > * {
    grid-column: 1 / -1;
}

.fmt-preview-grid--two-column .fmt-preview-field--half,
.fmt-preview-grid--two-column .fmt-preview-field--third {
    grid-column: span 6;
}

.fmt-preview-grid--three-column .fmt-preview-field--half {
    grid-column: span 8;
}

.fmt-preview-grid--three-column .fmt-preview-field--third {
    grid-column: span 4;
}

.fmt-form-field {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.fmt-form-label {
    font-weight: 500;
    font-size: 14px;
}

.formatrica:not([class*="__form--theme-"]) .fmt-form-label {
    color: #1d2327;
}

.fmt-form-required {
    color: #d63638;
    margin-left: 2px;
}

/* Mock input chrome applies ONLY to Classic (no preset modifier). Under a
   preset the REAL overlay stylesheet must own borders/underlines/tints —
   these scoped rules would otherwise out-specific it and mask the accent.
*/
.formatrica:not([class*="__form--theme-"]) .fmt-form-field input[type="text"],
.formatrica:not([class*="__form--theme-"]) .fmt-form-field input[type="email"],
.formatrica:not([class*="__form--theme-"]) .fmt-form-field input[type="tel"],
.formatrica:not([class*="__form--theme-"]) .fmt-form-field input[type="password"],
.formatrica:not([class*="__form--theme-"]) .fmt-form-field input[type="date"],
.formatrica:not([class*="__form--theme-"]) .fmt-form-field input[type="number"],
.formatrica:not([class*="__form--theme-"]) .fmt-form-field textarea,
.formatrica:not([class*="__form--theme-"]) .fmt-form-field select {
    padding: 8px 12px;
    border: 1px solid #8c8f94;
    border-radius: 4px;
    font-size: 14px;
    font-family: inherit;
    background: #fff;
    color: #1d2327;
}

/* Preview-only affordance, harmless under every preset. */
.fmt-form-field input,
.fmt-form-field textarea,
.fmt-form-field select {
    cursor: not-allowed;
    opacity: 0.85;
}

.fmt-form-field textarea {
    resize: vertical;
}

.fmt-form-radio-group,
.fmt-form-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.fmt-form-radio,
.fmt-form-checkbox {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: not-allowed;
}

.fmt-form-radio input,
.fmt-form-checkbox input {
    cursor: not-allowed;
}

.fmt-form-text-block {
    color: #50575e;
    line-height: 1.6;
}

.fmt-form-description {
    margin: 0;
    font-size: 13px;
    color: #646970;
}

.formatrica:not([class*="__form--theme-"]) .fmt-form-submit {
    padding: 10px 24px;
    /* Accent contract shared with the real frontend — Classic tints too. */
    background: var(--fmt-accent, #2271b1);
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
}

.fmt-form-submit {
    cursor: not-allowed;
}
</style>
