import { ref, computed } from "vue";
import { debounce } from "../utils/common.js";

// 当前激活的栏索引（用于TV导航）
const activeColumnIndex = ref(0);
const leftPanelVisible = ref(false);
const bottomPanelVisible = ref(false);

// 当前选中的分组/频道/日期/节目
const selectedGroup = ref("");
const selectedChannel = ref(null);
const selectedDate = ref("");
const selectedProgram = ref(null);

export function useUI() {
  const platform = import.meta.env.VITE_PLATFORM || "web";
  const isTV = platform === "tv";

  // 显示左侧面板
  const showLeftPanel = () => {
    leftPanelVisible.value = true;
    bottomPanelVisible.value = false;
    activeColumnIndex.value = 0;
  };

  // 隐藏左侧面板
  const hideLeftPanel = () => {
    leftPanelVisible.value = false;
    activeColumnIndex.value = 0;
  };

  // 切换左侧面板
  const toggleLeftPanel = () => {
    if (leftPanelVisible.value) {
      hideLeftPanel();
    } else {
      showLeftPanel();
    }
  };

  // 显示底部栏（启动防抖隐藏）
  const showBottomPanel = () => {
    bottomPanelVisible.value = true;
    hideBottomPanel();
  };

  // 隐藏底部栏
  const hideBottomPanel = debounce(() => {
    bottomPanelVisible.value = false;
  }, 3000);

  // 设置选中项
  const setSelectedGroup = (group) => {
    selectedGroup.value = group;
  };

  const setSelectedChannel = (channel) => {
    selectedChannel.value = channel;
  };

  const setSelectedDate = (date) => {
    selectedDate.value = date;
  };

  const setSelectedProgram = (program) => {
    selectedProgram.value = program;
  };

  // TV 导航：切换栏
  const moveColumn = (direction) => {
    if (!leftPanelVisible.value) return;

    const maxIndex = 3; // 0-3 四栏
    if (direction === "right") {
      activeColumnIndex.value = Math.min(activeColumnIndex.value + 1, maxIndex);
    } else if (direction === "left") {
      activeColumnIndex.value = Math.max(activeColumnIndex.value - 1, 0);
    }
  };

  // TV 导航：获取当前激活的栏索引
  const currentActiveColumn = computed(() => activeColumnIndex.value);

  return {
    // 状态
    leftPanelVisible,
    bottomPanelVisible,
    selectedGroup,
    selectedChannel,
    selectedDate,
    selectedProgram,

    // 计算属性
    isTV,
    currentActiveColumn,

    // 方法
    showLeftPanel,
    hideLeftPanel,
    toggleLeftPanel,
    showBottomPanel,
    hideBottomPanel,
    setSelectedGroup,
    setSelectedChannel,
    setSelectedDate,
    setSelectedProgram,
    moveColumn,
  };
}
