import { useCallback, useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent } from "react"
import {
  APPEARANCE_TOKEN_NAMES,
  normalizeAppearanceConfigDocument,
  type AppearanceConfigDocument,
  type AppearanceTokenMap,
  type AppearanceTokenName,
} from "../../../shared/appearance"
import { applyAppearanceOverrides, normalizeAppearanceColorInputValue, readResolvedAppearanceTokenValues } from "./appearance-theme"
import {
  DEFAULT_RIGHT_SIDEBAR_WIDTH,
  DEFAULT_SIDEBAR_WIDTH,
  RIGHT_SIDEBAR_MIN_LEFT_EDGE_RATIO,
  SIDEBAR_KEYBOARD_STEP,
} from "./constants"
import {
  DEFAULT_ASSISTANT_TRACE_VISIBILITY,
  type AssistantTraceVisibility,
  type AssistantTraceVisibilityKey,
  type BrandTheme,
  type ColorMode,
  type WindowAction,
} from "./types"
import { clamp, resolveRightSidebarWidthBounds, resolveSidebarWidthBounds } from "./utils"
import { SIDEBAR_RESIZE_END_EVENT } from "./sidebar-resize-events"

const ACTIVITY_RAIL_VISIBILITY_STORAGE_KEY = "desktop.activityRailVisible"
const COLOR_MODE_STORAGE_KEY = "desktop.colorMode"
const BRAND_THEME_STORAGE_KEY = "desktop.brandTheme"
const DEBUG_UI_REGIONS_STORAGE_KEY = "desktop.debugUiRegions"
const DEBUG_LINE_COLORS_STORAGE_KEY = "desktop.debugLineColors"
const AGENT_DEBUG_TRACE_STORAGE_KEY = "desktop.agentDebugTrace"
const ASSISTANT_TRACE_VISIBILITY_STORAGE_KEY = "desktop.assistantTraceVisibility.v1"
const WINDOW_CONTROLS_CLEARANCE_FALLBACK = 124
const WINDOW_CONTROLS_CLEARANCE_PADDING = 24
const APPEARANCE_CONFIG_SAVE_DEBOUNCE_MS = 160

const EMPTY_APPEARANCE_TOKEN_VALUES = Object.fromEntries(
  APPEARANCE_TOKEN_NAMES.map((tokenName) => [tokenName, "#000000"]),
) as Record<AppearanceTokenName, string>

type SidebarResizerSide = "left" | "right"

interface ActivePointerCapture {
  element: HTMLDivElement
  pointerId: number
}

interface ActiveSidebarResize {
  appShell: HTMLElement
  bounds: {
    max: number
    min: number
  }
  containerLeft: number
  containerRight: number
  didCommit: boolean
  frameID: number | null
  latestWidth: number
  leftRailDisplayWidth: number
  originalWidth: number
  side: SidebarResizerSide
}

function readBooleanPreference(key: string, fallback: boolean) {
  if (typeof window === "undefined") return fallback

  try {
    const storedValue = window.localStorage.getItem(key)
    if (storedValue === null) return fallback
    return storedValue !== "false"
  } catch {
    return fallback
  }
}

function readActivityRailVisibilityPreference() {
  return readBooleanPreference(ACTIVITY_RAIL_VISIBILITY_STORAGE_KEY, true)
}

function readColorModePreference(): ColorMode {
  if (typeof window === "undefined") return "system"
  try {
    const stored = window.localStorage.getItem(COLOR_MODE_STORAGE_KEY)
    if (stored === "light" || stored === "dark" || stored === "system") return stored
    return "system"
  } catch {
    return "system"
  }
}

function readBrandThemePreference(): BrandTheme {
  if (typeof window === "undefined") return "terra"
  try {
    const stored = window.localStorage.getItem(BRAND_THEME_STORAGE_KEY)
    if (stored === "terra" || stored === "sage") return stored
    return "terra"
  } catch {
    return "terra"
  }
}

function readDebugUiRegionsPreference() {
  return readBooleanPreference(DEBUG_UI_REGIONS_STORAGE_KEY, false)
}

function readDebugLineColorsPreference() {
  return readBooleanPreference(DEBUG_LINE_COLORS_STORAGE_KEY, false)
}

function readAgentDebugTracePreference() {
  return readBooleanPreference(AGENT_DEBUG_TRACE_STORAGE_KEY, false)
}

function mergeAssistantTraceVisibilityPreference(value: unknown): AssistantTraceVisibility {
  const merged = { ...DEFAULT_ASSISTANT_TRACE_VISIBILITY }
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return merged
  }

  for (const key of Object.keys(DEFAULT_ASSISTANT_TRACE_VISIBILITY) as AssistantTraceVisibilityKey[]) {
    if (typeof (value as Record<string, unknown>)[key] === "boolean") {
      merged[key] = (value as Record<string, boolean>)[key]
    }
  }

  return merged
}

function readAssistantTraceVisibilityPreference() {
  if (typeof window === "undefined") {
    return { ...DEFAULT_ASSISTANT_TRACE_VISIBILITY }
  }

  try {
    const storedValue = window.localStorage.getItem(ASSISTANT_TRACE_VISIBILITY_STORAGE_KEY)
    if (storedValue) {
      return mergeAssistantTraceVisibilityPreference(JSON.parse(storedValue))
    }
  } catch {
    // Ignore and fall back to defaults.
  }

  return {
    ...DEFAULT_ASSISTANT_TRACE_VISIBILITY,
    debugMetadata: readAgentDebugTracePreference(),
  }
}

export function useDesktopShell() {
  const appShellRef = useRef<HTMLElement | null>(null)
  const [windowControlsElement, setWindowControlsElement] = useState<HTMLDivElement | null>(null)
  const windowControlsRef = useCallback((node: HTMLDivElement | null) => {
    setWindowControlsElement((current) => (current === node ? current : node))
  }, [])
  const [platform, setPlatform] = useState("Desktop")
  const [isWindowMaximized, setIsWindowMaximized] = useState(false)
  const [windowControlsClearance, setWindowControlsClearance] = useState(WINDOW_CONTROLS_CLEARANCE_FALLBACK)
  const [sidebarWidth, setSidebarWidth] = useState(DEFAULT_SIDEBAR_WIDTH)
  const [rightSidebarWidth, setRightSidebarWidth] = useState(DEFAULT_RIGHT_SIDEBAR_WIDTH)
  const [isActivityRailVisible, setIsActivityRailVisible] = useState(readActivityRailVisibilityPreference)
  const [colorMode, setColorMode] = useState<ColorMode>(readColorModePreference)
  const [brandTheme, setBrandTheme] = useState<BrandTheme>(readBrandThemePreference)
  const [appearanceOverrides, setAppearanceOverrides] = useState<AppearanceTokenMap>({})
  const [appearanceTokenValues, setAppearanceTokenValues] =
    useState<Record<AppearanceTokenName, string>>(EMPTY_APPEARANCE_TOKEN_VALUES)
  const [appearanceConfigPath, setAppearanceConfigPath] = useState<string | null>(null)
  const [appearanceConfigError, setAppearanceConfigError] = useState<string | null>(null)
  const [isAppearanceConfigReady, setIsAppearanceConfigReady] = useState(false)
  const [isDebugUiRegionsEnabled, setIsDebugUiRegionsEnabled] = useState(readDebugUiRegionsPreference)
  const [isDebugLineColorsEnabled, setIsDebugLineColorsEnabled] = useState(readDebugLineColorsPreference)
  const [assistantTraceVisibility, setAssistantTraceVisibility] = useState(readAssistantTraceVisibilityPreference)
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false)
  const [isRightSidebarCollapsed, setIsRightSidebarCollapsed] = useState(false)
  const [agentDefaultDirectory, setAgentDefaultDirectory] = useState("")
  const [agentConnected, setAgentConnected] = useState(false)
  const lastExpandedSidebarWidthRef = useRef(DEFAULT_SIDEBAR_WIDTH)
  const lastExpandedRightSidebarWidthRef = useRef(DEFAULT_RIGHT_SIDEBAR_WIDTH)
  const activeSidebarResizerPointerRef = useRef<ActivePointerCapture | null>(null)
  const activeSidebarResizeRef = useRef<ActiveSidebarResize | null>(null)
  const activeSidebarResizeCleanupRef = useRef<(() => void) | null>(null)
  const isSidebarResizing = false
  const isRightSidebarResizing = false
  const isAgentDebugTraceEnabled = assistantTraceVisibility.debugMetadata

  function getLeftRailDisplayWidth() {
    return isActivityRailVisible ? 54 : 0
  }

  function resolveLeftSidebarBounds(containerWidth?: number) {
    if (!containerWidth || containerWidth <= 0) {
      return resolveSidebarWidthBounds(containerWidth)
    }

    const fixedWidth = getLeftRailDisplayWidth() + 10 + (isRightSidebarCollapsed ? 0 : rightSidebarWidth + 10)

    return resolveSidebarWidthBounds(containerWidth - fixedWidth)
  }

  function resolveRightSidebarBounds(containerWidth?: number) {
    if (!containerWidth || containerWidth <= 0) {
      return resolveRightSidebarWidthBounds(containerWidth, RIGHT_SIDEBAR_MIN_LEFT_EDGE_RATIO)
    }

    return resolveRightSidebarWidthBounds(containerWidth, RIGHT_SIDEBAR_MIN_LEFT_EDGE_RATIO)
  }

  function releaseActiveSidebarResizerPointerCapture() {
    const activePointer = activeSidebarResizerPointerRef.current
    activeSidebarResizerPointerRef.current = null
    if (!activePointer) return

    try {
      if (activePointer.element.hasPointerCapture?.(activePointer.pointerId)) {
        activePointer.element.releasePointerCapture(activePointer.pointerId)
      }
    } catch {
      // Pointer capture is best-effort; losing it should not keep resize active.
    }
  }

  function captureSidebarResizerPointer(event: PointerEvent<HTMLDivElement>) {
    releaseActiveSidebarResizerPointerCapture()

    try {
      event.currentTarget.setPointerCapture?.(event.pointerId)
      activeSidebarResizerPointerRef.current = {
        element: event.currentTarget,
        pointerId: event.pointerId,
      }
    } catch {
      activeSidebarResizerPointerRef.current = null
    }
  }

  function updateSidebarResizerAriaValue(width: number) {
    activeSidebarResizerPointerRef.current?.element.setAttribute("aria-valuenow", String(Math.round(width)))
  }

  function applySidebarResizePreview(resizeState: ActiveSidebarResize, width: number) {
    const widthValue = `${width}px`
    if (resizeState.side === "left") {
      resizeState.appShell.style.setProperty("--sidebar-display-width", widthValue)
      resizeState.appShell.style.setProperty("--sidebar-width", widthValue)
    } else {
      resizeState.appShell.style.setProperty("--right-sidebar-display-width", widthValue)
      resizeState.appShell.style.setProperty("--right-sidebar-width", widthValue)
    }
    updateSidebarResizerAriaValue(width)
  }

  function restoreSidebarResizePreview(resizeState: ActiveSidebarResize) {
    applySidebarResizePreview(resizeState, resizeState.originalWidth)
  }

  function clearSidebarResizeFrame(resizeState: ActiveSidebarResize) {
    if (resizeState.frameID === null) return
    window.cancelAnimationFrame(resizeState.frameID)
    resizeState.frameID = null
  }

  function queueSidebarResizePreview(resizeState: ActiveSidebarResize, width: number) {
    resizeState.latestWidth = width
    if (resizeState.frameID !== null) return

    resizeState.frameID = window.requestAnimationFrame(() => {
      resizeState.frameID = null
      applySidebarResizePreview(resizeState, resizeState.latestWidth)
    })
  }

  function resolveSidebarResizeWidth(resizeState: ActiveSidebarResize, clientX: number) {
    const rawWidth = resizeState.side === "left"
      ? clientX - resizeState.containerLeft - resizeState.leftRailDisplayWidth
      : resizeState.containerRight - clientX

    return clamp(rawWidth, resizeState.bounds.min, resizeState.bounds.max)
  }

  useEffect(() => {
    let mounted = true

    window.desktop
      ?.getInfo()
      .then((info) => {
        if (mounted) setPlatform(info.platform)
      })
      .catch(() => {
        if (mounted && window.desktop?.platform) setPlatform(window.desktop.platform)
      })

    return () => {
      mounted = false
    }
  }, [])

  useEffect(() => {
    let mounted = true

    if (!window.desktop?.getAppearanceConfig) {
      setIsAppearanceConfigReady(true)
      return () => {
        mounted = false
      }
    }

    void window.desktop.getAppearanceConfig()
      .then((snapshot) => {
        if (!mounted) return

        const nextDocument = normalizeAppearanceConfigDocument(snapshot.document)
        setAppearanceConfigPath(snapshot.path)
        setAppearanceConfigError(null)
        setColorMode(nextDocument.colorMode)
        setBrandTheme(nextDocument.brandTheme)
        setAppearanceOverrides(nextDocument.overrides)
      })
      .catch((error) => {
        if (!mounted) return

        setAppearanceConfigError(error instanceof Error ? error.message : String(error))
      })
      .finally(() => {
        if (mounted) {
          setIsAppearanceConfigReady(true)
        }
      })

    return () => {
      mounted = false
    }
  }, [])

  useEffect(() => {
    const controls = windowControlsElement
    if (!controls) return

    const syncWindowControlsClearance = () => {
      const rect = controls.getBoundingClientRect()
      if (rect.width <= 0) return

      const nextClearance = Math.ceil(rect.width) + WINDOW_CONTROLS_CLEARANCE_PADDING
      setWindowControlsClearance((current) => (current === nextClearance ? current : nextClearance))
    }

    syncWindowControlsClearance()

    if (typeof ResizeObserver !== "undefined") {
      const observer = new ResizeObserver(() => {
        syncWindowControlsClearance()
      })
      observer.observe(controls)

      return () => {
        observer.disconnect()
      }
    }

    window.addEventListener("resize", syncWindowControlsClearance)
    return () => {
      window.removeEventListener("resize", syncWindowControlsClearance)
    }
  }, [windowControlsElement])

  useEffect(() => {
    let mounted = true

    window.desktop
      ?.getWindowState?.()
      .then((state) => {
        if (mounted) setIsWindowMaximized(state.isMaximized)
      })
      .catch(() => undefined)

    const unsubscribe = window.desktop?.onWindowStateChange?.((state) => {
      if (mounted) setIsWindowMaximized(state.isMaximized)
    })

    return () => {
      mounted = false
      unsubscribe?.()
    }
  }, [])

  useEffect(() => {
    let mounted = true

    const configPromise = window.desktop?.getAgentConfig
      ? window.desktop.getAgentConfig().catch(() => undefined)
      : Promise.resolve(undefined)
    const healthPromise = window.desktop?.getAgentHealth
      ? window.desktop.getAgentHealth().catch(() => undefined)
      : Promise.resolve(undefined)

    Promise.all([configPromise, healthPromise])
      .then(([config, health]) => {
        if (!mounted) return
        if (config?.defaultDirectory) setAgentDefaultDirectory(config.defaultDirectory)
        if (health) setAgentConnected(health.ok)
      })
      .catch(() => {
        if (mounted) setAgentConnected(false)
      })

    return () => {
      mounted = false
    }
  }, [])

  useEffect(() => {
    try {
      window.localStorage.setItem(ACTIVITY_RAIL_VISIBILITY_STORAGE_KEY, String(isActivityRailVisible))
    } catch {
      return
    }
  }, [isActivityRailVisible])

  useEffect(() => {
    if (colorMode === "system") {
      document.documentElement.removeAttribute("data-theme")
    } else {
      document.documentElement.setAttribute("data-theme", colorMode)
    }
    try {
      window.localStorage.setItem(COLOR_MODE_STORAGE_KEY, colorMode)
    } catch {
      return
    }
  }, [colorMode])

  useEffect(() => {
    document.documentElement.setAttribute("data-brand-theme", brandTheme)
    try {
      window.localStorage.setItem(BRAND_THEME_STORAGE_KEY, brandTheme)
    } catch {
      return
    }
  }, [brandTheme])

  useEffect(() => {
    applyAppearanceOverrides(document.documentElement, appearanceOverrides)
    setAppearanceTokenValues(readResolvedAppearanceTokenValues(document.documentElement))
  }, [appearanceOverrides, brandTheme, colorMode])

  useEffect(() => {
    const saveAppearanceConfig = window.desktop?.saveAppearanceConfig
    if (!isAppearanceConfigReady || !saveAppearanceConfig) return

    const timer = window.setTimeout(() => {
      const nextDocument: AppearanceConfigDocument = {
        version: 1,
        brandTheme,
        colorMode,
        overrides: appearanceOverrides,
        resolvedTokens: readResolvedAppearanceTokenValues(document.documentElement),
        updatedAt: Date.now(),
      }

      void saveAppearanceConfig({ document: nextDocument })
        .then((snapshot) => {
          setAppearanceConfigPath(snapshot.path)
          setAppearanceConfigError(null)
        })
        .catch((error) => {
          setAppearanceConfigError(error instanceof Error ? error.message : String(error))
        })
    }, APPEARANCE_CONFIG_SAVE_DEBOUNCE_MS)

    return () => {
      window.clearTimeout(timer)
    }
  }, [appearanceOverrides, brandTheme, colorMode, isAppearanceConfigReady])

  useEffect(() => {
    try {
      window.localStorage.setItem(DEBUG_UI_REGIONS_STORAGE_KEY, String(isDebugUiRegionsEnabled))
    } catch {
      return
    }
  }, [isDebugUiRegionsEnabled])

  useEffect(() => {
    try {
      window.localStorage.setItem(DEBUG_LINE_COLORS_STORAGE_KEY, String(isDebugLineColorsEnabled))
    } catch {
      return
    }
  }, [isDebugLineColorsEnabled])

  useEffect(() => {
    try {
      window.localStorage.setItem(
        ASSISTANT_TRACE_VISIBILITY_STORAGE_KEY,
        JSON.stringify(assistantTraceVisibility),
      )
      window.localStorage.setItem(AGENT_DEBUG_TRACE_STORAGE_KEY, String(assistantTraceVisibility.debugMetadata))
    } catch {
      return
    }
  }, [assistantTraceVisibility])

  useEffect(() => {
    function syncSidebarWidthToViewport() {
      const rect = appShellRef.current?.getBoundingClientRect()
      if (!rect || rect.width <= 0) return

      const leftBounds = resolveLeftSidebarBounds(rect.width)
      const rightBounds = resolveRightSidebarBounds(rect.width)

      setSidebarWidth((current) => {
        const nextWidth = clamp(current, leftBounds.min, leftBounds.max)
        lastExpandedSidebarWidthRef.current = clamp(lastExpandedSidebarWidthRef.current, leftBounds.min, leftBounds.max)
        return nextWidth
      })
      setRightSidebarWidth((current) => {
        const nextWidth = clamp(current, rightBounds.min, rightBounds.max)
        lastExpandedRightSidebarWidthRef.current = clamp(lastExpandedRightSidebarWidthRef.current, rightBounds.min, rightBounds.max)
        return nextWidth
      })
    }

    syncSidebarWidthToViewport()
    window.addEventListener("resize", syncSidebarWidthToViewport)
    return () => {
      window.removeEventListener("resize", syncSidebarWidthToViewport)
    }
  }, [isActivityRailVisible, isRightSidebarCollapsed, isSidebarCollapsed, rightSidebarWidth, sidebarWidth])

  useEffect(() => {
    return () => {
      activeSidebarResizeCleanupRef.current?.()
    }
  }, [])

  function startSidebarResize(resizeState: ActiveSidebarResize) {
    let isStopped = false
    function handlePointerMove(event: globalThis.PointerEvent) {
      if (event.pointerType === "mouse" && event.buttons === 0) {
        stopSidebarResize({ commit: true })
        return
      }

      queueSidebarResizePreview(resizeState, resolveSidebarResizeWidth(resizeState, event.clientX))
    }

    function handlePointerUp() {
      stopSidebarResize({ commit: true })
    }

    function handlePointerCancel() {
      stopSidebarResize({ commit: false })
    }

    function handleWindowBlur() {
      stopSidebarResize({ commit: true })
    }

    function stopSidebarResize({ commit }: { commit: boolean }) {
      if (isStopped) return
      isStopped = true
      clearSidebarResizeFrame(resizeState)
      if (commit) {
        applySidebarResizePreview(resizeState, resizeState.latestWidth)
        resizeState.didCommit = true
        if (resizeState.side === "left") {
          lastExpandedSidebarWidthRef.current = resizeState.latestWidth
          setSidebarWidth(resizeState.latestWidth)
        } else {
          lastExpandedRightSidebarWidthRef.current = resizeState.latestWidth
          setRightSidebarWidth(resizeState.latestWidth)
        }
      } else {
        restoreSidebarResizePreview(resizeState)
      }
      if (activeSidebarResizeRef.current === resizeState) {
        activeSidebarResizeRef.current = null
      }
      activeSidebarResizerPointerRef.current?.element.classList.remove("is-active")
      releaseActiveSidebarResizerPointerCapture()
      document.body.classList.remove("is-resizing-sidebar")
      window.removeEventListener("pointermove", handlePointerMove)
      window.removeEventListener("pointerup", handlePointerUp)
      window.removeEventListener("pointercancel", handlePointerCancel)
      window.removeEventListener("blur", handleWindowBlur)
      window.dispatchEvent(new Event(SIDEBAR_RESIZE_END_EVENT))
      if (activeSidebarResizeCleanupRef.current === cleanupSidebarResize) {
        activeSidebarResizeCleanupRef.current = null
      }
    }

    function cleanupSidebarResize() {
      stopSidebarResize({ commit: false })
    }

    activeSidebarResizeRef.current = resizeState
    activeSidebarResizeCleanupRef.current = cleanupSidebarResize
    activeSidebarResizerPointerRef.current?.element.classList.add("is-active")
    document.body.classList.add("is-resizing-sidebar")
    window.addEventListener("pointermove", handlePointerMove)
    window.addEventListener("pointerup", handlePointerUp)
    window.addEventListener("pointercancel", handlePointerCancel)
    window.addEventListener("blur", handleWindowBlur)
  }

  function adjustSidebarWidth(delta: number) {
    const rect = appShellRef.current?.getBoundingClientRect()
    const bounds = resolveLeftSidebarBounds(rect?.width)
    setSidebarWidth((current) => {
      const nextWidth = clamp(current + delta, bounds.min, bounds.max)
      lastExpandedSidebarWidthRef.current = nextWidth
      return nextWidth
    })
  }

  function adjustRightSidebarWidth(delta: number) {
    const rect = appShellRef.current?.getBoundingClientRect()
    const bounds = resolveRightSidebarBounds(rect?.width)
    setRightSidebarWidth((current) => {
      const nextWidth = clamp(current + delta, bounds.min, bounds.max)
      lastExpandedRightSidebarWidthRef.current = nextWidth
      return nextWidth
    })
  }

  function restoreSidebar() {
    const rect = appShellRef.current?.getBoundingClientRect()
    const bounds = resolveLeftSidebarBounds(rect?.width)
    const nextWidth = clamp(lastExpandedSidebarWidthRef.current, bounds.min, bounds.max)
    setSidebarWidth(nextWidth)
    setIsSidebarCollapsed(false)
  }

  function restoreRightSidebar() {
    const rect = appShellRef.current?.getBoundingClientRect()
    const bounds = resolveRightSidebarBounds(rect?.width)
    const nextWidth = clamp(lastExpandedRightSidebarWidthRef.current, bounds.min, bounds.max)
    setRightSidebarWidth(nextWidth)
    setIsRightSidebarCollapsed(false)
  }

  function handleSidebarResizerPointerDown(event: PointerEvent<HTMLDivElement>) {
    if (event.button !== 0) return

    const rect = appShellRef.current?.getBoundingClientRect()
    if (!rect || rect.width <= 0) return

    activeSidebarResizeCleanupRef.current?.()
    captureSidebarResizerPointer(event)
    const bounds = resolveLeftSidebarBounds(rect.width)
    const resizeState: ActiveSidebarResize = {
      appShell: appShellRef.current!,
      bounds,
      containerLeft: rect.left,
      containerRight: rect.right,
      didCommit: false,
      frameID: null,
      latestWidth: sidebarWidth,
      leftRailDisplayWidth: getLeftRailDisplayWidth(),
      originalWidth: sidebarWidth,
      side: "left",
    }
    queueSidebarResizePreview(resizeState, resolveSidebarResizeWidth(resizeState, event.clientX))

    event.preventDefault()
    startSidebarResize(resizeState)
  }

  function handleRightSidebarResizerPointerDown(event: PointerEvent<HTMLDivElement>) {
    if (event.button !== 0) return

    const rect = appShellRef.current?.getBoundingClientRect()
    if (!rect || rect.width <= 0) return

    activeSidebarResizeCleanupRef.current?.()
    captureSidebarResizerPointer(event)
    const bounds = resolveRightSidebarBounds(rect.width)
    const resizeState: ActiveSidebarResize = {
      appShell: appShellRef.current!,
      bounds,
      containerLeft: rect.left,
      containerRight: rect.right,
      didCommit: false,
      frameID: null,
      latestWidth: rightSidebarWidth,
      leftRailDisplayWidth: getLeftRailDisplayWidth(),
      originalWidth: rightSidebarWidth,
      side: "right",
    }
    queueSidebarResizePreview(resizeState, resolveSidebarResizeWidth(resizeState, event.clientX))

    event.preventDefault()
    startSidebarResize(resizeState)
  }

  function handleSidebarResizerKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    if (event.key === "ArrowLeft") {
      event.preventDefault()
      adjustSidebarWidth(-SIDEBAR_KEYBOARD_STEP)
      return
    }

    if (event.key === "ArrowRight") {
      event.preventDefault()
      adjustSidebarWidth(SIDEBAR_KEYBOARD_STEP)
      return
    }

    const rect = appShellRef.current?.getBoundingClientRect()
    const bounds = resolveLeftSidebarBounds(rect?.width)

    if (event.key === "Home") {
      event.preventDefault()
      lastExpandedSidebarWidthRef.current = bounds.min
      setSidebarWidth(bounds.min)
      return
    }

    if (event.key === "End") {
      event.preventDefault()
      lastExpandedSidebarWidthRef.current = bounds.max
      setSidebarWidth(bounds.max)
    }
  }

  function handleRightSidebarResizerKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    if (event.key === "ArrowLeft") {
      event.preventDefault()
      adjustRightSidebarWidth(SIDEBAR_KEYBOARD_STEP)
      return
    }

    if (event.key === "ArrowRight") {
      event.preventDefault()
      adjustRightSidebarWidth(-SIDEBAR_KEYBOARD_STEP)
      return
    }

    const rect = appShellRef.current?.getBoundingClientRect()
    const bounds = resolveRightSidebarBounds(rect?.width)

    if (event.key === "Home") {
      event.preventDefault()
      lastExpandedRightSidebarWidthRef.current = bounds.min
      setRightSidebarWidth(bounds.min)
      return
    }

    if (event.key === "End") {
      event.preventDefault()
      lastExpandedRightSidebarWidthRef.current = bounds.max
      setRightSidebarWidth(bounds.max)
    }
  }

  function handleSidebarToggle() {
    if (isSidebarCollapsed) {
      restoreSidebar()
      return
    }

    lastExpandedSidebarWidthRef.current = sidebarWidth
    activeSidebarResizeCleanupRef.current?.()
    setIsSidebarCollapsed(true)
  }

  function handleRightSidebarToggle() {
    if (isRightSidebarCollapsed) {
      restoreRightSidebar()
      return
    }

    lastExpandedRightSidebarWidthRef.current = rightSidebarWidth
    activeSidebarResizeCleanupRef.current?.()
    setIsRightSidebarCollapsed(true)
  }

  function handleActivityRailVisibilityChange(nextVisible: boolean) {
    if (!nextVisible) {
      activeSidebarResizeCleanupRef.current?.()
    }

    setIsActivityRailVisible(nextVisible)
  }

  function handleDebugUiRegionsChange(nextEnabled: boolean) {
    setIsDebugUiRegionsEnabled(nextEnabled)
  }

  function handleDebugLineColorsChange(nextEnabled: boolean) {
    setIsDebugLineColorsEnabled(nextEnabled)
  }

  function handleAssistantTraceVisibilityChange(key: AssistantTraceVisibilityKey, nextEnabled: boolean) {
    setAssistantTraceVisibility((current) => {
      if (current[key] === nextEnabled) return current
      return {
        ...current,
        [key]: nextEnabled,
      }
    })
  }

  function handleAgentDebugTraceChange(nextEnabled: boolean) {
    handleAssistantTraceVisibilityChange("debugMetadata", nextEnabled)
  }

  function handleAppearanceTokenChange(tokenName: AppearanceTokenName, nextValue: string) {
    const normalizedValue = normalizeAppearanceColorInputValue(nextValue)

    setAppearanceOverrides((current) => {
      if (current[tokenName] === normalizedValue) return current

      return {
        ...current,
        [tokenName]: normalizedValue,
      }
    })
  }

  function handleAppearanceTokenReset(tokenName: AppearanceTokenName) {
    setAppearanceOverrides((current) => {
      if (!(tokenName in current)) return current

      const nextOverrides = { ...current }
      delete nextOverrides[tokenName]
      return nextOverrides
    })
  }

  function handleAppearancePaletteReset() {
    setAppearanceOverrides({})
  }

  const handleWindowAction = useCallback((action: WindowAction) => {
    if (!window.desktop?.windowAction) {
      console.warn("[desktop] windowAction is unavailable. preload may not be loaded.")
      return
    }

    void window.desktop.windowAction(action).catch((error) => {
      console.error("[desktop] windowAction failed:", error)
    })
  }, [])

  const appShellStyle = {
    "--window-controls-clearance": `${windowControlsClearance}px`,
    "--window-controls-canvas-clearance": "0px",
    "--window-controls-right-sidebar-clearance": "0px",
    "--activity-rail-display-width": isActivityRailVisible ? "54px" : "0px",
    "--sidebar-display-width": isSidebarCollapsed ? "0px" : `${sidebarWidth}px`,
    "--sidebar-resizer-width": isSidebarCollapsed ? "0px" : "1px",
    "--sidebar-width": `${sidebarWidth}px`,
    "--right-sidebar-display-width": isRightSidebarCollapsed ? "0px" : `${rightSidebarWidth}px`,
    "--right-sidebar-resizer-width": isRightSidebarCollapsed ? "0px" : "1px",
    "--right-sidebar-width": `${rightSidebarWidth}px`,
  } as CSSProperties

  const currentAppShellWidth = appShellRef.current?.getBoundingClientRect().width
  const sidebarWidthBounds = resolveLeftSidebarBounds(currentAppShellWidth)
  const rightSidebarWidthBounds = resolveRightSidebarBounds(currentAppShellWidth)
  const appearanceConfigPreview = JSON.stringify(
    {
      version: 1,
      path: appearanceConfigPath,
      brandTheme,
      colorMode,
      overrides: appearanceOverrides,
      resolvedTokens: appearanceTokenValues,
    },
    null,
    2,
  )

  return {
    agentConnected,
    agentDefaultDirectory,
    appearanceConfigError,
    appearanceConfigPath,
    appearanceConfigPreview,
    appearanceOverrides,
    appearanceTokenValues,
    assistantTraceVisibility,
    appShellRef,
    appShellStyle,
    brandTheme,
    colorMode,
    handleBrandThemeChange: setBrandTheme,
    handleColorModeChange: setColorMode,
    handleActivityRailVisibilityChange,
    handleAppearancePaletteReset,
    handleAppearanceTokenChange,
    handleAppearanceTokenReset,
    handleAssistantTraceVisibilityChange,
    handleAgentDebugTraceChange,
    handleDebugLineColorsChange,
    handleDebugUiRegionsChange,
    handleSidebarResizerKeyDown,
    handleSidebarResizerPointerDown,
    handleSidebarToggle,
    handleRightSidebarResizerKeyDown,
    handleRightSidebarResizerPointerDown,
    handleRightSidebarToggle,
    handleWindowAction,
    isActivityRailVisible,
    isAgentDebugTraceEnabled,
    isDebugLineColorsEnabled,
    isDebugUiRegionsEnabled,
    isSidebarCollapsed,
    isSidebarResizing,
    isRightSidebarCollapsed,
    isRightSidebarResizing,
    isWindowMaximized,
    platform,
    rightSidebarWidthBounds,
    rightSidebarWidth,
    sidebarWidthBounds,
    sidebarWidth,
    windowControlsRef,
  }
}
