/**
 * Single source of truth for appearance-theme options, shared by the Appearance
 * settings tab (and any future preview picker) so they cannot drift on what they
 * offer or accept. Mirrors the server allowlist in Form_Sanitizer::sanitise_theme
 * and app/Frontend/Theme_Overlay_Resolver.
 */
import { __ } from "@/utils/i18n";

// Classic is Free; the four preset themes require the forms.themes capability
// (Pro, delivered by P17). isPro drives the builder lock.
export const THEME_PRESETS = [
    {
        value: "classic",
        label: __("Classic", "formatrica"),
        description: __("Inherits typography and colors from your WordPress theme. No overlay applied.", "formatrica"),
        isPro: false,
    },
    {
        value: "material",
        label: __("Material", "formatrica"),
        description: __("Filled inputs with a brand-colored underline on focus. Google-flavored, familiar.", "formatrica"),
        isPro: true,
    },
    {
        value: "clean",
        label: __("Clean", "formatrica"),
        description: __("Bordered inputs with a soft brand-colored focus ring. The Stripe, Linear, SaaS look.", "formatrica"),
        isPro: true,
    },
    {
        value: "card",
        label: __("Card", "formatrica"),
        description: __("Each field in its own soft-shadow card. Best for short forms where every question deserves visual breathing room.", "formatrica"),
        isPro: true,
    },
    {
        value: "underline",
        label: __("Underline", "formatrica"),
        description: __("No borders, just a single bottom underline. Editorial, minimalist.", "formatrica"),
        isPro: true,
    },
];

export const THEME_MODES = [
    { value: "inherit", label: __("Inherit", "formatrica") },
    { value: "light", label: __("Light", "formatrica") },
    { value: "dark", label: __("Dark", "formatrica") },
    { value: "auto", label: __("Auto (follow visitor preference)", "formatrica") },
];

const HEX_RE = /^#[0-9a-fA-F]{6}$/;

export function isValidBrandColor(value) {
    return typeof value === "string" && HEX_RE.test(value.trim());
}

export function normalizeBrandColor(value) {
    if (!isValidBrandColor(value)) {
        return "";
    }
    return value.trim().toLowerCase();
}

export function isKnownPreset(value) {
    return THEME_PRESETS.some((p) => p.value === value);
}

export function isProPreset(value) {
    const preset = THEME_PRESETS.find((p) => p.value === value);
    return !!preset && preset.isPro;
}

// A clean theme object with the canonical shape and sane fallbacks.
export function normalizeTheme(theme) {
    const t = theme && typeof theme === "object" ? theme : {};
    const preset = isKnownPreset(t.preset) ? t.preset : "classic";
    const mode = THEME_MODES.some((m) => m.value === t.mode) ? t.mode : "inherit";
    return {
        preset,
        brand_color: normalizeBrandColor(t.brand_color),
        mode,
    };
}
