/**
 * 充电桩大盘 - 主入口模块
 */

import { CONFIG } from './config.js';
import { state } from './state.js';
import { getPollModeText, startPolling } from './polling.js';
import { loadCacheFromStorage, updateFreeCache } from './cache.js';
import { renderStation, setFilter } from './render.js';
import { refreshData, retryConnect, showSubscribeModal, hideSubscribeModal, submitSubscribe } from './api.js';
import { getMockResponse } from './mock.js';
import { initAnalytics, destroyCharts, setAnalyticsDays } from './analytics.js';
import { initMockSettings, getMockSettings, isMockWorkday } from './mock-settings.js';
import { initGuideModal, showGuideModal, hideGuideModal } from './guide-modal.js';
import { showCommentModal, hideCommentModal, fillComment, submitComment } from './comment.js';
import { initVisit } from './visit.js';
import { play as playDCIntro } from './dc-intro.js';
import { celebrate } from './dc-celebration.js';
import { refreshIcons, refreshIconsNow } from './utils.js';

// 暴露全局函数供 HTML onclick 使用
window.refreshData = refreshData;
window.retryConnect = retryConnect;
window.setFilter = (filter) => setFilter(filter, state.station);
window.showSubscribeModal = showSubscribeModal;
window.hideSubscribeModal = hideSubscribeModal;
window.submitSubscribe = submitSubscribe;
window.switchTab = switchTab;
window.setAnalyticsDays = setAnalyticsDays;
window.checkNotifyTime = checkNotifyTime;
window.showGuideModal = showGuideModal;
window.hideGuideModal = hideGuideModal;
window.showCommentModal = showCommentModal;
window.hideCommentModal = hideCommentModal;
window.fillComment = fillComment;
window.submitComment = submitComment;

// Mock 模式并发保护锁
let mockRefreshLock = false;

// 当前激活的 Tab（暴露给 api.js 使用）
window.currentTab = 'monitor';
const DC_INTRO_PLAYED_KEY = 'dc_intro_played';

/**
 * 切换 Tab（实时监控 / 数据分析）
 */
function switchTab(tab) {
  if (tab === window.currentTab) return;
  window.currentTab = tab;

  // 更新桌面端 Tab 按钮样式
  const monitorBtn = document.getElementById('tab-monitor');
  const analyticsBtn = document.getElementById('tab-analytics');

  // 更新移动端底部导航按钮样式
  const mobileMonitorBtn = document.getElementById('mobile-tab-monitor');
  const mobileAnalyticsBtn = document.getElementById('mobile-tab-analytics');

  // 基础类（桌面端）
  const baseClasses = 'nav-tab px-4 py-2 text-sm font-medium transition-all duration-300 rounded-full whitespace-nowrap';

  // 移动端基础类
  const mobileBaseClasses = 'flex flex-col items-center gap-1 py-2 px-6 rounded-xl transition-all';

  // 移动端订阅栏
  const mobileSubscribeBar = document.getElementById('mobile-subscribe-bar');

  if (tab === 'monitor') {
    // 桌面端
    if (monitorBtn) monitorBtn.className = baseClasses + ' active bg-slate-800 text-white';
    if (analyticsBtn) analyticsBtn.className = baseClasses + ' text-slate-500 hover:text-slate-300';

    // 移动端
    if (mobileMonitorBtn) mobileMonitorBtn.className = mobileBaseClasses + ' text-emerald-400 bg-emerald-500/10';
    if (mobileAnalyticsBtn) mobileAnalyticsBtn.className = mobileBaseClasses + ' text-slate-500';

    document.getElementById('data-content').classList.remove('hidden');
    document.getElementById('analytics-content').classList.add('hidden');

    // 显示底部栏/导航
    const bottomBar = document.getElementById('bottom-bar');
    const mobileNav = document.getElementById('mobile-nav');
    if (bottomBar) {
      bottomBar.style.display = '';
      bottomBar.classList.remove('hidden');
    }
    if (mobileNav) mobileNav.classList.remove('hidden');
    if (mobileSubscribeBar) mobileSubscribeBar.classList.remove('hidden');
  } else {
    // 桌面端
    if (analyticsBtn) analyticsBtn.className = baseClasses + ' active bg-slate-800 text-white';
    if (monitorBtn) monitorBtn.className = baseClasses + ' text-slate-500 hover:text-slate-300';

    // 移动端
    if (mobileAnalyticsBtn) mobileAnalyticsBtn.className = mobileBaseClasses + ' text-cyan-400 bg-cyan-500/10';
    if (mobileMonitorBtn) mobileMonitorBtn.className = mobileBaseClasses + ' text-slate-500';

    document.getElementById('data-content').classList.add('hidden');
    document.getElementById('analytics-content').classList.remove('hidden');

    // 隐藏底部订阅栏
    const bottomBar = document.getElementById('bottom-bar');
    if (bottomBar) {
      bottomBar.style.display = 'none';
      bottomBar.classList.add('hidden');
    }
    if (mobileSubscribeBar) mobileSubscribeBar.classList.add('hidden');

    // 加载分析数据
    const groupId = CONFIG.STATION_ID;
    initAnalytics(groupId);
  }

  refreshIcons();
}

/**
 * 检查是否使用 Mock 模式
 */
function isMockMode() {
  // URL 参数指定 mock 模式
  const params = new URLSearchParams(window.location.search);
  if (params.get('mock') === 'true') return true;

  // localhost 且无后端服务时使用 mock
  if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    // 检查是否有 mock 参数或后端不可用
    return params.has('mock') || !window.RUNTIME_CONFIG?.apiAvailable;
  }

  return false;
}

/**
 * Mock 模式下的数据刷新
 */
async function refreshDataMock(silent = false) {
  // 并发保护：如果正在刷新则跳过
  if (mockRefreshLock) return;
  mockRefreshLock = true;

  const icon = document.getElementById('refresh-icon');
  if (!silent) {
    icon.classList.add('animate-spin');
  }

  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));

    const result = getMockResponse();
    state.station = result.data;
    updateFreeCache(result.data.connectors);
    renderStation(result.data);
    document.getElementById('error-state').classList.add('hidden');
    // 仅在监控 Tab 时显示 data-content
    if (window.currentTab !== 'analytics') {
      document.getElementById('data-content').classList.remove('hidden');
    }
    updateHeaderStatusMock(true, result.data.fetch_time);
    refreshIcons();
  } catch (e) {
    console.error('Mock 刷新失败:', e);
  } finally {
    mockRefreshLock = false;
    icon.classList.remove('animate-spin');
  }
}

/**
 * Mock 模式下的头部状态更新
 */
function updateHeaderStatusMock(online, time) {
  const statusEl = document.getElementById('header-status');
  const pollMode = 'Mock 模式 · 10秒刷新';

  if (online === true) {
    statusEl.innerHTML = `
      <span class="relative flex h-2 w-2">
        <span class="animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 bg-emerald-400"></span>
        <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
      </span>
      <span>数据更新于 ${time} · ${pollMode}</span>
    `;
  }
}

/**
 * 从充电桩数据中提取空闲 DC 列表
 */
function extractFreeDCList(station) {
  if (!station || !station.connectors) return [];
  return station.connectors
    .filter(c => c.type === 'DC' && c.state.type === 'free')
    .map(c => ({
      name: simplifyName(c.connector_name),
      power: String(c.power || '20'),
    }));
}

/**
 * 简化充电桩名称（用于卡牌显示）
 */
function simplifyName(name) {
  const sslMatch = name.match(/SSL-(\d+)/);
  if (sslMatch) return `${sslMatch[1]}号桩`;
  const jsfMatch = name.match(/JSF-(\d+)/);
  if (jsfMatch) return `J${jsfMatch[1]}号桩`;
  return name;
}

/**
 * 检查通知时间
 */
function checkNotifyTime() {
  // Mock 模式下使用 Mock 设置的时间判断
  const isMockModeActive = isMockMode();
  const isWeekday = isMockModeActive ? isMockWorkday() : (new Date().getDay() >= 1 && new Date().getDay() <= 5);
  state.isWeekday = isWeekday;

  // 桌面端订阅栏
  const bottomBar = document.getElementById('bottom-bar');
  const barTitle = document.getElementById('bar-title');
  const barSubtitle = document.getElementById('bar-subtitle');
  const subscribeBtn = document.getElementById('subscribe-btn');

  // 移动端订阅栏
  const mobileSubscribeBar = document.getElementById('mobile-subscribe-bar');
  const mobileBarTitle = document.getElementById('mobile-bar-title');
  const mobileBarSubtitle = document.getElementById('mobile-bar-subtitle');
  const mobileSubscribeBtn = document.getElementById('mobile-subscribe-btn');

  if (!isWeekday) {
    // 周末：置灰显示，不可点击
    if (bottomBar) bottomBar.classList.add('opacity-50', 'pointer-events-none');
    if (barTitle) barTitle.textContent = '无法周末订阅';
    if (barSubtitle) barSubtitle.textContent = '需要下周工作日才可以';
    if (subscribeBtn) subscribeBtn.disabled = true;

    // 移动端
    if (mobileSubscribeBar) mobileSubscribeBar.classList.add('opacity-50', 'pointer-events-none');
    if (mobileBarTitle) mobileBarTitle.textContent = '无法周末订阅';
    if (mobileBarSubtitle) mobileBarSubtitle.textContent = '下周工作日才可以';
    if (mobileSubscribeBtn) mobileSubscribeBtn.disabled = true;
  } else {
    // 工作日：正常显示
    if (bottomBar) bottomBar.classList.remove('opacity-50', 'pointer-events-none');
    if (barTitle) barTitle.textContent = '不想下楼扑空？';
    if (barSubtitle) barSubtitle.textContent = '有空位自动邮件叫你';
    if (subscribeBtn) subscribeBtn.disabled = false;

    // 移动端
    if (mobileSubscribeBar) mobileSubscribeBar.classList.remove('opacity-50', 'pointer-events-none');
    if (mobileBarTitle) mobileBarTitle.textContent = '不想下楼扑空？';
    if (mobileBarSubtitle) mobileBarSubtitle.textContent = '有空位自动邮件叫你';
    if (mobileSubscribeBtn) mobileSubscribeBtn.disabled = false;
  }
}

function shouldPlayDCIntro(freeDCList) {
  if (freeDCList.length === 0) return false;
  try {
    if (sessionStorage.getItem(DC_INTRO_PLAYED_KEY) === '1') return false;
    sessionStorage.setItem(DC_INTRO_PLAYED_KEY, '1');
  } catch (e) {
    // sessionStorage 不可用时仍允许播放一次当前流程
  }
  return true;
}

async function playIntroIfNeeded() {
  const freeDCList = extractFreeDCList(state.station);
  console.log('[dc-intro] freeDCList:', freeDCList.length, freeDCList);
  if (!shouldPlayDCIntro(freeDCList)) return;

  const introEl = document.getElementById('dc-intro');
  if (introEl) introEl.style.display = '';
  await playDCIntro(freeDCList);
  setTimeout(() => celebrate(freeDCList.length), 200);
}

/**
 * 初始化应用
 */
function init() {
  console.log('[初始化] 充电桩大盘启动');
  console.log('[模式]', isMockMode() ? 'Mock 数据' : '真实 API');

  refreshIconsNow();
  loadCacheFromStorage();
  checkNotifyTime();

  // 显示引导弹窗（首次访问或缓存过期时）
  initGuideModal();

  // 初始化 Mock 设置面板（仅 localhost 环境）
  initMockSettings();

  if (isMockMode()) {
    // Mock 模式：使用模拟数据
    window.refreshData = refreshDataMock;

    // 初始加载并检查是否有空闲 DC，触发入场特效
    (async () => {
      await refreshDataMock();
      await playIntroIfNeeded();
    })();

    // 10秒刷新一次（演示用）
    function scheduleMockRefresh() {
      setTimeout(() => {
        refreshDataMock(true).finally(() => {
          scheduleMockRefresh();
        });
      }, 10000);
    }
    scheduleMockRefresh();
  } else {
    // 真实模式：调用后端 API
    (async () => {
      await refreshData();
      await playIntroIfNeeded();
      startPolling(refreshData);
    })();
  }

  // 访问统计（不阻塞页面）
  initVisit();
}

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', init);
