import { useEffect, useMemo, useState, type RefObject } from "react";
import { useNavigate } from "react-router-dom";
import { convertFileSrc } from "@tauri-apps/api/core";
import VideoPlayer from "../../components/VideoPlayer";
import HotspotOverlay from "../../components/HotspotOverlay";
import ClickRippleOverlay from "../../components/ClickRippleOverlay";
import TerminalPlayer from "../../components/TerminalPlayer";
import Timeline from "../../components/Timeline";
import "../../components/FrameEditorLayout.css";
import EditorScriptView from "./EditorScriptView";
import { useEditor } from "./EditorContext";

type HeaderTab = "edit" | "script" | "preview" | "insights";
type InspectorSection = "design" | "metadata" | "audio" | "other";

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

interface EditorWorkspaceLayoutProps {
    videoRef: RefObject<HTMLVideoElement>;
}

const formatDuration = (seconds: number): string => {
    if (!Number.isFinite(seconds) || seconds <= 0) return "00:00.00";
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    const millis = Math.floor((seconds % 1) * 100);
    return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}.${millis
        .toString()
        .padStart(2, "0")}`;
};

const formatStepRange = (startMs: number, endMs: number): string => {
    const start = Math.max(0, Math.floor(startMs / 1000));
    const end = Math.max(0, Math.floor(endMs / 1000));
    const startMin = Math.floor(start / 60);
    const startSec = start % 60;
    const endMin = Math.floor(end / 60);
    const endSec = end % 60;
    return `${startMin}:${startSec.toString().padStart(2, "0")} - ${endMin}:${endSec
        .toString()
        .padStart(2, "0")}`;
};

const formatTranscriptTimestamp = (timestampMs: number): string => {
    const totalSeconds = Math.max(0, Math.floor(timestampMs / 1000));
    const mins = Math.floor(totalSeconds / 60);
    const secs = totalSeconds % 60;
    return `${mins}:${secs.toString().padStart(2, "0")}`;
};

const formatSessionDate = (createdAt: string | undefined): string => {
    if (!createdAt) return "Unknown date";
    const asNumber = Number(createdAt);
    if (!Number.isFinite(asNumber)) return createdAt;
    const ms = createdAt.length <= 10 ? asNumber * 1000 : asNumber;
    const d = new Date(ms);
    if (Number.isNaN(d.getTime())) return createdAt;
    return d.toDateString();
};

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

const isHexColor = (value: string): boolean => /^#[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 WINDOWS_ABSOLUTE_PATH = /^[a-zA-Z]:[\\/]/;

const isAbsolutePath = (value: string): boolean =>
    value.startsWith("/") || value.startsWith("\\\\") || WINDOWS_ABSOLUTE_PATH.test(value);

const getSessionDirectory = (recordingPath: string | null | undefined): string | null => {
    if (!recordingPath) return null;
    const slash = Math.max(recordingPath.lastIndexOf("/"), recordingPath.lastIndexOf("\\"));
    if (slash < 0) return null;
    return recordingPath.slice(0, slash);
};

const joinPath = (base: string, relative: string): string => {
    const normalizedBase = base.replace(/[\\/]+$/, "");
    const normalizedRelative = relative.replace(/^\.?[\\/]+/, "");
    return `${normalizedBase}/${normalizedRelative}`;
};

const fromFileUrlToPath = (value: string): string => {
    try {
        const url = new URL(value);
        const decoded = decodeURIComponent(url.pathname);
        if (WINDOWS_ABSOLUTE_PATH.test(decoded.slice(1))) {
            return decoded.slice(1);
        }
        return decoded;
    } catch {
        return value.replace(/^file:\/+/, "/");
    }
};

const resolvePreviewSource = (
    path: string | null | undefined,
    recordingPath: string | null | undefined
): string | null => {
    if (!path) return null;
    if (
        path.startsWith("http://") ||
        path.startsWith("https://") ||
        path.startsWith("tauri://") ||
        path.startsWith("asset:") ||
        path.startsWith("blob:") ||
        path.startsWith("data:")
    ) {
        return path;
    }

    const normalizedPath = path.startsWith("file://") ? fromFileUrlToPath(path) : path;
    const filePath =
        isAbsolutePath(normalizedPath) || !recordingPath
            ? normalizedPath
            : (() => {
                  const sessionDir = getSessionDirectory(recordingPath);
                  return sessionDir ? joinPath(sessionDir, normalizedPath) : normalizedPath;
              })();

    try {
        return convertFileSrc(filePath);
    } catch {
        return filePath;
    }
};

const INSPECTOR_SECTION_LABELS: Record<InspectorSection, string> = {
    design: "Design",
    metadata: "Metadata",
    audio: "Audio",
    other: "Other",
};

const renderInspectorShortcutIcon = (section: InspectorSection) => {
    if (section === "design") {
        return (
            <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
            >
                <circle cx="12" cy="12" r="8" />
                <circle cx="12" cy="12" r="3" />
            </svg>
        );
    }
    if (section === "metadata") {
        return (
            <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            >
                <rect x="4" y="4" width="16" height="16" rx="2" />
                <path d="M4 10h16" />
            </svg>
        );
    }
    if (section === "audio") {
        return (
            <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
            >
                <path d="M4 12h2" />
                <path d="M8 9v6" />
                <path d="M12 7v10" />
                <path d="M16 9v6" />
                <path d="M20 12h-2" />
            </svg>
        );
    }
    return (
        <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
        >
            <polyline points="8 6 3 12 8 18" />
            <polyline points="16 6 21 12 16 18" />
        </svg>
    );
};

function EditorWorkspaceLayout({ videoRef }: EditorWorkspaceLayoutProps) {
    const navigate = useNavigate();
    const {
        metadata,
        editorMode,
        setEditorMode,
        setSharing,
        activeTab,
        setActiveTab,
        steps,
        selectedStepId,
        handleSelectStep,
        splitSelectedStepAtCurrentFrame,
        handleRenameStep,
        updateStepConfig,
        moveStepUp,
        moveStepDown,
        duplicateStep,
        deleteStep,
        mergeSelectedStepWithNext,
        applyHotspotStylePreset,
        playing,
        setPlaying,
        togglePlay,
        currentTime,
        duration,
        currentFrame,
        totalFrames,
        fps,
        videoUrl,
        terminalUrl,
        hasTerminal,
        seekToTimestamp,
        seekToFrame,
        markers,
        clicks,
        showClickRipples,
        editingHotspots,
        setEditingHotspots,
        placingHotspot,
        setPlacingHotspot,
        placingHotspotStyle,
        setPlacingHotspotStyle,
        handleStageClick,
        hotspots,
        selectedHotspotId,
        setSelectedHotspotId,
        handleDeleteHotspot,
        handleUpdateHotspot,
        handleVideoLoadError,
        handleGenerateStepsFromActivity,
        handleAnalyzeSession,
        handleTranscribe,
        transcribing,
        transcript,
        transcriptError,
        exporting,
        exportFeedback,
        clearExportFeedback,
        handleExportMarkdown,
        handleExportMp4,
        undo,
        redo,
        canUndo,
        canRedo,
    } = useEditor();

    const [headerTab, setHeaderTab] = useState<HeaderTab>("edit");
    const [openSection, setOpenSection] = useState<InspectorSection>("design");
    const [muted, setMuted] = useState(false);
    const [editingTitleId, setEditingTitleId] = useState<string | null>(null);
    const [editingTitle, setEditingTitle] = useState("");
    const [backgroundDraft, setBackgroundDraft] = useState(DEFAULT_HOTSPOT_BG);
    const [textDraft, setTextDraft] = useState(DEFAULT_HOTSPOT_TEXT);
    const [activatedHotspotsByStep, setActivatedHotspotsByStep] = useState<
        Record<string, string[]>
    >({});
    const [completionBlockMessage, setCompletionBlockMessage] = useState<string | null>(null);
    const [showExportModal, setShowExportModal] = useState(false);
    const [exportFormat, setExportFormat] = useState<"markdown" | "mp4">("markdown");
    const [exportIncludeChapterCards, setExportIncludeChapterCards] = useState(true);
    const [isStepRailCollapsed, setIsStepRailCollapsed] = useState(false);
    const [isInspectorCollapsed, setIsInspectorCollapsed] = useState(false);
    const [inspectorCollapseTouched, setInspectorCollapseTouched] = useState(false);

    const selectedStep = useMemo(
        () => steps.find((step) => step.id === selectedStepId) ?? null,
        [steps, selectedStepId]
    );

    const selectedHotspot = useMemo(
        () => hotspots.find((hotspot) => hotspot.id === selectedHotspotId) ?? null,
        [hotspots, selectedHotspotId]
    );
    const selectedStepNumber = useMemo(() => {
        const selectedIndex = steps.findIndex((step) => step.id === selectedStepId);
        return selectedIndex >= 0 ? selectedIndex + 1 : 0;
    }, [steps, selectedStepId]);
    const framePreviewSources = useMemo(() => {
        const entries: Array<[string, string | null]> = steps.map((step) => [
            step.id,
            resolvePreviewSource(step.screenshot?.path, metadata?.recording_path),
        ]);
        return new Map<string, string | null>(entries);
    }, [metadata?.recording_path, steps]);

    const resolvedTitle = (metadata?.title ?? "").trim() || "Untitled session";
    const sessionDate = formatSessionDate(metadata?.created_at);
    const hotspotCountInStep = selectedStep?.hotspot_ids?.length ?? 0;

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

    useEffect(() => {
        if (!editingHotspots) return;
        if (selectedHotspotId) return;
        if (!hotspots.length) return;
        setSelectedHotspotId(hotspots[0].id);
    }, [editingHotspots, hotspots, selectedHotspotId, setSelectedHotspotId]);

    useEffect(() => {
        setCompletionBlockMessage(null);
    }, [selectedStepId]);

    useEffect(() => {
        if (inspectorCollapseTouched || typeof window === "undefined") return;
        const mediaQuery = window.matchMedia(`(max-width: ${INSPECTOR_AUTO_COLLAPSE_MAX_WIDTH}px)`);
        const applyViewportPreference = () => {
            setIsInspectorCollapsed(mediaQuery.matches);
        };
        applyViewportPreference();

        if (typeof mediaQuery.addEventListener === "function") {
            mediaQuery.addEventListener("change", applyViewportPreference);
            return () => mediaQuery.removeEventListener("change", applyViewportPreference);
        }

        mediaQuery.addListener(applyViewportPreference);
        return () => mediaQuery.removeListener(applyViewportPreference);
    }, [inspectorCollapseTouched]);

    const selectHeaderTab = (tab: HeaderTab) => {
        setHeaderTab(tab);
        if (tab === "edit" || tab === "script") setEditorMode("edit");
        if (tab === "preview" || tab === "insights") setEditorMode("preview");
    };

    const jumpBySeconds = (deltaSeconds: number) => {
        if (!duration) return;
        const next = clamp(currentTime + deltaSeconds, 0, duration);
        seekToTimestamp(next);
    };

    const toggleMuted = () => {
        const video = videoRef.current;
        if (!video) return;
        const next = !video.muted;
        video.muted = next;
        setMuted(next);
    };

    const insertAfterStep = (stepId: string, stepStartMs: number, stepEndMs: number) => {
        handleSelectStep(stepId);
        const insertionPointMs = Math.max(stepStartMs + 1, stepEndMs - 1);
        seekToTimestamp(insertionPointMs / 1000);
        window.requestAnimationFrame(() => splitSelectedStepAtCurrentFrame());
    };

    const startPlacing = (style: "pulse" | "callout") => {
        setEditingHotspots(true);
        setSelectedHotspotId(null);
        setPlacingHotspotStyle(style);
        if (placingHotspot && placingHotspotStyle === style) {
            setPlacingHotspot(false);
            return;
        }
        setPlacingHotspot(true);
    };

    const saveTitle = (stepId: string) => {
        handleRenameStep(stepId, editingTitle);
        setEditingTitleId(null);
        setEditingTitle("");
    };

    const hotspotToolActive = editingHotspots && placingHotspot && placingHotspotStyle === "pulse";
    const calloutToolActive =
        editingHotspots && placingHotspot && placingHotspotStyle === "callout";
    const isPreviewMode = headerTab === "preview";
    const isScriptMode = headerTab === "script";
    const inspectorSections: InspectorSection[] = ["design", "metadata", "audio", "other"];
    const showCanvasTools =
        !isPreviewMode && !isScriptMode && (activeTab === "video" || activeTab === "both");

    const handleNavigateToStep = (
        destination:
            | { type: "next_step" }
            | { type: "step"; stepId: string }
            | { type: "this_step" },
        hotspotId: string
    ) => {
        const sourceStep = steps.find((step) => (step.hotspot_ids ?? []).includes(hotspotId));
        if (!sourceStep) return;

        const requiredIds = (sourceStep.required_hotspot_ids ?? []).length
            ? (sourceStep.required_hotspot_ids ?? [])
            : (sourceStep.hotspot_ids ?? []);
        const activatedIds = new Set(activatedHotspotsByStep[sourceStep.id] ?? []);
        const completionMode = sourceStep.completion_mode ?? "none";
        const canAdvance =
            completionMode === "none" ||
            requiredIds.length === 0 ||
            (completionMode === "any"
                ? requiredIds.some((id) => activatedIds.has(id))
                : requiredIds.every((id) => activatedIds.has(id)));

        if (destination.type !== "this_step" && !canAdvance) {
            const progress = `${Math.min(
                requiredIds.filter((id) => activatedIds.has(id)).length,
                requiredIds.length
            )}/${requiredIds.length}`;
            setCompletionBlockMessage(
                completionMode === "all"
                    ? `Complete all required interactions before advancing (${progress}).`
                    : `Complete at least one required interaction before advancing (${progress}).`
            );
            return;
        }

        setCompletionBlockMessage(null);

        if (destination.type === "this_step") {
            return;
        }

        if (destination.type === "step") {
            const step = steps.find((item) => item.id === destination.stepId);
            if (!step) return;
            handleSelectStep(step.id);
            seekToTimestamp(step.start_ms / 1000);
            return;
        }

        const currentIndex = steps.findIndex((step) => step.id === sourceStep.id);
        if (currentIndex < 0) return;
        const nextStep = steps[currentIndex + 1];
        if (!nextStep) return;
        handleSelectStep(nextStep.id);
        seekToTimestamp(nextStep.start_ms / 1000);
    };

    const updateSelectedHotspot = (
        updater: (
            hotspot: NonNullable<typeof selectedHotspot>
        ) => NonNullable<typeof selectedHotspot>
    ) => {
        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);
            updateSelectedHotspot((current) => ({ ...current, backgroundColor: normalized }));
        } else {
            setTextDraft(normalized);
            updateSelectedHotspot((current) => ({ ...current, textColor: normalized }));
        }
    };

    const applyCurrentColors = (scope: "step" | "session", target: "hotspot" | "callout") => {
        const normalizedBackground = normalizeHexColor(backgroundDraft);
        const normalizedText = normalizeHexColor(textDraft);
        applyHotspotStylePreset(scope, target, {
            backgroundColor: normalizedBackground ?? undefined,
            textColor: normalizedText ?? undefined,
        });
    };

    const currentStepCompletionMode = selectedStep?.completion_mode ?? "none";
    const currentStepRequiredHotspotIds =
        (selectedStep?.required_hotspot_ids ?? []).length > 0
            ? (selectedStep?.required_hotspot_ids ?? [])
            : (selectedStep?.hotspot_ids ?? []);
    const currentStepActivatedHotspotIds = new Set(
        selectedStep ? (activatedHotspotsByStep[selectedStep.id] ?? []) : []
    );
    const currentStepCompletionProgress = selectedStep
        ? `${Math.min(
              currentStepRequiredHotspotIds.filter((id) => currentStepActivatedHotspotIds.has(id))
                  .length,
              currentStepRequiredHotspotIds.length
          )}/${currentStepRequiredHotspotIds.length}`
        : "0/0";
    const exportFeedbackTitle = exportFeedback
        ? exportFeedback.kind === "markdown"
            ? exportFeedback.status === "success"
                ? "Script Exported"
                : "Script Export Failed"
            : exportFeedback.status === "success"
              ? "MP4 Export Complete"
              : "MP4 Export Failed"
        : "";

    const openExportModal = () => {
        setShowExportModal(true);
    };

    const closeExportModal = () => {
        if (exporting) return;
        setShowExportModal(false);
    };

    const runExportWithOptions = async () => {
        if (exporting) return;
        if (exportFormat === "mp4") {
            await handleExportMp4(exportIncludeChapterCards);
        } else {
            await handleExportMarkdown();
        }
        setShowExportModal(false);
    };

    const toggleStepRail = () => {
        setIsStepRailCollapsed((current) => !current);
    };

    const toggleInspectorRail = () => {
        setInspectorCollapseTouched(true);
        setIsInspectorCollapsed((current) => !current);
    };

    const handleInspectorShortcut = (section: InspectorSection) => {
        setOpenSection(section);
        if (isInspectorCollapsed) {
            setInspectorCollapseTouched(true);
            setIsInspectorCollapsed(false);
        }
    };

    return (
        <div className="fe-editor-root">
            <header className="fe-top-nav" aria-label="Editor top navigation">
                <div className="fe-top-nav-left">
                    <nav aria-label="Breadcrumb">
                        <ol className="fe-breadcrumb">
                            <li>
                                <button
                                    type="button"
                                    className="fe-breadcrumb-link"
                                    onClick={() => navigate("/library")}
                                >
                                    Library
                                </button>
                            </li>
                            <li aria-hidden>/</li>
                            <li>
                                {resolvedTitle} ({sessionDate})
                            </li>
                        </ol>
                    </nav>
                </div>

                <div className="fe-top-nav-center" role="tablist" aria-label="Editor views">
                    <button
                        type="button"
                        role="tab"
                        aria-selected={headerTab === "edit"}
                        onClick={() => selectHeaderTab("edit")}
                    >
                        Edit
                    </button>
                    <button
                        type="button"
                        role="tab"
                        aria-selected={headerTab === "preview"}
                        onClick={() => selectHeaderTab("preview")}
                    >
                        Preview
                    </button>
                    <button
                        type="button"
                        role="tab"
                        aria-selected={headerTab === "script"}
                        onClick={() => selectHeaderTab("script")}
                    >
                        Script
                    </button>
                    <button
                        type="button"
                        role="tab"
                        aria-selected={headerTab === "insights"}
                        onClick={() => selectHeaderTab("insights")}
                    >
                        Insights
                    </button>
                </div>

                <div className="fe-top-nav-right">
                    <div className="fe-history-controls" role="group" aria-label="History actions">
                        <button
                            type="button"
                            onClick={undo}
                            disabled={!canUndo}
                            title="Undo (⌘Z)"
                            aria-label="Undo"
                        >
                            Undo
                        </button>
                        <button
                            type="button"
                            onClick={redo}
                            disabled={!canRedo}
                            title="Redo (⇧⌘Z)"
                            aria-label="Redo"
                        >
                            Redo
                        </button>
                    </div>
                    <button type="button" onClick={openExportModal} disabled={exporting}>
                        {exporting ? "Exporting..." : "Export"}
                    </button>
                    <button type="button" onClick={() => setSharing(true)} className="fe-share-btn">
                        Share
                    </button>
                    <button type="button" aria-label="Global actions">
                        ...
                    </button>
                </div>
            </header>
            {exportFeedback && (
                <div
                    className={`fe-export-feedback ${
                        exportFeedback.status === "success" ? "is-success" : "is-error"
                    }`}
                    role="status"
                    aria-live="polite"
                >
                    <div className="fe-export-feedback-text">
                        <strong>{exportFeedbackTitle}</strong>
                        <span>{exportFeedback.path ?? exportFeedback.message}</span>
                    </div>
                    <button
                        type="button"
                        className="fe-export-feedback-dismiss"
                        onClick={clearExportFeedback}
                    >
                        Dismiss
                    </button>
                </div>
            )}
            {showExportModal && (
                <div className="fe-export-modal-backdrop" onClick={closeExportModal}>
                    <div
                        className="fe-export-modal-card"
                        onClick={(event) => event.stopPropagation()}
                    >
                        <h2>Export Options</h2>
                        <p>Choose what to export and format options.</p>

                        <div
                            className="fe-export-option-group"
                            role="radiogroup"
                            aria-label="Export format"
                        >
                            <label className="fe-export-option-row">
                                <input
                                    type="radio"
                                    name="export-format"
                                    checked={exportFormat === "markdown"}
                                    onChange={() => setExportFormat("markdown")}
                                    disabled={exporting}
                                />
                                <span>
                                    <strong>Script (.md)</strong>
                                    <small>Export guide text and steps as Markdown.</small>
                                </span>
                            </label>
                            <label className="fe-export-option-row">
                                <input
                                    type="radio"
                                    name="export-format"
                                    checked={exportFormat === "mp4"}
                                    onChange={() => setExportFormat("mp4")}
                                    disabled={exporting}
                                />
                                <span>
                                    <strong>Video (.mp4)</strong>
                                    <small>Export rendered walkthrough video.</small>
                                </span>
                            </label>
                        </div>

                        {exportFormat === "mp4" && (
                            <label className="fe-export-checkbox-row">
                                <input
                                    type="checkbox"
                                    checked={exportIncludeChapterCards}
                                    onChange={(event) =>
                                        setExportIncludeChapterCards(event.target.checked)
                                    }
                                    disabled={exporting}
                                />
                                <span>Include chapter cards in video output</span>
                            </label>
                        )}

                        <div className="fe-export-modal-actions">
                            <button type="button" onClick={closeExportModal} disabled={exporting}>
                                Cancel
                            </button>
                            <button
                                type="button"
                                className="fe-share-btn"
                                onClick={() => void runExportWithOptions()}
                                disabled={exporting}
                            >
                                {exporting ? "Exporting..." : "Export"}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            <div
                className={`fe-workspace-grid ${isStepRailCollapsed ? "is-step-rail-collapsed" : ""} ${isInspectorCollapsed ? "is-inspector-collapsed" : ""}`}
                style={
                    isPreviewMode || isScriptMode
                        ? { gridTemplateColumns: "minmax(0, 1fr)" }
                        : undefined
                }
            >
                {!isPreviewMode && !isScriptMode && (
                    <aside
                        className={`fe-left-sidebar ${isStepRailCollapsed ? "is-collapsed" : ""}`}
                        aria-label="Frame stack sidebar"
                    >
                        <div className="fe-left-sidebar-header">
                            <button
                                type="button"
                                className="fe-sidebar-collapse-btn"
                                onClick={toggleStepRail}
                                aria-label={
                                    isStepRailCollapsed ? "Expand step rail" : "Collapse step rail"
                                }
                                title={
                                    isStepRailCollapsed ? "Expand step rail" : "Collapse step rail"
                                }
                                aria-expanded={!isStepRailCollapsed}
                            >
                                {isStepRailCollapsed ? (
                                    <svg
                                        width="16"
                                        height="16"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        aria-hidden
                                    >
                                        <path d="m9 18 6-6-6-6" />
                                    </svg>
                                ) : (
                                    <svg
                                        width="16"
                                        height="16"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        aria-hidden
                                    >
                                        <path d="m15 18-6-6 6-6" />
                                    </svg>
                                )}
                            </button>
                            {!isStepRailCollapsed && (
                                <div className="fe-left-sidebar-heading">
                                    <span>Steps</span>
                                    <small>{steps.length}</small>
                                </div>
                            )}
                        </div>

                        {isStepRailCollapsed ? (
                            <div className="fe-left-sidebar-collapsed-body">
                                <button
                                    type="button"
                                    className="fe-sidebar-compact-action"
                                    onClick={() => splitSelectedStepAtCurrentFrame()}
                                    aria-label="Add step"
                                    title="Add step"
                                >
                                    <svg
                                        width="16"
                                        height="16"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2.2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        aria-hidden
                                    >
                                        <path d="M12 5v14" />
                                        <path d="M5 12h14" />
                                    </svg>
                                </button>
                                <div
                                    className="fe-sidebar-compact-progress"
                                    aria-label={`Selected step ${selectedStepNumber || 0} of ${steps.length}`}
                                >
                                    <strong>{selectedStepNumber || "-"}</strong>
                                    <span>/{steps.length}</span>
                                </div>
                            </div>
                        ) : (
                            <>
                                <div className="fe-left-sidebar-scroll">
                                    <ol className="fe-frame-list">
                                        {steps.map((step, index) => {
                                            const selected = step.id === selectedStepId;
                                            const previewSrc =
                                                framePreviewSources.get(step.id) ?? null;
                                            return (
                                                <li key={step.id} className="fe-frame-list-item">
                                                    <article
                                                        className={`fe-frame-card ${selected ? "is-selected" : ""}`}
                                                    >
                                                        <button
                                                            type="button"
                                                            className="fe-frame-select"
                                                            onClick={() =>
                                                                handleSelectStep(step.id)
                                                            }
                                                        >
                                                            <div className="fe-frame-preview">
                                                                {previewSrc ? (
                                                                    <img
                                                                        src={previewSrc}
                                                                        alt={`Step ${index + 1} preview`}
                                                                        style={{
                                                                            width: "100%",
                                                                            height: "100%",
                                                                            objectFit: "cover",
                                                                        }}
                                                                    />
                                                                ) : (
                                                                    <div className="fe-frame-preview-empty">
                                                                        <svg
                                                                            width="20"
                                                                            height="20"
                                                                            viewBox="0 0 24 24"
                                                                            fill="none"
                                                                            stroke="currentColor"
                                                                            strokeWidth="1.7"
                                                                            aria-hidden
                                                                        >
                                                                            <rect
                                                                                x="3"
                                                                                y="4"
                                                                                width="18"
                                                                                height="14"
                                                                                rx="2"
                                                                            />
                                                                            <path d="M8 14l2.2-2.2a1.1 1.1 0 0 1 1.6 0L14 14l1.6-1.6a1.1 1.1 0 0 1 1.6 0L19 14" />
                                                                            <path d="M3 20l18-16" />
                                                                        </svg>
                                                                        <span>
                                                                            Preview unavailable
                                                                        </span>
                                                                        <small>
                                                                            Thumbnail failed to
                                                                            generate
                                                                        </small>
                                                                    </div>
                                                                )}
                                                            </div>
                                                            <div className="fe-frame-meta-row">
                                                                <span className="fe-frame-badge">
                                                                    {index + 1}
                                                                </span>
                                                                <span
                                                                    className="fe-frame-media-type"
                                                                    aria-label={`Media type: ${previewSrc ? "image" : "video"}`}
                                                                >
                                                                    {previewSrc ? "image" : "video"}
                                                                </span>
                                                            </div>
                                                        </button>

                                                        <div className="fe-frame-card-actions">
                                                            <details className="fe-frame-actions">
                                                                <summary
                                                                    className="fe-frame-overflow"
                                                                    style={{ cursor: "pointer" }}
                                                                    aria-label={`Frame ${index + 1} actions`}
                                                                >
                                                                    <span aria-hidden>•••</span>
                                                                </summary>
                                                                <div className="fe-frame-action-menu">
                                                                    <button
                                                                        type="button"
                                                                        className="fe-frame-action-item"
                                                                        onClick={() =>
                                                                            duplicateStep(step.id)
                                                                        }
                                                                    >
                                                                        Duplicate
                                                                    </button>
                                                                    <button
                                                                        type="button"
                                                                        className="fe-frame-action-item is-danger"
                                                                        onClick={() =>
                                                                            deleteStep(step.id)
                                                                        }
                                                                        disabled={steps.length <= 1}
                                                                    >
                                                                        Delete
                                                                    </button>
                                                                </div>
                                                            </details>
                                                        </div>

                                                        <div className="fe-frame-duration">
                                                            {formatStepRange(
                                                                step.start_ms,
                                                                step.end_ms
                                                            )}
                                                        </div>
                                                    </article>

                                                    {index < steps.length - 1 && (
                                                        <button
                                                            type="button"
                                                            className="fe-insert-step-btn"
                                                            aria-label={`Insert new frame after frame ${index + 1}`}
                                                            onClick={() =>
                                                                insertAfterStep(
                                                                    step.id,
                                                                    step.start_ms,
                                                                    step.end_ms
                                                                )
                                                            }
                                                        >
                                                            <svg
                                                                width="14"
                                                                height="14"
                                                                viewBox="0 0 24 24"
                                                                fill="none"
                                                                stroke="currentColor"
                                                                strokeWidth="2.5"
                                                                strokeLinecap="round"
                                                                strokeLinejoin="round"
                                                                aria-hidden
                                                            >
                                                                <path d="M12 5v14" />
                                                                <path d="M5 12h14" />
                                                            </svg>
                                                            <span className="fe-insert-step-label">
                                                                Add step
                                                            </span>
                                                        </button>
                                                    )}
                                                </li>
                                            );
                                        })}
                                    </ol>
                                </div>

                                <footer className="fe-left-sidebar-footer">
                                    <button
                                        type="button"
                                        className="fe-add-step-btn"
                                        onClick={() => splitSelectedStepAtCurrentFrame()}
                                    >
                                        Add Step
                                    </button>
                                </footer>
                            </>
                        )}
                    </aside>
                )}

                <main
                    className="fe-center-column"
                    aria-label="Step viewer"
                    style={isPreviewMode || isScriptMode ? { borderRight: "none" } : undefined}
                >
                    {isScriptMode ? (
                        <EditorScriptView />
                    ) : (
                        <>
                            {showCanvasTools && (
                                <div className="fe-editor-toolsbar" aria-label="Canvas tools">
                                    <div className="fe-canvas-tools-list">
                                        <button
                                            type="button"
                                            className={`fe-canvas-tool ${hotspotToolActive ? "is-active" : ""}`}
                                            title="Hotspot"
                                            aria-label="Hotspot"
                                            onClick={() => startPlacing("pulse")}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                            >
                                                <circle cx="12" cy="12" r="8" />
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className={`fe-canvas-tool ${calloutToolActive ? "is-active" : ""}`}
                                            title="Callout"
                                            aria-label="Callout"
                                            onClick={() => startPlacing("callout")}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                                strokeLinejoin="round"
                                            >
                                                <path d="M5 6h14v9H9l-4 3V6z" />
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className="fe-canvas-tool"
                                            title="Chapter"
                                            aria-label="Chapter"
                                            onClick={() => splitSelectedStepAtCurrentFrame()}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                                strokeLinejoin="round"
                                            >
                                                <path d="M5 7h14" />
                                                <path d="M7 11h10" />
                                                <path d="M9 15h6" />
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className="fe-canvas-tool"
                                            title="Transitions"
                                            aria-label="Transitions"
                                            onClick={() => setOpenSection("design")}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                            >
                                                <rect x="4" y="7" width="7" height="10" rx="1.5" />
                                                <rect x="13" y="7" width="7" height="10" rx="1.5" />
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className="fe-canvas-tool"
                                            title="Code"
                                            aria-label="Code"
                                            onClick={() => setOpenSection("other")}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                            >
                                                <polyline points="8 6 3 12 8 18" />
                                                <polyline points="16 6 21 12 16 18" />
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className="fe-canvas-tool"
                                            title="Layout"
                                            aria-label="Layout"
                                            onClick={() => setOpenSection("metadata")}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                            >
                                                <rect x="4" y="4" width="16" height="16" rx="2" />
                                                <path d="M4 10h16" />
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className="fe-canvas-tool"
                                            title="Audio"
                                            aria-label="Audio"
                                            onClick={() => setOpenSection("audio")}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                            >
                                                <path d="M4 12h2" />
                                                <path d="M8 9v6" />
                                                <path d="M12 7v10" />
                                                <path d="M16 9v6" />
                                                <path d="M20 12h-2" />
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className="fe-canvas-tool"
                                            title="Focus"
                                            aria-label="Focus"
                                            onClick={() => setOpenSection("design")}
                                        >
                                            <svg
                                                width="19"
                                                height="19"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="2"
                                            >
                                                <circle cx="12" cy="12" r="8" />
                                                <circle cx="12" cy="12" r="3" />
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            )}

                            <section className="fe-canvas-panel" aria-label="Canvas viewer">
                                {hasTerminal && (
                                    <div className="fe-canvas-topline">
                                        <div style={{ display: "flex", gap: "8px" }}>
                                            <button
                                                type="button"
                                                onClick={() => setActiveTab("video")}
                                                aria-pressed={activeTab === "video"}
                                            >
                                                Screen
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => setActiveTab("terminal")}
                                                aria-pressed={activeTab === "terminal"}
                                            >
                                                Terminal
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => setActiveTab("both")}
                                                aria-pressed={activeTab === "both"}
                                            >
                                                Both
                                            </button>
                                        </div>
                                    </div>
                                )}

                                <div className="fe-canvas-stage">
                                    <div
                                        style={{
                                            flex: 1,
                                            minHeight: 0,
                                            display: "flex",
                                            alignItems: "center",
                                            justifyContent: "center",
                                            gap: "16px",
                                        }}
                                    >
                                        {(activeTab === "video" || activeTab === "both") && (
                                            <div style={{ flex: 1, minWidth: 0 }}>
                                                <VideoPlayer
                                                    src={videoUrl}
                                                    videoRef={videoRef}
                                                    playing={playing}
                                                    currentFrame={currentFrame}
                                                    totalFrames={totalFrames}
                                                    onTogglePlay={togglePlay}
                                                    onPlay={() => setPlaying(true)}
                                                    onPause={() => setPlaying(false)}
                                                    onEnded={() => setPlaying(false)}
                                                    onLoadError={handleVideoLoadError}
                                                    onStageClick={
                                                        editorMode === "edit" && placingHotspot
                                                            ? handleStageClick
                                                            : undefined
                                                    }
                                                >
                                                    <HotspotOverlay
                                                        hotspots={hotspots}
                                                        currentFrame={currentFrame}
                                                        editable={
                                                            editorMode === "edit" && editingHotspots
                                                        }
                                                        selectedHotspotId={
                                                            editorMode === "edit" && editingHotspots
                                                                ? selectedHotspotId
                                                                : null
                                                        }
                                                        onSelectHotspot={
                                                            editorMode === "edit" && editingHotspots
                                                                ? setSelectedHotspotId
                                                                : undefined
                                                        }
                                                        onUpdateHotspot={
                                                            editorMode === "edit" && editingHotspots
                                                                ? handleUpdateHotspot
                                                                : undefined
                                                        }
                                                        onDeleteHotspot={
                                                            editorMode === "edit" && editingHotspots
                                                                ? handleDeleteHotspot
                                                                : undefined
                                                        }
                                                        onSeekToFrame={seekToFrame}
                                                        onNavigateToStep={handleNavigateToStep}
                                                        onHotspotActivated={(hotspotId) => {
                                                            const ownerStep = steps.find((step) =>
                                                                (step.hotspot_ids ?? []).includes(
                                                                    hotspotId
                                                                )
                                                            );
                                                            if (!ownerStep) return;
                                                            setActivatedHotspotsByStep(
                                                                (current) => {
                                                                    const existing = new Set(
                                                                        current[ownerStep.id] ?? []
                                                                    );
                                                                    existing.add(hotspotId);
                                                                    return {
                                                                        ...current,
                                                                        [ownerStep.id]:
                                                                            Array.from(existing),
                                                                    };
                                                                }
                                                            );
                                                            setCompletionBlockMessage(null);
                                                        }}
                                                    />
                                                    <ClickRippleOverlay
                                                        clicks={clicks}
                                                        currentTimeMs={currentTime * 1000}
                                                        enabled={showClickRipples}
                                                    />
                                                </VideoPlayer>
                                            </div>
                                        )}

                                        {(activeTab === "terminal" || activeTab === "both") &&
                                            terminalUrl && (
                                                <div
                                                    style={{
                                                        flex: activeTab === "both" ? 1 : undefined,
                                                        minWidth: 0,
                                                        border: "1px solid #d9d9d9",
                                                        borderRadius: "8px",
                                                        overflow: "hidden",
                                                    }}
                                                >
                                                    <TerminalPlayer
                                                        castUrl={terminalUrl}
                                                        showControls={activeTab === "terminal"}
                                                        playing={
                                                            activeTab === "both"
                                                                ? playing
                                                                : undefined
                                                        }
                                                        seekTo={
                                                            activeTab === "both"
                                                                ? currentTime
                                                                : undefined
                                                        }
                                                    />
                                                </div>
                                            )}
                                    </div>
                                </div>
                                {completionBlockMessage && (
                                    <div
                                        style={{
                                            marginTop: "10px",
                                            border: "1px solid var(--status-warning)",
                                            background:
                                                "color-mix(in srgb, var(--status-warning) 12%, transparent)",
                                            color: "var(--text-secondary)",
                                            borderRadius: "8px",
                                            padding: "8px 10px",
                                            fontSize: "12px",
                                            lineHeight: 1.4,
                                        }}
                                    >
                                        {completionBlockMessage}
                                    </div>
                                )}
                            </section>

                            {!isPreviewMode && (
                                <section className="fe-timeline-panel" aria-label="Timeline editor">
                                    <div className="fe-timeline-controls">
                                        <button type="button" onClick={() => jumpBySeconds(-5)}>
                                            Jump Back
                                        </button>
                                        <button type="button" onClick={() => togglePlay()}>
                                            {playing ? "Pause" : "Play"}
                                        </button>
                                        <button type="button" onClick={() => jumpBySeconds(5)}>
                                            Jump Forward
                                        </button>
                                        <button type="button" onClick={toggleMuted}>
                                            {muted ? "Unmute" : "Mute"}
                                        </button>
                                        <output>
                                            {formatDuration(currentTime)} /{" "}
                                            {formatDuration(duration)}
                                        </output>
                                    </div>

                                    <Timeline
                                        currentTime={currentTime}
                                        duration={duration}
                                        currentFrame={currentFrame}
                                        totalFrames={totalFrames}
                                        fps={fps}
                                        onSeekTime={seekToTimestamp}
                                        onSeekFrame={seekToFrame}
                                        markers={markers}
                                    />
                                </section>
                            )}
                        </>
                    )}
                </main>

                {!isPreviewMode && !isScriptMode && (
                    <aside
                        className={`fe-inspector ${isInspectorCollapsed ? "is-collapsed" : ""}`}
                        aria-label="Inspector panel"
                    >
                        <nav className="fe-inspector-shortcuts" aria-label="Inspector shortcuts">
                            <button
                                type="button"
                                className="fe-inspector-collapse-btn"
                                title={
                                    isInspectorCollapsed ? "Expand inspector" : "Collapse inspector"
                                }
                                aria-label={
                                    isInspectorCollapsed ? "Expand inspector" : "Collapse inspector"
                                }
                                aria-expanded={!isInspectorCollapsed}
                                onClick={toggleInspectorRail}
                            >
                                {isInspectorCollapsed ? (
                                    <svg
                                        width="16"
                                        height="16"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                    >
                                        <path d="m9 18 6-6-6-6" />
                                    </svg>
                                ) : (
                                    <svg
                                        width="16"
                                        height="16"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                    >
                                        <path d="m15 18-6-6 6-6" />
                                    </svg>
                                )}
                            </button>
                            {inspectorSections.map((section) => {
                                const active = openSection === section;
                                return (
                                    <button
                                        key={section}
                                        type="button"
                                        className={`fe-inspector-shortcut ${active ? "is-active" : ""}`}
                                        title={INSPECTOR_SECTION_LABELS[section]}
                                        aria-label={`Open ${INSPECTOR_SECTION_LABELS[section]} section`}
                                        aria-pressed={active}
                                        onClick={() => handleInspectorShortcut(section)}
                                    >
                                        <span className="fe-inspector-shortcut-icon" aria-hidden>
                                            {renderInspectorShortcutIcon(section)}
                                        </span>
                                        <span className="fe-inspector-shortcut-label">
                                            {INSPECTOR_SECTION_LABELS[section]}
                                        </span>
                                    </button>
                                );
                            })}
                            <button
                                type="button"
                                className="fe-inspector-shortcut is-share"
                                title="Share"
                                aria-label="Open share dialog"
                                onClick={() => setSharing(true)}
                            >
                                <span className="fe-inspector-shortcut-icon" aria-hidden>
                                    <svg
                                        width="16"
                                        height="16"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                    >
                                        <circle cx="18" cy="5" r="3" />
                                        <circle cx="6" cy="12" r="3" />
                                        <circle cx="18" cy="19" r="3" />
                                        <path d="m8.6 13.5 6.8 4" />
                                        <path d="m15.4 6.5-6.8 4" />
                                    </svg>
                                </span>
                                <span className="fe-inspector-shortcut-label">Share</span>
                            </button>
                        </nav>
                        {!isInspectorCollapsed && (
                            <div className="fe-inspector-content">
                                {metadata?.capture_limited && (
                                    <div
                                        style={{
                                            margin: "10px",
                                            border: "1px solid var(--status-warning)",
                                            background:
                                                "color-mix(in srgb, var(--status-warning) 12%, transparent)",
                                            color: "var(--text-secondary)",
                                            borderRadius: "8px",
                                            padding: "10px 12px",
                                            fontSize: "12px",
                                            lineHeight: 1.4,
                                        }}
                                    >
                                        Limited capture mode: recording is complete, but some global
                                        context (app/window or input telemetry) was unavailable.
                                        {metadata.capture_limit_reason
                                            ? ` ${metadata.capture_limit_reason}`
                                            : ""}
                                    </div>
                                )}
                                {inspectorSections.map((section) => {
                                    const isOpen = openSection === section;
                                    const panelId = `inspector-panel-${section}`;
                                    return (
                                        <section key={section} className="fe-inspector-section">
                                            <h2>
                                                <button
                                                    type="button"
                                                    aria-expanded={isOpen}
                                                    aria-controls={panelId}
                                                    onClick={() => setOpenSection(section)}
                                                >
                                                    {INSPECTOR_SECTION_LABELS[section]}
                                                </button>
                                            </h2>
                                            {isOpen && (
                                                <div
                                                    id={panelId}
                                                    className="fe-inspector-panel-body"
                                                >
                                                    {section === "design" && (
                                                        <div
                                                            style={{ display: "grid", gap: "8px" }}
                                                        >
                                                            <div>
                                                                Hotspots in step:{" "}
                                                                {hotspotCountInStep}
                                                                {selectedHotspot
                                                                    ? ` | Selected: ${selectedHotspot.style}`
                                                                    : ""}
                                                            </div>
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    setEditingHotspots(
                                                                        (current) => !current
                                                                    )
                                                                }
                                                            >
                                                                {editingHotspots
                                                                    ? "Disable Hotspot Editing"
                                                                    : "Enable Hotspot Editing"}
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    startPlacing("pulse")
                                                                }
                                                            >
                                                                {placingHotspot &&
                                                                placingHotspotStyle === "pulse"
                                                                    ? "Stop Placing Hotspot"
                                                                    : "Place Hotspot"}
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    startPlacing("callout")
                                                                }
                                                            >
                                                                {placingHotspot &&
                                                                placingHotspotStyle === "callout"
                                                                    ? "Stop Placing Callout"
                                                                    : "Place Callout"}
                                                            </button>
                                                            {!selectedHotspot &&
                                                                hotspots.length > 0 && (
                                                                    <button
                                                                        type="button"
                                                                        onClick={() =>
                                                                            setSelectedHotspotId(
                                                                                hotspots[0].id
                                                                            )
                                                                        }
                                                                    >
                                                                        Select First Hotspot
                                                                    </button>
                                                                )}
                                                            {selectedHotspot && (
                                                                <>
                                                                    <div
                                                                        style={{
                                                                            display: "grid",
                                                                            gridTemplateColumns:
                                                                                "1fr auto",
                                                                            gap: "8px",
                                                                            alignItems: "center",
                                                                        }}
                                                                    >
                                                                        <span>Text</span>
                                                                        <button
                                                                            type="button"
                                                                            title="AI copy assistance placeholder"
                                                                            style={{
                                                                                width: "auto",
                                                                            }}
                                                                        >
                                                                            Ask AI
                                                                        </button>
                                                                        <textarea
                                                                            value={
                                                                                selectedHotspot.text ??
                                                                                ""
                                                                            }
                                                                            onChange={(event) =>
                                                                                updateSelectedHotspot(
                                                                                    (current) => ({
                                                                                        ...current,
                                                                                        text: event
                                                                                            .target
                                                                                            .value,
                                                                                    })
                                                                                )
                                                                            }
                                                                            rows={3}
                                                                            placeholder="Explain the benefit of this hotspot"
                                                                            style={{
                                                                                gridColumn:
                                                                                    "1 / -1",
                                                                                width: "100%",
                                                                                resize: "vertical",
                                                                            }}
                                                                        />
                                                                    </div>

                                                                    <div
                                                                        style={{
                                                                            display: "grid",
                                                                            gap: "6px",
                                                                        }}
                                                                    >
                                                                        <span>Style</span>
                                                                        <div
                                                                            style={{
                                                                                display: "flex",
                                                                                gap: "8px",
                                                                                flexWrap: "wrap",
                                                                            }}
                                                                        >
                                                                            <button
                                                                                type="button"
                                                                                aria-pressed={
                                                                                    selectedHotspot.style ===
                                                                                        "pulse" ||
                                                                                    selectedHotspot.style ===
                                                                                        "circle"
                                                                                }
                                                                                onClick={() =>
                                                                                    updateSelectedHotspot(
                                                                                        (
                                                                                            current
                                                                                        ) => ({
                                                                                            ...current,
                                                                                            style: "pulse",
                                                                                        })
                                                                                    )
                                                                                }
                                                                            >
                                                                                Hotspot
                                                                            </button>
                                                                            <button
                                                                                type="button"
                                                                                aria-pressed={
                                                                                    selectedHotspot.style ===
                                                                                    "rectangle"
                                                                                }
                                                                                onClick={() =>
                                                                                    updateSelectedHotspot(
                                                                                        (
                                                                                            current
                                                                                        ) => ({
                                                                                            ...current,
                                                                                            style: "rectangle",
                                                                                            width: Math.max(
                                                                                                8,
                                                                                                current.width
                                                                                            ),
                                                                                            height: Math.max(
                                                                                                8,
                                                                                                current.height
                                                                                            ),
                                                                                        })
                                                                                    )
                                                                                }
                                                                            >
                                                                                Area
                                                                            </button>
                                                                            <button
                                                                                type="button"
                                                                                aria-pressed={
                                                                                    selectedHotspot.style ===
                                                                                    "callout"
                                                                                }
                                                                                onClick={() =>
                                                                                    updateSelectedHotspot(
                                                                                        (
                                                                                            current
                                                                                        ) => ({
                                                                                            ...current,
                                                                                            style: "callout",
                                                                                        })
                                                                                    )
                                                                                }
                                                                            >
                                                                                Callout
                                                                            </button>
                                                                        </div>
                                                                    </div>

                                                                    <div
                                                                        style={{
                                                                            display: "grid",
                                                                            gap: "6px",
                                                                        }}
                                                                    >
                                                                        <span>Colors</span>
                                                                        <div
                                                                            style={{
                                                                                display: "grid",
                                                                                gap: "8px",
                                                                            }}
                                                                        >
                                                                            <label
                                                                                style={{
                                                                                    display: "flex",
                                                                                    gap: "8px",
                                                                                    alignItems:
                                                                                        "center",
                                                                                }}
                                                                            >
                                                                                <span
                                                                                    style={{
                                                                                        minWidth:
                                                                                            "92px",
                                                                                    }}
                                                                                >
                                                                                    Background
                                                                                </span>
                                                                                <input
                                                                                    type="color"
                                                                                    value={
                                                                                        isHexColor(
                                                                                            backgroundDraft
                                                                                        )
                                                                                            ? backgroundDraft
                                                                                            : DEFAULT_HOTSPOT_BG
                                                                                    }
                                                                                    onChange={(
                                                                                        event
                                                                                    ) => {
                                                                                        const next =
                                                                                            event
                                                                                                .target
                                                                                                .value;
                                                                                        setBackgroundDraft(
                                                                                            next
                                                                                        );
                                                                                        updateSelectedHotspot(
                                                                                            (
                                                                                                current
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                backgroundColor:
                                                                                                    next,
                                                                                            })
                                                                                        );
                                                                                    }}
                                                                                />
                                                                                <input
                                                                                    value={
                                                                                        backgroundDraft
                                                                                    }
                                                                                    onChange={(
                                                                                        event
                                                                                    ) =>
                                                                                        setBackgroundDraft(
                                                                                            event
                                                                                                .target
                                                                                                .value
                                                                                        )
                                                                                    }
                                                                                    onBlur={() =>
                                                                                        commitColorDraft(
                                                                                            "background"
                                                                                        )
                                                                                    }
                                                                                />
                                                                            </label>
                                                                            <label
                                                                                style={{
                                                                                    display: "flex",
                                                                                    gap: "8px",
                                                                                    alignItems:
                                                                                        "center",
                                                                                }}
                                                                            >
                                                                                <span
                                                                                    style={{
                                                                                        minWidth:
                                                                                            "92px",
                                                                                    }}
                                                                                >
                                                                                    Text
                                                                                </span>
                                                                                <input
                                                                                    type="color"
                                                                                    value={
                                                                                        isHexColor(
                                                                                            textDraft
                                                                                        )
                                                                                            ? textDraft
                                                                                            : DEFAULT_HOTSPOT_TEXT
                                                                                    }
                                                                                    onChange={(
                                                                                        event
                                                                                    ) => {
                                                                                        const next =
                                                                                            event
                                                                                                .target
                                                                                                .value;
                                                                                        setTextDraft(
                                                                                            next
                                                                                        );
                                                                                        updateSelectedHotspot(
                                                                                            (
                                                                                                current
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                textColor:
                                                                                                    next,
                                                                                            })
                                                                                        );
                                                                                    }}
                                                                                />
                                                                                <input
                                                                                    value={
                                                                                        textDraft
                                                                                    }
                                                                                    onChange={(
                                                                                        event
                                                                                    ) =>
                                                                                        setTextDraft(
                                                                                            event
                                                                                                .target
                                                                                                .value
                                                                                        )
                                                                                    }
                                                                                    onBlur={() =>
                                                                                        commitColorDraft(
                                                                                            "text"
                                                                                        )
                                                                                    }
                                                                                />
                                                                            </label>
                                                                        </div>
                                                                        <div
                                                                            style={{
                                                                                display: "flex",
                                                                                flexWrap: "wrap",
                                                                                gap: "6px",
                                                                            }}
                                                                        >
                                                                            <button
                                                                                type="button"
                                                                                onClick={() =>
                                                                                    applyCurrentColors(
                                                                                        "step",
                                                                                        selectedHotspot.style ===
                                                                                            "callout"
                                                                                            ? "callout"
                                                                                            : "hotspot"
                                                                                    )
                                                                                }
                                                                            >
                                                                                Apply To Step
                                                                            </button>
                                                                            <button
                                                                                type="button"
                                                                                onClick={() =>
                                                                                    applyCurrentColors(
                                                                                        "session",
                                                                                        selectedHotspot.style ===
                                                                                            "callout"
                                                                                            ? "callout"
                                                                                            : "hotspot"
                                                                                    )
                                                                                }
                                                                            >
                                                                                Apply To All
                                                                            </button>
                                                                        </div>
                                                                    </div>

                                                                    {selectedHotspot.style ===
                                                                        "rectangle" && (
                                                                        <div
                                                                            style={{
                                                                                display: "grid",
                                                                                gap: "6px",
                                                                            }}
                                                                        >
                                                                            <span>
                                                                                Spotlight Area
                                                                            </span>
                                                                            <label
                                                                                style={{
                                                                                    display: "flex",
                                                                                    alignItems:
                                                                                        "center",
                                                                                    gap: "8px",
                                                                                }}
                                                                            >
                                                                                <input
                                                                                    type="checkbox"
                                                                                    checked={Boolean(
                                                                                        selectedHotspot.spotlight
                                                                                    )}
                                                                                    onChange={(
                                                                                        event
                                                                                    ) =>
                                                                                        updateSelectedHotspot(
                                                                                            (
                                                                                                current
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                spotlight:
                                                                                                    event
                                                                                                        .target
                                                                                                        .checked,
                                                                                            })
                                                                                        )
                                                                                    }
                                                                                />
                                                                                Enable spotlight
                                                                            </label>
                                                                            <label
                                                                                style={{
                                                                                    display: "grid",
                                                                                    gap: "4px",
                                                                                }}
                                                                            >
                                                                                <span>Shape</span>
                                                                                <select
                                                                                    value={
                                                                                        selectedHotspot.spotlightShape ??
                                                                                        "rounded"
                                                                                    }
                                                                                    onChange={(
                                                                                        event
                                                                                    ) =>
                                                                                        updateSelectedHotspot(
                                                                                            (
                                                                                                current
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                spotlightShape:
                                                                                                    event
                                                                                                        .target
                                                                                                        .value as
                                                                                                        | "square"
                                                                                                        | "rounded"
                                                                                                        | "circle",
                                                                                            })
                                                                                        )
                                                                                    }
                                                                                >
                                                                                    <option value="rounded">
                                                                                        Rounded
                                                                                    </option>
                                                                                    <option value="square">
                                                                                        Square
                                                                                    </option>
                                                                                    <option value="circle">
                                                                                        Circle
                                                                                    </option>
                                                                                </select>
                                                                            </label>
                                                                            <label
                                                                                style={{
                                                                                    display: "grid",
                                                                                    gap: "4px",
                                                                                }}
                                                                            >
                                                                                <span>
                                                                                    Overlay color /
                                                                                    opacity
                                                                                </span>
                                                                                <div
                                                                                    style={{
                                                                                        display:
                                                                                            "flex",
                                                                                        gap: "8px",
                                                                                        alignItems:
                                                                                            "center",
                                                                                    }}
                                                                                >
                                                                                    <input
                                                                                        type="color"
                                                                                        value={
                                                                                            normalizeHexColor(
                                                                                                selectedHotspot.spotlightOverlayColor ??
                                                                                                    "#0B1020"
                                                                                            ) ??
                                                                                            "#0B1020"
                                                                                        }
                                                                                        onChange={(
                                                                                            event
                                                                                        ) =>
                                                                                            updateSelectedHotspot(
                                                                                                (
                                                                                                    current
                                                                                                ) => ({
                                                                                                    ...current,
                                                                                                    spotlightOverlayColor:
                                                                                                        event
                                                                                                            .target
                                                                                                            .value,
                                                                                                })
                                                                                            )
                                                                                        }
                                                                                    />
                                                                                    <input
                                                                                        type="range"
                                                                                        min={0}
                                                                                        max={0.9}
                                                                                        step={0.05}
                                                                                        value={
                                                                                            selectedHotspot.spotlightOverlayOpacity ??
                                                                                            0.58
                                                                                        }
                                                                                        onChange={(
                                                                                            event
                                                                                        ) =>
                                                                                            updateSelectedHotspot(
                                                                                                (
                                                                                                    current
                                                                                                ) => ({
                                                                                                    ...current,
                                                                                                    spotlightOverlayOpacity:
                                                                                                        Number(
                                                                                                            event
                                                                                                                .target
                                                                                                                .value
                                                                                                        ),
                                                                                                })
                                                                                            )
                                                                                        }
                                                                                    />
                                                                                </div>
                                                                            </label>
                                                                            <label
                                                                                style={{
                                                                                    display: "grid",
                                                                                    gap: "4px",
                                                                                }}
                                                                            >
                                                                                <span>
                                                                                    Border opacity
                                                                                </span>
                                                                                <input
                                                                                    type="range"
                                                                                    min={0.1}
                                                                                    max={1}
                                                                                    step={0.05}
                                                                                    value={
                                                                                        selectedHotspot.spotlightBorderOpacity ??
                                                                                        1
                                                                                    }
                                                                                    onChange={(
                                                                                        event
                                                                                    ) =>
                                                                                        updateSelectedHotspot(
                                                                                            (
                                                                                                current
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                spotlightBorderOpacity:
                                                                                                    Number(
                                                                                                        event
                                                                                                            .target
                                                                                                            .value
                                                                                                    ),
                                                                                            })
                                                                                        )
                                                                                    }
                                                                                />
                                                                            </label>
                                                                        </div>
                                                                    )}

                                                                    <label
                                                                        style={{
                                                                            display: "grid",
                                                                            gap: "6px",
                                                                        }}
                                                                    >
                                                                        <span>Destination</span>
                                                                        <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={(event) => {
                                                                                const value =
                                                                                    event.target
                                                                                        .value;
                                                                                if (
                                                                                    value === "none"
                                                                                ) {
                                                                                    updateSelectedHotspot(
                                                                                        (
                                                                                            current
                                                                                        ) => ({
                                                                                            ...current,
                                                                                            action: {
                                                                                                type: "none",
                                                                                            },
                                                                                        })
                                                                                    );
                                                                                    return;
                                                                                }
                                                                                if (
                                                                                    value ===
                                                                                    "next_step"
                                                                                ) {
                                                                                    updateSelectedHotspot(
                                                                                        (
                                                                                            current
                                                                                        ) => ({
                                                                                            ...current,
                                                                                            action: {
                                                                                                type: "next_step",
                                                                                            },
                                                                                        })
                                                                                    );
                                                                                    return;
                                                                                }
                                                                                if (
                                                                                    value ===
                                                                                    "this_step"
                                                                                ) {
                                                                                    updateSelectedHotspot(
                                                                                        (
                                                                                            current
                                                                                        ) => ({
                                                                                            ...current,
                                                                                            action: {
                                                                                                type: "this_step",
                                                                                            },
                                                                                        })
                                                                                    );
                                                                                    return;
                                                                                }
                                                                                if (
                                                                                    value.startsWith(
                                                                                        "step:"
                                                                                    )
                                                                                ) {
                                                                                    const stepId =
                                                                                        value.slice(
                                                                                            "step:"
                                                                                                .length
                                                                                        );
                                                                                    updateSelectedHotspot(
                                                                                        (
                                                                                            current
                                                                                        ) => ({
                                                                                            ...current,
                                                                                            action: {
                                                                                                type: "step",
                                                                                                stepId,
                                                                                            },
                                                                                        })
                                                                                    );
                                                                                }
                                                                            }}
                                                                        >
                                                                            <option value="next_step">
                                                                                Next step
                                                                            </option>
                                                                            <option value="this_step">
                                                                                This step
                                                                            </option>
                                                                            <option value="none">
                                                                                None
                                                                            </option>
                                                                            {steps.map(
                                                                                (step, index) => (
                                                                                    <option
                                                                                        key={
                                                                                            step.id
                                                                                        }
                                                                                        value={`step:${step.id}`}
                                                                                    >
                                                                                        Step{" "}
                                                                                        {index + 1}:{" "}
                                                                                        {step.title}
                                                                                    </option>
                                                                                )
                                                                            )}
                                                                        </select>
                                                                    </label>

                                                                    <button
                                                                        type="button"
                                                                        onClick={() => {
                                                                            handleDeleteHotspot(
                                                                                selectedHotspot.id
                                                                            );
                                                                            setSelectedHotspotId(
                                                                                null
                                                                            );
                                                                            if (
                                                                                hotspots.length <= 1
                                                                            ) {
                                                                                setEditingHotspots(
                                                                                    false
                                                                                );
                                                                            }
                                                                        }}
                                                                    >
                                                                        Delete
                                                                    </button>
                                                                </>
                                                            )}
                                                        </div>
                                                    )}

                                                    {section === "metadata" && (
                                                        <div
                                                            style={{ display: "grid", gap: "6px" }}
                                                        >
                                                            <div>Session: {resolvedTitle}</div>
                                                            <div>Date: {sessionDate}</div>
                                                            <div>
                                                                Duration: {formatDuration(duration)}
                                                            </div>
                                                            <div>FPS: {fps}</div>
                                                            <div>
                                                                Resolution:{" "}
                                                                {metadata?.display?.resolution ??
                                                                    "unknown"}
                                                            </div>
                                                        </div>
                                                    )}

                                                    {section === "audio" && (
                                                        <div
                                                            style={{ display: "grid", gap: "8px" }}
                                                        >
                                                            <button
                                                                type="button"
                                                                onClick={() => handleTranscribe()}
                                                                disabled={transcribing}
                                                            >
                                                                {transcribing
                                                                    ? "Transcribing..."
                                                                    : "Generate Transcript"}
                                                            </button>
                                                            <div>
                                                                Segments:{" "}
                                                                {transcript?.segments?.length ?? 0}
                                                            </div>
                                                            {transcript && (
                                                                <>
                                                                    {!!transcript.full_text?.trim() && (
                                                                        <div
                                                                            style={{
                                                                                border: "1px solid var(--border-default)",
                                                                                background:
                                                                                    "var(--bg-elevated)",
                                                                                borderRadius: "8px",
                                                                                padding: "8px 10px",
                                                                                fontSize: "12px",
                                                                                lineHeight: 1.45,
                                                                                color: "var(--text-primary)",
                                                                                maxHeight: "96px",
                                                                                overflowY: "auto",
                                                                            }}
                                                                        >
                                                                            {transcript.full_text}
                                                                        </div>
                                                                    )}

                                                                    {transcript.segments.length >
                                                                    0 ? (
                                                                        <div
                                                                            style={{
                                                                                display: "grid",
                                                                                gap: "6px",
                                                                                maxHeight: "220px",
                                                                                overflowY: "auto",
                                                                            }}
                                                                        >
                                                                            {transcript.segments.map(
                                                                                (segment, idx) => (
                                                                                    <button
                                                                                        key={`transcript-segment-${idx}`}
                                                                                        type="button"
                                                                                        onClick={() =>
                                                                                            seekToTimestamp(
                                                                                                segment.start_ms /
                                                                                                    1000
                                                                                            )
                                                                                        }
                                                                                        style={{
                                                                                            display:
                                                                                                "flex",
                                                                                            gap: "8px",
                                                                                            width: "100%",
                                                                                            border: "1px solid var(--border-default)",
                                                                                            background:
                                                                                                "var(--bg-elevated)",
                                                                                            borderRadius:
                                                                                                "8px",
                                                                                            padding:
                                                                                                "8px 10px",
                                                                                            textAlign:
                                                                                                "left",
                                                                                            cursor: "pointer",
                                                                                        }}
                                                                                    >
                                                                                        <span
                                                                                            style={{
                                                                                                fontSize:
                                                                                                    "11px",
                                                                                                fontFamily:
                                                                                                    "var(--font-mono)",
                                                                                                color: "var(--accent-2)",
                                                                                                flexShrink: 0,
                                                                                            }}
                                                                                        >
                                                                                            {formatTranscriptTimestamp(
                                                                                                segment.start_ms
                                                                                            )}
                                                                                        </span>
                                                                                        <span
                                                                                            style={{
                                                                                                fontSize:
                                                                                                    "12px",
                                                                                                color: "var(--text-primary)",
                                                                                                lineHeight: 1.35,
                                                                                            }}
                                                                                        >
                                                                                            {
                                                                                                segment.text
                                                                                            }
                                                                                        </span>
                                                                                    </button>
                                                                                )
                                                                            )}
                                                                        </div>
                                                                    ) : (
                                                                        <div
                                                                            style={{
                                                                                fontSize: "12px",
                                                                                color: "var(--text-muted)",
                                                                            }}
                                                                        >
                                                                            No transcript segments
                                                                            found for this session.
                                                                        </div>
                                                                    )}
                                                                </>
                                                            )}
                                                            {transcriptError && (
                                                                <div
                                                                    style={{
                                                                        padding: "8px 10px",
                                                                        borderRadius: "8px",
                                                                        border: "1px solid var(--status-error)",
                                                                        background:
                                                                            "var(--status-error-muted)",
                                                                        color: "var(--status-error)",
                                                                        fontSize: "12px",
                                                                        lineHeight: 1.45,
                                                                    }}
                                                                >
                                                                    {transcriptError}
                                                                </div>
                                                            )}
                                                        </div>
                                                    )}

                                                    {section === "other" && (
                                                        <div
                                                            style={{ display: "grid", gap: "8px" }}
                                                        >
                                                            {selectedStep && (
                                                                <div
                                                                    style={{
                                                                        border: "1px solid var(--border-default)",
                                                                        borderRadius: "8px",
                                                                        padding: "10px",
                                                                        display: "grid",
                                                                        gap: "8px",
                                                                        background:
                                                                            "var(--bg-elevated)",
                                                                    }}
                                                                >
                                                                    <div
                                                                        style={{
                                                                            fontSize: "12px",
                                                                            fontWeight: 700,
                                                                            color: "var(--text-primary)",
                                                                        }}
                                                                    >
                                                                        Step Completion
                                                                    </div>
                                                                    <label
                                                                        style={{
                                                                            display: "grid",
                                                                            gap: "4px",
                                                                            fontSize: "12px",
                                                                        }}
                                                                    >
                                                                        <span>Rule</span>
                                                                        <select
                                                                            value={
                                                                                currentStepCompletionMode
                                                                            }
                                                                            onChange={(event) =>
                                                                                updateStepConfig(
                                                                                    selectedStep.id,
                                                                                    (step) => ({
                                                                                        ...step,
                                                                                        completion_mode:
                                                                                            event
                                                                                                .target
                                                                                                .value as
                                                                                                | "none"
                                                                                                | "any"
                                                                                                | "all",
                                                                                    })
                                                                                )
                                                                            }
                                                                        >
                                                                            <option value="none">
                                                                                No required
                                                                                interaction
                                                                            </option>
                                                                            <option value="any">
                                                                                Any required hotspot
                                                                            </option>
                                                                            <option value="all">
                                                                                All required
                                                                                hotspots
                                                                            </option>
                                                                        </select>
                                                                    </label>
                                                                    <label
                                                                        style={{
                                                                            display: "flex",
                                                                            alignItems: "center",
                                                                            gap: "8px",
                                                                            fontSize: "12px",
                                                                        }}
                                                                    >
                                                                        <input
                                                                            type="checkbox"
                                                                            checked={Boolean(
                                                                                selectedStep.autoplay
                                                                            )}
                                                                            onChange={(event) =>
                                                                                updateStepConfig(
                                                                                    selectedStep.id,
                                                                                    (step) => ({
                                                                                        ...step,
                                                                                        autoplay:
                                                                                            event
                                                                                                .target
                                                                                                .checked,
                                                                                    })
                                                                                )
                                                                            }
                                                                        />
                                                                        Autoplay this step
                                                                    </label>
                                                                    <div
                                                                        style={{
                                                                            display: "flex",
                                                                            flexWrap: "wrap",
                                                                            gap: "6px",
                                                                        }}
                                                                    >
                                                                        <button
                                                                            type="button"
                                                                            onClick={() =>
                                                                                updateStepConfig(
                                                                                    selectedStep.id,
                                                                                    (step) => ({
                                                                                        ...step,
                                                                                        required_hotspot_ids:
                                                                                            step.hotspot_ids ??
                                                                                            [],
                                                                                    })
                                                                                )
                                                                            }
                                                                        >
                                                                            Require Linked Hotspots
                                                                        </button>
                                                                        <button
                                                                            type="button"
                                                                            onClick={() =>
                                                                                updateStepConfig(
                                                                                    selectedStep.id,
                                                                                    (step) => ({
                                                                                        ...step,
                                                                                        required_hotspot_ids:
                                                                                            [],
                                                                                    })
                                                                                )
                                                                            }
                                                                        >
                                                                            Clear Required Set
                                                                        </button>
                                                                    </div>
                                                                    <div
                                                                        style={{
                                                                            fontSize: "11px",
                                                                            color: "var(--text-muted)",
                                                                        }}
                                                                    >
                                                                        Progress:{" "}
                                                                        {
                                                                            currentStepCompletionProgress
                                                                        }
                                                                    </div>
                                                                </div>
                                                            )}
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    if (!selectedStep) return;
                                                                    setEditingTitleId(
                                                                        selectedStep.id
                                                                    );
                                                                    setEditingTitle(
                                                                        selectedStep.title
                                                                    );
                                                                }}
                                                                disabled={!selectedStep}
                                                            >
                                                                Rename Selected Step
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    handleGenerateStepsFromActivity()
                                                                }
                                                            >
                                                                Generate Steps from Activity
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    handleAnalyzeSession()
                                                                }
                                                            >
                                                                Analyze Session
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    mergeSelectedStepWithNext()
                                                                }
                                                            >
                                                                Merge With Next
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    if (!selectedStep) return;
                                                                    duplicateStep(selectedStep.id);
                                                                }}
                                                                disabled={!selectedStep}
                                                            >
                                                                Duplicate Selected Step
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    if (!selectedStep) return;
                                                                    deleteStep(selectedStep.id);
                                                                }}
                                                                disabled={
                                                                    !selectedStep ||
                                                                    steps.length <= 1
                                                                }
                                                            >
                                                                Delete Selected Step
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    if (!selectedStep) return;
                                                                    moveStepUp(selectedStep.id);
                                                                }}
                                                                disabled={!selectedStep}
                                                            >
                                                                Move Step Up
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    if (!selectedStep) return;
                                                                    moveStepDown(selectedStep.id);
                                                                }}
                                                                disabled={!selectedStep}
                                                            >
                                                                Move Step Down
                                                            </button>
                                                        </div>
                                                    )}
                                                </div>
                                            )}
                                        </section>
                                    );
                                })}
                            </div>
                        )}
                    </aside>
                )}
            </div>

            {editingTitleId && (
                <form
                    onSubmit={(e) => {
                        e.preventDefault();
                        saveTitle(editingTitleId);
                    }}
                    style={{
                        position: "fixed",
                        left: "50%",
                        bottom: "16px",
                        transform: "translateX(-50%)",
                        display: "flex",
                        gap: "8px",
                        border: "1px solid #d9d9d9",
                        padding: "8px",
                        background: "white",
                        borderRadius: "8px",
                        zIndex: 20,
                    }}
                >
                    <input
                        value={editingTitle}
                        onChange={(e) => setEditingTitle(e.target.value)}
                        placeholder="Rename selected step"
                    />
                    <button type="submit">Save</button>
                    <button
                        type="button"
                        onClick={() => {
                            setEditingTitleId(null);
                            setEditingTitle("");
                        }}
                    >
                        Cancel
                    </button>
                </form>
            )}
        </div>
    );
}

export default EditorWorkspaceLayout;
