<template>
    <div class="fmt-theme-popover" role="dialog" :aria-label="__('Preview themes', 'formatrica')">
        <strong class="fmt-theme-popover__title">{{ __("Preview themes", "formatrica") }}</strong>

        <div class="fmt-theme-popover__presets" role="radiogroup" :aria-label="__('Theme', 'formatrica')">
            <label
                v-for="preset in visiblePresets"
                :key="preset.value"
                class="fmt-theme-popover__preset"
                :class="{
                    'is-active': local.preset === preset.value,
                    'is-locked': isPresetLocked(preset),
                }"
                :title="isPresetLocked(preset) && PRO_BADGE_TITLE ? PRO_BADGE_TITLE : undefined"
                @mouseenter="hoverPreset = preset.value"
                @mouseleave="hoverPreset = null"
            >
                <input
                    type="radio"
                    name="fmt-preview-preset"
                    :value="preset.value"
                    v-model="local.preset"
                    :disabled="isPresetLocked(preset)"
                />
                <span>{{ preset.label }}</span>
            </label>
        </div>

        <div class="fmt-theme-popover__field">
            <span>{{ __("Form accent color", "formatrica") }}</span>
            <div class="fmt-theme-popover__brand">
                <input
                    type="color"
                    :value="brandColorInputValue"
                    @input="onBrandColorInput"
                    :aria-label="__('Form accent color', 'formatrica')"
                />
                <input
                    type="text"
                    :value="local.brand_color"
                    @input="onBrandColorTextInput"
                    placeholder="#3b82f6"
                    pattern="^#[A-Fa-f0-9]{6}$"
                    maxlength="7"
                    spellcheck="false"
                    autocomplete="off"
                />
                <button
                    type="button"
                    class="fmt-theme-popover__reset-color"
                    :disabled="!local.brand_color"
                    @click="local.brand_color = ''"
                >
                    {{ __("Reset", "formatrica") }}
                </button>
            </div>
        </div>

        <div class="fmt-theme-popover__field">
            <span>{{ __("Color scheme", "formatrica") }}</span>
            <div class="fmt-theme-popover__modes" role="radiogroup" :aria-label="__('Color scheme', 'formatrica')">
                <label v-for="mode in THEME_MODES" :key="mode.value">
                    <input type="radio" name="fmt-preview-mode" :value="mode.value" v-model="local.mode" />
                    <span>{{ mode.label }}</span>
                </label>
            </div>
        </div>

        <div class="fmt-theme-popover__footer">
            <button type="button" class="fmt-theme-popover__reset" @click="resetPreview">
                {{ __("Reset preview", "formatrica") }}
            </button>
            <button type="button" class="button button-primary" @click="apply">
                {{ __("Apply", "formatrica") }}
            </button>
        </div>
    </div>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import { __ } from "@/utils/i18n";
import { useCapabilities } from "@/admin/composables/useCapabilities";
import { THEME_PRESETS, THEME_MODES, isValidBrandColor, normalizeTheme } from "@/admin/utils/themeAppearance";

// Vite define — a literal after build, so the minifier deletes dead branches.
// eslint-disable-next-line no-undef
const PRO_UI = __FMT_PRO_UI__;
// eslint-disable-next-line no-undef
const PRO_BADGE_TITLE = __FMT_PRO_UI__ ? __("Pro themes", "formatrica") : "";

const props = defineProps({
    /** The SAVED form theme (reset target + lock snapshot). */
    theme: { type: Object, default: null },
});
const emit = defineEmits(["change", "apply"]);

const { has } = useCapabilities();
const hasThemes = has("forms.themes");

// Snapshot the saved preset once: a grandfathered Pro preset stays selectable
// but you cannot switch BETWEEN Pro presets on Free.
const savedTheme = normalizeTheme(props.theme);
const local = reactive({ ...savedTheme });
const hoverPreset = ref(null);

// Full bundle shows all presets; free bundle hides Pro entries unless one is
// the saved value (grandfathered, plain).
const visiblePresets = computed(() =>
    THEME_PRESETS.filter((p) => !p.isPro || PRO_UI || savedTheme.preset === p.value),
);
const isPresetLocked = (preset) =>
    preset.isPro && !hasThemes && savedTheme.preset !== preset.value;

// Hovering a selectable preset live-previews it without committing (J parity).
const previewTheme = computed(() => {
    const hovered = hoverPreset.value;
    const hoverOk =
        hovered &&
        hovered !== local.preset &&
        !isPresetLocked(THEME_PRESETS.find((p) => p.value === hovered) || { isPro: false });
    return {
        preset: hoverOk ? hovered : local.preset,
        brand_color: local.brand_color,
        mode: local.mode,
    };
});

watch(previewTheme, (theme) => emit("change", { ...theme }), { immediate: true, deep: true });

const brandColorInputValue = computed(() =>
    isValidBrandColor(local.brand_color) ? local.brand_color : "#9ca3af",
);
const onBrandColorInput = (event) => {
    const value = String(event.target.value || "");
    if (isValidBrandColor(value)) {
        local.brand_color = value.toLowerCase();
    }
};
const onBrandColorTextInput = (event) => {
    const value = String(event.target.value || "").trim();
    if (value === "") {
        local.brand_color = "";
        return;
    }
    if (isValidBrandColor(value)) {
        local.brand_color = value.toLowerCase();
    }
};

// Revert to the saved theme without closing; the watcher re-emits `change`.
const resetPreview = () => {
    Object.assign(local, savedTheme);
    hoverPreset.value = null;
};

const apply = () => emit("apply", { ...normalizeTheme(local) });
</script>

<style scoped>
.fmt-theme-popover {
    position: absolute;
    top: calc(100% + 6px);
    right: 0;
    z-index: 30;
    width: 260px;
    background: #fff;
    border: 1px solid #dcdcde;
    border-radius: 8px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.18);
    padding: 14px;
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.fmt-theme-popover__title {
    font-size: 0.95rem;
}
.fmt-theme-popover__presets {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
}
.fmt-theme-popover__preset {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 8px;
    border: 1px solid #dcdcde;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.9rem;
}
.fmt-theme-popover__preset.is-active {
    border-color: #2271b1;
    background: rgba(34, 113, 177, 0.08);
}
.fmt-theme-popover__preset.is-locked {
    opacity: 0.55;
    cursor: not-allowed;
}
.fmt-theme-popover__field > span {
    display: block;
    font-weight: 600;
    font-size: 0.85rem;
    margin-bottom: 4px;
}
.fmt-theme-popover__brand {
    display: flex;
    align-items: center;
    gap: 6px;
}
.fmt-theme-popover__brand input[type="color"] {
    width: 34px;
    height: 28px;
    padding: 1px;
    border: 1px solid #dcdcde;
    border-radius: 4px;
    background: #fff;
}
.fmt-theme-popover__brand input[type="text"] {
    width: 100px;
    font-family: monospace;
    font-size: 0.85rem;
}
.fmt-theme-popover__reset-color {
    border: 0;
    background: transparent;
    color: #2271b1;
    text-decoration: underline;
    cursor: pointer;
    padding: 0;
    font-size: 0.85rem;
}
.fmt-theme-popover__reset-color:disabled {
    color: #9ca3af;
    text-decoration: none;
    cursor: not-allowed;
}
.fmt-theme-popover__modes {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.fmt-theme-popover__modes label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.9rem;
}
.fmt-theme-popover__footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid #f0f0f1;
    padding-top: 10px;
}
.fmt-theme-popover__reset {
    border: 0;
    background: transparent;
    color: #2271b1;
    text-decoration: underline;
    cursor: pointer;
    padding: 0;
}
</style>
