import { Head } from "@inertiajs/react";
import {
    AlertCircle,
    Check,
    CircleHelp,
    RotateCcw,
    Save,
    Settings2,
    SlidersHorizontal,
    ShieldCheck,
    Layers,
    Cpu,
    PieChart,
    BarChart3,
    Compass,
    Lock,
    Activity,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from "@/components/ui/accordion";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";

import { AdminOperationalStrip } from "@/components/admin-operational-strip";
import { useI18n } from "@/lib/i18n";
type Mode = "strict" | "balanced" | "flexible";
type Market = "spot" | "futures";
type Config = Record<string, any>;

const modes: Mode[] = ["strict", "balanced", "flexible"];
const markets: Market[] = ["spot", "futures"];
const directions = [
    { key: "long", label: "LONG" },
    { key: "short", label: "SHORT" },
] as const;

const modeDescriptions: Record<Mode, string> = {
    strict: "Konfirmasi ketat & berlapis sebelum setup divalidasi.",
    balanced: "Kompromi optimal antara jumlah setup dan akurasi.",
    flexible: "Filter lebih longgar dengan guard eksekusi ketat.",
};

const labels: Record<string, string> = {
    require_bias: "Higher-timeframe bias",
    require_setup: "Setup timeframe",
    require_trend: "Trend alignment",
    require_momentum: "Momentum confirmation",
    require_structure: "Market structure",
    require_adx_di: "ADX / DI confirmation",
    require_rsi: "RSI threshold",
    require_btc_context: "BTC context gate",
    require_volatility: "ATR volatility guard",
    require_volume: "Volume confirmation",
    require_pattern: "Candlestick pattern",
};

const numericFields = [
    {
        key: "score_threshold",
        label: "Minimum signal score",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "score",
    },
    {
        key: "mtf_gate_threshold",
        label: "MTF gate threshold",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "score",
    },
    {
        key: "min_alignment_pct",
        label: "Minimum MTF alignment",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "%",
    },
    {
        key: "min_adx",
        label: "Minimum ADX",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "ADX",
    },
    {
        key: "min_rsi_long",
        label: "Minimum RSI for LONG",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "RSI",
    },
    {
        key: "max_rsi_short",
        label: "Maximum RSI for SHORT",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "RSI",
    },
    {
        key: "min_volume_ratio",
        label: "Minimum volume ratio",
        min: 0,
        max: 20,
        step: 0.01,
        suffix: "×",
    },
    {
        key: "max_atr_pct",
        label: "Maximum ATR volatility",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "%",
    },
    {
        key: "min_risk_reward",
        label: "Minimum risk / reward",
        min: 0,
        max: 20,
        step: 0.1,
        suffix: "R",
    },
    {
        key: "min_strategy_quality",
        label: "Minimum strategy quality",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "%",
    },
    {
        key: "min_strategy_weight",
        label: "Minimum strategy weight",
        min: 0,
        max: 1,
        step: 0.01,
        suffix: "0–1",
    },
    {
        key: "min_pattern_quality",
        label: "Minimum pattern quality",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "%",
    },
] as const;

const marketNumericFields = [
    {
        key: "max_stop_distance_pct",
        label: "Maximum stop distance",
        min: 0,
        max: 100,
        step: 0.1,
        suffix: "% entry",
    },
    {
        key: "max_stop_atr",
        label: "Maximum stop distance",
        min: 0,
        max: 20,
        step: 0.1,
        suffix: "ATR",
    },
    {
        key: "btc_context_max_adjustment",
        label: "BTC context score cap",
        min: 0,
        max: 20,
        step: 0.1,
        suffix: "score",
    },
] as const;

const indicatorFields = [
    {
        key: "rsi",
        label: "RSI period",
        min: 5,
        max: 50,
        step: 1,
        suffix: "candles",
    },
    {
        key: "adx",
        label: "ADX period",
        min: 5,
        max: 50,
        step: 1,
        suffix: "candles",
    },
    {
        key: "atr",
        label: "ATR period",
        min: 5,
        max: 50,
        step: 1,
        suffix: "candles",
    },
    {
        key: "ema_fast",
        label: "EMA fast",
        min: 5,
        max: 100,
        step: 1,
        suffix: "period",
    },
    {
        key: "ema_medium",
        label: "EMA medium",
        min: 10,
        max: 200,
        step: 1,
        suffix: "period",
    },
    {
        key: "ema_slow",
        label: "EMA slow",
        min: 50,
        max: 500,
        step: 1,
        suffix: "period",
    },
    {
        key: "bollinger_period",
        label: "Bollinger period",
        min: 5,
        max: 100,
        step: 1,
        suffix: "candles",
    },
    {
        key: "bollinger_deviation",
        label: "Bollinger deviation",
        min: 0.5,
        max: 4,
        step: 0.1,
        suffix: "σ",
    },
    {
        key: "volume_ma",
        label: "Volume MA period",
        min: 5,
        max: 100,
        step: 1,
        suffix: "candles",
    },
    {
        key: "roc",
        label: "ROC period",
        min: 2,
        max: 50,
        step: 1,
        suffix: "candles",
    },
    {
        key: "macd_fast",
        label: "MACD fast",
        min: 2,
        max: 50,
        step: 1,
        suffix: "period",
    },
    {
        key: "macd_slow",
        label: "MACD slow",
        min: 5,
        max: 100,
        step: 1,
        suffix: "period",
    },
    {
        key: "macd_signal",
        label: "MACD signal",
        min: 2,
        max: 30,
        step: 1,
        suffix: "period",
    },
] as const;

const scoringWeightFields = [
    { key: "trend", label: "Trend" },
    { key: "momentum", label: "Momentum" },
    { key: "structure", label: "Structure" },
    { key: "volatility", label: "Volatility" },
    { key: "volume", label: "Volume" },
] as const;

const mtfIntervals = [
    "1m",
    "5m",
    "15m",
    "30m",
    "1h",
    "4h",
    "1d",
    "1w",
] as const;

const executionGuardFields = [
    {
        key: "require_mtf_alignment",
        label: "Require MTF alignment",
        description:
            "Jika aktif, alignment MTF menjadi syarat signal pada mode ini.",
    },
    {
        key: "alignment_hard",
        label: "Hard MTF alignment",
        description:
            "Jika aktif, kegagalan alignment menjadi hard gate; jika nonaktif hanya menjadi warning.",
    },
    {
        key: "risk_guard_hard",
        label: "Hard stop-distance / risk-reward guard",
        description:
            "Jika aktif, batas stop-distance dan minimum risk/reward menjadi hard gate.",
    },
] as const;

const strategyConfirmationFields = [
    {
        key: "require_strategy",
        label: "Strategy engine confirmation",
        description:
            "Hasil strategy engine wajib memenuhi quality dan weight minimum.",
    },
    {
        key: "require_trigger",
        label: "Strategy trigger confirmed",
        description: "Trigger dari strategy engine harus terkonfirmasi.",
    },
    {
        key: "require_trade_plan",
        label: "Require trade plan",
        description:
            "Trade plan valid wajib tersedia sebelum signal dianggap valid.",
    },
] as const;

const clone = <T,>(value: T): T => JSON.parse(JSON.stringify(value));

function csrfToken(): string {
    return (
        document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')
            ?.content ?? ""
    );
}

async function readResponse(response: Response): Promise<Record<string, any>> {
    const text = await response.text();
    try {
        return text ? JSON.parse(text) : {};
    } catch {
        return {
            message:
                response.status === 419
                    ? "Sesi atau CSRF token sudah kedaluwarsa."
                    : `Kesalahan server (${response.status}).`,
        };
    }
}

export default function SignalConfiguration() {
    const { t } = useI18n();
    const [mode, setMode] = useState<Mode>("balanced");
    const [market, setMarket] = useState<Market>("spot");
    const [configs, setConfigs] = useState<Record<Mode, Config>>(
        {} as Record<Mode, Config>,
    );
    const [savedConfigs, setSavedConfigs] = useState<Record<Mode, Config>>(
        {} as Record<Mode, Config>,
    );
    const [loading, setLoading] = useState(true);
    const [busy, setBusy] = useState(false);
    const [resetDialogOpen, setResetDialogOpen] = useState(false);
    const [message, setMessage] = useState<{
        type: "success" | "error";
        text: string;
    } | null>(null);

    const dirty = useMemo(
        () => JSON.stringify(configs) !== JSON.stringify(savedConfigs),
        [configs, savedConfigs],
    );
    const current = configs[mode] ?? {};
    const marketConfig = current.market?.[market] ?? {};

    const enabledFilters = useMemo(
        () => Object.keys(labels).filter((key) => Boolean(current[key])).length,
        [current],
    );
    const enabledStrategyGuards = useMemo(
        () =>
            strategyConfirmationFields.filter((field) =>
                Boolean(current[field.key]),
            ).length,
        [current],
    );
    const enabledExecutionGuards = useMemo(
        () =>
            executionGuardFields.filter((field) => Boolean(current[field.key]))
                .length,
        [current],
    );
    const scoringTotal = useMemo(
        () =>
            scoringWeightFields.reduce(
                (total, field) =>
                    total + Number(current.scoring_weights?.[field.key] ?? 0),
                0,
            ),
        [current],
    );
    const mtfWeights = current.mtf_context_weights ?? {};

    const updateNested = (section: string, key: string, value: number) => {
        setConfigs((previous) => ({
            ...previous,
            [mode]: {
                ...previous[mode],
                [section]: { ...previous[mode]?.[section], [key]: value },
            },
        }));
        setMessage(null);
    };

    const updateMtfWeight = (
        interval: string,
        frame: string,
        value: number,
    ) => {
        setConfigs((previous) => ({
            ...previous,
            [mode]: {
                ...previous[mode],
                mtf_context_weights: {
                    ...previous[mode]?.mtf_context_weights,
                    [interval]: {
                        ...previous[mode]?.mtf_context_weights?.[interval],
                        [frame]: value,
                    },
                },
            },
        }));
        setMessage(null);
    };

    const load = async () => {
        setLoading(true);
        setMessage(null);
        try {
            const response = await fetch("/admin/settings/signal-policy", {
                headers: { Accept: "application/json" },
                credentials: "same-origin",
            });
            const data = await readResponse(response);
            if (!response.ok)
                throw new Error(data.message ?? "Gagal memuat konfigurasi.");
            const next = (data.configurations ?? {}) as Record<Mode, Config>;
            setConfigs(clone(next));
            setSavedConfigs(clone(next));
        } catch (error) {
            setMessage({
                type: "error",
                text: error instanceof Error ? error.message : "Gagal memuat.",
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        void load();
    }, []);

    useEffect(() => {
        const handler = (event: BeforeUnloadEvent) => {
            if (!dirty) return;
            event.preventDefault();
            event.returnValue = "";
        };
        window.addEventListener("beforeunload", handler);
        return () => window.removeEventListener("beforeunload", handler);
    }, [dirty]);

    const update = (key: string, value: boolean | number) => {
        setConfigs((previous) => ({
            ...previous,
            [mode]: { ...previous[mode], [key]: value },
        }));
        setMessage(null);
    };

    const updateMarket = (key: string, value: number) => {
        setConfigs((previous) => ({
            ...previous,
            [mode]: {
                ...previous[mode],
                market: {
                    ...previous[mode]?.market,
                    [market]: {
                        ...previous[mode]?.market?.[market],
                        [key]: value,
                    },
                },
            },
        }));
        setMessage(null);
    };

    const updateMarketDirection = (
        direction: "long" | "short",
        enabled: boolean,
    ) => {
        const currentDirections = Array.isArray(marketConfig.allowed_directions)
            ? marketConfig.allowed_directions.filter(
                  (item: unknown): item is "long" | "short" =>
                      item === "long" || item === "short",
              )
            : ["long"];

        if (market === "spot") {
            setMessage({
                type: "error",
                text: "Spot hanya mendukung posisi LONG.",
            });
            return;
        }

        const nextDirections = enabled
            ? Array.from(new Set([...currentDirections, direction]))
            : currentDirections.filter(
                  (item: "long" | "short") => item !== direction,
              );

        if (nextDirections.length === 0) {
            setMessage({
                type: "error",
                text: "Minimal satu arah posisi harus aktif.",
            });
            return;
        }

        setConfigs((previous) => ({
            ...previous,
            [mode]: {
                ...previous[mode],
                market: {
                    ...previous[mode]?.market,
                    [market]: {
                        ...previous[mode]?.market?.[market],
                        allowed_directions: nextDirections,
                    },
                },
            },
        }));
        setMessage(null);
    };

    const save = async () => {
        if (!dirty) {
            setMessage({ type: "success", text: "Tidak ada perubahan." });
            return;
        }
        setBusy(true);
        setMessage(null);
        try {
            const response = await fetch("/admin/settings/signal-policy", {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json",
                    Accept: "application/json",
                    "X-CSRF-TOKEN": csrfToken(),
                },
                credentials: "same-origin",
                body: JSON.stringify({ configurations: configs }),
            });
            const data = await readResponse(response);
            if (!response.ok)
                throw new Error(data.message ?? "Gagal menyimpan.");
            const next = (data.configurations ?? configs) as Record<
                Mode,
                Config
            >;
            setConfigs(clone(next));
            setSavedConfigs(clone(next));
            setMessage({
                type: "success",
                text: data.message ?? "Berhasil disimpan.",
            });
        } catch (error) {
            setMessage({
                type: "error",
                text:
                    error instanceof Error ? error.message : "Gagal menyimpan.",
            });
        } finally {
            setBusy(false);
        }
    };

    const resetToDefaults = async () => {
        setBusy(true);
        setMessage(null);
        try {
            const response = await fetch(
                "/admin/settings/signal-policy/reset",
                {
                    method: "POST",
                    headers: {
                        Accept: "application/json",
                        "X-CSRF-TOKEN": csrfToken(),
                    },
                    credentials: "same-origin",
                },
            );
            const data = await readResponse(response);
            if (!response.ok) throw new Error(data.message ?? "Reset gagal.");
            const next = (data.configurations ?? {}) as Record<Mode, Config>;
            setConfigs(clone(next));
            setSavedConfigs(clone(next));
            setMessage({
                type: "success",
                text: "Berhasil dikembalikan ke default.",
            });
        } catch (error) {
            setMessage({
                type: "error",
                text: error instanceof Error ? error.message : "Reset gagal.",
            });
        } finally {
            setBusy(false);
        }
    };

    return (
        <>
            <Head title={t("Signal Configuration Center")} />

            <div className="mx-auto max-w-7xl space-y-8 p-4 md:p-8 pb-28">
                {/* Header Section */}
                <div className="flex flex-col gap-4 border-b pb-6 lg:flex-row lg:items-center lg:justify-between">
                    <div className="space-y-1.5">
                        <div className="flex items-center gap-3">
                            <div className="rounded-xl bg-primary/10 p-2.5 text-primary">
                                <Activity className="size-6" />
                            </div>
                            <div>
                                <h1 className="text-2xl font-bold tracking-tight text-foreground">
                                    {t("Signal Engine & Policy Center")}
                                </h1>
                                <p className="text-sm text-muted-foreground">
                                    {t(
                                        "Konfigurasi parameter kuantitatif, manajemen risiko, dan filter sinyal secara presisi.",
                                    )}
                                </p>
                            </div>
                        </div>
                    </div>

                    <div className="flex flex-wrap items-center gap-2.5">
                        <Badge
                            variant="outline"
                            className="gap-1.5 bg-background/50 px-3 py-1.5 text-xs font-medium"
                        >
                            <SlidersHorizontal className="size-3.5 text-primary" />
                            {enabledFilters} {t("Filter Aktif")}
                        </Badge>
                        {dirty ? (
                            <Badge
                                variant="outline"
                                className="border-warning/40 bg-warning/10 px-3 py-1.5 text-xs font-semibold text-warning animate-pulse"
                            >
                                {t("● Perubahan Belum Disimpan")}
                            </Badge>
                        ) : (
                            <Badge
                                variant="outline"
                                className="border-success/30 bg-success/5 px-3 py-1.5 text-xs text-success"
                            >
                                {t("✓ Sinkron")}
                            </Badge>
                        )}
                    </div>
                </div>

                {/* Status Alert Banner */}
                {message && (
                    <div
                        role="status"
                        className={`flex items-center gap-3 rounded-2xl border p-4 text-sm shadow-sm transition-all animate-in fade-in ${
                            message.type === "error"
                                ? "border-destructive/30 bg-destructive/10 text-destructive font-medium"
                                : "border-success/30 bg-success/10 text-success font-medium"
                        }`}
                    >
                        {message.type === "error" ? (
                            <AlertCircle className="size-5 shrink-0" />
                        ) : (
                            <Check className="size-5 shrink-0" />
                        )}
                        <span>{message.text}</span>
                    </div>
                )}

                <AdminOperationalStrip
                    metrics={[
                        {
                            label: "Active policy",
                            value: <span className="capitalize">{mode}</span>,
                            detail: modeDescriptions[mode],
                            tone: dirty ? "warning" : "success",
                        },
                        {
                            label: "Market scope",
                            value: <span className="capitalize">{market}</span>,
                            detail:
                                market === "spot"
                                    ? "Long only"
                                    : "Long & short",
                        },
                        {
                            label: "Candidate filters",
                            value: enabledFilters,
                            detail: "Boolean gates enabled",
                        },
                        {
                            label: "Safety guards",
                            value:
                                enabledStrategyGuards +
                                enabledExecutionGuards,
                            detail: `${enabledStrategyGuards} strategy · ${enabledExecutionGuards} execution`,
                            tone:
                                enabledExecutionGuards > 0
                                    ? "success"
                                    : "warning",
                        },
                    ]}
                />

                {/* Active Policy Scope */}
                <Card className="overflow-hidden border-border/70 shadow-sm">
                    <CardHeader className="border-b bg-muted/20 pb-4">
                        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                            <div className="flex items-start gap-3">
                                <div className="rounded-lg bg-primary/10 p-2 text-primary">
                                    <Compass className="size-5" />
                                </div>
                                <div>
                                    <CardTitle className="text-base">
                                        {t("Active Policy")}
                                    </CardTitle>
                                    <CardDescription className="mt-1">
                                        {t(
                                            "Pilih policy yang ingin diedit. Perubahan berlaku pada konfigurasi mode terpilih setelah disimpan.",
                                        )}
                                    </CardDescription>
                                </div>
                            </div>
                            <Badge
                                variant="outline"
                                className={
                                    dirty
                                        ? "border-warning/40 bg-warning/10 text-warning"
                                        : "border-success/30 bg-success/5 text-success"
                                }
                            >
                                {dirty ? t("Unsaved changes") : t("In sync")}
                            </Badge>
                        </div>
                    </CardHeader>
                    <CardContent className="space-y-5 p-5">
                        <div className="grid gap-3 md:grid-cols-3">
                            {modes.map((item: Mode) => (
                                <button
                                    key={item}
                                    type="button"
                                    onClick={() => setMode(item)}
                                    className={`group rounded-xl border p-4 text-left transition-all ${
                                        mode === item
                                            ? "border-primary bg-primary/5 ring-1 ring-primary/20"
                                            : "border-border/70 hover:border-primary/30 hover:bg-muted/30"
                                    }`}
                                >
                                    <div className="flex items-center justify-between gap-3">
                                        <span className="font-semibold capitalize">
                                            {item}
                                        </span>
                                        {mode === item ? (
                                            <Badge className="text-[10px] uppercase tracking-wider">
                                                {t("Editing")}
                                            </Badge>
                                        ) : null}
                                    </div>
                                    <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
                                        {modeDescriptions[item]}
                                    </p>
                                </button>
                            ))}
                        </div>

                        <div className="flex flex-col gap-3 rounded-xl border border-border/70 bg-muted/20 p-4 sm:flex-row sm:items-center sm:justify-between">
                            <div>
                                <p className="text-sm font-semibold">
                                    {t("Market scope")}
                                </p>
                                <p className="mt-0.5 text-xs text-muted-foreground">
                                    {market === "spot"
                                        ? t(
                                              "Spot policy dikunci LONG-only oleh engine.",
                                          )
                                        : t(
                                              "Futures policy dapat mengatur LONG dan SHORT.",
                                          )}
                                </p>
                            </div>
                            <div className="flex gap-2">
                                {markets.map((m: Market) => (
                                    <Button
                                        key={m}
                                        type="button"
                                        variant={
                                            market === m ? "default" : "outline"
                                        }
                                        size="sm"
                                        onClick={() => setMarket(m)}
                                        className="capitalize"
                                    >
                                        {m === "spot" ? "Spot" : "Futures"}
                                    </Button>
                                ))}
                            </div>
                        </div>
                    </CardContent>
                </Card>

                {!loading && (
                    <div className="grid gap-4 lg:grid-cols-[1.5fr_1fr]">
                        <Card className="border-border/70 shadow-none">
                            <CardContent className="flex gap-3 p-4">
                                <ShieldCheck className="mt-0.5 size-5 shrink-0 text-success" />
                                <div>
                                    <p className="text-sm font-semibold">
                                        {t("Policy intent")}
                                    </p>
                                    <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
                                        {t(
                                            "Candidate filter menentukan kelayakan awal. Strategy, MTF, risk dan execution guard mempersempit kandidat sebelum dianggap valid.",
                                        )}
                                    </p>
                                </div>
                            </CardContent>
                        </Card>
                        <Card className="border-border/70 shadow-none">
                            <CardContent className="flex items-center justify-between gap-4 p-4">
                                <div>
                                    <p className="text-xs font-semibold uppercase tracking-[0.12em] text-muted-foreground">
                                        {t("Minimum score")}
                                    </p>
                                    <p className="mt-1 text-2xl font-semibold tracking-tight">
                                        {Number(
                                            current.score_threshold ?? 0,
                                        ).toFixed(1)}
                                    </p>
                                </div>
                                <Badge variant="outline">
                                    {t("Current policy")}
                                </Badge>
                            </CardContent>
                        </Card>
                    </div>
                )}

                {loading ? (
                    <div className="grid gap-6 lg:grid-cols-2">
                        {[1, 2, 3, 4].map((item: number) => (
                            <Card
                                key={item}
                                className="animate-pulse border-border/40"
                            >
                                <CardHeader className="space-y-2">
                                    <div className="h-5 w-44 rounded bg-muted" />
                                    <div className="h-4 w-72 rounded bg-muted/60" />
                                </CardHeader>
                                <CardContent>
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        {[1, 2, 3, 4, 5, 6].map(
                                            (cell: number) => (
                                                <div
                                                    key={cell}
                                                    className="h-14 rounded-xl bg-muted/40"
                                                />
                                            ),
                                        )}
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>
                ) : (
                    <Accordion
                        type="multiple"
                        defaultValue={["filter-persyaratan-kandidat"]}
                        className="space-y-4"
                    >
                        {/* Filter Kandidat */}
                        <AccordionItem
                            value="filter-persyaratan-kandidat"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <ShieldCheck className="size-5 text-primary shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t(
                                                "Filter & Persyaratan Kandidat Sinyal",
                                            )}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Konfirmasi utama yang wajib dipenuhi oleh kandidat analisis pada mode",
                                            )}{" "}
                                            {mode}.
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2">
                                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                                    {Object.entries(labels).map(
                                        ([key, label]: [string, string]) => (
                                            <label
                                                key={key}
                                                className="flex cursor-pointer items-center justify-between gap-4 rounded-xl border border-border/60 bg-background/50 p-4 transition-all hover:border-primary/40 hover:bg-muted/40"
                                            >
                                                <span className="text-sm font-medium text-foreground">
                                                    {label}
                                                </span>
                                                <Checkbox
                                                    checked={Boolean(
                                                        current[key],
                                                    )}
                                                    onCheckedChange={(
                                                        value: boolean | string,
                                                    ) =>
                                                        update(
                                                            key,
                                                            value === true,
                                                        )
                                                    }
                                                />
                                            </label>
                                        ),
                                    )}
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Indicator Parameters */}
                        <AccordionItem
                            value="indicator-parameters"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <BarChart3 className="size-5 text-primary shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t("Parameter Teknis Indikator")}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Sesuaikan periode indikator teknikal spesifik untuk mode aktif tanpa modifikasi kode.",
                                            )}
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2">
                                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                                    {indicatorFields.map((field) => (
                                        <label
                                            key={field.key}
                                            className="space-y-1.5"
                                        >
                                            <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                                                {field.label}
                                            </span>
                                            <div className="relative">
                                                <input
                                                    type="number"
                                                    min={field.min}
                                                    max={field.max}
                                                    step={field.step}
                                                    value={
                                                        current
                                                            .indicator_periods?.[
                                                            field.key
                                                        ] ?? ""
                                                    }
                                                    onChange={(event) =>
                                                        updateNested(
                                                            "indicator_periods",
                                                            field.key,
                                                            Number(
                                                                event.target
                                                                    .value,
                                                            ),
                                                        )
                                                    }
                                                    className="h-10 w-full rounded-xl border border-input bg-background px-3 pr-20 text-sm shadow-sm outline-none transition-all focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                />
                                                <span className="pointer-events-none absolute inset-y-0 right-3 flex items-center text-xs font-medium text-muted-foreground">
                                                    {field.suffix}
                                                </span>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Scoring Weights */}
                        <AccordionItem
                            value="scoring-weights"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <PieChart className="size-5 text-primary shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t(
                                                "Skor Komposit & Bobot Kategori (Scoring Weights)",
                                            )}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Distribusi bobot penilaian indikator. Total kumulatif wajib tepat 100%.",
                                            )}
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2 space-y-4">
                                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                                    {scoringWeightFields.map((field) => (
                                        <label
                                            key={field.key}
                                            className="space-y-1.5"
                                        >
                                            <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                                                {field.label}
                                            </span>
                                            <div className="relative">
                                                <input
                                                    type="number"
                                                    min={0}
                                                    max={100}
                                                    step={0.5}
                                                    value={
                                                        current
                                                            .scoring_weights?.[
                                                            field.key
                                                        ] ?? ""
                                                    }
                                                    onChange={(event) =>
                                                        updateNested(
                                                            "scoring_weights",
                                                            field.key,
                                                            Number(
                                                                event.target
                                                                    .value,
                                                            ),
                                                        )
                                                    }
                                                    className="h-10 w-full rounded-xl border border-input bg-background px-3 pr-10 text-sm shadow-sm outline-none transition-all focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                />
                                                <span className="pointer-events-none absolute inset-y-0 right-3 flex items-center text-xs font-bold text-muted-foreground">
                                                    %
                                                </span>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                                <div
                                    className={`flex items-center justify-between rounded-xl border px-4 py-3 text-sm font-medium ${Math.abs(scoringTotal - 100) < 0.01 ? "border-success/30 bg-success/5 text-success" : "border-warning/30 bg-warning/5 text-warning"}`}
                                >
                                    <span>{t("Total Bobot Kumulatif")}</span>
                                    <span className="font-bold text-base">
                                        {scoringTotal.toFixed(1)}%{" "}
                                        {Math.abs(scoringTotal - 100) < 0.01
                                            ? "— (Valid)"
                                            : "— (Harus 100%)"}
                                    </span>
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* MTF Context Weights */}
                        <AccordionItem
                            value="mtf-context-weights"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <Layers className="size-5 text-primary shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t(
                                                "Multi-Timeframe (MTF) Context Weights",
                                            )}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Pengaturan bobot hierarki antar timeframe (otomatis dinormalisasi).",
                                            )}
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2">
                                <div className="space-y-4">
                                    {mtfIntervals.map((interval: string) => {
                                        const weights =
                                            mtfWeights[interval] ?? {};
                                        const entries = Object.entries(
                                            weights,
                                        ) as Array<[string, number]>;
                                        if (entries.length === 0) return null;
                                        const total = entries.reduce(
                                            (
                                                sum: number,
                                                [, value]: [string, number],
                                            ) => sum + Number(value || 0),
                                            0,
                                        );
                                        return (
                                            <div
                                                key={interval}
                                                className="rounded-xl border border-border/60 bg-background/50 p-4 space-y-3"
                                            >
                                                <div className="flex items-center justify-between">
                                                    <div>
                                                        <span className="text-sm font-bold text-foreground">
                                                            {t(
                                                                "Timeframe Sinyal:",
                                                            )}{" "}
                                                            {interval}
                                                        </span>
                                                        <p className="text-xs text-muted-foreground">
                                                            {t(
                                                                "Normalisasi otomatis aktif saat evaluasi engine.",
                                                            )}
                                                        </p>
                                                    </div>
                                                    <Badge
                                                        variant="outline"
                                                        className="text-xs font-semibold"
                                                    >
                                                        {t("Total")}
                                                        {total.toFixed(2)}
                                                    </Badge>
                                                </div>
                                                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
                                                    {entries.map(
                                                        ([frame, value]: [
                                                            string,
                                                            number,
                                                        ]) => (
                                                            <label
                                                                key={frame}
                                                                className="space-y-1"
                                                            >
                                                                <span className="text-[11px] font-semibold text-muted-foreground">
                                                                    {frame}
                                                                </span>
                                                                <input
                                                                    type="number"
                                                                    min={0}
                                                                    max={1}
                                                                    step={0.01}
                                                                    value={
                                                                        value ??
                                                                        0
                                                                    }
                                                                    onChange={(
                                                                        event,
                                                                    ) =>
                                                                        updateMtfWeight(
                                                                            interval,
                                                                            frame,
                                                                            Number(
                                                                                event
                                                                                    .target
                                                                                    .value,
                                                                            ),
                                                                        )
                                                                    }
                                                                    className="h-9 w-full rounded-lg border border-input bg-background px-3 text-sm shadow-sm outline-none transition-all focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                                />
                                                            </label>
                                                        ),
                                                    )}
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Strategy & Entry Confirmation */}
                        <AccordionItem
                            value="strategy-entry-confirmation"
                            className="rounded-2xl border border-primary/30 bg-primary/1 shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <Cpu className="size-5 text-primary shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t("Strategy & Entry Confirmation")}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Isolasi konfirmasi engine, trigger strategi, dan ketersediaan trade plan.",
                                            )}
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2">
                                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                                    {strategyConfirmationFields.map((field) => (
                                        <label
                                            key={field.key}
                                            className="flex cursor-pointer items-start justify-between gap-4 rounded-xl border border-border/60 bg-card p-4 transition-all hover:border-primary/40 hover:bg-muted/30"
                                        >
                                            <div className="space-y-1">
                                                <span className="text-sm font-semibold text-foreground">
                                                    {field.label}
                                                </span>
                                                <p className="text-xs leading-relaxed text-muted-foreground">
                                                    {field.description}
                                                </p>
                                            </div>
                                            <Checkbox
                                                checked={Boolean(
                                                    current[field.key],
                                                )}
                                                onCheckedChange={(
                                                    value: boolean | string,
                                                ) =>
                                                    update(
                                                        field.key,
                                                        value === true,
                                                    )
                                                }
                                            />
                                        </label>
                                    ))}
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Ambang Parameter */}
                        <AccordionItem
                            value="ambang-parameter"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <Settings2 className="size-5 text-primary shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t(
                                                "Ambang Batas Nilai Parameter (Thresholds)",
                                            )}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Pengaturan nilai numerik limitasi minimum dan maksimum policy.",
                                            )}
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2">
                                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                                    {numericFields.map((field) => (
                                        <label
                                            key={field.key}
                                            className="space-y-1.5"
                                        >
                                            <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                                                {field.label}
                                            </span>
                                            <div className="relative">
                                                <input
                                                    type="number"
                                                    min={field.min}
                                                    max={field.max}
                                                    step={field.step}
                                                    value={
                                                        current[field.key] ?? ""
                                                    }
                                                    onChange={(event) =>
                                                        update(
                                                            field.key,
                                                            Number(
                                                                event.target
                                                                    .value,
                                                            ),
                                                        )
                                                    }
                                                    className="h-10 w-full rounded-xl border border-input bg-background px-3 pr-20 text-sm shadow-sm outline-none transition-all focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                />
                                                <span className="pointer-events-none absolute inset-y-0 right-3 flex items-center text-xs font-medium text-muted-foreground">
                                                    {field.suffix}
                                                </span>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Market Risk Rules */}
                        <AccordionItem
                            value="market-specific-risk-rules"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center justify-between w-full pr-4 text-left">
                                    <div className="flex items-center gap-3">
                                        <Lock className="size-5 text-primary shrink-0" />
                                        <div>
                                            <span className="text-base font-semibold text-foreground">
                                                {t(
                                                    "Market-Specific Risk Rules",
                                                )}
                                            </span>
                                            <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                                {t(
                                                    "Aturan risiko spesifik untuk market aktif:",
                                                )}{" "}
                                                <span className="font-semibold uppercase text-primary">
                                                    {market}
                                                </span>
                                            </span>
                                        </div>
                                    </div>
                                    <Badge
                                        variant="outline"
                                        className="font-semibold uppercase"
                                    >
                                        {market === "spot"
                                            ? "Long Only"
                                            : "Long & Short"}
                                    </Badge>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2">
                                <div className="grid gap-4 md:grid-cols-3">
                                    {marketNumericFields.map((field) => (
                                        <label
                                            key={field.key}
                                            className="space-y-1.5"
                                        >
                                            <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                                                {field.label}
                                            </span>
                                            <div className="relative">
                                                <input
                                                    type="number"
                                                    min={field.min}
                                                    max={field.max}
                                                    step={field.step}
                                                    value={
                                                        marketConfig[
                                                            field.key
                                                        ] ?? ""
                                                    }
                                                    onChange={(event) =>
                                                        updateMarket(
                                                            field.key,
                                                            Number(
                                                                event.target
                                                                    .value,
                                                            ),
                                                        )
                                                    }
                                                    className="h-10 w-full rounded-xl border border-input bg-background px-3 pr-20 text-sm shadow-sm outline-none transition-all focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                />
                                                <span className="pointer-events-none absolute inset-y-0 right-3 flex items-center text-xs font-medium text-muted-foreground">
                                                    {field.suffix}
                                                </span>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Market Direction Rules */}
                        <AccordionItem
                            value="market-direction-rules"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center justify-between w-full pr-4 text-left">
                                    <div className="flex items-center gap-3">
                                        <Compass className="size-5 text-primary shrink-0" />
                                        <div>
                                            <span className="text-base font-semibold text-foreground">
                                                {t(
                                                    "Market Direction Permissions",
                                                )}
                                            </span>
                                            <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                                {t(
                                                    "Izin arah skenario analisis pada market",
                                                )}
                                                {market}.
                                            </span>
                                        </div>
                                    </div>
                                    <Badge
                                        variant="outline"
                                        className="font-semibold uppercase"
                                    >
                                        {market === "spot"
                                            ? "Locked (Spot)"
                                            : "Configurable"}
                                    </Badge>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2 space-y-4">
                                <div className="grid gap-3 sm:grid-cols-2">
                                    {directions.map((direction) => {
                                        const checked = Array.isArray(
                                            marketConfig.allowed_directions,
                                        )
                                            ? marketConfig.allowed_directions.includes(
                                                  direction.key,
                                              )
                                            : direction.key === "long";
                                        const locked = market === "spot";

                                        return (
                                            <label
                                                key={direction.key}
                                                className={`flex items-center justify-between gap-4 rounded-xl border p-4 transition-all ${locked ? "cursor-not-allowed bg-muted/20 opacity-75" : "cursor-pointer border-border/60 hover:border-primary/40 hover:bg-muted/30"}`}
                                            >
                                                <div>
                                                    <span className="text-sm font-bold text-foreground">
                                                        {direction.label}
                                                    </span>
                                                    <p className="mt-0.5 text-xs text-muted-foreground">
                                                        {direction.key ===
                                                        "long"
                                                            ? "Setup posisi beli (Bullish)."
                                                            : "Setup posisi jual/short (Bearish)."}
                                                    </p>
                                                </div>
                                                <Checkbox
                                                    checked={checked}
                                                    disabled={locked}
                                                    onCheckedChange={(
                                                        value: boolean | string,
                                                    ) =>
                                                        updateMarketDirection(
                                                            direction.key,
                                                            value === true,
                                                        )
                                                    }
                                                />
                                            </label>
                                        );
                                    })}
                                </div>
                                <div className="flex items-center gap-2 rounded-xl bg-muted/40 p-3 text-xs text-muted-foreground">
                                    <CircleHelp className="size-4 shrink-0 text-primary" />
                                    <span>
                                        {t(
                                            "Spot market dikunci khusus LONG karena arsitektur risk & execution engine tidak mendukung posisi SHORT di market Spot.",
                                        )}
                                    </span>
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Execution Guards */}
                        <AccordionItem
                            value="execution-guards"
                            className="rounded-2xl border border-warning/25 bg-warning/5 shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <SlidersHorizontal className="size-5 text-warning shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t(
                                                "Execution Guards & Testing Safeguards",
                                            )}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Aktifkan atau nonaktifkan guard proteksi eksekusi untuk keperluan diagnosis dan testing.",
                                            )}
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2 space-y-4">
                                <div className="grid gap-3 sm:grid-cols-2">
                                    {executionGuardFields.map((field) => (
                                        <label
                                            key={field.key}
                                            className="flex cursor-pointer items-start justify-between gap-4 rounded-xl border border-border/60 bg-card p-4 transition-all hover:border-primary/40 hover:bg-muted/30"
                                        >
                                            <div className="space-y-1">
                                                <span className="text-sm font-semibold text-foreground">
                                                    {field.label}
                                                </span>
                                                <p className="text-xs leading-relaxed text-muted-foreground">
                                                    {field.description}
                                                </p>
                                            </div>
                                            <Checkbox
                                                checked={Boolean(
                                                    current[field.key],
                                                )}
                                                onCheckedChange={(
                                                    value: boolean | string,
                                                ) =>
                                                    update(
                                                        field.key,
                                                        value === true,
                                                    )
                                                }
                                            />
                                        </label>
                                    ))}
                                </div>
                            </AccordionContent>
                        </AccordionItem>

                        {/* Policy Diagnostics */}
                        <AccordionItem
                            value="policy-diagnostics"
                            className="rounded-2xl border border-border/60 bg-card shadow-sm px-6"
                        >
                            <AccordionTrigger className="py-5 hover:no-underline">
                                <div className="flex items-center gap-3 text-left">
                                    <Activity className="size-5 text-primary shrink-0" />
                                    <div>
                                        <span className="text-base font-semibold text-foreground">
                                            {t("Ringkasan Policy Diagnostics")}
                                        </span>
                                        <span className="block text-xs font-normal text-muted-foreground mt-0.5">
                                            {t(
                                                "Ringkasan parameter policy aktif untuk",
                                            )}
                                            {mode} / {market}.
                                        </span>
                                    </div>
                                </div>
                            </AccordionTrigger>
                            <AccordionContent className="pb-6 pt-2 space-y-4">
                                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                                    <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
                                        <p className="text-xs font-medium text-muted-foreground">
                                            {t("Candidate Filters")}
                                        </p>
                                        <p className="mt-1 text-2xl font-bold text-foreground">
                                            {enabledFilters}
                                        </p>
                                    </div>
                                    <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
                                        <p className="text-xs font-medium text-muted-foreground">
                                            {t("Strategy Guards")}
                                        </p>
                                        <p className="mt-1 text-2xl font-bold text-foreground">
                                            {enabledStrategyGuards}
                                        </p>
                                    </div>
                                    <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
                                        <p className="text-xs font-medium text-muted-foreground">
                                            {t("Execution Guards")}
                                        </p>
                                        <p className="mt-1 text-2xl font-bold text-foreground">
                                            {enabledExecutionGuards}
                                        </p>
                                    </div>
                                    <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
                                        <p className="text-xs font-medium text-muted-foreground">
                                            {t("Min Score Threshold")}
                                        </p>
                                        <p className="mt-1 text-2xl font-bold text-foreground">
                                            {Number(
                                                current.score_threshold ?? 0,
                                            ).toFixed(1)}
                                        </p>
                                    </div>
                                </div>
                            </AccordionContent>
                        </AccordionItem>
                    </Accordion>
                )}

                {/* Sticky Action Footer Bar (Fixed with left spacing for sidebar) */}
                <div className="fixed bottom-0 right-0 left-0 md:left-64 z-40 border-t bg-background/90 px-6 py-4 shadow-2xl backdrop-blur-md">
                    <div className="mx-auto flex max-w-7xl items-center justify-between gap-4">
                        <div className="text-xs font-medium text-muted-foreground hidden sm:block">
                            {dirty ? (
                                <span className="text-warning font-semibold">
                                    {t("● Perubahan belum disimpan pada mode")}
                                    {mode} ({market}).
                                </span>
                            ) : (
                                <span>
                                    {t(
                                        "Semua konfigurasi policy telah tersinkronisasi.",
                                    )}
                                </span>
                            )}
                        </div>
                        <div className="flex flex-wrap items-center gap-2.5 w-full sm:w-auto justify-end">
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => void load()}
                                disabled={busy || loading}
                                className="gap-2"
                            >
                                <RotateCcw className="size-4" />
                                {t("Muat Ulang")}
                            </Button>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => setResetDialogOpen(true)}
                                disabled={busy}
                                className="gap-2 text-destructive hover:text-destructive"
                            >
                                <RotateCcw className="size-4" />
                                {t("Default")}
                            </Button>
                            <Button
                                size="sm"
                                onClick={() => void save()}
                                disabled={busy || !dirty}
                                className="gap-2 px-6 font-semibold shadow-sm"
                            >
                                <Save className="size-4" />
                                {busy ? "Menyimpan..." : "Simpan Konfigurasi"}
                            </Button>
                        </div>
                    </div>
                </div>
            </div>

            <AlertDialog
                open={resetDialogOpen}
                onOpenChange={setResetDialogOpen}
            >
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>
                            {t(
                                "Restore configuration?",
                                "Restore configuration?",
                            )}
                        </AlertDialogTitle>
                        <AlertDialogDescription>
                            {t(
                                "Restore all configuration to defaults? Unsaved changes will be lost.",
                                "Restore all configuration to defaults? Unsaved changes will be lost.",
                            )}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel disabled={busy}>
                            {t("Batal", "Cancel")}
                        </AlertDialogCancel>
                        <AlertDialogAction
                            disabled={busy}
                            onClick={(event) => {
                                event.preventDefault();
                                setResetDialogOpen(false);
                                void resetToDefaults();
                            }}
                        >
                            {t("Kembalikan Default", "Restore defaults")}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    );
}
