/**
 * 充电桩大盘 - 访问统计模块
 * 记录 PV/UV，左侧边缘显示今日访问次数
 */

import { CONFIG } from './config.js';

// Mock 模式检测
function isMockMode() {
  const params = new URLSearchParams(window.location.search);
  if (params.get('mock') === 'true') return true;
  if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    return params.has('mock') || !window.RUNTIME_CONFIG?.apiAvailable;
  }
  return false;
}

/**
 * 生成设备指纹哈希（SHA256 前16位）
 * 使用 localStorage UUID + User-Agent 组合
 */
async function getDeviceHash() {
  let uuid = localStorage.getItem('visit_device_id');
  if (!uuid) {
    uuid = crypto.randomUUID ? crypto.randomUUID() :
      'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = Math.random() * 16 | 0;
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
      });
    localStorage.setItem('visit_device_id', uuid);
  }

  const raw = uuid + navigator.userAgent;

  try {
    const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
    return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('').slice(0, 16);
  } catch {
    // fallback: 简单哈希（HTTP 环境无 crypto.subtle）
    let h1 = 0, h2 = 0;
    for (let i = 0; i < raw.length; i++) {
      h1 = ((h1 << 5) - h1 + raw.charCodeAt(i)) | 0;
      h2 = ((h2 << 7) - h2 + raw.charCodeAt(i) * 31) | 0;
    }
    return Math.abs(h1).toString(16).padStart(8, '0') + Math.abs(h2).toString(16).padStart(8, '0');
  }
}

/**
 * 上报访问（sendBeacon + fetch fallback）
 * 返回今日统计 {pv, uv}，失败返回 null
 */
async function reportVisit(deviceHash) {
  const body = JSON.stringify({ device_hash: deviceHash });

  // 尝试 sendBeacon（不阻塞页面）
  try {
    const blob = new Blob([body], { type: 'application/json' });
    const sent = navigator.sendBeacon(`${CONFIG.API_BASE}/visit`, blob);
    if (sent) {
      // sendBeacon 无法读取响应，延迟获取统计
      await new Promise(r => setTimeout(r, 500));
      return await fetchTodayStats();
    }
  } catch {}

  // fallback: fetch keepalive
  try {
    const res = await fetch(`${CONFIG.API_BASE}/visit`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body,
      keepalive: true
    });
    const result = await res.json();
    if (result.success) return result.data;
  } catch {}

  return null;
}

/**
 * 获取今日统计
 */
async function fetchTodayStats() {
  try {
    const res = await fetch(`${CONFIG.API_BASE}/visit/today`);
    const result = await res.json();
    if (result.success) return result.data;
  } catch {}
  return null;
}

/**
 * 渲染访问次数悬浮标牌
 */
function renderVisitBadge(pv) {
  const existing = document.getElementById('visit-badge');
  if (existing) {
    existing.querySelector('.visit-count').textContent = pv;
    return;
  }

  const badge = document.createElement('div');
  badge.id = 'visit-badge';
  badge.className = 'visit-badge';
  badge.innerHTML = `今日访问 <span class="visit-count">${pv}</span> 次`;
  document.body.appendChild(badge);
}

/**
 * 初始化访问统计
 */
export async function initVisit() {
  // Mock 模式显示静态数据
  if (isMockMode()) {
    renderVisitBadge(42);
    return;
  }

  const deviceHash = await getDeviceHash();
  const stats = await reportVisit(deviceHash);

  if (stats) {
    renderVisitBadge(stats.pv);
  }

  // 每 5 分钟刷新统计（不重新上报）
  setInterval(async () => {
    const fresh = await fetchTodayStats();
    if (fresh) renderVisitBadge(fresh.pv);
  }, 5 * 60 * 1000);
}
