import { installSfxRuntime } from './utils/sfx.js'
import React from 'react'
import ReactDOM from 'react-dom/client'
import { MemoryRouter, useLocation, useNavigate, useNavigationType } from 'react-router-dom'
import { getLastPath, rememberPath, setCurrentAppPath } from './lib/singleUrl.js'
import App from './App.jsx'
import './index.css'
import './home-widgets.css'
import './chatShapes.css'

// 兜底：把 React 挂到全局，避免某些库在开发态访问全局 React
window.React = React

// V754：应用启动即注册 /sw.js。Android Chrome/Edge 判定「可安装 PWA」需要站点已注册
// Service Worker；此前 SW 只在开启消息提醒时才注册，导致未开启提醒的设备「添加到桌面」
// 退化成普通快捷方式，桌面图标取不到 manifest 里的自定义图片。
// V758：SW 增加了运行时缓存（页面 network-first、哈希资源 cache-first）。
// 仅在生产环境注册——开发态 vite 的模块 URL 每次启动都变，缓存只会带来干扰。
if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator && import.meta.env.PROD) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => {})
  })
}

// V774：全站文本输入框默认关闭「自动填充」建议条（键盘上方带钥匙/银行卡/个人信息图标的那一行）。
// 只处理 text/search/textarea；密码、邮箱、电话、数字等类型不动；组件自己写了 autocomplete 的也不覆盖。
if (typeof document !== 'undefined' && typeof MutationObserver !== 'undefined') {
  const OK_TYPES = new Set(['', 'text', 'search'])
  const markNoAutofill = (el) => {
    if (!el || el.nodeType !== 1 || el.hasAttribute('data-mp-noautofill')) return
    if (el.tagName === 'INPUT' && !OK_TYPES.has((el.getAttribute('type') || '').toLowerCase())) return
    if (!el.hasAttribute('autocomplete')) el.setAttribute('autocomplete', 'off')
    el.setAttribute('data-lpignore', 'true')
    el.setAttribute('data-1p-ignore', 'true')
    el.setAttribute('data-form-type', 'other')
    el.setAttribute('data-mp-noautofill', '1')
  }
  const scan = (root) => {
    if (!root || root.nodeType !== 1) return
    if (root.matches?.('input, textarea')) markNoAutofill(root)
    root.querySelectorAll?.('input, textarea').forEach(markNoAutofill)
  }
  scan(document.documentElement)
  new MutationObserver((records) => {
    for (const r of records) r.addedNodes.forEach(scan)
  }).observe(document.documentElement, { childList: true, subtree: true })
}

// V780：键盘弹出时给 <html> 挂 mp-kb-open 类。
// Android（Edge/Chrome）弹键盘默认只平移视觉视口、不缩小布局视口，输入栏的
// safe-area-inset-bottom 内边距会整段露在输入栏和键盘之间（一条空白带）。
// 键盘高度 ≈ innerHeight - visualViewport.height，超过阈值即认为键盘弹出；
// CSS 侧据此收起输入栏底部内边距，让输入栏贴住键盘。
if (typeof window !== 'undefined' && window.visualViewport) {
  const syncKbClass = () => {
    const kbHeight = window.innerHeight - window.visualViewport.height
    document.documentElement.classList.toggle('mp-kb-open', kbHeight > 120)
  }
  window.visualViewport.addEventListener('resize', syncKbClass)
  window.addEventListener('resize', syncKbClass)
  syncKbClass()
}

// 水合等待 + 引擎初始化现在都挪进了 App.jsx 的 isBooting 状态里；
// 业务页面会在水合完成后渲染，日常“星图指引”再以纯视觉覆盖层显示。
let INITIAL_DEPTH = 1
function PathTracker() {
  // 浏览器历史与应用内页面栈一一对应：应用内每「进」一页就真实 pushState 一条（发生在用户点击里，
  // 浏览器不会把它当作无交互记录跳过），按返回键时再把应用内也退一页。
  const loc = useLocation()
  const navigate = useNavigate()
  const navType = useNavigationType()
  const depth = React.useRef(INITIAL_DEPTH)
  const skipPops = React.useRef(0) // 我们自己调 history.go 引起的 popstate，不再反向处理
  const fromBrowser = React.useRef(false)
  const first = React.useRef(true)
  React.useEffect(() => {
    setCurrentAppPath(loc.pathname)
    rememberPath(loc.pathname + loc.search)
    if (first.current) { first.current = false; return }
    try {
      if (navType === 'PUSH') { depth.current += 1; window.history.pushState({ mp: depth.current }, '', '/') }
      else if (navType === 'POP') {
        depth.current = Math.max(1, depth.current - 1)
        if (fromBrowser.current) fromBrowser.current = false
        else { skipPops.current += 1; window.history.go(-1) } // 应用内「返回」：同步退掉浏览器多出的那一条
      }
    } catch { /* ignore */ }
  }, [loc.key]) // eslint-disable-line react-hooks/exhaustive-deps
  React.useEffect(() => {
    const onPop = () => {
      if (skipPops.current > 0) { skipPops.current -= 1; return }
      if (depth.current > 1) { fromBrowser.current = true; navigate(-1) }
      // 已在最底层：不处理，浏览器正常离开本站
    }
    window.addEventListener('popstate', onPop)
    return () => window.removeEventListener('popstate', onPop)
  }, [navigate])
  return null
}

// 固定使用单一网址：地址栏始终是站点根地址。
// 起始栈 = [首页, 上次所在页]：刷新后点页面左上角的返回，也能退回首页而不是没反应。
const startPath = (typeof window !== 'undefined' && window.location.pathname !== '/') ? window.location.pathname + window.location.search : getLastPath()
const initialEntries = startPath && startPath !== '/' ? ['/', startPath] : ['/']
INITIAL_DEPTH = initialEntries.length
if (typeof window !== 'undefined') {
  try {
    window.history.replaceState({ mp: 1 }, '', '/')
    for (let i = 2; i <= initialEntries.length; i += 1) window.history.pushState({ mp: i }, '', '/')
  } catch { /* ignore */ }
}

installSfxRuntime()

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <MemoryRouter initialEntries={initialEntries} initialIndex={initialEntries.length - 1}><PathTracker /><App /></MemoryRouter>
  </React.StrictMode>,
)
