import { useEffect, useState } from "react";
import type { LoopMode, ObjectFit } from "../types.ts";
import { getNumberFromStorage, getStringFromStorage, saveToStorage } from "../utils";

export function usePlayerState() {
  const [isPlaying, setIsPlaying] = useState(true);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [volume, setVolume] = useState(() => getNumberFromStorage("aweme_player_volume", 1));
  const [rate, setRate] = useState(() => getNumberFromStorage("aweme_player_rate", 1));
  const [progress, setProgress] = useState(0);
  const [rotation, setRotation] = useState(0);
  const [progressRestored, setProgressRestored] = useState(false);
  const [objectFit, setObjectFit] = useState<ObjectFit>("contain");
  const [loopMode, setLoopMode] = useState<LoopMode>(() => {
    const saved = getStringFromStorage("aweme_player_loop_mode", "loop");
    return saved === "sequential" ? "sequential" : "loop";
  });

  // 持久化音量
  useEffect(() => {
    saveToStorage("aweme_player_volume", volume);
  }, [volume]);

  // 持久化倍速
  useEffect(() => {
    saveToStorage("aweme_player_rate", rate);
  }, [rate]);

  // 持久化循环模式
  useEffect(() => {
    saveToStorage("aweme_player_loop_mode", loopMode);
  }, [loopMode]);

  // 监听全屏状态
  useEffect(() => {
    const onFsChange = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener("fullscreenchange", onFsChange);
    return () => document.removeEventListener("fullscreenchange", onFsChange);
  }, []);

  return {
    isPlaying,
    setIsPlaying,
    isFullscreen,
    setIsFullscreen,
    volume,
    setVolume,
    rate,
    setRate,
    progress,
    setProgress,
    rotation,
    setRotation,
    progressRestored,
    setProgressRestored,
    objectFit,
    setObjectFit,
    loopMode,
    setLoopMode,
  };
}
