import { useEffect, useMemo, useState } from "react";
import { useEditor } from "./EditorContext";
import { generateVoiceoverScript, localizeCopy } from "../../lib/api";
import type { Hotspot } from "../../types/annotations";

type HotspotSuggestion = {
    id: string;
    hotspot: Hotspot;
    label: string;
    timestamp_ms: number;
};

const DEFAULT_HOTSPOT_BG = "#5E6AD2";
const DEFAULT_HOTSPOT_TEXT = "#FFFFFF";

const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));

function formatTime(seconds: number) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
}

const isHexColor = (value: string) => /^#[0-9a-fA-F]{6}$/.test(value.trim());

const normalizeHexColor = (value: string): string | null => {
    const trimmed = value.trim();
    if (isHexColor(trimmed)) return trimmed;
    if (/^[0-9a-fA-F]{6}$/.test(trimmed)) return `#${trimmed}`;
    if (/^#[0-9a-fA-F]{3}$/.test(trimmed)) {
        const [r, g, b] = trimmed.slice(1).split("");
        if (!r || !g || !b) return null;
        return `#${r}${r}${g}${g}${b}${b}`;
    }
    if (/^[0-9a-fA-F]{3}$/.test(trimmed)) {
        const [r, g, b] = trimmed.split("");
        if (!r || !g || !b) return null;
        return `#${r}${r}${g}${g}${b}${b}`;
    }
    return null;
};

const DEFAULT_ASSIST_LANGUAGE = "es";
const DEFAULT_VOICEOVER_TONE = "confident and concise";

const normalizeLanguageTag = (value: string): string => {
    const normalized = value.trim().toLowerCase();
    return normalized || DEFAULT_ASSIST_LANGUAGE;
};

const errorMessage = (error: unknown): string => {
    if (error instanceof Error && error.message) return error.message;
    return String(error);
};

const EditorHotspotInspector = () => {
    const {
        fps,
        totalFrames,
        clicks,
        markers,
        hotspots,
        steps,
        selectedHotspotId,
        setSelectedHotspotId,
        placingHotspot,
        setPlacingHotspot,
        selectedStep,
        selectedStepId,
        seekToTimestamp,
        handleAddHotspot,
        handleUpdateHotspot,
        handleDeleteHotspot,
        setEditingHotspots,
        setWalkthroughMode,
    } = useEditor();

    const [suggestions, setSuggestions] = useState<HotspotSuggestion[]>([]);
    const [suggesting, setSuggesting] = useState(false);
    const [backgroundDraft, setBackgroundDraft] = useState(DEFAULT_HOTSPOT_BG);
    const [textDraft, setTextDraft] = useState(DEFAULT_HOTSPOT_TEXT);
    const [assistLanguage, setAssistLanguage] = useState(DEFAULT_ASSIST_LANGUAGE);
    const [aiBusy, setAiBusy] = useState<null | "translate" | "voiceover">(null);
    const [aiError, setAiError] = useState<string | null>(null);
    const [aiNotice, setAiNotice] = useState<string | null>(null);

    const selectedHotspot = useMemo(
        () => hotspots.find((hotspot) => hotspot.id === selectedHotspotId) ?? null,
        [hotspots, selectedHotspotId]
    );
    const normalizedAssistLanguage = useMemo(
        () => normalizeLanguageTag(assistLanguage),
        [assistLanguage]
    );
    const languageLabel = useMemo(
        () => normalizedAssistLanguage.toUpperCase(),
        [normalizedAssistLanguage]
    );
    const localizedCopyPreview = useMemo(() => {
        if (!selectedHotspot) return "";
        return selectedHotspot.translations?.[normalizedAssistLanguage]?.text ?? "";
    }, [selectedHotspot, normalizedAssistLanguage]);
    const localizedVoiceoverPreview = useMemo(() => {
        if (!selectedHotspot) return "";
        return (
            selectedHotspot.translations?.[normalizedAssistLanguage]?.voiceover ??
            selectedHotspot.voiceoverScript ??
            ""
        );
    }, [selectedHotspot, normalizedAssistLanguage]);

    useEffect(() => {
        if (!selectedHotspot) return;
        setBackgroundDraft(selectedHotspot.backgroundColor ?? DEFAULT_HOTSPOT_BG);
        setTextDraft(selectedHotspot.textColor ?? DEFAULT_HOTSPOT_TEXT);
    }, [selectedHotspotId, selectedHotspot?.backgroundColor, selectedHotspot?.textColor]);

    useEffect(() => {
        setAiError(null);
        setAiNotice(null);
    }, [selectedHotspotId]);

    const stepWindow = useMemo(() => {
        if (!selectedStep) return null;
        return { start_ms: selectedStep.start_ms, end_ms: selectedStep.end_ms };
    }, [selectedStep]);

    const suggestionsDisabledReason = useMemo(() => {
        if (!selectedStep) return "Select a step to generate suggestions.";
        if (!stepWindow) return "Select a step to generate suggestions.";
        const clicksInStep = clicks.filter(
            (c) => c.timestamp_ms >= stepWindow.start_ms && c.timestamp_ms <= stepWindow.end_ms
        );
        if (clicksInStep.length === 0) return "No clicks captured in this step.";
        return null;
    }, [clicks, selectedStep, stepWindow]);

    const buildSuggestions = () => {
        if (!selectedStep || !stepWindow) return [];

        const clicksInStep = clicks
            .filter(
                (c) => c.timestamp_ms >= stepWindow.start_ms && c.timestamp_ms <= stepWindow.end_ms
            )
            .sort((a, b) => a.timestamp_ms - b.timestamp_ms);

        if (clicksInStep.length === 0) return [];

        const maxSuggestions = 3;
        const picked: typeof clicksInStep = [];
        const minMsDelta = 650;
        const minDist = 3.5; // percent distance in the stage coordinates

        for (const click of clicksInStep) {
            const last = picked[picked.length - 1];
            if (last) {
                const dt = Math.abs(click.timestamp_ms - last.timestamp_ms);
                const dx = click.x - last.x;
                const dy = click.y - last.y;
                const dist = Math.sqrt(dx * dx + dy * dy);
                if (dt < minMsDelta && dist < minDist) continue;
            }
            picked.push(click);
            if (picked.length >= maxSuggestions) break;
        }

        const nearestClickLabel = (timestampMs: number) => {
            let best: { delta: number; label: string } | null = null;
            for (const marker of markers) {
                if (marker.type !== "click") continue;
                const delta = Math.abs(marker.timestamp_ms - timestampMs);
                if (delta > 1600) continue;
                if (!best || delta < best.delta) {
                    best = { delta, label: marker.label };
                }
            }
            const label = best?.label?.trim() ?? "";
            if (!label) return "Click here";
            if (label.toLowerCase() === "click") return "Click here";
            return label;
        };

        return picked.map((click) => {
            const frame = clamp(Math.floor((click.timestamp_ms / 1000) * fps), 0, totalFrames);
            const suggested: Hotspot = {
                id: `hotspot-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,
                frameStart: frame,
                frameEnd: clamp(frame + 90, frame, totalFrames),
                x: clamp(click.x, 0, 100),
                y: clamp(click.y, 0, 100),
                width: 4,
                height: 4,
                style: "pulse",
                text: nearestClickLabel(click.timestamp_ms),
                action: { type: "next_step" },
            };

            return {
                id: `suggestion-${click.timestamp_ms}-${Math.random().toString(16).slice(2, 6)}`,
                hotspot: suggested,
                label: suggested.text?.trim() ? suggested.text : "Hotspot",
                timestamp_ms: click.timestamp_ms,
            };
        });
    };

    const runSuggestions = () => {
        if (suggestionsDisabledReason) return;
        setSuggesting(true);
        try {
            setSuggestions(buildSuggestions());
        } finally {
            setSuggesting(false);
        }
    };

    const closeInspector = () => {
        setWalkthroughMode(false);
        setPlacingHotspot(false);
        if (selectedHotspotId) {
            setSelectedHotspotId(null);
            return;
        }
        setEditingHotspots(false);
    };

    const updateSelected = (updater: (hotspot: Hotspot) => Hotspot) => {
        if (!selectedHotspot) return;
        handleUpdateHotspot(selectedHotspot.id, updater);
    };

    const commitColorDraft = (kind: "background" | "text") => {
        if (!selectedHotspot) return;
        const draft = kind === "background" ? backgroundDraft : textDraft;
        const normalized = normalizeHexColor(draft);
        if (!normalized) {
            if (kind === "background") {
                setBackgroundDraft(selectedHotspot.backgroundColor ?? DEFAULT_HOTSPOT_BG);
            } else {
                setTextDraft(selectedHotspot.textColor ?? DEFAULT_HOTSPOT_TEXT);
            }
            return;
        }

        if (kind === "background") {
            setBackgroundDraft(normalized);
            updateSelected((c) => ({ ...c, backgroundColor: normalized }));
        } else {
            setTextDraft(normalized);
            updateSelected((c) => ({ ...c, textColor: normalized }));
        }
    };

    const runTranslateHotspotCopy = async () => {
        if (!selectedHotspot) return;
        const source = (selectedHotspot.text ?? "").trim();
        if (!source) {
            setAiError("Add hotspot text before running translation.");
            setAiNotice(null);
            return;
        }

        setAiBusy("translate");
        setAiError(null);
        setAiNotice(null);

        try {
            const response = await localizeCopy(source, normalizedAssistLanguage);
            const language = normalizeLanguageTag(response.target_language || normalizedAssistLanguage);

            updateSelected((current) => {
                const translations = { ...(current.translations ?? {}) };
                const existing = { ...(translations[language] ?? {}) };
                translations[language] = {
                    ...existing,
                    text: response.text,
                };
                return {
                    ...current,
                    translations,
                };
            });

            setAiNotice(`Localized copy saved for ${language.toUpperCase()}.`);
        } catch (error) {
            setAiError(errorMessage(error));
        } finally {
            setAiBusy(null);
        }
    };

    const runGenerateVoiceover = async () => {
        if (!selectedHotspot) return;
        const translated = selectedHotspot.translations?.[normalizedAssistLanguage]?.text?.trim();
        const source = translated || (selectedHotspot.text ?? "").trim();
        if (!source) {
            setAiError("Add hotspot text before generating a voiceover script.");
            setAiNotice(null);
            return;
        }

        setAiBusy("voiceover");
        setAiError(null);
        setAiNotice(null);

        try {
            const response = await generateVoiceoverScript(source, {
                language: normalizedAssistLanguage,
                tone: DEFAULT_VOICEOVER_TONE,
                maxSeconds: 12,
            });

            updateSelected((current) => {
                const translations = { ...(current.translations ?? {}) };
                const existing = { ...(translations[normalizedAssistLanguage] ?? {}) };
                const script = response.script.trim();
                translations[normalizedAssistLanguage] = {
                    ...existing,
                    voiceover: script,
                };
                return {
                    ...current,
                    translations,
                    voiceoverScript:
                        normalizedAssistLanguage === "en"
                            ? script
                            : (current.voiceoverScript ?? undefined),
                };
            });

            setAiNotice(`Voiceover script saved for ${languageLabel}.`);
        } catch (error) {
            setAiError(errorMessage(error));
        } finally {
            setAiBusy(null);
        }
    };

    const updateLocalizedCopy = (nextText: string) => {
        if (!selectedHotspot) return;
        updateSelected((current) => {
            const translations = { ...(current.translations ?? {}) };
            const existing = { ...(translations[normalizedAssistLanguage] ?? {}) };
            translations[normalizedAssistLanguage] = {
                ...existing,
                text: nextText,
            };
            return {
                ...current,
                translations,
            };
        });
    };

    const updateLocalizedVoiceover = (nextText: string) => {
        if (!selectedHotspot) return;
        updateSelected((current) => {
            const translations = { ...(current.translations ?? {}) };
            const existing = { ...(translations[normalizedAssistLanguage] ?? {}) };
            translations[normalizedAssistLanguage] = {
                ...existing,
                voiceover: nextText,
            };
            return {
                ...current,
                translations,
                voiceoverScript:
                    normalizedAssistLanguage === "en"
                        ? nextText
                        : (current.voiceoverScript ?? undefined),
            };
        });
    };

    const styleLabel = (style: Hotspot["style"]) => {
        if (style === "rectangle") return "Area";
        if (style === "callout") return "Callout";
        return "Hotspot";
    };

    return (
        <aside
            style={{
                width: "360px",
                minWidth: "360px",
                maxWidth: "360px",
                background: "var(--bg-surface)",
                borderLeft: "1px solid var(--border-default)",
                display: "flex",
                flexDirection: "column",
                overflow: "hidden",
            }}
        >
            <div
                style={{
                    padding: "16px 16px 12px",
                    borderBottom: "1px solid var(--border-default)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    gap: "12px",
                }}
            >
                <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ display: "flex", alignItems: "baseline", gap: "10px" }}>
                        <div
                            style={{
                                fontSize: "16px",
                                fontWeight: 800,
                                color: "var(--text-primary)",
                                letterSpacing: "-0.01em",
                            }}
                        >
                            {selectedHotspot ? styleLabel(selectedHotspot.style) : "Hotspots"}
                        </div>
                        <div
                            style={{
                                fontSize: "12px",
                                color: "var(--text-muted)",
                                fontFamily: "var(--font-mono)",
                                whiteSpace: "nowrap",
                            }}
                        >
                            {hotspots.length} in step
                        </div>
                    </div>
                    <div
                        style={{
                            marginTop: "4px",
                            fontSize: "12px",
                            color: "var(--text-tertiary)",
                            lineHeight: 1.35,
                        }}
                    >
                        {selectedHotspot
                            ? "Edit the hotspot text, style, and colors."
                            : "Select a hotspot on the video, or add a new one."}
                    </div>
                </div>

                <button
                    onClick={closeInspector}
                    aria-label="Close hotspot editor"
                    style={{
                        width: "34px",
                        height: "34px",
                        display: "grid",
                        placeItems: "center",
                        border: "1px solid var(--border-default)",
                        background: "var(--bg-elevated)",
                        color: "var(--text-secondary)",
                        cursor: "pointer",
                        borderRadius: "10px",
                    }}
                >
                    <svg
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                    >
                        <path d="M18 6L6 18" />
                        <path d="M6 6l12 12" />
                    </svg>
                </button>
            </div>

            <div style={{ flex: 1, overflowY: "auto" }}>
                {!selectedHotspot ? (
                    <div style={{ padding: "16px" }}>
                        <button
                            onClick={() => setPlacingHotspot((c) => !c)}
                            style={{
                                width: "100%",
                                padding: "12px 14px",
                                borderRadius: "var(--radius-md)",
                                border: placingHotspot
                                    ? "1px solid var(--accent-1)"
                                    : "1px solid var(--border-default)",
                                background: placingHotspot
                                    ? "var(--accent-4)"
                                    : "var(--bg-elevated)",
                                color: placingHotspot ? "var(--accent-1)" : "var(--text-secondary)",
                                cursor: "pointer",
                                fontSize: "13px",
                                fontWeight: 700,
                                textAlign: "left",
                                transition: "all 150ms var(--ease-out)",
                            }}
                        >
                            {placingHotspot ? "Click on the video to place..." : "+ Add hotspot"}
                        </button>

                        <div
                            style={{
                                marginTop: "16px",
                                padding: "14px",
                                borderRadius: "var(--radius-lg)",
                                border: "1px solid var(--border-default)",
                                background: "var(--bg-elevated)",
                            }}
                        >
                            <div
                                style={{
                                    display: "flex",
                                    justifyContent: "space-between",
                                    alignItems: "center",
                                    gap: "12px",
                                    marginBottom: "10px",
                                }}
                            >
                                <div
                                    style={{
                                        fontSize: "12px",
                                        fontWeight: 800,
                                        color: "var(--text-primary)",
                                    }}
                                >
                                    Auto-detect
                                </div>
                                <button
                                    onClick={runSuggestions}
                                    disabled={!!suggestionsDisabledReason || suggesting}
                                    title={
                                        suggestionsDisabledReason ??
                                        "Suggest hotspots from captured clicks"
                                    }
                                    style={{
                                        padding: "7px 10px",
                                        borderRadius: "var(--radius-md)",
                                        border: "1px solid var(--accent-1)",
                                        background: "var(--accent-4)",
                                        color: "var(--accent-1)",
                                        cursor: suggestionsDisabledReason
                                            ? "not-allowed"
                                            : "pointer",
                                        fontSize: "12px",
                                        fontWeight: 800,
                                        opacity: suggestionsDisabledReason ? 0.6 : 1,
                                    }}
                                >
                                    {suggesting ? "Detecting..." : "Detect clicks"}
                                </button>
                            </div>

                            {suggestionsDisabledReason && (
                                <div
                                    style={{
                                        fontSize: "12px",
                                        color: "var(--text-muted)",
                                        background: "var(--bg-surface)",
                                        border: "1px solid var(--border-default)",
                                        borderRadius: "var(--radius-md)",
                                        padding: "10px 12px",
                                        lineHeight: 1.4,
                                    }}
                                >
                                    {suggestionsDisabledReason}
                                </div>
                            )}

                            {suggestions.length > 0 && (
                                <div
                                    style={{
                                        display: "flex",
                                        flexDirection: "column",
                                        gap: "10px",
                                    }}
                                >
                                    {suggestions.map((suggestion) => (
                                        <div
                                            key={suggestion.id}
                                            style={{
                                                border: "1px solid var(--border-default)",
                                                background: "var(--bg-surface)",
                                                borderRadius: "var(--radius-lg)",
                                                padding: "10px 12px",
                                            }}
                                        >
                                            <button
                                                onClick={() =>
                                                    seekToTimestamp(suggestion.timestamp_ms / 1000)
                                                }
                                                style={{
                                                    width: "100%",
                                                    border: "none",
                                                    background: "transparent",
                                                    padding: 0,
                                                    cursor: "pointer",
                                                    textAlign: "left",
                                                }}
                                                title="Jump to this click"
                                            >
                                                <div
                                                    style={{
                                                        fontSize: "12px",
                                                        fontWeight: 800,
                                                        color: "var(--text-primary)",
                                                        lineHeight: 1.35,
                                                    }}
                                                >
                                                    {suggestion.label}
                                                </div>
                                                <div
                                                    style={{
                                                        marginTop: "6px",
                                                        fontSize: "11px",
                                                        color: "var(--text-muted)",
                                                        fontFamily: "var(--font-mono)",
                                                    }}
                                                >
                                                    @{formatTime(suggestion.timestamp_ms / 1000)}
                                                </div>
                                            </button>

                                            <div
                                                style={{
                                                    marginTop: "10px",
                                                    display: "flex",
                                                    gap: "8px",
                                                }}
                                            >
                                                <button
                                                    onClick={() => {
                                                        handleAddHotspot(
                                                            suggestion.hotspot,
                                                            selectedStepId
                                                        );
                                                        setSuggestions((prev) =>
                                                            prev.filter(
                                                                (s) => s.id !== suggestion.id
                                                            )
                                                        );
                                                    }}
                                                    style={{
                                                        flex: 1,
                                                        padding: "8px 10px",
                                                        borderRadius: "var(--radius-md)",
                                                        border: "1px solid var(--status-success)",
                                                        background: "var(--status-success-muted)",
                                                        color: "var(--status-success)",
                                                        fontSize: "12px",
                                                        fontWeight: 900,
                                                        cursor: "pointer",
                                                    }}
                                                >
                                                    Add
                                                </button>
                                                <button
                                                    onClick={() =>
                                                        setSuggestions((prev) =>
                                                            prev.filter(
                                                                (s) => s.id !== suggestion.id
                                                            )
                                                        )
                                                    }
                                                    style={{
                                                        padding: "8px 10px",
                                                        borderRadius: "var(--radius-md)",
                                                        border: "1px solid var(--border-default)",
                                                        background: "transparent",
                                                        color: "var(--text-secondary)",
                                                        fontSize: "12px",
                                                        fontWeight: 800,
                                                        cursor: "pointer",
                                                    }}
                                                >
                                                    Dismiss
                                                </button>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        <div style={{ marginTop: "16px" }}>
                            {hotspots.length > 0 ? (
                                <div
                                    style={{ display: "flex", flexDirection: "column", gap: "6px" }}
                                >
                                    {hotspots.map((hotspot, idx) => {
                                        const label = hotspot.text?.trim()
                                            ? hotspot.text.trim()
                                            : "Hotspot";

                                        const badgeColor =
                                            hotspot.backgroundColor ?? DEFAULT_HOTSPOT_BG;

                                        return (
                                            <button
                                                key={hotspot.id}
                                                onClick={() => setSelectedHotspotId(hotspot.id)}
                                                style={{
                                                    width: "100%",
                                                    display: "flex",
                                                    alignItems: "center",
                                                    gap: "10px",
                                                    padding: "10px 12px",
                                                    borderRadius: "var(--radius-md)",
                                                    border: "1px solid var(--border-default)",
                                                    background: "var(--bg-surface)",
                                                    cursor: "pointer",
                                                    textAlign: "left",
                                                }}
                                            >
                                                <div
                                                    style={{
                                                        width: "28px",
                                                        height: "28px",
                                                        borderRadius: "10px",
                                                        background: "var(--bg-elevated)",
                                                        border: `1px solid color-mix(in srgb, ${badgeColor} 65%, transparent)`,
                                                        display: "grid",
                                                        placeItems: "center",
                                                        fontSize: "11px",
                                                        fontFamily: "var(--font-mono)",
                                                        fontWeight: 800,
                                                        color: badgeColor,
                                                    }}
                                                >
                                                    {idx + 1}
                                                </div>
                                                <div style={{ flex: 1, minWidth: 0 }}>
                                                    <div
                                                        style={{
                                                            fontSize: "13px",
                                                            fontWeight: 800,
                                                            color: "var(--text-primary)",
                                                            overflow: "hidden",
                                                            textOverflow: "ellipsis",
                                                            whiteSpace: "nowrap",
                                                        }}
                                                    >
                                                        {label}
                                                    </div>
                                                    <div
                                                        style={{
                                                            marginTop: "3px",
                                                            fontSize: "11px",
                                                            color: "var(--text-muted)",
                                                            fontFamily: "var(--font-mono)",
                                                        }}
                                                    >
                                                        {formatTime(hotspot.frameStart / fps)} →{" "}
                                                        {formatTime(hotspot.frameEnd / fps)}
                                                    </div>
                                                </div>
                                                <svg
                                                    width="16"
                                                    height="16"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="var(--text-muted)"
                                                    strokeWidth="2"
                                                >
                                                    <path d="M9 18l6-6-6-6" />
                                                </svg>
                                            </button>
                                        );
                                    })}
                                </div>
                            ) : (
                                <div
                                    style={{
                                        marginTop: "12px",
                                        padding: "14px 12px",
                                        borderRadius: "var(--radius-lg)",
                                        border: "1px dashed var(--border-default)",
                                        color: "var(--text-muted)",
                                        fontSize: "12px",
                                        lineHeight: 1.45,
                                    }}
                                >
                                    No hotspots yet. Add one, then click it to edit.
                                </div>
                            )}
                        </div>
                    </div>
                ) : (
                    <div style={{ padding: "16px" }}>
                        <div
                            style={{
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "space-between",
                                gap: "12px",
                                marginBottom: "12px",
                            }}
                        >
                            <div
                                style={{
                                    fontSize: "12px",
                                    fontWeight: 900,
                                    color: "var(--text-primary)",
                                }}
                            >
                                Text
                                <span style={{ color: "var(--text-muted)", marginLeft: "6px" }}>
                                    i
                                </span>
                            </div>
                            <div
                                style={{
                                    display: "flex",
                                    alignItems: "center",
                                    gap: "8px",
                                }}
                            >
                                <label
                                    style={{
                                        fontSize: "11px",
                                        fontWeight: 700,
                                        color: "var(--text-muted)",
                                        textTransform: "uppercase",
                                        letterSpacing: "0.05em",
                                    }}
                                >
                                    Lang
                                </label>
                                <input
                                    type="text"
                                    value={assistLanguage}
                                    onChange={(event) => setAssistLanguage(event.target.value)}
                                    placeholder="es"
                                    style={{
                                        width: "68px",
                                        height: "30px",
                                        padding: "0 8px",
                                        borderRadius: "8px",
                                        border: "1px solid var(--border-default)",
                                        background: "var(--bg-elevated)",
                                        color: "var(--text-primary)",
                                        fontSize: "12px",
                                        fontFamily: "var(--font-mono)",
                                        textTransform: "lowercase",
                                    }}
                                />
                            </div>
                        </div>

                        <textarea
                            value={selectedHotspot.text ?? ""}
                            onChange={(e) => {
                                const text = e.target.value;
                                updateSelected((c) => ({ ...c, text }));
                            }}
                            placeholder="Explain the benefit of this hotspot or Ask AI to help..."
                            style={{
                                width: "100%",
                                minHeight: "120px",
                                padding: "12px",
                                borderRadius: "var(--radius-lg)",
                                border: "1px solid var(--border-default)",
                                background: "var(--bg-elevated)",
                                color: "var(--text-primary)",
                                fontSize: "13px",
                                lineHeight: 1.45,
                                resize: "vertical",
                                outline: "none",
                            }}
                            onFocus={(e) => {
                                e.currentTarget.style.borderColor = "var(--accent-1)";
                            }}
                            onBlur={(e) => {
                                e.currentTarget.style.borderColor = "var(--border-default)";
                            }}
                        />

                        <div style={{ marginTop: "10px", display: "grid", gap: "8px" }}>
                            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" }}>
                                <button
                                    type="button"
                                    onClick={() => {
                                        void runTranslateHotspotCopy();
                                    }}
                                    disabled={aiBusy !== null}
                                    style={{
                                        padding: "10px 12px",
                                        borderRadius: "var(--radius-lg)",
                                        border: "1px solid var(--border-default)",
                                        background: "var(--bg-elevated)",
                                        color: "var(--text-primary)",
                                        cursor: aiBusy ? "not-allowed" : "pointer",
                                        fontSize: "12px",
                                        fontWeight: 900,
                                        opacity: aiBusy === "voiceover" ? 0.65 : 1,
                                    }}
                                >
                                    {aiBusy === "translate"
                                        ? "Translating..."
                                        : `Translate (${languageLabel})`}
                                </button>
                                <button
                                    type="button"
                                    onClick={() => {
                                        void runGenerateVoiceover();
                                    }}
                                    disabled={aiBusy !== null}
                                    style={{
                                        padding: "10px 12px",
                                        borderRadius: "var(--radius-lg)",
                                        border: "1px solid var(--border-default)",
                                        background: "var(--bg-elevated)",
                                        color: "var(--text-primary)",
                                        cursor: aiBusy ? "not-allowed" : "pointer",
                                        fontSize: "12px",
                                        fontWeight: 900,
                                        opacity: aiBusy === "translate" ? 0.65 : 1,
                                    }}
                                >
                                    {aiBusy === "voiceover" ? "Generating..." : "Generate voiceover"}
                                </button>
                            </div>

                            {aiError && (
                                <div
                                    style={{
                                        borderRadius: "10px",
                                        border: "1px solid var(--status-error)",
                                        background: "var(--status-error-muted)",
                                        color: "var(--status-error)",
                                        fontSize: "12px",
                                        lineHeight: 1.4,
                                        padding: "8px 10px",
                                    }}
                                >
                                    {aiError}
                                </div>
                            )}
                            {aiNotice && (
                                <div
                                    style={{
                                        borderRadius: "10px",
                                        border: "1px solid var(--status-success)",
                                        background: "var(--status-success-muted)",
                                        color: "var(--status-success)",
                                        fontSize: "12px",
                                        lineHeight: 1.4,
                                        padding: "8px 10px",
                                    }}
                                >
                                    {aiNotice}
                                </div>
                            )}

                            {localizedCopyPreview && (
                                <div>
                                    <div
                                        style={{
                                            fontSize: "11px",
                                            fontWeight: 700,
                                            textTransform: "uppercase",
                                            letterSpacing: "0.05em",
                                            color: "var(--text-muted)",
                                            marginBottom: "6px",
                                        }}
                                    >
                                        Localized Copy ({languageLabel})
                                    </div>
                                    <textarea
                                        value={localizedCopyPreview}
                                        onChange={(event) => {
                                            updateLocalizedCopy(event.target.value);
                                        }}
                                        style={{
                                            width: "100%",
                                            minHeight: "74px",
                                            padding: "10px",
                                            borderRadius: "10px",
                                            border: "1px solid var(--border-default)",
                                            background: "var(--bg-elevated)",
                                            color: "var(--text-primary)",
                                            fontSize: "12px",
                                            lineHeight: 1.4,
                                            resize: "vertical",
                                        }}
                                    />
                                </div>
                            )}

                            <div>
                                <div
                                    style={{
                                        fontSize: "11px",
                                        fontWeight: 700,
                                        textTransform: "uppercase",
                                        letterSpacing: "0.05em",
                                        color: "var(--text-muted)",
                                        marginBottom: "6px",
                                    }}
                                >
                                    Voiceover Script ({languageLabel})
                                </div>
                                <textarea
                                    value={localizedVoiceoverPreview}
                                    onChange={(event) => {
                                        updateLocalizedVoiceover(event.target.value);
                                    }}
                                    placeholder="Generate with AI, then refine this narration."
                                    style={{
                                        width: "100%",
                                        minHeight: "88px",
                                        padding: "10px",
                                        borderRadius: "10px",
                                        border: "1px solid var(--border-default)",
                                        background: "var(--bg-elevated)",
                                        color: "var(--text-primary)",
                                        fontSize: "12px",
                                        lineHeight: 1.4,
                                        resize: "vertical",
                                    }}
                                />
                            </div>
                        </div>

                        <div
                            style={{
                                marginTop: "16px",
                                paddingTop: "16px",
                                borderTop: "1px solid var(--border-default)",
                            }}
                        >
                            <div
                                style={{
                                    fontSize: "12px",
                                    fontWeight: 900,
                                    color: "var(--text-primary)",
                                    marginBottom: "10px",
                                }}
                            >
                                Style
                            </div>

                            <div
                                style={{
                                    display: "grid",
                                    gridTemplateColumns: "1fr 1fr 1fr",
                                    gap: "10px",
                                }}
                            >
                                {[
                                    {
                                        key: "hotspot",
                                        label: "Hotspot",
                                        active:
                                            selectedHotspot.style === "pulse" ||
                                            selectedHotspot.style === "circle",
                                        onClick: () =>
                                            updateSelected((c) => ({
                                                ...c,
                                                style: "pulse",
                                            })),
                                        icon: (
                                            <svg
                                                width="22"
                                                height="22"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                            >
                                                <circle cx="12" cy="12" r="8" />
                                                <circle cx="12" cy="12" r="2" fill="currentColor" />
                                            </svg>
                                        ),
                                    },
                                    {
                                        key: "area",
                                        label: "Area",
                                        active: selectedHotspot.style === "rectangle",
                                        onClick: () =>
                                            updateSelected((c) => ({
                                                ...c,
                                                style: "rectangle",
                                                width: c.width < 10 ? 18 : c.width,
                                                height: c.height < 10 ? 14 : c.height,
                                            })),
                                        icon: (
                                            <svg
                                                width="22"
                                                height="22"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                            >
                                                <rect x="5" y="6" width="14" height="12" rx="2" />
                                            </svg>
                                        ),
                                    },
                                    {
                                        key: "callout",
                                        label: "Callout",
                                        active: selectedHotspot.style === "callout",
                                        onClick: () =>
                                            updateSelected((c) => ({
                                                ...c,
                                                style: "callout",
                                                backgroundColor:
                                                    c.backgroundColor ?? DEFAULT_HOTSPOT_BG,
                                                textColor: c.textColor ?? DEFAULT_HOTSPOT_TEXT,
                                            })),
                                        icon: (
                                            <svg
                                                width="22"
                                                height="22"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                            >
                                                <path d="M5 6h14v9H9l-4 3V6z" />
                                            </svg>
                                        ),
                                    },
                                ].map((card) => (
                                    <button
                                        key={card.key}
                                        onClick={card.onClick}
                                        style={{
                                            display: "flex",
                                            flexDirection: "column",
                                            alignItems: "center",
                                            justifyContent: "center",
                                            gap: "10px",
                                            padding: "14px 10px",
                                            borderRadius: "var(--radius-lg)",
                                            border: card.active
                                                ? "1px solid var(--accent-1)"
                                                : "1px solid var(--border-default)",
                                            background: "var(--bg-elevated)",
                                            color: card.active
                                                ? "var(--text-primary)"
                                                : "var(--text-secondary)",
                                            cursor: "pointer",
                                            boxShadow: card.active ? "var(--shadow-glow)" : "none",
                                            transition: "all 150ms var(--ease-out)",
                                        }}
                                    >
                                        <div
                                            style={{
                                                width: "44px",
                                                height: "44px",
                                                borderRadius: "14px",
                                                background: card.active
                                                    ? "var(--accent-4)"
                                                    : "var(--bg-surface)",
                                                border: "1px solid var(--border-default)",
                                                display: "grid",
                                                placeItems: "center",
                                                color: card.active
                                                    ? "var(--accent-1)"
                                                    : "var(--text-muted)",
                                            }}
                                        >
                                            {card.icon}
                                        </div>
                                        <div style={{ fontSize: "12px", fontWeight: 900 }}>
                                            {card.label}
                                        </div>
                                    </button>
                                ))}
                            </div>

                            <div
                                style={{
                                    marginTop: "16px",
                                    paddingTop: "16px",
                                    borderTop: "1px solid var(--border-default)",
                                }}
                            >
                                <div
                                    style={{
                                        fontSize: "12px",
                                        fontWeight: 900,
                                        color: "var(--text-primary)",
                                        marginBottom: "10px",
                                    }}
                                >
                                    Colors
                                </div>

                                <div style={{ display: "grid", gap: "10px" }}>
                                    {[
                                        {
                                            kind: "background" as const,
                                            label: "Background",
                                            value: backgroundDraft,
                                            setValue: setBackgroundDraft,
                                        },
                                        {
                                            kind: "text" as const,
                                            label: "Text",
                                            value: textDraft,
                                            setValue: setTextDraft,
                                        },
                                    ].map((row) => {
                                        const safeValue = isHexColor(row.value)
                                            ? row.value
                                            : row.kind === "background"
                                              ? DEFAULT_HOTSPOT_BG
                                              : DEFAULT_HOTSPOT_TEXT;

                                        return (
                                            <div
                                                key={row.kind}
                                                style={{
                                                    display: "flex",
                                                    alignItems: "center",
                                                    justifyContent: "space-between",
                                                    gap: "12px",
                                                    padding: "10px 12px",
                                                    borderRadius: "var(--radius-lg)",
                                                    border: "1px solid var(--border-default)",
                                                    background: "var(--bg-elevated)",
                                                }}
                                            >
                                                <div
                                                    style={{
                                                        fontSize: "12px",
                                                        fontWeight: 800,
                                                        color: "var(--text-secondary)",
                                                    }}
                                                >
                                                    {row.label}
                                                </div>

                                                <div
                                                    style={{
                                                        display: "flex",
                                                        alignItems: "center",
                                                        gap: "10px",
                                                    }}
                                                >
                                                    <input
                                                        type="color"
                                                        value={safeValue}
                                                        onChange={(e) => {
                                                            const next = e.target.value;
                                                            row.setValue(next);
                                                            updateSelected((c) => {
                                                                if (row.kind === "background") {
                                                                    return {
                                                                        ...c,
                                                                        backgroundColor: next,
                                                                    };
                                                                }
                                                                return { ...c, textColor: next };
                                                            });
                                                        }}
                                                        style={{
                                                            width: "34px",
                                                            height: "28px",
                                                            border: "1px solid var(--border-default)",
                                                            background: "var(--bg-surface)",
                                                            borderRadius: "10px",
                                                            padding: 0,
                                                            cursor: "pointer",
                                                        }}
                                                    />
                                                    <input
                                                        value={row.value}
                                                        onChange={(e) =>
                                                            row.setValue(e.target.value)
                                                        }
                                                        onBlur={() => commitColorDraft(row.kind)}
                                                        placeholder="#RRGGBB"
                                                        style={{
                                                            width: "110px",
                                                            padding: "8px 10px",
                                                            borderRadius: "12px",
                                                            border: "1px solid var(--border-default)",
                                                            background: "var(--bg-surface)",
                                                            color: "var(--text-primary)",
                                                            fontSize: "12px",
                                                            fontFamily: "var(--font-mono)",
                                                            outline: "none",
                                                        }}
                                                        onFocus={(e) => {
                                                            e.currentTarget.style.borderColor =
                                                                "var(--accent-1)";
                                                        }}
                                                        onBlurCapture={(e) => {
                                                            e.currentTarget.style.borderColor =
                                                                "var(--border-default)";
                                                        }}
                                                    />
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>

                            <div
                                style={{
                                    marginTop: "16px",
                                    paddingTop: "16px",
                                    borderTop: "1px solid var(--border-default)",
                                }}
                            >
                                <div
                                    style={{
                                        fontSize: "12px",
                                        fontWeight: 900,
                                        color: "var(--text-primary)",
                                        marginBottom: "10px",
                                    }}
                                >
                                    Destination
                                </div>

                                <select
                                    value={(() => {
                                        if (selectedHotspot.action.type === "next_step") {
                                            return "next_step";
                                        }
                                        if (selectedHotspot.action.type === "this_step") {
                                            return "this_step";
                                        }
                                        if (selectedHotspot.action.type === "step") {
                                            return `step:${selectedHotspot.action.stepId}`;
                                        }
                                        return "none";
                                    })()}
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        if (value === "none") {
                                            updateSelected((c) => ({
                                                ...c,
                                                action: { type: "none" },
                                            }));
                                            return;
                                        }
                                        if (value === "next_step") {
                                            updateSelected((c) => ({
                                                ...c,
                                                action: { type: "next_step" },
                                            }));
                                            return;
                                        }
                                        if (value === "this_step") {
                                            updateSelected((c) => ({
                                                ...c,
                                                action: { type: "this_step" },
                                            }));
                                            return;
                                        }
                                        if (value.startsWith("step:")) {
                                            const stepId = value.slice("step:".length);
                                            updateSelected((c) => ({
                                                ...c,
                                                action: { type: "step", stepId },
                                            }));
                                        }
                                    }}
                                    style={{
                                        width: "100%",
                                        padding: "10px 12px",
                                        borderRadius: "var(--radius-lg)",
                                        border: "1px solid var(--border-default)",
                                        background: "var(--bg-elevated)",
                                        color: "var(--text-primary)",
                                        fontSize: "13px",
                                        fontWeight: 700,
                                        outline: "none",
                                    }}
                                    onFocus={(e) => {
                                        e.currentTarget.style.borderColor = "var(--accent-1)";
                                    }}
                                    onBlur={(e) => {
                                        e.currentTarget.style.borderColor = "var(--border-default)";
                                    }}
                                >
                                    <option value="next_step">Next step</option>
                                    <option value="this_step">This step</option>
                                    <option value="none">None</option>
                                    {steps.map((step, idx) => (
                                        <option key={step.id} value={`step:${step.id}`}>
                                            Step {idx + 1}: {step.title}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <button
                                type="button"
                                onClick={() => {
                                    handleDeleteHotspot(selectedHotspot.id);
                                    setSelectedHotspotId(null);
                                    if (hotspots.length <= 1) {
                                        setEditingHotspots(false);
                                    }
                                }}
                                style={{
                                    marginTop: "16px",
                                    width: "100%",
                                    padding: "10px 12px",
                                    borderRadius: "var(--radius-lg)",
                                    border: "1px solid color-mix(in srgb, var(--status-danger) 60%, transparent)",
                                    background:
                                        "color-mix(in srgb, var(--status-danger-muted) 80%, transparent)",
                                    color: "var(--status-danger)",
                                    cursor: "pointer",
                                    fontSize: "12px",
                                    fontWeight: 900,
                                }}
                            >
                                Delete
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </aside>
    );
};

export default EditorHotspotInspector;
