// Floating recording overlay - Developer-focused minimal UI
import { useState, useEffect, useCallback, useMemo } from "react";
import { emitTo } from "@tauri-apps/api/event";
import {
    enumerateDisplays,
    enumerateWindows,
    startRecording,
    startWindowRecording,
    startRegionRecording,
    stopRecording,
    onToggleRecordingHotkey,
    hideRecordingOverlay,
    resizeRecordingOverlay,
    showRegionSelector,
    hideRegionSelector,
    onRegionSelected,
    onRegionCancelled,
    recordStepMarker,
    onMarkerHotkey,
    type DisplayDevice,
    type WindowInfo,
    type RegionBounds,
} from "../lib/api";
import { trackWorkflowEvent } from "../lib/usageMetrics";

type RecordingMode = "display" | "window" | "region" | "terminal";

// Styles using design tokens
const styles = {
    container: {
        width: "100%",
        height: "100%",
        background: "rgba(9, 9, 11, 0.92)",
        backdropFilter: "blur(24px)",
        WebkitBackdropFilter: "blur(24px)",
        borderRadius: "var(--radius-xl)",
        border: "1px solid var(--border-default)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "0 var(--space-4)",
        boxSizing: "border-box" as const,
        userSelect: "none" as const,
        cursor: "default",
        fontFamily: "var(--font-sans)",
        boxShadow: "var(--shadow-xl)",
    },
    countdown: {
        width: "100%",
        height: "100%",
        background: "rgba(9, 9, 11, 0.95)",
        backdropFilter: "blur(24px)",
        borderRadius: "var(--radius-xl)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color: "var(--text-primary)",
        fontSize: "2.5rem",
        fontWeight: "var(--weight-bold)" as unknown as number,
        fontFamily: "var(--font-mono)",
        userSelect: "none" as const,
        letterSpacing: "var(--tracking-tight)",
    },
    countdownNumber: {
        animation: "countdown-pop 0.5s ease-out",
    },
    recordingState: {
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        width: "100%",
        gap: "var(--space-3)",
    },
    timerSection: {
        display: "flex",
        alignItems: "center",
        gap: "var(--space-2)",
    },
    recordingDot: {
        width: "10px",
        height: "10px",
        borderRadius: "50%",
        backgroundColor: "var(--accent-record)",
        boxShadow: "0 0 8px var(--accent-record-glow)",
    },
    timer: {
        color: "var(--text-primary)",
        fontSize: "var(--text-md)",
        fontWeight: "var(--weight-semibold)" as unknown as number,
        fontFamily: "var(--font-mono)",
        fontVariantNumeric: "tabular-nums",
        letterSpacing: "0.05em",
    },
    buttonGroup: {
        display: "flex",
        gap: "var(--space-2)",
    },
    stopBtn: {
        width: "34px",
        height: "34px",
        borderRadius: "var(--radius-md)",
        border: "none",
        background: "var(--accent-record)",
        color: "white",
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        transition: "var(--transition-all)",
        boxShadow: "0 0 12px var(--accent-record-glow)",
    },
    secondaryBtn: {
        width: "34px",
        height: "34px",
        borderRadius: "var(--radius-md)",
        border: "1px solid var(--border-strong)",
        background: "var(--bg-elevated)",
        color: "var(--text-secondary)",
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        transition: "var(--transition-all)",
    },
    preRecordingState: {
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        width: "100%",
        gap: "var(--space-3)",
    },
    modeButtons: {
        display: "flex",
        gap: "var(--space-1)",
    },
    modeBtn: {
        width: "36px",
        height: "36px",
        borderRadius: "var(--radius-md)",
        border: "1px solid transparent",
        background: "transparent",
        color: "var(--text-tertiary)",
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontSize: "var(--text-md)",
        transition: "var(--transition-all)",
    },
    modeBtnActive: {
        border: "1px solid var(--accent-primary)",
        background: "var(--accent-primary-muted)",
        color: "var(--accent-primary-hover)",
    },
    windowPicker: {
        position: "relative" as const,
        flex: 1,
        minWidth: 0,
    },
    windowPickerBtn: {
        width: "100%",
        padding: "var(--space-2) var(--space-3)",
        borderRadius: "var(--radius-md)",
        border: "1px solid var(--border-strong)",
        background: "var(--bg-elevated)",
        color: "var(--text-primary)",
        cursor: "pointer",
        fontSize: "var(--text-xs)",
        textAlign: "left" as const,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: "var(--space-2)",
        overflow: "hidden",
    },
    windowPickerText: {
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap" as const,
    },
    dropdown: {
        position: "absolute" as const,
        top: "100%",
        left: 0,
        right: 0,
        marginTop: "var(--space-1)",
        background: "var(--bg-surface)",
        border: "1px solid var(--border-strong)",
        borderRadius: "var(--radius-lg)",
        maxHeight: "200px",
        overflowY: "auto" as const,
        zIndex: "var(--z-dropdown)",
        boxShadow: "var(--shadow-lg)",
    },
    dropdownEmpty: {
        padding: "var(--space-3)",
        color: "var(--text-tertiary)",
        fontSize: "var(--text-xs)",
        textAlign: "center" as const,
    },
    dropdownItem: {
        width: "100%",
        padding: "var(--space-3)",
        border: "none",
        background: "transparent",
        color: "var(--text-primary)",
        cursor: "pointer",
        fontSize: "var(--text-xs)",
        textAlign: "left" as const,
        display: "block",
        borderBottom: "1px solid var(--border-subtle)",
        transition: "var(--transition-colors)",
    },
    dropdownItemTitle: {
        fontWeight: "var(--weight-medium)" as unknown as number,
    },
    dropdownItemSubtitle: {
        color: "var(--text-tertiary)",
        fontSize: "10px",
        marginTop: "2px",
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap" as const,
    },
    windowPanel: {
        marginTop: "var(--space-2)",
        background: "var(--bg-surface)",
        border: "1px solid var(--border-strong)",
        borderRadius: "var(--radius-lg)",
        padding: "var(--space-2)",
        boxShadow: "var(--shadow-lg)",
        maxHeight: "240px",
        overflow: "auto" as const,
    },
    windowGrid: {
        display: "grid",
        gridTemplateColumns: "repeat(3, minmax(0, 1fr))",
        gap: "var(--space-2)",
    },
    windowCard: {
        border: "1px solid var(--border-subtle)",
        borderRadius: "var(--radius-lg)",
        background: "rgba(255,255,255,0.02)",
        overflow: "hidden",
        cursor: "pointer",
        transition: "var(--transition-all)",
        textAlign: "left" as const,
        padding: 0,
    },
    windowCardSelected: {
        border: "1px solid var(--accent-primary)",
        boxShadow: "0 0 0 1px var(--accent-primary) inset",
        background: "var(--accent-primary-muted)",
    },
    windowThumb: {
        height: "72px",
        background:
            "linear-gradient(135deg, rgba(99,102,241,0.14) 0%, rgba(14,165,233,0.10) 45%, rgba(255,255,255,0.03) 100%)",
        position: "relative" as const,
    },
    windowChrome: {
        position: "absolute" as const,
        top: 0,
        left: 0,
        right: 0,
        height: "16px",
        background: "rgba(0,0,0,0.28)",
        borderBottom: "1px solid rgba(255,255,255,0.06)",
        display: "flex",
        alignItems: "center",
        padding: "0 8px",
        gap: "6px",
    },
    windowDot: {
        width: "6px",
        height: "6px",
        borderRadius: "50%",
        background: "rgba(255,255,255,0.28)",
    },
    windowCardBody: {
        padding: "10px 10px 10px",
        minWidth: 0,
    },
    windowCardApp: {
        color: "var(--text-secondary)",
        fontSize: "10px",
        letterSpacing: "0.02em",
        textTransform: "uppercase" as const,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap" as const,
    },
    windowCardTitle: {
        color: "var(--text-primary)",
        fontSize: "var(--text-xs)",
        marginTop: "2px",
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap" as const,
    },
    windowCardMeta: {
        color: "var(--text-tertiary)",
        fontSize: "10px",
        marginTop: "4px",
        fontFamily: "var(--font-mono)",
        opacity: 0.9,
    },
    windowCardCheck: {
        position: "absolute" as const,
        right: "8px",
        bottom: "8px",
        width: "22px",
        height: "22px",
        borderRadius: "999px",
        background: "var(--accent-primary)",
        color: "white",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        boxShadow: "0 6px 18px rgba(0,0,0,0.35)",
    },
    regionInfo: {
        flex: 1,
        display: "flex",
        alignItems: "center",
        gap: "var(--space-2)",
    },
    regionBadge: {
        padding: "var(--space-2) var(--space-3)",
        borderRadius: "var(--radius-md)",
        background: "var(--accent-primary-muted)",
        border: "1px solid var(--accent-primary)",
        color: "var(--accent-primary-hover)",
        fontSize: "var(--text-xs)",
        fontFamily: "var(--font-mono)",
        fontVariantNumeric: "tabular-nums",
    },
    regionBtn: {
        padding: "var(--space-2) var(--space-3)",
        borderRadius: "var(--radius-md)",
        border: "1px solid var(--border-strong)",
        background: "var(--bg-elevated)",
        color: "var(--text-primary)",
        cursor: "pointer",
        fontSize: "var(--text-xs)",
        transition: "var(--transition-colors)",
    },
    recordBtn: {
        height: "40px",
        minWidth: "154px",
        padding: "0 16px",
        borderRadius: "12px",
        border: "1px solid color-mix(in srgb, #ffffff 18%, transparent)",
        background: "linear-gradient(180deg, #ff4f5f 0%, #e83444 52%, #cf2232 100%)",
        color: "white",
        cursor: "pointer",
        fontSize: "15px",
        fontWeight: 760,
        letterSpacing: "0.01em",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        gap: "10px",
        whiteSpace: "nowrap" as const,
        boxShadow: "0 10px 24px rgba(232, 52, 68, 0.32), inset 0 1px 0 rgba(255,255,255,0.24)",
        transition: "transform 140ms var(--ease-out), box-shadow 140ms var(--ease-out)",
    },
    recordBtnDotShell: {
        width: "22px",
        height: "22px",
        borderRadius: "999px",
        background: "rgba(255, 255, 255, 0.16)",
        border: "1px solid rgba(255, 255, 255, 0.22)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.18)",
    },
    error: {
        position: "absolute" as const,
        bottom: "-44px",
        left: "50%",
        transform: "translateX(-50%)",
        background: "var(--accent-record)",
        color: "white",
        padding: "var(--space-2) var(--space-4)",
        borderRadius: "var(--radius-lg)",
        fontSize: "var(--text-xs)",
        whiteSpace: "nowrap" as const,
        boxShadow: "var(--shadow-md)",
        animation: "fade-in-up 0.2s ease-out",
    },
    closeBtn: {
        width: "28px",
        height: "28px",
        borderRadius: "var(--radius-md)",
        border: "none",
        background: "transparent",
        color: "var(--text-muted)",
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontSize: "var(--text-xs)",
        transition: "var(--transition-colors)",
    },
    boxShadow: "var(--shadow-md)",
    animation: "fade-in-up 0.2s ease-out",
    markerFeedback: {
        position: "absolute" as const,
        top: "-40px",
        left: "50%",
        transform: "translateX(-50%)",
        background: "var(--bg-elevated)",
        border: "1px solid var(--border-strong)",
        color: "var(--text-primary)",
        padding: "var(--space-2) var(--space-4)",
        borderRadius: "var(--radius-full)",
        fontSize: "var(--text-xs)",
        fontWeight: "var(--weight-medium)" as unknown as number,
        display: "flex",
        alignItems: "center",
        gap: "var(--space-2)",
        boxShadow: "var(--shadow-lg)",
        animation: "slide-down-fade 0.3s ease-out",
        zIndex: 100,
    },
    stepBtn: {
        height: "34px",
        padding: "0 var(--space-3)",
        borderRadius: "var(--radius-md)",
        border: "1px solid var(--border-strong)",
        background: "var(--bg-elevated)",
        color: "var(--text-primary)",
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        gap: "var(--space-2)",
        fontSize: "var(--text-xs)",
        fontWeight: "var(--weight-medium)" as unknown as number,
        transition: "var(--transition-all)",
    },
};

// SVG Icons
const icons = {
    display: (
        <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <rect x="2" y="3" width="20" height="14" rx="2" />
            <path d="M8 21h8M12 17v4" />
        </svg>
    ),
    window: (
        <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <rect x="3" y="3" width="18" height="18" rx="2" />
            <path d="M3 9h18" />
            <circle cx="6" cy="6" r="1" fill="currentColor" />
            <circle cx="9" cy="6" r="1" fill="currentColor" />
        </svg>
    ),
    region: (
        <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeDasharray="3 3"
        >
            <rect x="3" y="3" width="18" height="18" rx="2" />
        </svg>
    ),
    terminal: (
        <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <polyline points="4 17 10 11 4 5" />
            <line x1="12" y1="19" x2="20" y2="19" />
        </svg>
    ),
    stop: (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <rect x="6" y="6" width="12" height="12" rx="2" />
        </svg>
    ),
    restart: (
        <svg
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
            <path d="M3 3v5h5" />
        </svg>
    ),
    close: (
        <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <path d="M18 6 6 18M6 6l12 12" />
        </svg>
    ),
    record: (
        <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
            <circle cx="12" cy="12" r="8" />
        </svg>
    ),
    chevronUp: (
        <svg
            width="10"
            height="10"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <polyline points="18 15 12 9 6 15" />
        </svg>
    ),
    chevronDown: (
        <svg
            width="10"
            height="10"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <polyline points="6 9 12 15 18 9" />
        </svg>
    ),
    plus: (
        <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <path d="M12 5v14M5 12h14" />
        </svg>
    ),
    check: (
        <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <polyline points="20 6 9 17 4 12" />
        </svg>
    ),
    library: (
        <svg
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
        >
            <path d="M4 19a2 2 0 0 0 2 2h14" />
            <path d="M4 5a2 2 0 0 1 2-2h14v18H6a2 2 0 0 1-2-2V5z" />
            <path d="M8 7h8" />
            <path d="M8 11h8" />
        </svg>
    ),
};

function OverlayView() {
    const [recording, setRecording] = useState(false);
    const [stopping, setStopping] = useState(false);
    const [elapsedTime, setElapsedTime] = useState(0);
    const [countdown, setCountdown] = useState<number | null>(null);
    const [mode, setMode] = useState<RecordingMode>("display");
    const [displays, setDisplays] = useState<DisplayDevice[]>([]);
    const [selectedDisplay, setSelectedDisplay] = useState<string | null>(null);
    const [windows, setWindows] = useState<WindowInfo[]>([]);
    const [selectedWindow, setSelectedWindow] = useState<WindowInfo | null>(null);
    const [windowPickerOpen, setWindowPickerOpen] = useState(false);
    const [selectedRegion, setSelectedRegion] = useState<RegionBounds | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [markerFeedback, setMarkerFeedback] = useState<string | null>(null);

    // Load displays on mount
    useEffect(() => {
        async function loadDisplays() {
            try {
                const displayList = await enumerateDisplays();
                setDisplays(displayList);
                const primary = displayList.find((d) => d.is_primary);
                if (primary) {
                    setSelectedDisplay(primary.id);
                } else if (displayList.length > 0) {
                    setSelectedDisplay(displayList[0].id);
                }
            } catch (err) {
                console.error("Failed to enumerate displays:", err);
            }
        }
        loadDisplays();
    }, []);

    // Load windows when window mode is selected
    useEffect(() => {
        async function loadWindows() {
            if (mode !== "window") return;
            try {
                const windowList = await enumerateWindows();
                setWindows(windowList);
                if (!selectedWindow && windowList.length > 0) {
                    setSelectedWindow(windowList[0]);
                }
                setWindowPickerOpen(true);
            } catch (err) {
                console.error("Failed to enumerate windows:", err);
                setError("Failed to get window list");
            }
        }
        loadWindows();
    }, [mode]);

    const overlayExpanded = useMemo(() => {
        return !recording && mode === "window" && windowPickerOpen;
    }, [recording, mode, windowPickerOpen]);

    // Expand the overlay while the window picker is open so the menu isn't clipped by the WebView.
    useEffect(() => {
        if (recording) return;
        resizeRecordingOverlay(false, overlayExpanded).catch(() => {
            // Best-effort: if resize fails, keep UI functional.
        });
    }, [recording, overlayExpanded]);

    // Listen for region selection events
    useEffect(() => {
        let unlistenSelected: (() => void) | undefined;
        let unlistenCancelled: (() => void) | undefined;

        const setupListeners = async () => {
            unlistenSelected = await onRegionSelected((region) => {
                console.log("Region selected:", region);
                setSelectedRegion(region);
                setMode("region");
            });

            unlistenCancelled = await onRegionCancelled(() => {
                console.log("Region selection cancelled");
            });
        };

        setupListeners();

        return () => {
            if (unlistenSelected) unlistenSelected();
            if (unlistenCancelled) unlistenCancelled();
        };
    }, []);

    // Timer logic
    useEffect(() => {
        let interval: NodeJS.Timeout;
        if (recording) {
            interval = setInterval(() => {
                setElapsedTime((prev) => prev + 1);
            }, 1000);
        } else {
            setElapsedTime(0);
        }
        return () => clearInterval(interval);
    }, [recording]);

    // Countdown logic
    useEffect(() => {
        if (countdown === null) return;

        if (countdown === 0) {
            setCountdown(null);
            doStartRecording();
            return;
        }

        const timer = setTimeout(() => {
            setCountdown(countdown - 1);
        }, 1000);

        return () => clearTimeout(timer);
    }, [countdown]);

    const initiateCountdown = useCallback(() => {
        if (mode === "display" && !selectedDisplay) {
            setError("No display selected");
            return;
        }
        if (mode === "window" && !selectedWindow) {
            setError("No window selected");
            return;
        }
        if (mode === "region" && !selectedRegion) {
            setError("No region selected");
            return;
        }
        setError(null);
        setWindowPickerOpen(false);
        setCountdown(3);
    }, [mode, selectedDisplay, selectedWindow, selectedRegion]);

    const doStartRecording = useCallback(async () => {
        try {
            let startedSessionId: string | null = null;
            if (mode === "region") {
                if (!selectedRegion) {
                    setError("No region selected");
                    return;
                }
                startedSessionId = await startRegionRecording(
                    selectedRegion.x,
                    selectedRegion.y,
                    selectedRegion.width,
                    selectedRegion.height
                );
            } else if (mode === "window") {
                if (!selectedWindow) {
                    setError("No window selected");
                    return;
                }
                startedSessionId = await startWindowRecording(
                    selectedWindow.id,
                    Math.round(selectedWindow.bounds.width),
                    Math.round(selectedWindow.bounds.height)
                );
            } else {
                if (!selectedDisplay) {
                    setError("No display selected");
                    return;
                }
                const display = displays.find((d) => d.id === selectedDisplay);
                if (!display) {
                    setError("Display not found");
                    return;
                }
                startedSessionId = await startRecording(
                    display.id,
                    display.resolution.width,
                    display.resolution.height
                );
            }
            if (startedSessionId) {
                trackWorkflowEvent("recording_started", {
                    sessionId: startedSessionId,
                    metadata: { surface: "overlay", mode },
                });
            }
            setRecording(true);
            await resizeRecordingOverlay(true);
        } catch (err) {
            setError(`Failed to start: ${err}`);
        }
    }, [mode, selectedDisplay, displays, selectedWindow, selectedRegion]);

    const regionBadgeText = (() => {
        if (!selectedRegion) return "";
        const w = selectedRegion.logicalWidth ?? selectedRegion.width;
        const h = selectedRegion.logicalHeight ?? selectedRegion.height;
        const suffix =
            selectedRegion.logicalWidth != null &&
            selectedRegion.scaleFactor != null &&
            selectedRegion.scaleFactor !== 1
                ? ` @${selectedRegion.scaleFactor}x`
                : "";
        return `${Math.round(w)} x ${Math.round(h)}${suffix}`;
    })();

    const handleStopRecording = useCallback(async () => {
        setRecording(false);
        setStopping(true);

        try {
            const sid = await stopRecording();
            trackWorkflowEvent("recording_stopped", {
                sessionId: sid,
                metadata: { surface: "overlay", reason: "stop" },
            });
            // Best-effort: hide the region frame after recording so it doesn't linger on screen.
            try {
                await hideRegionSelector();
            } catch {
                // ignore
            }
            const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
            const mainWindow = await WebviewWindow.getByLabel("main");
            if (mainWindow) {
                await mainWindow.show();
                await mainWindow.setFocus();
            } else {
                setError("Main window is unavailable. Use tray menu: Open Library.");
                return;
            }
            await emitTo("main", "navigate-to-editor", { sessionId: sid });
            await hideRecordingOverlay();
        } catch (err) {
            setError(`Failed to stop: ${err}`);
        } finally {
            setStopping(false);
        }
    }, []);

    const handleOpenLibrary = useCallback(async () => {
        if (recording || stopping) return;
        try {
            const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
            const mainWindow = await WebviewWindow.getByLabel("main");
            if (mainWindow) {
                await mainWindow.show();
                await mainWindow.setFocus();
            } else {
                setError("Main window is unavailable. Use tray menu: Open Library.");
                return;
            }
            await emitTo("main", "navigate-to-library", {});
            await hideRecordingOverlay();
        } catch (err) {
            setError(`Failed to open library: ${err}`);
        }
    }, [recording, stopping]);

    const handleCancel = useCallback(async () => {
        setStopping(true);
        try {
            const sid = await stopRecording();
            trackWorkflowEvent("recording_stopped", {
                sessionId: sid,
                metadata: { surface: "overlay", reason: "cancel" },
            });
            setRecording(false);
            try {
                await hideRegionSelector();
            } catch {
                // ignore
            }
            await hideRecordingOverlay();
        } catch (err) {
            console.error("Cancel failed:", err);
        } finally {
            setStopping(false);
        }
    }, []);

    const handleRestart = useCallback(async () => {
        setStopping(true);
        try {
            const sid = await stopRecording();
            trackWorkflowEvent("recording_stopped", {
                sessionId: sid,
                metadata: { surface: "overlay", reason: "restart" },
            });
            setRecording(false);
            await resizeRecordingOverlay(false);
            try {
                await hideRegionSelector();
            } catch {
                // ignore
            }

            setTimeout(() => {
                setStopping(false);
                initiateCountdown();
            }, 500);
        } catch (err) {
            setError(`Restart failed: ${err}`);
        }
    }, [initiateCountdown]);

    const handleMarkStep = useCallback(async () => {
        if (!recording) return;

        try {
            await recordStepMarker("Manual Step");
            // Show feedback
            setMarkerFeedback("Step Marked");
            setTimeout(() => setMarkerFeedback(null), 2000);
        } catch (err) {
            console.error("Failed to mark step:", err);
        }
    }, [recording]);

    useEffect(() => {
        let unlisten: () => void;
        let unlistenMarker: () => void;

        const setupHotkeys = async () => {
            unlisten = await onToggleRecordingHotkey(() => {
                if (recording) {
                    handleStopRecording();
                }
            });

            unlistenMarker = await onMarkerHotkey(() => {
                handleMarkStep();
            });
        };

        setupHotkeys();

        return () => {
            if (unlisten) unlisten();
            if (unlistenMarker) unlistenMarker();
        };
    }, [recording, handleStopRecording, handleMarkStep]);

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

    const modeOptions: { mode: RecordingMode; icon: JSX.Element; label: string }[] = [
        { mode: "display", icon: icons.display, label: "Display" },
        { mode: "window", icon: icons.window, label: "Window" },
        { mode: "region", icon: icons.region, label: "Region" },
        { mode: "terminal", icon: icons.terminal, label: "Terminal" },
    ];

    // Countdown view
    if (countdown !== null) {
        return (
            <div data-tauri-drag-region style={styles.countdown}>
                <span key={countdown} style={styles.countdownNumber}>
                    {countdown > 0 ? countdown : "REC"}
                </span>
                <style>{`
                    @keyframes countdown-pop {
                        0% { transform: scale(0.5); opacity: 0; }
                        50% { transform: scale(1.1); }
                        100% { transform: scale(1); opacity: 1; }
                    }
                `}</style>
            </div>
        );
    }

    return (
        <div
            data-tauri-drag-region
            style={{
                ...styles.container,
                justifyContent: overlayExpanded
                    ? ("flex-start" as const)
                    : styles.container.justifyContent,
                padding: overlayExpanded
                    ? "var(--space-3) var(--space-4)"
                    : styles.container.padding,
            }}
        >
            {recording ? (
                // Recording State
                <div data-tauri-drag-region style={styles.recordingState}>
                    <div data-tauri-drag-region style={styles.timerSection}>
                        <div className="animate-pulse-record" style={styles.recordingDot} />
                        <span style={styles.timer}>{formatTime(elapsedTime)}</span>
                    </div>

                    <div data-tauri-drag-region style={styles.buttonGroup}>
                        <button
                            onMouseDown={(e) => e.stopPropagation()}
                            onClick={handleMarkStep}
                            disabled={stopping}
                            title="New Step (Cmd+Shift+M)"
                            style={styles.stepBtn}
                            onMouseEnter={(e) => {
                                if (!stopping) {
                                    e.currentTarget.style.borderColor = "var(--accent-primary)";
                                    e.currentTarget.style.color = "var(--accent-primary-hover)";
                                }
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.borderColor = "var(--border-strong)";
                                e.currentTarget.style.color = "var(--text-primary)";
                            }}
                        >
                            {icons.plus}
                            <span>Step</span>
                        </button>
                        <button
                            onMouseDown={(e) => e.stopPropagation()}
                            onClick={handleStopRecording}
                            disabled={stopping}
                            title="Stop Recording"
                            style={{
                                ...styles.stopBtn,
                                opacity: stopping ? 0.6 : 1,
                                cursor: stopping ? "wait" : "pointer",
                            }}
                            onMouseEnter={(e) => {
                                if (!stopping) {
                                    e.currentTarget.style.transform = "scale(1.05)";
                                    e.currentTarget.style.boxShadow =
                                        "0 0 20px var(--accent-record-glow)";
                                }
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.transform = "scale(1)";
                                e.currentTarget.style.boxShadow =
                                    "0 0 12px var(--accent-record-glow)";
                            }}
                        >
                            {icons.stop}
                        </button>
                        <button
                            onMouseDown={(e) => e.stopPropagation()}
                            onClick={handleRestart}
                            disabled={stopping}
                            title="Restart Recording"
                            style={{
                                ...styles.secondaryBtn,
                                opacity: stopping ? 0.6 : 1,
                                cursor: stopping ? "wait" : "pointer",
                            }}
                            onMouseEnter={(e) => {
                                if (!stopping) {
                                    e.currentTarget.style.background = "var(--bg-hover)";
                                    e.currentTarget.style.color = "var(--text-primary)";
                                }
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.background = "var(--bg-elevated)";
                                e.currentTarget.style.color = "var(--text-secondary)";
                            }}
                        >
                            {icons.restart}
                        </button>
                        <button
                            onMouseDown={(e) => e.stopPropagation()}
                            onClick={handleCancel}
                            disabled={stopping}
                            title="Cancel Recording"
                            style={{
                                ...styles.secondaryBtn,
                                opacity: stopping ? 0.6 : 1,
                                cursor: stopping ? "wait" : "pointer",
                            }}
                            onMouseEnter={(e) => {
                                if (!stopping) {
                                    e.currentTarget.style.background = "var(--bg-hover)";
                                    e.currentTarget.style.color = "var(--text-primary)";
                                }
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.background = "var(--bg-elevated)";
                                e.currentTarget.style.color = "var(--text-secondary)";
                            }}
                        >
                            {icons.close}
                        </button>
                    </div>
                </div>
            ) : (
                // Pre-recording State
                <div
                    data-tauri-drag-region
                    style={{
                        ...styles.preRecordingState,
                        alignItems: overlayExpanded
                            ? ("flex-start" as const)
                            : styles.preRecordingState.alignItems,
                    }}
                >
                    {/* Mode selector */}
                    <div data-tauri-drag-region style={styles.modeButtons}>
                        {modeOptions.map(({ mode: m, icon, label }) => (
                            <button
                                key={m}
                                onMouseDown={(e) => e.stopPropagation()}
                                onClick={async () => {
                                    if (m === "terminal") {
                                        emitTo("main", "navigate-to-record", {});
                                    } else if (m === "region") {
                                        setMode(m);
                                        await showRegionSelector();
                                    } else {
                                        setMode(m);
                                    }
                                }}
                                title={label}
                                style={{
                                    ...styles.modeBtn,
                                    ...(mode === m ? styles.modeBtnActive : {}),
                                }}
                                onMouseEnter={(e) => {
                                    if (mode !== m) {
                                        e.currentTarget.style.background = "var(--bg-hover)";
                                        e.currentTarget.style.color = "var(--text-secondary)";
                                    }
                                }}
                                onMouseLeave={(e) => {
                                    if (mode !== m) {
                                        e.currentTarget.style.background = "transparent";
                                        e.currentTarget.style.color = "var(--text-tertiary)";
                                    }
                                }}
                            >
                                {icon}
                            </button>
                        ))}
                    </div>

                    {/* Window picker dropdown for window mode */}
                    {mode === "window" && (
                        <div style={styles.windowPicker}>
                            <button
                                onMouseDown={(e) => e.stopPropagation()}
                                onClick={() => setWindowPickerOpen(!windowPickerOpen)}
                                style={styles.windowPickerBtn}
                            >
                                <span style={styles.windowPickerText}>
                                    {selectedWindow
                                        ? `${selectedWindow.owner_name}${selectedWindow.title ? ` - ${selectedWindow.title}` : ""}`
                                        : "Choose a window"}
                                </span>
                                <span style={{ flexShrink: 0 }}>
                                    {windowPickerOpen ? icons.chevronUp : icons.chevronDown}
                                </span>
                            </button>
                            {windowPickerOpen && (
                                <div
                                    onMouseDown={(e) => e.stopPropagation()}
                                    style={styles.windowPanel}
                                >
                                    {windows.length === 0 ? (
                                        <div style={styles.dropdownEmpty}>No windows found</div>
                                    ) : (
                                        <div style={styles.windowGrid}>
                                            {windows.map((win) => {
                                                const isSelected = selectedWindow?.id === win.id;
                                                const sizeLabel = `${Math.round(win.bounds.width)} x ${Math.round(win.bounds.height)}`;
                                                return (
                                                    <button
                                                        key={win.id}
                                                        onClick={() => {
                                                            setSelectedWindow(win);
                                                            setWindowPickerOpen(false);
                                                        }}
                                                        style={{
                                                            ...styles.windowCard,
                                                            ...(isSelected
                                                                ? styles.windowCardSelected
                                                                : {}),
                                                        }}
                                                        onMouseEnter={(e) => {
                                                            if (!isSelected) {
                                                                e.currentTarget.style.borderColor =
                                                                    "var(--border-strong)";
                                                                e.currentTarget.style.transform =
                                                                    "translateY(-1px)";
                                                            }
                                                        }}
                                                        onMouseLeave={(e) => {
                                                            e.currentTarget.style.borderColor =
                                                                isSelected
                                                                    ? "var(--accent-primary)"
                                                                    : "var(--border-subtle)";
                                                            e.currentTarget.style.transform =
                                                                "translateY(0)";
                                                        }}
                                                    >
                                                        <div style={styles.windowThumb}>
                                                            <div style={styles.windowChrome}>
                                                                <span style={styles.windowDot} />
                                                                <span style={styles.windowDot} />
                                                                <span style={styles.windowDot} />
                                                            </div>
                                                            {isSelected && (
                                                                <div
                                                                    style={styles.windowCardCheck}
                                                                    aria-hidden
                                                                >
                                                                    <svg
                                                                        width="14"
                                                                        height="14"
                                                                        viewBox="0 0 24 24"
                                                                        fill="none"
                                                                        stroke="currentColor"
                                                                        strokeWidth="3"
                                                                        strokeLinecap="round"
                                                                        strokeLinejoin="round"
                                                                    >
                                                                        <polyline points="20 6 9 17 4 12" />
                                                                    </svg>
                                                                </div>
                                                            )}
                                                        </div>
                                                        <div style={styles.windowCardBody}>
                                                            <div style={styles.windowCardApp}>
                                                                {win.owner_name || "App"}
                                                            </div>
                                                            <div style={styles.windowCardTitle}>
                                                                {win.title || "(Untitled)"}
                                                            </div>
                                                            <div style={styles.windowCardMeta}>
                                                                {sizeLabel}
                                                            </div>
                                                        </div>
                                                    </button>
                                                );
                                            })}
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    )}

                    {/* Region info display when in region mode */}
                    {mode === "region" && (
                        <div data-tauri-drag-region style={styles.regionInfo}>
                            {selectedRegion ? (
                                <div style={styles.regionBadge}>
                                    {regionBadgeText} @ {Math.round(selectedRegion.x)},
                                    {Math.round(selectedRegion.y)}
                                </div>
                            ) : (
                                <button
                                    onMouseDown={(e) => e.stopPropagation()}
                                    onClick={() => showRegionSelector()}
                                    style={styles.regionBtn}
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style.borderColor = "var(--accent-primary)";
                                        e.currentTarget.style.color = "var(--accent-primary-hover)";
                                    }}
                                    onMouseLeave={(e) => {
                                        e.currentTarget.style.borderColor = "var(--border-strong)";
                                        e.currentTarget.style.color = "var(--text-primary)";
                                    }}
                                >
                                    Select Region...
                                </button>
                            )}
                        </div>
                    )}

                    {/* Record button */}
                    <button
                        onMouseDown={(e) => e.stopPropagation()}
                        onClick={
                            mode === "region" && !selectedRegion
                                ? () => showRegionSelector()
                                : initiateCountdown
                        }
                        style={styles.recordBtn}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.transform = "translateY(-1px)";
                            e.currentTarget.style.boxShadow =
                                "0 14px 28px rgba(232, 52, 68, 0.44), inset 0 1px 0 rgba(255,255,255,0.28)";
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.transform = "translateY(0)";
                            e.currentTarget.style.boxShadow =
                                "0 10px 24px rgba(232, 52, 68, 0.32), inset 0 1px 0 rgba(255,255,255,0.24)";
                        }}
                    >
                        <span style={styles.recordBtnDotShell}>{icons.record}</span>
                        {mode === "region" ? (selectedRegion ? "Record" : "Select") : "Record"}
                    </button>

                    {/* Close button */}
                    <button
                        onMouseDown={(e) => e.stopPropagation()}
                        onClick={() => {
                            void handleOpenLibrary();
                        }}
                        disabled={recording || stopping}
                        title={recording ? "Stop recording before opening Library" : "Open Library"}
                        style={{
                            ...styles.closeBtn,
                            opacity: recording || stopping ? 0.5 : 1,
                            cursor: recording || stopping ? "not-allowed" : "pointer",
                        }}
                        onMouseEnter={(e) => {
                            if (recording || stopping) return;
                            e.currentTarget.style.background = "var(--bg-hover)";
                            e.currentTarget.style.color = "var(--text-secondary)";
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.background = "transparent";
                            e.currentTarget.style.color = "var(--text-muted)";
                        }}
                    >
                        {icons.library}
                    </button>
                    <button
                        onMouseDown={(e) => e.stopPropagation()}
                        onClick={() => hideRecordingOverlay()}
                        style={styles.closeBtn}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.background = "var(--bg-hover)";
                            e.currentTarget.style.color = "var(--text-secondary)";
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.background = "transparent";
                            e.currentTarget.style.color = "var(--text-muted)";
                        }}
                    >
                        {icons.close}
                    </button>
                </div>
            )}

            {markerFeedback && (
                <div style={styles.markerFeedback}>
                    {icons.check}
                    {markerFeedback}
                </div>
            )}
            {error && <div style={styles.error}>{error}</div>}

            <style>{`
                @keyframes pulse-record {
                    0%, 100% {
                        opacity: 1;
                        box-shadow: 0 0 8px var(--accent-record-glow);
                    }
                    50% {
                        opacity: 0.6;
                        box-shadow: 0 0 16px var(--accent-record-glow);
                    }
                }
                .animate-pulse-record {
                    animation: pulse-record 1.5s ease-in-out infinite;
                }
                @keyframes fade-in-up {
                    from { opacity: 0; transform: translateX(-50%) translateY(8px); }
                    to { opacity: 1; transform: translateX(-50%) translateY(0); }
                }
            `}</style>
        </div>
    );
}

export default OverlayView;
