"use client"

import { useEffect, useState } from "react"

export type Position = { x: number; y: number }

export const STORAGE_KEY = "ai-widget-position"
export const HIDE_THRESHOLD = 0.55
export const BALL_SIZE = 56
export const MARGIN = 16

/**
 * 将位置限制在视口内
 */
export function clampPosition(pos: Position): Position {
  if (typeof window === "undefined") return pos
  const maxX = window.innerWidth - BALL_SIZE - MARGIN
  const maxY = window.innerHeight - BALL_SIZE - MARGIN
  return {
    x: Math.min(Math.max(pos.x, MARGIN), Math.max(maxX, MARGIN)),
    y: Math.min(Math.max(pos.y, MARGIN), Math.max(maxY, MARGIN)),
  }
}

/**
 * 从 localStorage 加载位置，失败时返回默认右下角位置
 */
export function loadPosition(): Position {
  if (typeof window === "undefined") {
    return { x: 9999, y: 9999 }
  }
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (raw) {
      const parsed = JSON.parse(raw) as Partial<Position>
      if (typeof parsed.x === "number" && typeof parsed.y === "number") {
        return clampPosition({ x: parsed.x, y: parsed.y })
      }
    }
  } catch {
    // ignore
  }
  const x = window.innerWidth - BALL_SIZE - MARGIN * 2
  const y = window.innerHeight - BALL_SIZE - MARGIN * 4
  return clampPosition({ x, y })
}

/**
 * 持久化位置到 localStorage
 */
export function savePosition(pos: Position): void {
  if (typeof window === "undefined") return
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(pos))
  } catch {
    // ignore
  }
}

/**
 * 默认位置（右下角）
 */
export function getDefaultPosition(): Position {
  if (typeof window === "undefined") return { x: 9999, y: 9999 }
  return clampPosition({
    x: window.innerWidth - BALL_SIZE - MARGIN * 2,
    y: window.innerHeight - BALL_SIZE - MARGIN * 4,
  })
}

/**
 * 位置持久化 Hook
 *
 * 管理 position 状态，mount 时从 localStorage 加载，resize 时校正。
 * 服务端与客户端首次渲染一致（position 在屏幕外），避免 hydration mismatch。
 */
export function usePositionPersistence(): {
  position: Position
  setPosition: React.Dispatch<React.SetStateAction<Position>>
} {
  const [position, setPosition] = useState<Position>({ x: 9999, y: 9999 })

  // 初始化位置：在客户端 mount 后加载真实位置
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setPosition(loadPosition())
  }, [])

  // 窗口 resize 时校正
  useEffect(() => {
    const handleResize = (): void => {
      setPosition((prev) => clampPosition(prev))
    }
    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [])

  return { position, setPosition }
}
