<template>
    <div class="fmt-settings-section">
        <h2 class="fmt-settings-heading">{{ __("Appearance", "formatrica") }}</h2>

        <div class="fmt-setting">
            <span>
                {{ __("Theme", "formatrica") }}
                <span v-if="PRO_UI && !hasThemes" class="fmt-theme-preset__pro">{{ PRO_THEMES_BADGE }}</span>
            </span>
            <div class="fmt-theme-presets" role="radiogroup" :aria-label="__('Theme', 'formatrica')">
                <label
                    v-for="preset in visiblePresets"
                    :key="preset.value"
                    class="fmt-theme-preset"
                    :class="{
                        'fmt-theme-preset--active': local.theme.preset === preset.value,
                        'fmt-theme-preset--locked': isLocked(preset),
                    }"
                >
                    <input
                        type="radio"
                        name="fmt-theme-preset"
                        :value="preset.value"
                        v-model="local.theme.preset"
                        :disabled="isLocked(preset)"
                    />
                    <span class="fmt-theme-preset__name">{{ preset.label }}</span>
                    <small class="fmt-theme-preset__desc">{{ preset.description }}</small>
                </label>
            </div>
            <small class="fmt-setting__hint">{{ PRESET_HINT }}</small>
        </div>

        <div class="fmt-setting">
            <span>{{ __("Form accent color", "formatrica") }}</span>
            <div class="fmt-theme-brand">
                <input
                    type="color"
                    class="fmt-theme-brand__swatch"
                    :value="brandColorInputValue"
                    @input="onBrandColorInput"
                    :aria-label="__('Form accent color', 'formatrica')"
                />
                <input
                    type="text"
                    class="fmt-theme-brand__hex"
                    :value="local.theme.brand_color"
                    @input="onBrandColorTextInput"
                    placeholder="#3b82f6"
                    pattern="^#[A-Fa-f0-9]{6}$"
                    maxlength="7"
                    spellcheck="false"
                    autocomplete="off"
                />
                <button
                    type="button"
                    class="fmt-theme-brand__reset"
                    :disabled="!local.theme.brand_color"
                    @click="local.theme.brand_color = ''"
                >
                    {{ __("Reset", "formatrica") }}
                </button>
            </div>
            <small class="fmt-setting__hint">
                {{ __("Optional. Tints the submit button, focus rings, and accent details. Leave blank to use the theme's default accent.", "formatrica") }}
            </small>
        </div>

        <div class="fmt-setting">
            <span>{{ __("Color scheme", "formatrica") }}</span>
            <div class="fmt-theme-modes" role="radiogroup" :aria-label="__('Color scheme', 'formatrica')">
                <label v-for="mode in THEME_MODES" :key="mode.value" class="fmt-theme-mode">
                    <input type="radio" name="fmt-theme-mode" :value="mode.value" v-model="local.theme.mode" />
                    <span>{{ mode.label }}</span>
                </label>
            </div>
            <small class="fmt-setting__hint">
                {{ __("Inherit uses the site-wide default. Auto follows the visitor's OS preference. Light or Dark forces a specific scheme regardless of preference.", "formatrica") }}
            </small>
        </div>

        <div class="fmt-setting" v-if="PRO_UI || (local.wrapper_class || '') !== ''">
            <span>
                {{ __("Wrapper CSS class", "formatrica") }}
                <span v-if="PRO_UI && !hasWrapperClass" class="fmt-theme-preset__pro">{{ __("Pro", "formatrica") }}</span>
            </span>
            <input
                type="text"
                v-model="local.wrapper_class"
                :disabled="!hasWrapperClass"
                :placeholder="__('e.g. my-brand-form', 'formatrica')"
            />
            <small class="fmt-setting__hint">
                {{ __("Added to the form's outer wrapper for custom styling. Space-separate multiple classes.", "formatrica") }}
            </small>
        </div>
    </div>
</template>

<script setup>
import { inject, computed } from "vue";
import { __ } from "@/utils/i18n";
import { useCapabilities } from "@/admin/composables/useCapabilities";
import { THEME_PRESETS, THEME_MODES, isValidBrandColor } 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_THEMES_BADGE = __FMT_PRO_UI__ ? __("Pro themes", "formatrica") : "";
// Free-bundle variant folds the "Pro themes are gated" phrasing out.
// eslint-disable-next-line no-undef
const PRESET_HINT = __FMT_PRO_UI__
    ? __("Pick a visual preset. The form preview reflects your choice instantly. Pro themes are gated; pick Classic to inherit your WordPress theme.", "formatrica")
    : __("Pick a visual preset. The form preview reflects your choice instantly.", "formatrica");

const ctx = inject("formSettingsContext");
if (!ctx) {
    throw new Error("Form settings context not provided");
}
const { local } = ctx;

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

// Full bundle: all five cards always visible (those without forms.themes shown
// read-only). Free bundle: Pro cards hidden unless one IS the saved preset
// (grandfathered, shown plainly).
const visiblePresets = computed(() =>
    THEME_PRESETS.filter(
        (preset) => !preset.isPro || PRO_UI || local.theme.preset === preset.value,
    ),
);

// A Pro preset is locked unless the capability is granted OR it is already the
// saved value (preserve-existing: a downgraded install keeps its Pro preset,
// but cannot switch BETWEEN Pro presets.
const isLocked = (preset) =>
    preset.isPro && !hasThemes && local.theme.preset !== preset.value;

// Swatch shows the picked hex, or an honest neutral grey when unset — never a
// stale color pretending to be the current value.
const brandColorInputValue = computed(() =>
    isValidBrandColor(local.theme.brand_color) ? local.theme.brand_color : "#9ca3af",
);

const onBrandColorInput = (event) => {
    const value = String(event.target.value || "");
    if (isValidBrandColor(value)) {
        local.theme.brand_color = value.toLowerCase();
    }
};

// Blank clears (cascade fallback); a full valid hex is stored lowercased;
// partial typing is ignored so the swatch doesn't flicker mid-keystroke.
const onBrandColorTextInput = (event) => {
    const value = String(event.target.value || "").trim();
    if (value === "") {
        local.theme.brand_color = "";
        return;
    }
    if (isValidBrandColor(value)) {
        local.theme.brand_color = value.toLowerCase();
    }
};
</script>

<style scoped>
.fmt-theme-presets {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    gap: 8px;
    margin-top: 4px;
}
.fmt-theme-preset {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 12px;
    border: 1px solid #dcdcde;
    border-radius: 6px;
    background: #fff;
    cursor: pointer;
    transition: border-color 150ms ease, background-color 150ms ease;
}
.fmt-theme-preset:hover {
    border-color: #2271b1;
}
.fmt-theme-preset--active {
    border-color: #2271b1;
    background: rgba(34, 113, 177, 0.08);
}
.fmt-theme-preset--locked {
    opacity: 0.6;
    cursor: not-allowed;
}
.fmt-theme-preset input[type="radio"] {
    align-self: flex-start;
}
.fmt-theme-preset__name {
    font-weight: 500;
}
.fmt-theme-preset__desc {
    color: #646970;
    font-size: 0.85rem;
    line-height: 1.3;
}
.fmt-theme-preset__pro {
    font-size: 0.7rem;
    font-weight: 700;
    text-transform: uppercase;
    color: #8b5cf6;
    border: 1px solid currentColor;
    border-radius: 4px;
    padding: 1px 5px;
    margin-left: 6px;
    vertical-align: middle;
}
.fmt-theme-brand {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 4px;
}
.fmt-theme-brand__swatch {
    width: 40px;
    height: 32px;
    padding: 2px;
    border: 1px solid #dcdcde;
    border-radius: 4px;
    background: #fff;
}
.fmt-theme-brand__hex {
    width: 140px;
    font-family: monospace;
    font-size: 0.875rem;
}
.fmt-theme-brand__reset {
    border: 0;
    background: transparent;
    color: #2271b1;
    text-decoration: underline;
    cursor: pointer;
    padding: 0;
}
.fmt-theme-brand__reset:disabled {
    color: #9ca3af;
    text-decoration: none;
    cursor: not-allowed;
}
.fmt-theme-modes {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    margin-top: 4px;
}
.fmt-theme-mode {
    display: flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
}
</style>
