import { lazy, Suspense, useEffect } from "react"
import { Routes, Route, Navigate, useLocation, useParams, useSearchParams } from "react-router-dom"
import { Spin } from "antd"
import AuthLayout from "./layouts/AuthLayout"
import DashboardLayout from "./layouts/DashboardLayout"
import StoreLayout from "./layouts/StoreLayout"
import ProtectedRoute from "./components/ProtectedRoute"
import { AdminAuthProvider } from "./admin/contexts/AdminAuthContext"
import AdminLicenseGate from "./admin/components/AdminLicenseGate"
import AdminProtectedRoute from "./admin/components/AdminProtectedRoute"
import AdminLayout from "./admin/components/AdminLayout"
import { captureAffiliateAttribution } from "./utils/affiliateAttribution"
import { useBranding } from "./contexts/BrandingContext"

const Home = lazy(() => import("./pages/Home"))
const Solutions = lazy(() => import("./pages/Solutions"))
const SolutionDetail = lazy(() => import("./pages/SolutionDetail"))
const Cooperation = lazy(() => import("./pages/Cooperation"))
const Activities = lazy(() => import("./pages/Activities"))
const ActivityDetail = lazy(() => import("./pages/ActivityDetail"))
const Login = lazy(() => import("./pages/Login"))
const Register = lazy(() => import("./pages/Register"))
const AgentCenter = lazy(() => import("./pages/AgentCenter"))
const Dashboard = lazy(() => import("./pages/Dashboard"))
const Settings = lazy(() => import("./pages/Settings"))
const NotFound = lazy(() => import("./pages/NotFound"))
const StoreGroupList = lazy(() => import("./pages/StoreGroupList"))
const StoreProducts = lazy(() => import("./pages/StoreProducts"))
const Cart = lazy(() => import("./pages/Cart"))
const Finance = lazy(() => import("./pages/Finance"))
const Membership = lazy(() => import("./pages/Membership"))
const Promotion = lazy(() => import("./pages/Promotion"))
const PointsMall = lazy(() => import("./pages/PointsMall"))
const PointsCenter = lazy(() => import("./pages/PointsCenter"))
const Orders = lazy(() => import("./pages/Orders"))
const OrderDetail = lazy(() => import("./pages/OrderDetail"))
const Notifications = lazy(() => import("./pages/Notifications"))
const ServerList = lazy(() => import("./pages/ServerList"))
const ServerDetail = lazy(() => import("./pages/ServerDetail"))
const SecurityGroups = lazy(() => import("./pages/SecurityGroups"))
const SecurityGroupDetail = lazy(() => import("./pages/SecurityGroupDetail"))
const Tickets = lazy(() => import("./pages/Tickets"))
const TicketCreate = lazy(() => import("./pages/TicketCreate"))
const TicketDetail = lazy(() => import("./pages/TicketDetail"))
const VncConsole = lazy(() => import("./pages/VncConsole"))
const OAuthCallback = lazy(() => import("./pages/OAuthCallback"))

const AdminLogin = lazy(() => import("./admin/pages/AdminLogin"))
const AdminDashboard = lazy(() => import("./admin/pages/AdminDashboard"))
const AdminAgents = lazy(() => import("./admin/pages/AdminAgents"))
const AdminAgentTiers = lazy(() => import("./admin/pages/AdminAgentTiers"))
const AdminAgentSettlements = lazy(() => import("./admin/pages/AdminAgentSettlements"))
const AdminAffiliate = lazy(() => import("./admin/pages/AdminAffiliate"))
const AdminCloudServers = lazy(() => import("./admin/pages/AdminCloudServers"))
const AdminProductCatalog = lazy(() => import("./admin/pages/AdminProductCatalog"))
const AdminProducts = lazy(() => import("./admin/pages/AdminProducts"))
const AdminProductIntegration = lazy(() => import("./admin/pages/AdminProductIntegration"))
const AdminProvisionPlugins = lazy(() => import("./admin/pages/AdminProvisionPlugins"))
const AdminProductEdit = lazy(() => import("./admin/pages/AdminProductEdit"))
const AdminMembership = lazy(() => import("./admin/pages/AdminMembership"))
const AdminSettings = lazy(() => import("./admin/pages/AdminSettings"))
const AdminFrontendConfig = lazy(() => import("./admin/pages/AdminFrontendConfig"))
const AdminSystemInfo = lazy(() => import("./admin/pages/AdminSystemInfo"))
const AdminPluginDiagnostics = lazy(() => import("./admin/pages/AdminPluginDiagnostics"))
const AdminNotificationPlugins = lazy(() => import("./admin/pages/AdminNotificationPlugins"))
const AdminTasks = lazy(() => import("./admin/pages/AdminTasks"))
const AdminUsers = lazy(() => import("./admin/pages/AdminUsers"))
const AdminUserDetail = lazy(() => import("./admin/pages/AdminUserDetail"))
const AdminInstances = lazy(() => import("./admin/pages/AdminInstances"))
const AdminInstanceDetail = lazy(() => import("./admin/pages/AdminInstanceDetail"))
const AdminFinance = lazy(() => import("./admin/pages/AdminFinance"))
const AdminServiceOrders = lazy(() => import("./admin/pages/AdminServiceOrders"))
const AdminActivities = lazy(() => import("./admin/pages/AdminActivities"))
const AdminPromoCodes = lazy(() => import("./admin/pages/AdminPromoCodes"))
const AdminMall = lazy(() => import("./admin/pages/AdminMall"))
const AdminUpstreamActions = lazy(() => import("./admin/pages/AdminUpstreamActions"))
const AdminTickets = lazy(() => import("./admin/pages/AdminTickets"))
const AdminTicketDetail = lazy(() => import("./admin/pages/AdminTicketDetail"))
const AdminTicketDepartments = lazy(() => import("./admin/pages/AdminTicketDepartments"))
const AdminTicketReplyTemplates = lazy(() => import("./admin/pages/AdminTicketReplyTemplates"))
const AdminAnnouncements = lazy(() => import("./admin/pages/AdminAnnouncements"))

export default function App() {
  return (
    <>
      <DocumentTitle />
      <AffiliateAttributionTracker />
      <Suspense fallback={<RouteFallback />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/solutions" element={<Solutions />} />
          <Route path="/solutions/:slug" element={<SolutionDetail />} />
          <Route path="/cooperation" element={<Cooperation />} />
          <Route path="/cooperation/:section" element={<Cooperation />} />
          <Route path="/activities" element={<Activities />} />
          <Route path="/activities/:id" element={<ActivityDetail />} />
          <Route path="/oauth/callback" element={<OAuthCallback />} />

          {/* 商店 — 全宽，无需登录 */}
          <Route element={<StoreLayout />}>
            <Route path="/store" element={<StoreIndexRedirect />} />
            <Route path="/store/:categorySlug" element={<StoreGroupList />} />
            <Route path="/store/:categorySlug/:groupSlug/:productSku" element={<LegacyProductRedirect />} />
            <Route path="/store/:categorySlug/:groupSlug" element={<StoreProducts />} />
          </Route>

          <Route element={<AuthLayout />}>
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
          </Route>

          <Route path="/products" element={<Navigate to="/store" replace />} />

          <Route element={<ProtectedRoute />}>
            <Route element={<DashboardLayout />}>
              <Route path="/dashboard" element={<Dashboard />} />
              <Route path="/settings" element={<Settings />} />
              <Route path="/agent" element={<AgentCenter />} />
              <Route path="/finance" element={<Finance />} />
              <Route path="/membership" element={<Membership />} />
              <Route path="/points-mall" element={<PointsMall />} />
              <Route path="/points-center" element={<PointsCenter />} />
              <Route path="/promotion" element={<Promotion />} />
              <Route path="/orders" element={<Orders />} />
              <Route path="/orders/:orderId" element={<OrderDetail />} />
              <Route path="/notifications" element={<Notifications />} />
              <Route path="/control/server" element={<ServerList />} />
              <Route path="/control/server/:id" element={<ServerDetail />} />
              <Route path="/control/security-groups" element={<SecurityGroups />} />
              <Route path="/control/security-groups/:id" element={<SecurityGroupDetail />} />
              <Route path="/tickets" element={<Tickets />} />
              <Route path="/tickets/new" element={<TicketCreate />} />
              <Route path="/tickets/create" element={<TicketCreate />} />
              <Route path="/tickets/:id" element={<TicketDetail />} />
            </Route>
            <Route path="/cart" element={<Cart />} />
            {/* VNC 远程桌面 — 全屏，无 Dashboard 框架 */}
            <Route path="/control/server/:id/vnc" element={<VncConsole />} />
          </Route>

          <Route
            path="/admin/*"
            element={
              <AdminAuthProvider>
                <Routes>
                  <Route path="login" element={<AdminLogin />} />
                  <Route element={<AdminProtectedRoute />}>
                    <Route element={<AdminLicenseGate />}>
                      <Route element={<AdminLayout />}>
                        <Route index element={<AdminDashboard />} />
                        <Route path="agents" element={<AdminAgents />} />
                        <Route path="agent-tiers" element={<AdminAgentTiers />} />
                        <Route path="agent-settlements" element={<AdminAgentSettlements />} />
                        <Route path="affiliate" element={<AdminAffiliate />} />
                        <Route path="users" element={<AdminUsers />} />
                        <Route path="instances" element={<AdminInstances />} />
                        <Route path="instances/:instanceId" element={<AdminInstanceDetail />} />
                        <Route path="users/:userId/instances/:instanceId" element={<AdminInstanceDetail />} />
                        <Route path="users/:id" element={<AdminUserDetail />} />
                        <Route path="finance" element={<AdminFinance />} />
                        <Route path="service-orders" element={<AdminServiceOrders />} />
                        <Route path="activities" element={<AdminActivities />} />
                        <Route path="promo-codes" element={<AdminPromoCodes />} />
                        <Route path="mall" element={<AdminMall />} />
                        <Route path="upstream-actions" element={<AdminUpstreamActions />} />
                        <Route path="tickets" element={<AdminTickets />} />
                        <Route path="tickets/departments" element={<AdminTicketDepartments />} />
                        <Route path="tickets/templates" element={<AdminTicketReplyTemplates />} />
                        <Route path="tickets/:id" element={<AdminTicketDetail />} />
                        <Route path="membership" element={<AdminMembership />} />
                        <Route path="settings" element={<AdminSettings />} />
                        <Route path="frontend-config" element={<AdminFrontendConfig />} />
                        <Route path="system-info" element={<AdminSystemInfo />} />
                        <Route path="plugin-diagnostics" element={<AdminPluginDiagnostics />} />
                        <Route path="notification-plugins" element={<AdminNotificationPlugins />} />
                        <Route path="tasks" element={<AdminTasks />} />
                        <Route path="announcements" element={<AdminAnnouncements />} />
                        <Route path="cloud-servers" element={<AdminCloudServers />} />
                        <Route path="product-catalog" element={<AdminProductCatalog />} />
                        <Route path="product-integration" element={<AdminProductIntegration />} />
                        <Route path="provision-plugins" element={<AdminProvisionPlugins />} />
                        <Route path="products" element={<AdminProducts />} />
                        <Route path="products/:id" element={<AdminProductEdit />} />
                      </Route>
                    </Route>
                  </Route>
                </Routes>
              </AdminAuthProvider>
            }
          />

          <Route path="*" element={<NotFound />} />
        </Routes>
      </Suspense>
    </>
  )
}

// 活动商品等入口会生成 /store?category=xxx&group=yyy&sku=zzz 的 query 链接，
// 这里把它规范化到实际的 path 路由 /store/:categorySlug/:groupSlug?sku=zzz。
function StoreIndexRedirect() {
  const [params] = useSearchParams()
  const category = params.get("category") ?? params.get("category_slug")
  const group = params.get("group") ?? params.get("group_slug")
  const sku = params.get("sku")

  if (category && group) {
    const query = sku ? `?sku=${encodeURIComponent(sku)}` : ""
    return (
      <Navigate
        to={`/store/${encodeURIComponent(category)}/${encodeURIComponent(group)}${query}`}
        replace
      />
    )
  }
  if (category) {
    return <Navigate to={`/store/${encodeURIComponent(category)}`} replace />
  }
  return null
}

function LegacyProductRedirect() {
  const { categorySlug, groupSlug, productSku } = useParams<{
    categorySlug: string
    groupSlug: string
    productSku: string
  }>()
  if (!categorySlug || !groupSlug || !productSku) return <Navigate to="/store" replace />
  return (
    <Navigate
      to={`/store/${encodeURIComponent(categorySlug)}/${encodeURIComponent(groupSlug)}?sku=${encodeURIComponent(productSku)}`}
      replace
    />
  )
}

function AffiliateAttributionTracker() {
  const location = useLocation()

  useEffect(() => {
    if (location.pathname.startsWith("/admin")) return
    captureAffiliateAttribution(location.search, window.location.href)
  }, [location.pathname, location.search])

  return null
}

function RouteFallback() {
  return (
    <div style={{ minHeight: 260, display: "flex", alignItems: "center", justifyContent: "center" }}>
      <Spin size="large" description="正在加载页面" />
    </div>
  )
}

function DocumentTitle() {
  const { pathname } = useLocation()
  const { site_name } = useBranding()

  useEffect(() => {
    const title = resolvePageTitle(pathname)
    document.title = title === site_name ? title : `${title} - ${site_name}`
  }, [pathname, site_name])

  return null
}

function resolvePageTitle(pathname: string) {
  if (pathname === "/") return "网站"
  if (pathname === "/solutions") return "解决方案"
  if (pathname.startsWith("/solutions/")) return "解决方案详情"
  if (pathname === "/cooperation") return "生态合作"
	if (pathname === "/activities") return "最新活动"
	if (pathname.startsWith("/activities/")) return "活动详情"
  if (pathname === "/cooperation/partner") return "合作伙伴计划"
  if (pathname === "/cooperation/affiliate") return "推广合作计划"
  if (pathname === "/login") return "登录"
  if (pathname === "/register") return "注册"
  if (pathname === "/dashboard") return "控制台"
  if (pathname === "/settings") return "账户设置"
  if (pathname === "/agent") return "代理中心"
  if (pathname === "/finance") return "财务管理"
  if (pathname === "/membership") return "会员中心"
  if (pathname === "/points-mall") return "积分商城"
  if (pathname === "/points-center") return "积分中心"
  if (pathname === "/promotion") return "推广中心"
  if (pathname === "/cart") return "购物车"
  if (pathname === "/orders") return "订单管理"
  if (pathname.startsWith("/orders/")) return "订单详情"
  if (pathname === "/notifications") return "消息通知"
  if (pathname === "/control/server") return "服务器管理"
  if (pathname === "/control/security-groups") return "安全组管理"
  if (pathname.startsWith("/control/security-groups/")) return "安全组管理"
  if (pathname === "/tickets") return "工单支持"
  if (pathname === "/tickets/new" || pathname === "/tickets/create") return "创建工单"
  if (pathname.startsWith("/tickets/")) return "工单详情"
  if (pathname.endsWith("/vnc") && pathname.startsWith("/control/server/")) return "远程桌面"
  if (pathname.startsWith("/control/server/")) return "服务器详情"
  if (pathname.startsWith("/store")) return "购买服务器"
  if (pathname === "/products") return "产品服务"

  if (pathname === "/admin/login") return "管理员登录"
  if (pathname === "/admin" || pathname === "/admin/") return "管理后台"
  if (pathname.startsWith("/admin/agent-settlements")) return "代理结算流水"
  if (pathname.startsWith("/admin/affiliate")) return "AFF 渠道"
  if (pathname.startsWith("/admin/agent-tiers")) return "代理档位配置"
  if (pathname.startsWith("/admin/agents")) return "代理管理"
  if (/^\/admin\/users\/\d+\/instances\/\d+/.test(pathname)) return "实例详情"
  if (/^\/admin\/instances\/\d+/.test(pathname)) return "实例详情"
  if (pathname.startsWith("/admin/instances")) return "实例管理"
  if (pathname.startsWith("/admin/users/")) return "用户详情"
  if (pathname.startsWith("/admin/users")) return "用户管理"
  if (pathname.startsWith("/admin/finance")) return "后台财务"
  if (pathname.startsWith("/admin/service-orders")) return "服务订单处理"
  if (pathname.startsWith("/admin/activities")) return "活动管理"
  if (pathname.startsWith("/admin/promo-codes")) return "优惠券管理"
  if (pathname.startsWith("/admin/mall")) return "积分商城管理"
  if (pathname.startsWith("/admin/upstream-actions")) return "资源操作审计"
  if (pathname.startsWith("/admin/tickets/departments")) return "工单部门配置"
  if (pathname.startsWith("/admin/tickets/templates")) return "回复模板"
  if (pathname.startsWith("/admin/tickets/")) return "工单详情"
  if (pathname.startsWith("/admin/tickets")) return "工单管理"
  if (pathname.startsWith("/admin/membership")) return "会员与伙伴"
  if (pathname.startsWith("/admin/plugin-diagnostics")) return "插件诊断"
  if (pathname.startsWith("/admin/notification-plugins")) return "功能插件"
  if (pathname.startsWith("/admin/tasks")) return "任务中心"
  if (pathname.startsWith("/admin/system-info")) return "系统信息"
  if (pathname.startsWith("/admin/settings")) return "系统设置"
  if (pathname.startsWith("/admin/announcements")) return "公告管理"
  if (pathname.startsWith("/admin/cloud-servers")) return "云服务器节点"
  if (pathname.startsWith("/admin/product-catalog")) return "产品目录"
  if (pathname.startsWith("/admin/product-integration")) return "商品对接"
  if (pathname.startsWith("/admin/provision-plugins")) return "开通接口"
  if (pathname.startsWith("/admin/products")) return "产品管理"

  return "页面未找到"
}
