<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AILange · 大脑营行 AI 诊断引擎</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    /* ========== 设计系统 ========== */
    :root {
      --primary: #2563EB;
      --primary-dark: #1d4ed8;
      --indigo: #6366F1;
      --emerald: #10B981;
      --amber: #F59E0B;
      --rose: #F43F5E;
      --purple: #8B5CF6;
      --slate: #64748B;
      --surface: #FFFFFF;
      --bg: #F8FAFC;
      --border: #E2E8F0;
      --text: #0F172A;
      --text-muted: #64748B;
      --sidebar-w: 260px;
      --header-h: 64px;
      --radius: 12px;
      --shadow: 0 4px 20px rgba(0,0,0,0.08);
      --shadow-lg: 0 20px 60px rgba(0,0,0,0.15);
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
      background: var(--bg);
      color: var(--text);
      line-height: 1.6;
      min-height: 100vh;
    }

    /* ========== 通用组件 ========== */
    .btn {
      display: inline-flex; align-items: center; gap: 8px;
      padding: 10px 20px; border-radius: 8px; font-size: 14px;
      font-weight: 600; cursor: pointer; border: none;
      transition: all 0.15s; text-decoration: none; white-space: nowrap;
    }
    .btn-primary { background: var(--primary); color: #fff; }
    .btn-primary:hover { background: var(--primary-dark); transform: translateY(-1px); box-shadow: 0 4px 12px rgba(37,99,235,0.3); }
    .btn-ghost { background: transparent; color: var(--slate); border: 1.5px solid var(--border); }
    .btn-ghost:hover { border-color: var(--primary); color: var(--primary); }
    .btn-indigo { background: var(--indigo); color: #fff; }
    .btn-indigo:hover { background: #4f46e5; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(99,102,241,0.35); }
    .btn-lg { padding: 14px 28px; font-size: 16px; border-radius: 10px; }
    .btn-sm { padding: 6px 14px; font-size: 13px; }

    .badge {
      display: inline-flex; align-items: center;
      padding: 3px 10px; border-radius: 20px;
      font-size: 12px; font-weight: 600;
    }
    .badge-free { background: #F1F5F9; color: #64748B; }
    .badge-pro { background: #EEF2FF; color: #6366F1; }
    .badge-enterprise { background: #FFFBEB; color: #D97706; }

    .card {
      background: var(--surface); border-radius: var(--radius);
      border: 1px solid var(--border); box-shadow: var(--shadow);
    }

    input, textarea, select {
      width: 100%; padding: 10px 14px;
      border: 1.5px solid var(--border); border-radius: 8px;
      font-family: inherit; font-size: 14px; color: var(--text);
      background: var(--surface); outline: none;
      transition: border-color 0.15s;
    }
    input:focus, textarea:focus { border-color: var(--primary); }
    label { display: block; font-size: 13px; font-weight: 600; color: var(--slate); margin-bottom: 6px; }
    .form-group { margin-bottom: 16px; }
    .form-error { color: var(--rose); font-size: 12px; margin-top: 4px; }

    /* ========== VIEWS ========== */
    .view { display: none; }
    .view.active { display: block; }

    /* ========== AUTH PAGES (Landing + Login + Register) ========== */
    .auth-layout {
      min-height: 100vh;
      display: grid;
      grid-template-columns: 1fr 480px;
    }
    .auth-left {
      background: linear-gradient(135deg, #0a0e27 0%, #1a1f4e 50%, #0f1729 100%);
      display: flex; flex-direction: column;
      justify-content: center; padding: 60px;
      position: relative; overflow: hidden;
    }
    .auth-left::before {
      content: '';
      position: absolute; top: -200px; right: -200px;
      width: 600px; height: 600px;
      background: radial-gradient(circle, rgba(99,102,241,0.15) 0%, transparent 70%);
      pointer-events: none;
    }
    .auth-left::after {
      content: '';
      position: absolute; bottom: -150px; left: -100px;
      width: 400px; height: 400px;
      background: radial-gradient(circle, rgba(16,185,129,0.1) 0%, transparent 70%);
      pointer-events: none;
    }
    .auth-brand {
      display: flex; align-items: center; gap: 12px;
      margin-bottom: 60px;
    }
    .auth-brand-icon {
      width: 44px; height: 44px; background: var(--indigo);
      border-radius: 12px; display: flex; align-items: center;
      justify-content: center; font-size: 22px;
    }
    .auth-brand-name { font-size: 22px; font-weight: 800; color: #fff; letter-spacing: -0.5px; }
    .auth-brand-sub { font-size: 11px; color: #94A3B8; margin-top: 1px; }
    .auth-hero-title {
      font-size: 42px; font-weight: 800; color: #fff;
      line-height: 1.2; margin-bottom: 20px; letter-spacing: -1px;
    }
    .auth-hero-title span { color: #818CF8; }
    .auth-hero-desc { font-size: 16px; color: #94A3B8; line-height: 1.7; max-width: 480px; }
    .auth-features { margin-top: 48px; display: flex; flex-direction: column; gap: 16px; }
    .auth-feature {
      display: flex; align-items: flex-start; gap: 14px;
    }
    .auth-feature-icon {
      width: 36px; height: 36px; border-radius: 10px;
      display: flex; align-items: center; justify-content: center;
      font-size: 16px; flex-shrink: 0;
    }
    .auth-feature-text h4 { color: #E2E8F0; font-size: 14px; margin-bottom: 2px; }
    .auth-feature-text p { color: #64748B; font-size: 13px; }

    .auth-right {
      background: var(--surface); padding: 48px 40px;
      display: flex; flex-direction: column; justify-content: center;
    }
    .auth-right h2 { font-size: 26px; font-weight: 800; margin-bottom: 6px; letter-spacing: -0.5px; }
    .auth-right p.subtitle { font-size: 14px; color: var(--slate); margin-bottom: 32px; }
    .auth-switch { font-size: 14px; color: var(--slate); text-align: center; margin-top: 24px; }
    .auth-switch a { color: var(--primary); cursor: pointer; font-weight: 600; text-decoration: none; }
    .auth-switch a:hover { text-decoration: underline; }
    .divider {
      display: flex; align-items: center; gap: 12px;
      margin: 20px 0; color: var(--slate); font-size: 12px;
    }
    .divider::before, .divider::after {
      content: ''; flex: 1; height: 1px; background: var(--border);
    }
    .agreement { font-size: 12px; color: var(--slate); text-align: center; margin-top: 16px; }
    .agreement a { color: var(--primary); }

    /* ========== APP LAYOUT ========== */
    .app-layout {
      display: grid;
      grid-template-rows: var(--header-h) 1fr;
      grid-template-columns: var(--sidebar-w) 1fr;
      height: 100vh;
      overflow: hidden;
    }

    /* Header */
    .app-header {
      grid-column: 1 / -1;
      background: var(--surface);
      border-bottom: 1px solid var(--border);
      display: flex; align-items: center; padding: 0 24px;
      gap: 16px; z-index: 100;
    }
    .header-brand {
      display: flex; align-items: center; gap: 10px;
      cursor: pointer;
    }
    .header-logo {
      width: 36px; height: 36px; background: var(--indigo);
      border-radius: 10px; display: flex; align-items: center;
      justify-content: center; font-size: 18px; color: #fff;
    }
    .header-title { font-size: 18px; font-weight: 800; letter-spacing: -0.5px; }
    .header-spacer { flex: 1; }
    .header-nav { display: flex; gap: 4px; }
    .header-nav-item {
      padding: 6px 14px; border-radius: 8px; font-size: 13px;
      font-weight: 600; cursor: pointer; transition: all 0.15s;
      color: var(--slate);
    }
    .header-nav-item:hover { background: var(--bg); color: var(--text); }
    .header-nav-item.active { background: #EEF2FF; color: var(--indigo); }
    .header-user {
      display: flex; align-items: center; gap: 10px;
      padding: 6px 12px 6px 8px; border-radius: 10px;
      cursor: pointer; transition: background 0.15s;
    }
    .header-user:hover { background: var(--bg); }
    .user-avatar {
      width: 32px; height: 32px; border-radius: 8px;
      background: linear-gradient(135deg, var(--indigo), var(--purple));
      display: flex; align-items: center; justify-content: center;
      font-size: 14px; font-weight: 700; color: #fff;
    }
    .user-info { text-align: left; }
    .user-name { font-size: 13px; font-weight: 600; }
    .user-tier { font-size: 11px; color: var(--slate); }

    /* Sidebar */
    .app-sidebar {
      background: var(--surface);
      border-right: 1px solid var(--border);
      padding: 20px 12px;
      overflow-y: auto;
    }
    .new-diag-btn {
      width: 100%; padding: 10px 16px; border-radius: 10px;
      background: linear-gradient(135deg, var(--indigo), var(--primary));
      color: #fff; font-size: 14px; font-weight: 700;
      cursor: pointer; border: none; display: flex;
      align-items: center; gap: 8px; margin-bottom: 20px;
      transition: all 0.15s;
    }
    .new-diag-btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(99,102,241,0.35); }
    .sidebar-section { font-size: 11px; font-weight: 700; color: var(--slate); letter-spacing: 0.08em; text-transform: uppercase; padding: 0 6px; margin: 16px 0 8px; }
    .sidebar-item {
      display: flex; align-items: center; gap: 10px;
      padding: 9px 10px; border-radius: 8px; font-size: 13px;
      font-weight: 500; cursor: pointer; transition: all 0.12s;
      color: var(--slate);
    }
    .sidebar-item:hover { background: var(--bg); color: var(--text); }
    .sidebar-item.active { background: #EEF2FF; color: var(--indigo); }
    .sidebar-item .icon { font-size: 16px; width: 20px; text-align: center; }
    .history-item {
      padding: 10px 10px; border-radius: 8px; cursor: pointer;
      transition: all 0.12s; margin-bottom: 4px;
    }
    .history-item:hover { background: var(--bg); }
    .history-item.active { background: #EEF2FF; }
    .history-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
    .history-title { font-size: 13px; font-weight: 600; }
    .history-date { font-size: 11px; color: var(--slate); margin-top: 2px; }

    /* Main Content */
    .app-main {
      overflow-y: auto; padding: 32px;
      background: var(--bg);
    }

    /* ========== PAGE: 工作台 ========== */
    .welcome-area { text-align: center; padding: 32px 0 40px; }
    .welcome-badge {
      display: inline-flex; align-items: center; gap: 6px;
      background: #EEF2FF; color: var(--indigo);
      padding: 6px 14px; border-radius: 20px; font-size: 13px;
      font-weight: 600; margin-bottom: 20px;
    }
    .welcome-title { font-size: 36px; font-weight: 800; letter-spacing: -1px; line-height: 1.2; margin-bottom: 14px; }
    .welcome-title .highlight { background: linear-gradient(135deg, var(--indigo), var(--primary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
    .welcome-desc { font-size: 15px; color: var(--slate); max-width: 540px; margin: 0 auto 32px; }

    .quick-cards { display: grid; grid-template-columns: repeat(4,1fr); gap: 14px; margin-bottom: 28px; }
    .quick-card {
      background: var(--surface); border: 1.5px solid var(--border);
      border-radius: var(--radius); padding: 18px;
      cursor: pointer; transition: all 0.15s; text-align: left;
    }
    .quick-card:hover { border-color: var(--indigo); box-shadow: 0 4px 16px rgba(99,102,241,0.12); transform: translateY(-2px); }
    .quick-card-icon { font-size: 22px; margin-bottom: 10px; }
    .quick-card-title { font-size: 13px; font-weight: 700; margin-bottom: 4px; }
    .quick-card-desc { font-size: 12px; color: var(--slate); line-height: 1.5; }

    .input-area {
      background: var(--surface); border: 1.5px solid var(--border);
      border-radius: 14px; overflow: hidden; box-shadow: var(--shadow);
    }
    .input-area textarea {
      border: none; border-radius: 0; padding: 18px 20px;
      font-size: 15px; resize: none; height: 120px;
      background: transparent;
    }
    .input-toolbar {
      display: flex; align-items: center; gap: 12px;
      padding: 12px 16px; border-top: 1px solid var(--border);
    }
    .char-count { font-size: 12px; color: var(--slate); }

    /* ========== PAGE: 五大维度 ========== */
    .dim-tabs { display: flex; gap: 8px; margin-bottom: 24px; flex-wrap: wrap; }
    .dim-tab {
      padding: 8px 18px; border-radius: 20px; font-size: 13px;
      font-weight: 600; cursor: pointer; border: 1.5px solid var(--border);
      transition: all 0.15s; background: var(--surface);
    }
    .dim-tab.active-product { background: #EFF6FF; border-color: var(--primary); color: var(--primary); }
    .dim-tab.active-customer { background: #F0FDF4; border-color: var(--emerald); color: var(--emerald); }
    .dim-tab.active-channel { background: #FFFBEB; border-color: var(--amber); color: var(--amber); }
    .dim-tab.active-team { background: #F5F3FF; border-color: var(--purple); color: var(--purple); }
    .dim-tab.active-finance { background: #FFF1F2; border-color: var(--rose); color: var(--rose); }

    .tools-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
    .tool-item {
      display: flex; align-items: center; gap: 12px;
      background: var(--surface); border: 1px solid var(--border);
      border-radius: 10px; padding: 14px; cursor: pointer;
      transition: all 0.12s;
    }
    .tool-item:hover { border-color: var(--primary); box-shadow: 0 2px 12px rgba(37,99,235,0.08); }
    .tool-num {
      width: 28px; height: 28px; border-radius: 8px;
      display: flex; align-items: center; justify-content: center;
      font-size: 13px; font-weight: 700; color: #fff; flex-shrink: 0;
    }
    .tool-name { font-size: 13px; font-weight: 600; }
    .tool-desc { font-size: 11px; color: var(--slate); margin-top: 2px; }
    .tool-arrow { margin-left: auto; color: var(--slate); font-size: 18px; }

    /* ========== 工具详情面板 ========== */
    .tool-panel-overlay {
      position: fixed; inset: 0; background: rgba(15,23,42,0.4);
      z-index: 1000; display: none; align-items: center; justify-content: center;
    }
    .tool-panel-overlay.active { display: flex; }
    .tool-panel {
      background: var(--surface); border-radius: 16px; width: 520px; max-width: 95vw;
      max-height: 90vh; overflow-y: auto; box-shadow: 0 24px 80px rgba(0,0,0,0.25);
      animation: panelSlideIn 0.25s ease;
    }
    @keyframes panelSlideIn {
      from { opacity: 0; transform: translateY(20px) scale(0.96); }
      to { opacity: 1; transform: translateY(0) scale(1); }
    }
    .tool-panel-header {
      padding: 24px 28px 0; display: flex; justify-content: space-between; align-items: flex-start;
    }
    .tool-panel-header h3 { font-size: 18px; font-weight: 700; letter-spacing: -0.3px; }
    .tool-panel-header .dim-badge {
      font-size: 11px; padding: 3px 10px; border-radius: 100px; font-weight: 600;
    }
    .tool-panel-close {
      width: 32px; height: 32px; border-radius: 8px; border: none;
      background: var(--bg); cursor: pointer; font-size: 18px; color: var(--slate);
      display: flex; align-items: center; justify-content: center; flex-shrink: 0;
    }
    .tool-panel-close:hover { background: #E2E8F0; color: var(--text); }
    .tool-panel-body { padding: 20px 28px 28px; }
    .tool-panel-body .form-group { margin-bottom: 16px; }
    .tool-panel-body label {
      display: block; font-size: 13px; font-weight: 600; margin-bottom: 6px; color: var(--text);
    }
    .tool-panel-body label .required { color: var(--rose); }
    .tool-panel-body input, .tool-panel-body textarea, .tool-panel-body select {
      width: 100%; padding: 10px 14px; border: 1px solid var(--border);
      border-radius: 8px; font-size: 14px; font-family: inherit;
      transition: border-color 0.15s; background: var(--bg); outline: none;
    }
    .tool-panel-body input:focus, .tool-panel-body textarea:focus, .tool-panel-body select:focus {
      border-color: var(--primary); box-shadow: 0 0 0 3px rgba(37,99,235,0.1);
    }
    .tool-panel-body textarea { min-height: 80px; resize: vertical; }
    .tool-panel-body .form-hint { font-size: 11px; color: var(--slate); margin-top: 4px; }
    .tool-generate-btn {
      width: 100%; padding: 12px; font-size: 15px; font-weight: 700;
      margin-top: 8px; justify-content: center;
    }
    .tool-generate-btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
    .tool-result-box {
      background: #F0FDF4; border: 1px solid #86EFAC; border-radius: 10px;
      padding: 16px; margin-top: 16px; display: none;
    }
    .tool-result-box.active { display: block; }
    .tool-result-box h4 { font-size: 14px; color: #166534; margin-bottom: 8px; }
    .tool-result-box .dl-btn {
      display: inline-flex; align-items: center; gap: 6px;
      padding: 8px 18px; background: var(--emerald); color: #fff;
      border-radius: 8px; font-weight: 600; font-size: 13px; text-decoration: none;
    }
    .tool-result-box .dl-btn:hover { background: #059669; }

    .tool-generating {
      display: none; align-items: center; gap: 10px; padding: 12px 16px;
      background: #EFF6FF; border: 1px solid #BFDBFE; border-radius: 10px; margin-top: 16px;
    }
    .tool-generating.active { display: flex; }
    .tool-generating .spinner-small {
      width: 20px; height: 20px; border: 2px solid #BFDBFE;
      border-top-color: var(--primary); border-radius: 50%;
      animation: spin 0.8s linear infinite;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
    .tool-generating span { font-size: 13px; color: var(--primary); font-weight: 500; }

    /* 企业档案快捷选择 */
    .profile-picker {
      background: #F0F9FF; border: 1px solid #BAE6FD; border-radius: 10px;
      padding: 14px 16px; margin-bottom: 18px;
    }
    .profile-picker-header {
      display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;
    }
    .profile-picker-header span {
      font-size: 12px; font-weight: 700; color: #0369A1; text-transform: uppercase; letter-spacing: 0.5px;
    }
    .profile-picker-actions { display: flex; gap: 6px; }
    .profile-picker-actions button {
      font-size: 11px; padding: 4px 10px; border-radius: 6px; border: none; cursor: pointer;
      font-weight: 600; transition: all 0.15s;
    }
    .btn-save-profile { background: #0EA5E9; color: #fff; }
    .btn-save-profile:hover { background: #0284C7; }
    .btn-del-profile { background: #FEE2E2; color: #DC2626; display: none; }
    .btn-del-profile:hover { background: #FECACA; }
    .btn-del-profile.visible { display: inline-block; }
    .profile-select {
      width: 100%; padding: 8px 12px; border: 1px solid #BAE6FD;
      border-radius: 8px; font-size: 13px; font-family: inherit;
      background: #fff; cursor: pointer; outline: none; color: var(--text);
    }
    .profile-select:focus { border-color: var(--primary); }
    .profile-empty { font-size: 12px; color: #64748B; padding: 4px 0; }
    .profile-preview {
      margin-top: 8px; font-size: 12px; color: #475569;
      display: flex; flex-wrap: wrap; gap: 6px 14px;
    }
    .profile-preview span { background: #E0F2FE; padding: 2px 8px; border-radius: 100px; white-space: nowrap; }

    /* ========== PAGE: 诊断结果 ========== */
    .result-header {
      display: flex; justify-content: space-between; align-items: flex-start;
      margin-bottom: 28px;
    }
    .score-grid { display: grid; grid-template-columns: repeat(5,1fr); gap: 12px; margin-bottom: 24px; }
    .score-card {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 16px; text-align: center;
    }
    .score-num { font-size: 32px; font-weight: 800; }
    .score-label { font-size: 12px; color: var(--slate); margin-top: 4px; }
    .score-bar { height: 4px; border-radius: 2px; margin-top: 10px; background: var(--border); overflow: hidden; }
    .score-bar-fill { height: 100%; border-radius: 2px; transition: width 0.8s ease; }

    .radar-container { display: flex; justify-content: center; padding: 20px 0; }

    .issues-list { display: flex; flex-direction: column; gap: 12px; }
    .issue-item {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 16px;
      display: flex; gap: 14px; align-items: flex-start;
    }
    .issue-priority {
      width: 24px; height: 24px; border-radius: 6px;
      display: flex; align-items: center; justify-content: center;
      font-size: 11px; font-weight: 700; color: #fff; flex-shrink: 0;
    }

    /* ========== PAGE: 文档生成 ========== */
    .doc-cards { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 28px; }
    .doc-card {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 24px;
    }
    .doc-type-icon { font-size: 36px; margin-bottom: 14px; }
    .progress-bar {
      height: 8px; background: var(--border); border-radius: 4px;
      overflow: hidden; margin: 12px 0;
    }
    .progress-fill { height: 100%; border-radius: 4px; transition: width 0.5s; }

    /* ========== PAGE: 知识库 ========== */
    .kb-search {
      display: flex; gap: 10px; margin-bottom: 24px;
    }
    .kb-search input { flex: 1; }
    .doc-list { display: flex; flex-direction: column; gap: 10px; }
    .doc-row {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: 10px; padding: 14px 18px;
      display: flex; align-items: center; gap: 14px;
      cursor: pointer; transition: all 0.12s;
    }
    .doc-row:hover { border-color: var(--primary); }
    .doc-icon { font-size: 20px; }
    .doc-info { flex: 1; }
    .doc-title { font-size: 14px; font-weight: 600; }
    .doc-meta { font-size: 12px; color: var(--slate); margin-top: 2px; }
    .doc-tag {
      padding: 3px 10px; border-radius: 12px;
      font-size: 11px; font-weight: 600;
    }

    /* ========== PAGE: 会员中心 ========== */
    .member-hero {
      background: linear-gradient(135deg, #0f172a, #1e1b4b);
      border-radius: 16px; padding: 40px; color: #fff; margin-bottom: 32px;
      position: relative; overflow: hidden;
    }
    .member-hero::before {
      content: '';
      position: absolute; top: -80px; right: -80px;
      width: 300px; height: 300px;
      background: radial-gradient(circle, rgba(99,102,241,0.3) 0%, transparent 70%);
    }
    .member-hero h2 { font-size: 24px; font-weight: 800; margin-bottom: 8px; }
    .member-hero p { color: #94A3B8; margin-bottom: 24px; }
    .member-stats { display: flex; gap: 32px; }
    .member-stat-val { font-size: 28px; font-weight: 800; }
    .member-stat-label { font-size: 12px; color: #94A3B8; }

    .pricing-cards { display: grid; grid-template-columns: repeat(3,1fr); gap: 20px; }
    .pricing-card {
      background: var(--surface); border: 2px solid var(--border);
      border-radius: 16px; padding: 28px; transition: all 0.15s;
      position: relative; overflow: hidden;
    }
    .pricing-card:hover { transform: translateY(-4px); box-shadow: var(--shadow-lg); }
    .pricing-card.popular {
      border-color: var(--indigo);
    }
    .popular-badge {
      position: absolute; top: 16px; right: 16px;
      background: var(--indigo); color: #fff; font-size: 11px;
      font-weight: 700; padding: 4px 10px; border-radius: 12px;
    }
    .pricing-tier { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 12px; }
    .pricing-price { margin-bottom: 20px; }
    .pricing-price .amount { font-size: 36px; font-weight: 800; }
    .pricing-price .unit { font-size: 14px; color: var(--slate); }
    .pricing-price .yearly { font-size: 12px; color: var(--emerald); margin-top: 4px; }
    .pricing-features { list-style: none; margin: 20px 0; display: flex; flex-direction: column; gap: 10px; }
    .pricing-features li {
      font-size: 13px; color: var(--slate);
      display: flex; align-items: center; gap: 8px;
    }
    .pricing-features li::before { content: '✓'; color: var(--emerald); font-weight: 700; }

    /* ========== PAGE: 个人中心 ========== */
    .profile-card {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 28px; margin-bottom: 20px;
    }
    .profile-avatar {
      width: 72px; height: 72px; border-radius: 16px;
      background: linear-gradient(135deg, var(--indigo), var(--purple));
      display: flex; align-items: center; justify-content: center;
      font-size: 28px; font-weight: 700; color: #fff; margin-bottom: 16px;
    }

    /* ========== MODAL ========== */
    .modal-overlay {
      display: none; position: fixed; inset: 0;
      background: rgba(0,0,0,0.5); z-index: 1000;
      align-items: center; justify-content: center;
    }
    .modal-overlay.open { display: flex; }
    .modal {
      background: var(--surface); border-radius: 16px;
      padding: 32px; max-width: 420px; width: 90%;
      box-shadow: var(--shadow-lg); position: relative;
    }
    .modal-title { font-size: 18px; font-weight: 700; margin-bottom: 20px; }
    .modal-close {
      position: absolute; top: 16px; right: 16px;
      background: none; border: none; cursor: pointer;
      font-size: 20px; color: var(--slate);
    }

    /* ========== TOAST ========== */
    .toast-container {
      position: fixed; bottom: 24px; right: 24px; z-index: 9999;
      display: flex; flex-direction: column; gap: 10px;
    }
    .toast {
      background: #0F172A; color: #fff;
      padding: 12px 20px; border-radius: 10px;
      font-size: 14px; max-width: 320px;
      box-shadow: 0 8px 24px rgba(0,0,0,0.2);
      display: flex; align-items: center; gap: 10px;
      animation: slideIn 0.2s ease;
    }
    .toast-success { border-left: 4px solid var(--emerald); }
    .toast-error { border-left: 4px solid var(--rose); }
    .toast-info { border-left: 4px solid var(--indigo); }
    @keyframes slideIn { from { transform: translateX(30px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
    @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }

    /* ========== ADMIN PANEL ========== */
    .admin-layout { padding: 0; }
    .admin-section { margin-bottom: 28px; }
    .admin-section-title { font-size: 18px; font-weight: 700; margin-bottom: 14px; letter-spacing: -0.5px; }
    .admin-stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 24px; }
    .admin-stat-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px; }
    .admin-stat-card .stat-value { font-size: 28px; font-weight: 800; letter-spacing: -1px; }
    .admin-stat-card .stat-label { font-size: 13px; color: var(--slate); margin-top: 4px; }
    .admin-table-wrap { overflow-x: auto; }
    .admin-table { width: 100%; border-collapse: collapse; font-size: 13px; }
    .admin-table th { padding: 10px 14px; text-align: left; font-weight: 600; color: var(--slate); border-bottom: 2px solid var(--border); white-space: nowrap; background: var(--bg); position: sticky; top: 0; }
    .admin-table td { padding: 10px 14px; border-bottom: 1px solid var(--border); vertical-align: middle; }
    .admin-table tr:hover td { background: #F8FAFC; }
    .admin-row-actions { display: flex; gap: 6px; }
    .admin-search-bar { display: flex; gap: 10px; margin-bottom: 16px; align-items: center; }
    .admin-search-bar input { max-width: 320px; }
    .admin-badge { padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
    .admin-badge-free { background: #F1F5F9; color: #64748B; }
    .admin-badge-pro { background: #EEF2FF; color: #6366F1; }
    .admin-badge-enterprise { background: #FFFBEB; color: #D97706; }
    .admin-nav { display: flex; gap: 4px; margin-bottom: 24px; background: #F1F5F9; border-radius: 10px; padding: 4px; width: fit-content; }
    .admin-nav-item { padding: 8px 18px; border-radius: 8px; font-size: 13px; font-weight: 600; cursor: pointer; border: none; background: transparent; color: var(--slate); transition: all 0.15s; }
    .admin-nav-item.active { background: var(--surface); color: var(--text); box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
    /* ========== RESPONSIVE ========== */
    @media (max-width: 900px) {
      .auth-layout { grid-template-columns: 1fr; }
      .auth-left { display: none; }
      .quick-cards { grid-template-columns: 1fr 1fr; }
      .score-grid { grid-template-columns: repeat(3,1fr); }
      .pricing-cards { grid-template-columns: 1fr; }
    }
  </style>
</head>
<body>

<!-- ====== AUTH: Landing / 未登录入口 ====== -->
<div id="view-landing" class="view active">
  <div class="auth-layout">
    <div class="auth-left">
      <div class="auth-brand">
        <div class="auth-brand-icon">🧠</div>
        <div>
          <div class="auth-brand-name">AILange</div>
          <div class="auth-brand-sub">大脑营行 · AI 诊断引擎</div>
        </div>
      </div>
      <div class="auth-hero-title">
        让AI帮你做<span>企业诊断</span><br>找准经营着力点
      </div>
      <p class="auth-hero-desc">
        基于苏引华系统思维课程体系，AI智能体通过<strong>五大维度45个着力点</strong>，
        快速定位企业经营问题，一键生成诊断报告与解决方案。
      </p>
      <div class="auth-features">
        <div class="auth-feature">
          <div class="auth-feature-icon" style="background:rgba(99,102,241,0.2)">🧭</div>
          <div class="auth-feature-text">
            <h4>五大维度深度诊断</h4>
            <p>产品 · 客户 · 渠道 · 团队 · 财务，全方位体检</p>
          </div>
        </div>
        <div class="auth-feature">
          <div class="auth-feature-icon" style="background:rgba(16,185,129,0.2)">⚡</div>
          <div class="auth-feature-text">
            <h4>30秒出具诊断报告</h4>
            <p>AI自动匹配着力点，生成优先级行动清单</p>
          </div>
        </div>
        <div class="auth-feature">
          <div class="auth-feature-icon" style="background:rgba(245,158,11,0.2)">📊</div>
          <div class="auth-feature-text">
            <h4>一键导出 Excel + PPT</h4>
            <p>标准化诊断报告，可直接用于客户汇报</p>
          </div>
        </div>
      </div>
    </div>
    <div class="auth-right">
      <div style="text-align:center;margin-bottom:28px">
        <div style="font-size:28px;margin-bottom:8px">🧠</div>
        <h2>欢迎回来</h2>
        <p class="subtitle">登录开始 AI 企业诊断</p>
      </div>
      <div class="form-group">
        <label>手机号码</label>
        <input type="tel" id="login-phone" placeholder="请输入手机号" maxlength="11">
      </div>
      <div class="form-group">
        <label>密码 <a href="#" onclick="showView('view-forgot')" style="float:right;font-size:12px;color:var(--primary);font-weight:500">忘记密码？</a></label>
        <input type="password" id="login-password" placeholder="••••••••">
        <div class="form-error" id="login-error"></div>
      </div>
      <button class="btn btn-primary btn-lg" style="width:100%;justify-content:center" onclick="handleLogin()">
        <span>🚀</span> 立即登录
      </button>
      <div class="divider">或者</div>
      <button class="btn btn-ghost btn-lg" style="width:100%;justify-content:center" onclick="showView('view-register')">
        没有账号？免费注册
      </button>
    </div>
  </div>
</div>

<!-- ====== AUTH: 注册 ====== -->
<div id="view-register" class="view">
  <div class="auth-layout">
    <div class="auth-left">
      <div class="auth-brand">
        <div class="auth-brand-icon">🧠</div>
        <div>
          <div class="auth-brand-name">AILange</div>
          <div class="auth-brand-sub">大脑营行 · AI 诊断引擎</div>
        </div>
      </div>
      <div class="auth-hero-title">开始你的<br><span>AI诊断</span>之旅</div>
      <p class="auth-hero-desc">免费注册，立即获得每日3次诊断机会。升级专业版解锁无限诊断与报告导出。</p>
      <div style="background:rgba(99,102,241,0.1);border:1px solid rgba(99,102,241,0.2);border-radius:12px;padding:20px;margin-top:40px">
        <div style="font-size:13px;color:#C7D2FE;font-weight:700;margin-bottom:12px">🎁 注册即送</div>
        <div style="font-size:13px;color:#A5B4FC">✓ 每日3次免费诊断</div>
        <div style="font-size:13px;color:#A5B4FC;margin-top:6px">✓ 基础五大维度分析</div>
        <div style="font-size:13px;color:#A5B4FC;margin-top:6px">✓ 诊断历史记录保存</div>
        <div style="font-size:13px;color:#A5B4FC;margin-top:6px">✓ 知识库基础浏览</div>
      </div>
    </div>
    <div class="auth-right" style="overflow-y:auto">
      <h2>免费注册</h2>
      <p class="subtitle">创建你的 AILange 账号，开始 AI 企业诊断</p>
      <div class="form-group">
        <label>手机号码 *</label>
        <input type="tel" id="reg-phone" placeholder="请输入手机号" maxlength="11">
      </div>
      <div class="form-group">
        <label>用户名 *</label>
        <input type="text" id="reg-username" placeholder="你的昵称">
      </div>
      <div class="form-group">
        <label>密码 * <span style="font-weight:400;color:var(--slate)">（至少6位）</span></label>
        <input type="password" id="reg-password" placeholder="设置登录密码">
      </div>
      <div class="form-group">
        <label>邮箱地址 <span style="font-weight:400;color:var(--slate)">（选填）</span></label>
        <input type="email" id="reg-email" placeholder="your@email.com">
      </div>
      <div class="form-group">
        <label>公司/品牌名称 <span style="font-weight:400;color:var(--slate)">（选填）</span></label>
        <input type="text" id="reg-company" placeholder="你在哪里工作？">
      </div>
      <div class="form-group">
        <label>你的职位角色 <span style="font-weight:400;color:var(--slate)">（选填）</span></label>
        <select id="reg-role">
          <option value="">请选择...</option>
          <option>企业主/老板</option>
          <option>咨询顾问</option>
          <option>营销总监</option>
          <option>销售经理</option>
          <option>运营总监</option>
          <option>其他</option>
        </select>
      </div>
      <div class="form-error" id="reg-error"></div>
      <button class="btn btn-primary btn-lg" style="width:100%;justify-content:center;margin-top:8px" onclick="handleRegister()">
        🎉 立即免费注册
      </button>
      <p class="agreement">注册即代表你同意 <a href="#">服务条款</a> 和 <a href="#">隐私政策</a></p>
      <p class="auth-switch">已有账号？<a onclick="showView('view-landing')">立即登录</a></p>
    </div>
  </div>
</div>

<!-- ====== AUTH: 忘记密码 ====== -->
<div id="view-forgot" class="view">
  <div class="auth-layout">
    <div class="auth-left">
      <div class="auth-brand">
        <div class="auth-brand-icon">🧠</div>
        <div><div class="auth-brand-name">AILange</div><div class="auth-brand-sub">大脑营行 · AI 诊断引擎</div></div>
      </div>
      <div class="auth-hero-title">找回你的<span>账号</span></div>
      <p class="auth-hero-desc">输入注册手机号，我们将发送短信验证码到你的手机。</p>
    </div>
    <div class="auth-right">
      <div style="text-align:center;margin-bottom:28px">
        <div style="font-size:36px;margin-bottom:8px">🔑</div>
        <h2>忘记密码</h2>
        <p class="subtitle">输入手机号，接收短信验证码</p>
      </div>
      <div class="form-group">
        <label>注册手机号</label>
        <input type="tel" id="forgot-phone" placeholder="请输入手机号" maxlength="11">
      </div>
      <div class="form-group" id="forgot-code-group" style="display:none">
        <label>短信验证码</label>
        <div style="display:flex;gap:10px">
          <input type="text" id="forgot-code" placeholder="6位验证码" maxlength="6" style="flex:1">
          <button class="btn btn-ghost btn-sm" onclick="handleSendSms()" style="white-space:nowrap" id="resend-btn">发送验证码</button>
        </div>
      </div>
      <div class="form-group" id="forgot-pwd-group" style="display:none">
        <label>新密码 <span style="font-weight:400;color:var(--slate)">（至少6位）</span></label>
        <input type="password" id="forgot-new-pwd" placeholder="设置新密码">
      </div>
      <button class="btn btn-primary btn-lg" style="width:100%;justify-content:center" id="forgot-btn" onclick="handleForgot()">
        获取验证码
      </button>
      <p class="auth-switch" style="margin-top:20px"><a onclick="showView('view-landing')">← 返回登录</a></p>
    </div>
  </div>
</div>

<!-- ====== APP: 主应用 ====== -->
<div id="view-app" class="view">
  <div class="app-layout">
    <!-- Header -->
    <header class="app-header">
      <div class="header-brand" onclick="appNavigate('workbench')">
        <div class="header-logo">🧠</div>
        <div style="font-size:18px;font-weight:800;letter-spacing:-0.5px">AILange</div>
      </div>
      <div class="header-nav" style="margin-left:24px">
        <div class="header-nav-item active" id="nav-workbench" onclick="appNavigate('workbench')">🔍 诊断工作台</div>
        <div class="header-nav-item" id="nav-dimensions" onclick="appNavigate('dimensions')">🧭 五大维度</div>
        <div class="header-nav-item" id="nav-results" onclick="appNavigate('results')">📊 诊断结果</div>
        <div class="header-nav-item" id="nav-generate" onclick="appNavigate('generate')">📄 文档生成</div>
        <div class="header-nav-item" id="nav-knowledge" onclick="appNavigate('knowledge')">📚 知识库</div>
        <div class="header-nav-item" id="nav-mydocs" onclick="appNavigate('my-docs')">📋 我的文档</div>
      </div>
      <div class="header-spacer"></div>
      <div class="header-nav">
        <div class="header-nav-item" id="nav-membership" onclick="appNavigate('membership')">💎 升级会员</div>
        <div class="header-nav-item" id="nav-admin" onclick="enterAdmin()" style="display:none">⚙️ 管理</div>
      </div>
      <div class="header-user" onclick="appNavigate('profile')">
        <div class="user-avatar" id="user-avatar-text">U</div>
        <div class="user-info">
          <div class="user-name" id="header-username">用户</div>
          <div class="user-tier" id="header-tier">免费版</div>
        </div>
      </div>
    </header>

    <!-- Sidebar -->
    <aside class="app-sidebar">
      <button class="new-diag-btn" onclick="appNavigate('workbench')">
        ＋ 新建诊断
      </button>
      <div class="sidebar-section">最近诊断</div>
      <div class="history-item active" onclick="appNavigate('results')">
        <div style="display:flex;align-items:center;gap:8px">
          <div class="history-dot" style="background:var(--rose)"></div>
          <div>
            <div class="history-title">业绩下滑诊断</div>
            <div class="history-date">2小时前 · 5个着力点</div>
          </div>
        </div>
      </div>
      <div class="history-item" onclick="appNavigate('results')">
        <div style="display:flex;align-items:center;gap:8px">
          <div class="history-dot" style="background:var(--purple)"></div>
          <div>
            <div class="history-title">团队执行力不足</div>
            <div class="history-date">昨天 · 3个着力点</div>
          </div>
        </div>
      </div>
      <div class="history-item" onclick="appNavigate('results')">
        <div style="display:flex;align-items:center;gap:8px">
          <div class="history-dot" style="background:var(--emerald)"></div>
          <div>
            <div class="history-title">客户流失分析</div>
            <div class="history-date">3天前 · 7个着力点</div>
          </div>
        </div>
      </div>
      <div class="sidebar-section">工具导航</div>
      <div class="sidebar-item" id="sidebar-dimensions" onclick="appNavigate('dimensions')"><span class="icon">🧭</span> 五大维度总览</div>
      <div class="sidebar-item" id="sidebar-knowledge" onclick="appNavigate('knowledge')"><span class="icon">📚</span> 知识库</div>
      <div class="sidebar-item" id="sidebar-mydocs" onclick="appNavigate('my-docs')"><span class="icon">📋</span> 我的文档</div>
      <div class="sidebar-item" id="sidebar-generate" onclick="appNavigate('generate')"><span class="icon">📄</span> 文档中心</div>
      <div class="sidebar-item" id="sidebar-membership" onclick="appNavigate('membership')"><span class="icon">💎</span> 会员中心</div>
      <div class="sidebar-item" id="sidebar-profile" onclick="appNavigate('profile')"><span class="icon">👤</span> 个人中心</div>
      <div class="sidebar-section">系统</div>
      <div class="sidebar-item" style="color:var(--rose)" onclick="handleLogout()"><span class="icon">🚪</span> 退出登录</div>
    </aside>

    <!-- Main Pages -->
    <main class="app-main">

      <!-- 诊断工作台 -->
      <div id="app-workbench" class="view active">
        <div class="welcome-area">
          <div class="welcome-badge">🧠 AI 智能诊断引擎 · 45大着力点</div>
          <h1 class="welcome-title">你好，<span class="highlight" id="welcome-name">浪哥</span><br>今天要诊断哪个业务问题？</h1>
          <p class="welcome-desc">输入企业业务痛点，AI基于系统思维<strong>五大维度45个着力点</strong>快速定位问题，一键生成诊断Excel与解决方案PPT</p>
        </div>
        <div class="quick-cards">
          <div class="quick-card" onclick="fillInput('业绩持续下滑，客户成交率低，不知道问题出在哪里')">
            <div class="quick-card-icon">📉</div>
            <div class="quick-card-title">业绩下滑</div>
            <div class="quick-card-desc">成交率低，业绩停滞，找不到增长突破口</div>
          </div>
          <div class="quick-card" onclick="fillInput('客户不断流失，老客户不复购，新客开发成本越来越高')">
            <div class="quick-card-icon">👥</div>
            <div class="quick-card-title">客户流失</div>
            <div class="quick-card-desc">老客不复购，新客难开发，获客成本飙升</div>
          </div>
          <div class="quick-card" onclick="fillInput('团队执行力差，安排的事情做不到位，人员流动大')">
            <div class="quick-card-icon">⚡</div>
            <div class="quick-card-title">团队问题</div>
            <div class="quick-card-desc">执行力弱，人才流失，管理混乱</div>
          </div>
          <div class="quick-card" onclick="fillInput('渠道拓展遇到瓶颈，代理商积极性不高，销售增长乏力')">
            <div class="quick-card-icon">🌐</div>
            <div class="quick-card-title">渠道瓶颈</div>
            <div class="quick-card-desc">渠道拓展难，代理积极性低，销售受阻</div>
          </div>
        </div>
        <div class="input-area">
          <textarea id="diag-input" placeholder="📝 描述你的业务痛点...例如：我们做餐饮7年了，但最近半年客流量持续下降，主要客群流失，口碑在下滑，想知道问题出在哪里以及怎么解决……"></textarea>
          <div class="input-toolbar">
            <span class="char-count" id="char-count">0 / 2000字</span>
            <div style="flex:1"></div>
            <button class="btn btn-ghost btn-sm" onclick="clearInput()">清空</button>
            <button class="btn btn-indigo" style="padding:10px 28px" onclick="startDiagnosis()" id="diag-submit-btn">
              🚀 开始诊断
            </button>
          </div>
        </div>
        <div style="margin-top:20px;display:grid;grid-template-columns:repeat(3,1fr);gap:12px">
          <div class="card" style="padding:16px;display:flex;gap:12px;align-items:center">
            <div style="font-size:24px">🎯</div>
            <div><div style="font-size:13px;font-weight:700">精准定位</div><div style="font-size:12px;color:var(--slate)">45个着力点匹配</div></div>
          </div>
          <div class="card" style="padding:16px;display:flex;gap:12px;align-items:center">
            <div style="font-size:24px">⚡</div>
            <div><div style="font-size:13px;font-weight:700">30秒出报告</div><div style="font-size:12px;color:var(--slate)">AI实时分析</div></div>
          </div>
          <div class="card" style="padding:16px;display:flex;gap:12px;align-items:center">
            <div style="font-size:24px">📊</div>
            <div><div style="font-size:13px;font-weight:700">一键导出</div><div style="font-size:12px;color:var(--slate)">Excel + PPT报告</div></div>
          </div>
        </div>
      </div>

      <!-- 五大维度 -->
      <div id="app-dimensions" class="view">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
          <div>
            <h2 style="font-size:22px;font-weight:800;letter-spacing:-0.5px">五大维度工具</h2>
            <p style="font-size:13px;color:var(--slate);margin-top:4px">系统思维课程体系 · 共45个工具，全方位诊断企业经营健康度</p>
          </div>
          <button class="btn btn-primary" onclick="appNavigate('workbench')">开始诊断 →</button>
        </div>
        <div class="dim-tabs">
          <div class="dim-tab active-product" id="tab-product" onclick="switchDim('product')">🏭 产品系统 <span style="font-size:11px;margin-left:4px;opacity:0.7">9大工具</span></div>
          <div class="dim-tab" id="tab-customer" onclick="switchDim('customer')">👥 客户系统 <span style="font-size:11px;margin-left:4px;opacity:0.7">9大工具</span></div>
          <div class="dim-tab" id="tab-channel" onclick="switchDim('channel')">🌐 渠道系统 <span style="font-size:11px;margin-left:4px;opacity:0.7">9大工具</span></div>
          <div class="dim-tab" id="tab-team" onclick="switchDim('team')">👔 团队系统 <span style="font-size:11px;margin-left:4px;opacity:0.7">9大工具</span></div>
          <div class="dim-tab" id="tab-finance" onclick="switchDim('finance')">💰 财务系统 <span style="font-size:11px;margin-left:4px;opacity:0.7">9大工具</span></div>
        </div>
        <div id="dim-content"></div>
      </div>

      <!-- 诊断结果 -->
      <div id="app-results" class="view">
        <div class="result-header">
          <div>
            <h2 style="font-size:22px;font-weight:800;letter-spacing:-0.5px">诊断结果报告</h2>
            <p style="font-size:13px;color:var(--slate);margin-top:4px">诊断主题：<span id="diag-topic">-</span> · 生成于 <span id="diag-time">-</span></p>
            <p style="font-size:11px;color:var(--slate);margin-top:2px" id="diag-meta"></p>
          </div>
          <div style="display:flex;gap:10px">
            <button class="btn btn-ghost btn-sm" onclick="appNavigate('generate')">📊 导出报告</button>
            <button class="btn btn-primary btn-sm" onclick="appNavigate('workbench')">新建诊断</button>
          </div>
        </div>
        <div class="score-grid" id="score-cards">
          <div style="text-align:center;padding:40px;color:var(--slate);grid-column:1/-1">
            🔍 暂无诊断数据，请先在工作台发起诊断
          </div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 340px;gap:24px">
          <div>
            <h3 style="font-size:16px;font-weight:700;margin-bottom:14px">🔍 核心问题清单（按优先级）</h3>
            <div class="issues-list" id="issues-list"></div>
            <div style="margin-top:20px">
              <h3 style="font-size:16px;font-weight:700;margin-bottom:14px">📋 诊断总结</h3>
              <div style="padding:16px;background:#F8FAFC;border-radius:10px;font-size:14px;line-height:1.8;color:var(--text)" id="diag-summary"></div>
            </div>
          </div>
          <div>
            <h3 style="font-size:16px;font-weight:700;margin-bottom:14px">🎯 优先行动计划</h3>
            <div style="display:flex;flex-direction:column;gap:8px" id="priority-actions"></div>
            <div style="background:#FFF1F2;border:1px solid #FECDD3;border-radius:10px;padding:14px;margin-top:16px;display:none" id="risk-alert"></div>
          </div>
        </div>
      </div>

      <!-- 文档生成 -->
      <div id="app-generate" class="view">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
          <div>
            <h2 style="font-size:22px;font-weight:800;letter-spacing:-0.5px">文档生成中心</h2>
            <p style="font-size:13px;color:var(--slate);margin-top:4px">一键导出专业诊断报告</p>
          </div>
        </div>
        <div class="doc-cards">
          <div class="doc-card">
            <div class="doc-type-icon">📊</div>
            <h3 style="font-size:16px;font-weight:700;margin-bottom:6px">诊断报告 Excel</h3>
            <p style="font-size:13px;color:var(--slate);margin-bottom:14px">包含五大维度评分、45项着力点分析、优先级矩阵、行动计划表</p>
            <div class="progress-bar"><div class="progress-fill" id="excel-progress" style="width:87%;background:var(--emerald)"></div></div>
            <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">
              <span style="font-size:12px;color:var(--slate)">生成中 87%...</span>
              <span style="font-size:12px;color:var(--emerald);font-weight:600">预计 8s</span>
            </div>
            <button class="btn btn-primary btn-sm" style="margin-top:16px" onclick="showToast('Excel报告即将生成，专业版用户无限导出','success')">📥 下载 Excel</button>
          </div>
          <div class="doc-card">
            <div class="doc-type-icon">📑</div>
            <h3 style="font-size:16px;font-weight:700;margin-bottom:6px">解决方案 PPT</h3>
            <p style="font-size:13px;color:var(--slate);margin-bottom:14px">专业汇报模板，含问题分析、改善方案、实施路径、预期成果</p>
            <div class="progress-bar"><div class="progress-fill" id="ppt-progress" style="width:42%;background:var(--indigo)"></div></div>
            <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">
              <span style="font-size:12px;color:var(--slate)">生成中 42%...</span>
              <span style="font-size:12px;color:var(--indigo);font-weight:600">预计 23s</span>
            </div>
            <button class="btn btn-ghost btn-sm" style="margin-top:16px" onclick="appNavigate('membership')">🔒 专业版解锁 PPT</button>
          </div>
        </div>
        <h3 style="font-size:16px;font-weight:700;margin-bottom:14px">📁 历史文档</h3>
        <div class="doc-list">
          <div class="doc-row"><div class="doc-icon">📊</div><div class="doc-info"><div class="doc-title">业绩下滑诊断_20260614.xlsx</div><div class="doc-meta">2小时前 · 256KB</div></div><div class="doc-tag" style="background:#F0FDF4;color:var(--emerald)">已完成</div></div>
          <div class="doc-row"><div class="doc-icon">📑</div><div class="doc-info"><div class="doc-title">团队管理方案_20260613.pptx</div><div class="doc-meta">昨天 · 1.2MB</div></div><div class="doc-tag" style="background:#F0FDF4;color:var(--emerald)">已完成</div></div>
          <div class="doc-row"><div class="doc-icon">📊</div><div class="doc-info"><div class="doc-title">客户流失分析_20260611.xlsx</div><div class="doc-meta">3天前 · 312KB</div></div><div class="doc-tag" style="background:#F0FDF4;color:var(--emerald)">已完成</div></div>
        </div>
      </div>

      <!-- 知识库 -->
      <div id="app-knowledge" class="view">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
          <div>
            <h2 style="font-size:22px;font-weight:800;letter-spacing:-0.5px">知识库</h2>
            <p style="font-size:13px;color:var(--slate);margin-top:4px">苏引华系统思维课程体系 · 大脑营行方法论</p>
          </div>
        </div>
        <div class="kb-search">
          <input type="text" placeholder="🔍 搜索知识库...">
          <button class="btn btn-primary btn-sm">搜索</button>
        </div>
        <div style="display:flex;gap:8px;margin-bottom:20px;flex-wrap:wrap">
          <button class="btn btn-indigo btn-sm">全部</button>
          <button class="btn btn-ghost btn-sm">产品系统</button>
          <button class="btn btn-ghost btn-sm">客户系统</button>
          <button class="btn btn-ghost btn-sm">渠道系统</button>
          <button class="btn btn-ghost btn-sm">团队系统</button>
          <button class="btn btn-ghost btn-sm">财务系统</button>
        </div>
        <div class="doc-list">
          <div class="doc-row"><div class="doc-icon">📖</div><div class="doc-info"><div class="doc-title">【系统思维】五大核心模块：重构企业竞争力的底层逻辑</div><div class="doc-meta">系统思维 · 2024-11-20</div></div><div class="doc-tag" style="background:#EEF2FF;color:var(--indigo)">核心文章</div></div>
          <div class="doc-row"><div class="doc-icon">🖼️</div><div class="doc-info"><div class="doc-title">系统思维着力点业务流框架（完整版）</div><div class="doc-meta">框架图 · 45个着力点工具</div></div><div class="doc-tag" style="background:#FFF1F2;color:var(--rose)">重要资料</div></div>
          <div class="doc-row"><div class="doc-icon">📖</div><div class="doc-info"><div class="doc-title">产品定位三步法：从价值主张到差异化定位</div><div class="doc-meta">产品系统 · 着力点工具讲解</div></div><div class="doc-tag" style="background:#EEF2FF;color:var(--indigo)">精选</div></div>
          <div class="doc-row"><div class="doc-icon">📖</div><div class="doc-info"><div class="doc-title">客户画像四维建模方法：精准识别你的目标客群</div><div class="doc-meta">客户系统 · 实操指南</div></div><div class="doc-tag" style="background:#EEF2FF;color:var(--indigo)">精选</div></div>
          <div class="doc-row"><div class="doc-icon">📖</div><div class="doc-info"><div class="doc-title">渠道招商：项目包装到落地执行的完整路径</div><div class="doc-meta">渠道系统 · 实操手册</div></div><div class="doc-tag" style="background:#EEF2FF;color:var(--indigo)">精选</div></div>
          <div class="doc-row"><div class="doc-icon">📖</div><div class="doc-info"><div class="doc-title">如何设计有效的绩效管理体系？</div><div class="doc-meta">团队系统 · 管理工具</div></div><div class="doc-tag" style="background:#F0FDF4;color:var(--emerald)">实用</div></div>
          <div class="doc-row"><div class="doc-icon">📖</div><div class="doc-info"><div class="doc-title">现金流管理：中小企业财务健康度自检手册</div><div class="doc-meta">财务系统 · 自查工具</div></div><div class="doc-tag" style="background:#F0FDF4;color:var(--emerald)">实用</div></div>
        </div>
      </div>

      <!-- 会员中心 -->
      <div id="app-membership" class="view">
        <div class="member-hero">
          <h2>会员中心</h2>
          <p id="member-desc">升级专业版，解锁无限诊断与报告导出</p>
          <div class="member-stats">
            <div>
              <div class="member-stat-val" id="diag-count-today">0/3</div>
              <div class="member-stat-label">今日诊断次数</div>
            </div>
            <div>
              <div class="member-stat-val" id="export-count">0/1</div>
              <div class="member-stat-label">本月导出次数</div>
            </div>
            <div>
              <div class="member-stat-val" id="current-tier-name">免费版</div>
              <div class="member-stat-label">当前套餐</div>
            </div>
          </div>
        </div>
        <div style="display:flex;gap:10px;margin-bottom:20px">
          <button class="btn btn-primary" id="plan-monthly" onclick="switchPlan('monthly')">按月付费</button>
          <button class="btn btn-ghost" id="plan-yearly" onclick="switchPlan('yearly')">按年付费 <span style="font-size:12px;color:var(--emerald);margin-left:4px">省2个月</span></button>
        </div>
        <div class="pricing-cards">
          <!-- 免费版 -->
          <div class="pricing-card">
            <div class="pricing-tier" style="color:var(--slate)">Free · 免费版</div>
            <div class="pricing-price">
              <span class="amount">¥0</span>
              <span class="unit">/月</span>
            </div>
            <ul class="pricing-features">
              <li>每日3次诊断</li>
              <li>基础五大维度分析</li>
              <li>Excel导出（每月1次）</li>
              <li>知识库基础浏览</li>
            </ul>
            <button class="btn btn-ghost" style="width:100%;justify-content:center" disabled>当前方案</button>
          </div>
          <!-- 专业版 -->
          <div class="pricing-card popular">
            <div class="popular-badge">🔥 最受欢迎</div>
            <div class="pricing-tier" style="color:var(--indigo)">Pro · 专业版</div>
            <div class="pricing-price">
              <span class="amount" id="pro-price">¥99</span>
              <span class="unit">/月</span>
              <div class="yearly" id="pro-yearly-hint" style="display:none">年付仅 ¥82.5/月，节省 ¥198</div>
            </div>
            <ul class="pricing-features">
              <li>每日10次诊断</li>
              <li>全维度深度分析</li>
              <li>Excel/PPT无限导出</li>
              <li>知识库全文搜索</li>
              <li>历史记录永久保存</li>
              <li>优先AI响应通道</li>
            </ul>
            <button class="btn btn-indigo" style="width:100%;justify-content:center" onclick="purchaseTier('pro')">
              立即升级专业版
            </button>
          </div>
          <!-- 企业版 -->
          <div class="pricing-card" style="opacity:0.6">
            <div class="pricing-tier" style="color:var(--amber)">Enterprise · 企业版</div>
            <div class="pricing-price">
              <span class="amount">暂不开放</span>
            </div>
            <ul class="pricing-features">
              <li>无限次诊断</li>
              <li>定制化深度诊断方案</li>
              <li>无限Excel/PPT导出</li>
              <li>知识库全文搜索+上传</li>
              <li>团队协作（最多10人）</li>
              <li>专属AI模型调优</li>
              <li>API接口对接</li>
              <li>7×24专属客服</li>
            </ul>
            <button class="btn btn-ghost" style="width:100%;justify-content:center;border-color:#d1d5db;color:#9ca3af;cursor:not-allowed" disabled>
              🚧 暂不开放
            </button>
          </div>
        </div>
      </div>

      <!-- 我的文档 -->
      <div id="app-my-docs" class="view">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px">
          <div>
            <h2 style="font-size:22px;font-weight:800;letter-spacing:-0.5px;margin-bottom:4px">📋 我的文档</h2>
            <p style="font-size:13px;color:var(--slate)">查看和重新下载你生成的工具方案</p>
          </div>
          <button class="btn btn-primary" onclick="appNavigate('dimensions')" style="font-size:13px;padding:8px 18px">🪄 生成新工具</button>
        </div>
        <div id="my-tools-list"></div>
      </div>

      <!-- 个人中心 -->
      <div id="app-profile" class="view">
        <h2 style="font-size:22px;font-weight:800;letter-spacing:-0.5px;margin-bottom:24px">个人中心</h2>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
          <div>
            <div class="profile-card">
              <div class="profile-avatar" id="profile-avatar">U</div>
              <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
                <div>
                  <div style="font-size:18px;font-weight:700" id="profile-name">-</div>
                  <div style="font-size:13px;color:var(--slate)" id="profile-email">-</div>
                </div>
                <div style="margin-left:auto">
                  <span class="badge badge-free" id="profile-badge">免费版</span>
                </div>
              </div>
              <div style="display:flex;flex-direction:column;gap:12px">
                <div class="form-group" style="margin:0">
                  <label>用户名</label>
                  <input type="text" id="edit-username" placeholder="你的用户名">
                </div>
                <div class="form-group" style="margin:0">
                  <label>手机号</label>
                  <input type="tel" id="edit-phone" placeholder="联系电话">
                </div>
                <div class="form-group" style="margin:0">
                  <label>公司名称</label>
                  <input type="text" id="edit-company" placeholder="你在哪里工作">
                </div>
                <div class="form-group" style="margin:0">
                  <label>职位角色</label>
                  <input type="text" id="edit-role" placeholder="你的职位">
                </div>
                <button class="btn btn-primary" style="margin-top:8px" onclick="saveProfile()">保存更改</button>
              </div>
            </div>
          </div>
          <div>
            <div class="profile-card">
              <h3 style="font-size:16px;font-weight:700;margin-bottom:16px">修改密码</h3>
              <div class="form-group">
                <label>当前密码</label>
                <input type="password" id="old-pwd" placeholder="输入旧密码">
              </div>
              <div class="form-group">
                <label>新密码</label>
                <input type="password" id="new-pwd" placeholder="输入新密码">
              </div>
              <div class="form-group">
                <label>确认新密码</label>
                <input type="password" id="confirm-pwd" placeholder="再次输入新密码">
              </div>
              <button class="btn btn-primary" onclick="changePassword()">更新密码</button>
            </div>
            <div class="profile-card" style="margin-top:20px">
              <h3 style="font-size:16px;font-weight:700;margin-bottom:16px">我的订单</h3>
              <div id="order-list" style="font-size:13px;color:var(--slate)">暂无订单记录</div>
            </div>
          </div>
        </div>
      </div>

    </main>
  </div>
</div>

<!-- 购买/支付弹窗 -->
<div class="modal-overlay" id="purchase-modal">
  <div class="modal" style="max-width:480px">
    <button class="modal-close" onclick="closeModal('purchase-modal')">✕</button>
    <div class="modal-title" id="purchase-title">🎉 升级会员</div>
    <div id="purchase-content"></div>
    <div style="display:flex;gap:10px;margin-top:20px" id="purchase-actions">
      <button class="btn btn-ghost" style="flex:1;justify-content:center" onclick="closeModal('purchase-modal')">取消</button>
    </div>
  </div>
</div>

<!-- Toast -->
<div class="toast-container" id="toast-container"></div>

<!-- ====== ADMIN: 管理后台 ====== -->
<div id="view-admin" class="view">
  <div style="display:flex;height:100vh;background:var(--bg)">
    <!-- Admin Sidebar -->
    <aside style="width:240px;background:#0F172A;color:#fff;display:flex;flex-direction:column;flex-shrink:0">
      <div style="padding:20px;border-bottom:1px solid rgba(255,255,255,0.1)">
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px">
          <div style="font-size:20px">🧠</div>
          <div style="font-size:17px;font-weight:800">AILange Admin</div>
        </div>
        <div style="font-size:12px;color:#94A3B8">管理后台 v1.0</div>
      </div>
      <nav style="flex:1;padding:12px">
        <div class="admin-nav-vertical" style="display:flex;flex-direction:column;gap:2px">
          <div class="admin-nav-side active" onclick="adminSwitchTab('dashboard')" id="admin-nav-dashboard">📊 数据仪表盘</div>
          <div class="admin-nav-side" onclick="adminSwitchTab('users')" id="admin-nav-users">👥 用户管理</div>
          <div class="admin-nav-side" onclick="adminSwitchTab('diagnoses')" id="admin-nav-diagnoses">🔍 诊断记录</div>
          <div class="admin-nav-side" onclick="adminSwitchTab('orders')" id="admin-nav-orders">💰 订单管理</div>
          <div class="admin-nav-side" onclick="adminSwitchTab('knowledge')" id="admin-nav-knowledge">📚 知识库</div>
        </div>
      </nav>
      <div style="padding:16px;border-top:1px solid rgba(255,255,255,0.1);display:flex;align-items:center;gap:10px">
        <div style="width:32px;height:32px;border-radius:50%;background:var(--indigo);display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700" id="admin-avatar">A</div>
        <div>
          <div style="font-size:13px;font-weight:600;color:#E2E8F0" id="admin-name">管理员</div>
          <a onclick="showView('view-app');appNavigate('workbench')" style="font-size:11px;color:#64748B;cursor:pointer;text-decoration:none">← 返回前台</a>
        </div>
      </div>
    </aside>

    <!-- Admin Main Content -->
    <main style="flex:1;overflow-y:auto;padding:28px 32px">
      <!-- Dashboard -->
      <div id="admin-tab-dashboard">
        <h2 style="font-size:22px;font-weight:800;margin-bottom:4px;letter-spacing:-0.5px">📊 数据仪表盘</h2>
        <p style="font-size:13px;color:var(--slate);margin-bottom:24px">平台运营数据概览</p>

        <div class="admin-stats-grid" id="admin-stats-cards">
          <div class="admin-stat-card"><div class="stat-value">-</div><div class="stat-label">总用户数</div></div>
          <div class="admin-stat-card"><div class="stat-value">-</div><div class="stat-label">总诊断次数</div></div>
          <div class="admin-stat-card"><div class="stat-value">-</div><div class="stat-label">总订单数</div></div>
          <div class="admin-stat-card"><div class="stat-value">-</div><div class="stat-label">今日新增用户</div></div>
        </div>

        <div style="display:grid;grid-template-columns:1fr 300px;gap:24px">
          <div class="card" style="padding:20px">
            <h3 style="font-size:15px;font-weight:700;margin-bottom:16px">📈 近7天趋势</h3>
            <div style="height:200px;display:flex;align-items:flex-end;gap:12px" id="admin-trend-chart"></div>
          </div>
          <div class="card" style="padding:20px">
            <h3 style="font-size:15px;font-weight:700;margin-bottom:16px">👥 会员分布</h3>
            <div id="admin-tier-chart"></div>
          </div>
        </div>
      </div>

      <!-- Users -->
      <div id="admin-tab-users" style="display:none">
        <h2 style="font-size:22px;font-weight:800;margin-bottom:4px">👥 用户管理</h2>
        <p style="font-size:13px;color:var(--slate);margin-bottom:20px">管理平台所有注册用户</p>
        <div class="admin-search-bar">
          <input type="text" placeholder="搜索手机号/用户名/公司..." id="admin-user-search" oninput="adminLoadUsers()">
          <span style="font-size:13px;color:var(--slate)" id="admin-user-count"></span>
        </div>
        <div class="admin-table-wrap card">
          <table class="admin-table">
            <thead><tr>
              <th>ID</th><th>手机号</th><th>用户名</th><th>公司</th><th>会员等级</th><th>注册时间</th><th>状态</th><th>操作</th>
            </tr></thead>
            <tbody id="admin-users-tbody"></tbody>
          </table>
        </div>
        <div style="display:flex;justify-content:center;gap:6px;margin-top:16px" id="admin-users-pager"></div>
      </div>

      <!-- Diagnoses -->
      <div id="admin-tab-diagnoses" style="display:none">
        <h2 style="font-size:22px;font-weight:800;margin-bottom:4px">🔍 诊断记录</h2>
        <p style="font-size:13px;color:var(--slate);margin-bottom:20px">查看所有用户的AI诊断记录</p>
        <div class="admin-table-wrap card">
          <table class="admin-table">
            <thead><tr>
              <th>ID</th><th>用户</th><th>诊断主题</th><th>维度</th><th>时间</th><th>操作</th>
            </tr></thead>
            <tbody id="admin-diags-tbody"></tbody>
          </table>
        </div>
        <div style="display:flex;justify-content:center;gap:6px;margin-top:16px" id="admin-diags-pager"></div>
      </div>

      <!-- Orders -->
      <div id="admin-tab-orders" style="display:none">
        <h2 style="font-size:22px;font-weight:800;margin-bottom:4px">💰 订单管理</h2>
        <p style="font-size:13px;color:var(--slate);margin-bottom:20px">查看所有支付订单</p>
        <div class="admin-table-wrap card">
          <table class="admin-table">
            <thead><tr>
              <th>订单号</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>时间</th>
            </tr></thead>
            <tbody id="admin-orders-tbody"></tbody>
          </table>
        </div>
      </div>

      <!-- Knowledge Base -->
      <div id="admin-tab-knowledge" style="display:none">
        <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:20px">
          <div>
            <h2 style="font-size:22px;font-weight:800;margin-bottom:4px">📚 内部知识库</h2>
            <p style="font-size:13px;color:var(--slate)">沉淀原始素材与实战案例，持续迭代</p>
          </div>
          <button class="btn btn-indigo" onclick="knowledgeShowForm()" id="knowledge-add-btn">＋ 新建文章</button>
          <button class="btn btn-ghost" onclick="knowledgeBatchImport()" title="批量导入文件并自动解析内容、建立向量索引">📦 批量导入</button>
          <button class="btn btn-ghost btn-sm" onclick="knowledgeReindexAll()" title="重建所有文章的向量搜索索引" style="font-size:11px">🔄 重建索引</button>
        </div>

        <!-- Stats bar -->
        <div id="knowledge-stats-bar" style="display:flex;gap:16px;margin-bottom:20px"></div>

        <!-- Filters -->
        <div class="admin-search-bar">
          <input type="text" placeholder="搜索标题/标签/内容..." id="knowledge-search" oninput="adminLoadKnowledge()">
          <select id="knowledge-category-filter" onchange="adminLoadKnowledge()" style="padding:8px 12px;border:1px solid var(--border);border-radius:8px;font-size:13px;background:var(--surface)">
            <option value="">全部分类</option>
            <option value="material">📦 原始素材</option>
            <option value="case">📋 实战案例</option>
          </select>
          <span style="font-size:13px;color:var(--slate)" id="knowledge-count"></span>
        </div>

        <!-- Article list -->
        <div id="knowledge-list-view">
          <div class="admin-table-wrap card">
            <table class="admin-table">
              <thead><tr>
                <th style="width:50px">ID</th><th>标题</th><th style="width:60px">附件</th><th>分类</th><th>标签</th><th>作者</th><th>更新时间</th><th style="width:100px">操作</th>
              </tr></thead>
              <tbody id="knowledge-tbody"></tbody>
            </table>
          </div>
          <div style="display:flex;justify-content:center;gap:6px;margin-top:16px" id="knowledge-pager"></div>
        </div>

        <!-- Article form (create / edit) -->
        <div id="knowledge-form-view" style="display:none">
          <div class="card" style="padding:24px">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
              <button class="btn btn-ghost btn-sm" onclick="knowledgeBackToList()">← 返回列表</button>
              <h3 style="font-size:18px;font-weight:700" id="knowledge-form-title">新建文章</h3>
            </div>

            <div style="display:flex;flex-direction:column;gap:16px">
              <div>
                <label style="font-size:13px;font-weight:600;margin-bottom:6px;display:block">分类 <span style="color:var(--rose)">*</span></label>
                <select id="knowledge-edit-category" style="padding:10px 14px;border:1px solid var(--border);border-radius:8px;font-size:14px;width:100%;background:var(--surface)">
                  <option value="material">📦 原始素材</option>
                  <option value="case">📋 实战案例</option>
                </select>
              </div>

              <div>
                <label style="font-size:13px;font-weight:600;margin-bottom:6px;display:block">标题 <span style="color:var(--rose)">*</span></label>
                <input type="text" id="knowledge-edit-title" placeholder="请输入文章标题..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:8px;font-size:14px;box-sizing:border-box">
              </div>

              <div>
                <label style="font-size:13px;font-weight:600;margin-bottom:6px;display:block">标签（逗号分隔）</label>
                <input type="text" id="knowledge-edit-tags" placeholder="例如：获客, 转化, 裂变" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:8px;font-size:14px;box-sizing:border-box">
              </div>

              <div>
                <label style="font-size:13px;font-weight:600;margin-bottom:6px;display:block">附件上传 <span style="color:var(--slate);font-weight:400;font-size:11px">（支持 Excel/Word/图片/PPT/PDF/Markdown，最大 50MB）</span></label>
                <div id="knowledge-upload-zone" style="border:2px dashed var(--border);border-radius:12px;padding:28px;text-align:center;cursor:pointer;transition:all 0.2s;background:var(--bg)" 
                  onclick="document.getElementById('knowledge-file-input').click()"
                  ondragover="event.preventDefault();this.style.borderColor='var(--indigo)';this.style.background='#EEF2FF'"
                  ondragleave="this.style.borderColor='var(--border)';this.style.background='var(--bg)'"
                  ondrop="knowledgeHandleFileDrop(event)">
                  <div style="font-size:36px;margin-bottom:8px">📎</div>
                  <div style="font-size:13px;font-weight:600;color:var(--text)">拖拽文件到此处，或点击上传</div>
                  <div style="font-size:11px;color:var(--slate);margin-top:4px">Excel (.xlsx) / Word (.docx) / 图片 / PPT (.pptx) / PDF / Markdown</div>
                </div>
                <input type="file" id="knowledge-file-input" style="display:none" accept=".jpg,.jpeg,.png,.gif,.webp,.bmp,.svg,.doc,.docx,.xls,.xlsx,.csv,.ppt,.pptx,.pdf,.txt,.md" onchange="knowledgeHandleFileSelect(event)">
                <!-- File preview area -->
                <div id="knowledge-file-preview" style="display:none;margin-top:12px;padding:14px;background:#F8FAFC;border:1px solid var(--border);border-radius:10px">
                  <div style="display:flex;align-items:center;gap:12px" id="knowledge-file-preview-content"></div>
                  <button class="btn btn-ghost btn-sm" style="color:var(--rose);margin-top:8px;font-size:12px" onclick="knowledgeRemoveFile()">✕ 移除文件</button>
                </div>
              </div>

              <div>
                <label style="font-size:13px;font-weight:600;margin-bottom:6px;display:block">内容 <span style="color:var(--slate);font-weight:400;font-size:11px">（文本描述或摘要，如已上传文件可为空）</span></label>
                <textarea id="knowledge-edit-content" placeholder="请在此粘贴或编写原始素材/案例内容..." style="width:100%;min-height:320px;padding:14px;border:1px solid var(--border);border-radius:8px;font-size:14px;line-height:1.8;resize:vertical;box-sizing:border-box;font-family:inherit"></textarea>
                <div style="font-size:11px;color:var(--slate);margin-top:4px">支持纯文本内容。后续可扩展 Markdown 或富文本编辑器。</div>
              </div>

              <div style="display:flex;gap:10px">
                <button class="btn btn-indigo" onclick="knowledgeSave()" id="knowledge-save-btn">💾 保存</button>
                <button class="btn btn-ghost" onclick="knowledgeBackToList()">取消</button>
                <span style="flex:1"></span>
                <button class="btn btn-ghost btn-sm" style="color:var(--rose);display:none" id="knowledge-delete-btn" onclick="knowledgeDelete()">🗑 删除</button>
              </div>
            </div>
          </div>
        </div>

        <!-- Article detail view -->
        <div id="knowledge-detail-view" style="display:none">
          <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
            <button class="btn btn-ghost btn-sm" onclick="knowledgeBackToList()">← 返回列表</button>
            <button class="btn btn-ghost btn-sm" onclick="knowledgeShowForm(true)" style="margin-left:auto">✏️ 编辑</button>
          </div>
          <div class="card" style="padding:28px" id="knowledge-detail-content"></div>
        </div>
      </div>
    </main>
  </div>
</div>

<style>
  .admin-nav-side { padding: 10px 14px; border-radius: 8px; font-size: 14px; cursor: pointer; color: #94A3B8; transition: all 0.15s; display: flex; align-items: center; gap: 10px; }
  .admin-nav-side:hover { background: rgba(255,255,255,0.06); color: #E2E8F0; }
  .admin-nav-side.active { background: rgba(99,102,241,0.2); color: #A5B4FC; font-weight: 600; }
</style>

<script>
  /* ===========================
     配置
  =========================== */
  // 自动适配：本地开发用 localhost，生产环境用相对路径（Nginx 反代统一域名）
  const API = (location.hostname === 'localhost' || location.hostname === '127.0.0.1')
    ? 'http://localhost:3456/api'
    : '/api';

  /* ===========================
     状态管理
  =========================== */
  let state = {
    user: null,
    token: localStorage.getItem('ailang_token'),
    currentPage: 'workbench',
    currentDim: 'product',
    currentPlan: 'monthly',
    purchaseTierKey: null,
    purchasePlan: 'monthly',
    purchaseAmount: 0,
    lastDiagnosis: null,
    lastQuery: '',
    isAdmin: false
  };

  /* ===========================
     工具数据
  =========================== */
  const DIM_DATA = {
    product: {
      color: 'var(--primary)', bg: '#EFF6FF',
      tools: [
        ['产品定位工具','明确产品核心价值与差异化竞争优势'],['竞品分析框架','系统拆解竞品，发现差距与机会'],
        ['产品线规划','产品矩阵设计与SKU优化'],['价格策略设计','定价模型与价格体系搭建'],
        ['产品优化路径','基于用户反馈的持续迭代方法'],['爆品打造策略','选品逻辑与爆款产品孵化'],
        ['产品故事包装','将产品价值转化为动人的销售故事'],['研发立项决策','新产品是否值得做的评估框架'],
        ['供应链管理','稳定质量、控制成本的供应商体系']
      ]
    },
    customer: {
      color: 'var(--emerald)', bg: '#F0FDF4',
      tools: [
        ['客户画像工具','四维建模精准识别目标客户群体'],['精准获客方案','低成本高效吸引目标客户的策略'],
        ['客户分级管理','ABC分类管理，聚焦核心客户'],['成交流程设计','从线索到签约的完整转化路径'],
        ['客户关系维护','提升客户满意度与粘性的方法'],['复购激活方案','激活沉默客户，提升重购率'],
        ['转介绍体系','让老客户主动帮你带来新客户'],['客户成功计划','帮助客户实现价值，降低流失率'],
        ['客户数据分析','用数据洞察客户行为与需求趋势']
      ]
    },
    channel: {
      color: 'var(--amber)', bg: '#FFFBEB',
      tools: [
        ['项目包装','品牌背书、案例包装与渠道招商吸引力打造'],['渠道模式设计','直销/分销/联盟模式选择与设计'],
        ['渠道画像工具','理想渠道商特征建模与筛选'],['招商政策设计','吸引优质渠道商的政策体系'],
        ['招商落地执行','招商会议、谈判与签约流程'],['动销方案生成','提升渠道销量的激活策略'],
        ['渠道赋能系统','培训、工具、素材全方位支持'],['渠道激发计划','竞赛、激励与荣誉体系设计'],
        ['渠道复盘升级','渠道效能分析与优化迭代']
      ]
    },
    team: {
      color: 'var(--purple)', bg: '#F5F3FF',
      tools: [
        ['组织架构设计','部门设置、权责划分与管理层级优化'],['岗位职责说明书','清晰边界，消除责任真空地带'],
        ['绩效管理体系','OKR/KPI设计与考核机制'],['晋升机制设计','职业发展通道与晋升标准'],
        ['薪酬激励方案','固浮比设计、超额奖励机制'],['招聘面试系统','人才画像、面试题库与评估'],
        ['培训复制手册','标准化SOP与人才快速复制'],['氛围建设方案','文化价值观、团队凝聚力打造'],
        ['团队复盘升级','组织效能分析与持续改进']
      ]
    },
    finance: {
      color: 'var(--rose)', bg: '#FFF1F2',
      tools: [
        ['利润分析工具','拆解收入结构，找到利润漏洞'],['现金流管理','资金流动预警与现金流优化'],
        ['成本控制系统','成本分类分析与管控方法'],['定价收益优化','价格策略与毛利率提升路径'],
        ['财务预算规划','月度/季度预算制定与跟踪'],['融资方案设计','不同阶段的融资策略与方案'],
        ['财务风险预警','识别财务危机信号，提前预防'],['股权激励设计','用股权留住核心人才'],
        ['财务报表解读','读懂三大报表，做出正确决策']
      ]
    }
  };

  /* ===========================
     API 请求
  =========================== */
  async function api(endpoint, options = {}) {
    const headers = { 'Content-Type': 'application/json' };
    if (state.token) headers['Authorization'] = 'Bearer ' + state.token;
    try {
      const resp = await fetch(API + endpoint, { ...options, headers });
      return await resp.json();
    } catch(e) {
      return { error: '网络连接失败，请检查后端服务是否启动' };
    }
  }

  /* ===========================
     视图切换
  =========================== */
  function showView(id) {
    document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
    document.getElementById(id).classList.add('active');
  }

  /* ===========================
     登录 / 注册
  =========================== */
  async function handleLogin() {
    const phone = document.getElementById('login-phone').value.trim();
    const password = document.getElementById('login-password').value;
    document.getElementById('login-error').textContent = '';

    if (!phone || !password) {
      document.getElementById('login-error').textContent = '请输入手机号和密码';
      return;
    }

    const data = await api('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ phone, password })
    });

    if (data.error) {
      document.getElementById('login-error').textContent = data.error;
    } else {
      state.token = data.token;
      state.user = data.user;
      localStorage.setItem('ailang_token', data.token);
      showToast('登录成功，欢迎回来！', 'success');
      enterApp();
    }
  }

  async function handleRegister() {
    const phone = document.getElementById('reg-phone').value.trim();
    const username = document.getElementById('reg-username').value.trim();
    const password = document.getElementById('reg-password').value;
    const email = document.getElementById('reg-email').value.trim();
    const company = document.getElementById('reg-company').value.trim();
    const role = document.getElementById('reg-role').value;
    document.getElementById('reg-error').textContent = '';

    if (!phone || !username || !password) {
      document.getElementById('reg-error').textContent = '请填写手机号、用户名和密码';
      return;
    }

    const data = await api('/auth/register', {
      method: 'POST',
      body: JSON.stringify({ phone, username, password, email, company, role })
    });

    if (data.error) {
      document.getElementById('reg-error').textContent = data.error;
    } else {
      state.token = data.token;
      state.user = data.user;
      localStorage.setItem('ailang_token', data.token);
      showToast('注册成功！欢迎加入 AILange 🎉', 'success');
      enterApp();
    }
  }

  let forgotStep = 0; // 0=输入手机号, 1=输入验证码+新密码, 2=重置成功
  async function handleForgot() {
    const phone = document.getElementById('forgot-phone').value.trim();

    if (forgotStep === 0) {
      // 第一步：发送验证码
      if (!phone) { showToast('请输入手机号', 'error'); return; }
      const data = await api('/auth/forgot-password', {
        method: 'POST',
        body: JSON.stringify({ phone })
      });
      if (data.error) { showToast(data.error, 'error'); return; }
      showToast('验证码已发送（开发环境可查看终端）', 'info');
      if (data._dev_code) {
        document.getElementById('forgot-code').value = data._dev_code;
        showToast('开发环境：验证码已自动填入', 'success');
      }
      forgotStep = 1;
      document.getElementById('forgot-code-group').style.display = 'block';
      document.getElementById('forgot-pwd-group').style.display = 'block';
      document.getElementById('forgot-btn').textContent = '重置密码';
      document.getElementById('forgot-phone').disabled = true;
      document.getElementById('resend-btn').textContent = '60s';
    } else if (forgotStep === 1) {
      // 第二步：验证码 + 新密码
      const code = document.getElementById('forgot-code').value.trim();
      const newPassword = document.getElementById('forgot-new-pwd').value;
      if (!code || !newPassword) { showToast('请输入验证码和新密码', 'error'); return; }
      const data = await api('/auth/reset-password', {
        method: 'POST',
        body: JSON.stringify({ phone, code, newPassword })
      });
      if (data.error) { showToast(data.error, 'error'); return; }
      showToast('密码重置成功！请重新登录', 'success');
      forgotStep = 0;
      document.getElementById('forgot-phone').value = '';
      document.getElementById('forgot-phone').disabled = false;
      document.getElementById('forgot-code').value = '';
      document.getElementById('forgot-new-pwd').value = '';
      document.getElementById('forgot-code-group').style.display = 'none';
      document.getElementById('forgot-pwd-group').style.display = 'none';
      document.getElementById('forgot-btn').textContent = '获取验证码';
      showView('view-landing');
    }
  }

  async function handleSendSms() {
    const phone = document.getElementById('forgot-phone').value.trim();
    if (!phone) { showToast('请先输入手机号', 'error'); return; }
    const data = await api('/auth/forgot-password', {
      method: 'POST',
      body: JSON.stringify({ phone })
    });
    if (data._dev_code) {
      document.getElementById('forgot-code').value = data._dev_code;
      showToast('开发环境：验证码已自动填入', 'success');
    }
    showToast('验证码已重新发送', 'info');
  }

  async function demoLogin() {
    // 演示账号：直接进入应用
    state.user = {
      id: 0, phone: '13800000000', email: 'demo@ailang.cn', username: '演示账号',
      membership_tier: 'pro', company: '大脑营行', role: '企业主'
    };
    state.token = 'demo-token';
    showToast('已进入演示模式 (专业版体验)', 'info');
    enterApp();
  }

  /* ===========================
     进入应用
  =========================== */
  function enterApp() {
    if (!state.user) return;
    const name = state.user.username || (state.user.phone || '').slice(-4);
    const tierMap = { free: '免费版', pro: '专业版', enterprise: '企业版' };
    const tierName = tierMap[state.user.membership_tier] || '免费版';

    document.getElementById('header-username').textContent = name;
    document.getElementById('header-tier').textContent = tierName;
    document.getElementById('user-avatar-text').textContent = name[0].toUpperCase();
    document.getElementById('welcome-name').textContent = name;
    document.getElementById('current-tier-name').textContent = tierName;

    // 个人中心
    document.getElementById('profile-avatar').textContent = name[0].toUpperCase();
    document.getElementById('profile-name').textContent = name;
    document.getElementById('profile-email').textContent = state.user.phone || state.user.email || '';
    document.getElementById('edit-username').value = state.user.username || '';
    document.getElementById('edit-phone').value = state.user.phone || '';
    document.getElementById('edit-company').value = state.user.company || '';
    document.getElementById('edit-role').value = state.user.role || '';

    const badgeClass = { free: 'badge-free', pro: 'badge-pro', enterprise: 'badge-enterprise' };
    document.getElementById('profile-badge').className = 'badge ' + (badgeClass[state.user.membership_tier] || 'badge-free');
    document.getElementById('profile-badge').textContent = tierName;

    showView('view-app');
    appNavigate('workbench');
    renderDim('product');
    document.getElementById('diag-time').textContent = new Date().toLocaleDateString('zh-CN');

    // 检查是否是管理员
    checkAdminStatus();
  }

  async function checkAdminStatus() {
    try {
      const data = await api('/admin/dashboard');
      if (!data.error) {
        state.isAdmin = true;
        document.getElementById('nav-admin').style.display = '';
      }
    } catch(e) { /* not admin */ }
  }

  /* ===========================
     应用内导航
  =========================== */
  function appNavigate(page) {
    state.currentPage = page;
    // 重置所有页面
    document.querySelectorAll('[id^="app-"]').forEach(el => el.classList.remove('active'));
    const target = document.getElementById('app-' + page);
    if (target) target.classList.add('active');

    // 更新 header nav
    document.querySelectorAll('.header-nav-item').forEach(el => el.classList.remove('active'));
    const navEl = document.getElementById('nav-' + page);
    if (navEl) navEl.classList.add('active');

    // 更新 sidebar
    document.querySelectorAll('.sidebar-item').forEach(el => el.classList.remove('active'));
    const sidebarEl = document.getElementById('sidebar-' + page);
    if (sidebarEl) sidebarEl.classList.add('active');

    // 页面特定初始化
    if (page === 'my-docs') loadMyTools();
  }

  /* ===========================
     五大维度
  =========================== */
  function switchDim(dim) {
    state.currentDim = dim;
    const dimKeys = ['product','customer','channel','team','finance'];
    const activeClasses = ['active-product','active-customer','active-channel','active-team','active-finance'];
    dimKeys.forEach((d, i) => {
      const tab = document.getElementById('tab-' + d);
      tab.className = 'dim-tab' + (d === dim ? ' ' + activeClasses[i] : '');
    });
    renderDim(dim);
  }

  function renderDim(dim) {
    const d = DIM_DATA[dim];
    const dimNames = { product: '产品系统', customer: '客户系统', channel: '渠道系统', team: '团队系统', finance: '财务系统' };
    const html = `
      <div class="tools-grid">
        ${d.tools.map((t, i) => `
          <div class="tool-item" onclick="openToolPanel('${dim}','${dimNames[dim]}','${t[0].replace(/'/g, "\\'")}','${t[1].replace(/'/g, "\\'")}')">
            <div class="tool-num" style="background:${d.color}">${'①②③④⑤⑥⑦⑧⑨'[i]}</div>
            <div class="tool-info">
              <div class="tool-name">${t[0]}</div>
              <div class="tool-desc">${t[1]}</div>
            </div>
            <span class="tool-arrow">›</span>
          </div>
        `).join('')}
      </div>`;
    document.getElementById('dim-content').innerHTML = html;
  }

  /* ===========================
     工作台
  =========================== */
  function fillInput(text) {
    const ta = document.getElementById('diag-input');
    ta.value = text;
    ta.focus();
    updateCharCount();
  }

  function clearInput() {
    document.getElementById('diag-input').value = '';
    updateCharCount();
  }

  function updateCharCount() {
    const len = document.getElementById('diag-input').value.length;
    document.getElementById('char-count').textContent = `${len} / 2000字`;
  }

  document.addEventListener('DOMContentLoaded', () => {
    const ta = document.getElementById('diag-input');
    if (ta) ta.addEventListener('input', updateCharCount);
  });

  async function startDiagnosis() {
    const text = document.getElementById('diag-input').value.trim();
    if (!text) { showToast('请描述你的业务问题', 'error'); return; }
    if (text.length < 5) { showToast('请至少输入5个字描述问题', 'error'); return; }

    const btn = document.getElementById('diag-submit-btn');
    const origText = btn.textContent;
    btn.textContent = '⏳ AI 诊断中...';
    btn.disabled = true;

    try {
      // 调用真实 AI 诊断 API
      const data = await api('/ai/diagnose', {
        method: 'POST',
        body: JSON.stringify({ query: text, dimensions_selected: [] })
      });

      if (data.error) {
        if (data.hint) {
          showToast(data.error + ' — ' + data.hint, 'error');
        } else {
          showToast(data.error || 'AI 服务暂不可用', 'error');
        }
        btn.textContent = origText;
        btn.disabled = false;
        return;
      }

      // 保存诊断结果到 state
      state.lastDiagnosis = data;
      state.lastQuery = text;

      // 渲染动态结果
      renderDiagnosisResult(data, text);
      appNavigate('results');
      showToast('✨ AI 诊断完成！共发现 ' + (data.issues?.length || 0) + ' 个问题', 'success');
    } catch (e) {
      showToast('AI 服务连接失败，请确保后端已启动并配置 DeepSeek API Key', 'error');
    } finally {
      btn.textContent = origText;
      btn.disabled = false;
    }
  }

  function renderDiagnosisResult(data, query) {
    const scores = data.scores || {};
    const issues = data.issues || [];
    const dimColors = {
      product: 'var(--primary)', customer: 'var(--emerald)',
      channel: 'var(--amber)', team: 'var(--purple)', finance: 'var(--rose)'
    };
    const dimNames = {
      product: '产品系统', customer: '客户系统',
      channel: '渠道系统', team: '团队系统', finance: '财务系统'
    };
    const severityColors = { '高': 'var(--rose)', '中': 'var(--amber)', '低': 'var(--emerald)' };

    // 诊断时间
    document.getElementById('diag-time').textContent = new Date().toLocaleDateString('zh-CN');
    document.getElementById('diag-topic').textContent = query.substring(0, 50) + (query.length > 50 ? '...' : '');

    // 评分卡片
    let scoreHTML = '';
    Object.entries(scores).forEach(([key, val]) => {
      const color = dimColors[key] || 'var(--slate)';
      scoreHTML += `
        <div class="score-card">
          <div class="score-num" style="color:${color}">${val}</div>
          <div class="score-label">${dimNames[key] || key}</div>
          <div class="score-bar"><div class="score-bar-fill" style="width:${val}%;background:${color}"></div></div>
        </div>`;
    });
    document.getElementById('score-cards').innerHTML = scoreHTML;

    // 关键问题
    let issuesHTML = '';
    issues.forEach((issue, i) => {
      const sevColor = severityColors[issue.severity] || 'var(--slate)';
      issuesHTML += `
        <div class="issue-item">
          <div class="issue-priority" style="background:${sevColor}">P${i+1}</div>
          <div>
            <div style="font-weight:700;font-size:14px">${issue.description || issue.tool}</div>
            <div style="font-size:13px;color:var(--slate);margin-top:4px">匹配着力点：${issue.tool || ''} · ${dimNames[issue.dimension] || issue.dimension}</div>
            <div style="font-size:13px;margin-top:6px;color:var(--text)">${issue.suggestion || ''}</div>
          </div>
        </div>`;
    });
    document.getElementById('issues-list').innerHTML = issuesHTML || '<p style="color:var(--slate);padding:20px;text-align:center">暂无问题数据</p>';

    // 总结
    document.getElementById('diag-summary').textContent = data.summary || '诊断完成，请查看上方详情。';

    // 优先行动
    const actions = data.priority_actions || [];
    document.getElementById('priority-actions').innerHTML = actions.map((a, i) =>
      `<div style="padding:10px 14px;background:#F8FAFC;border-radius:8px;font-size:13px;display:flex;align-items:center;gap:10px">
        <span style="background:var(--indigo);color:#fff;width:24px;height:24px;display:flex;align-items:center;justify-content:center;border-radius:6px;font-size:12px;font-weight:700;flex-shrink:0">${i+1}</span>
        ${a}
      </div>`
    ).join('');

    // 风险预警
    const risk = data.risk_alert || '';
    const riskEl = document.getElementById('risk-alert');
    if (risk) {
      riskEl.style.display = 'block';
      riskEl.innerHTML = `<div style="font-size:13px;font-weight:700;color:var(--rose);margin-bottom:6px">⚠️ 重点关注</div><div style="font-size:12px;color:#BE123C">${risk}</div>`;
    } else {
      riskEl.style.display = 'none';
    }

    // AI 元信息
    const meta = data._meta || {};
    document.getElementById('diag-meta').textContent = meta.model
      ? `由 ${meta.model} 生成 · 消耗 ${meta.tokens_used || 0} tokens`
      : '';
  }

  /* ===========================
     会员 & 购买
  =========================== */
  function switchPlan(plan) {
    state.currentPlan = plan;
    document.getElementById('plan-monthly').className = 'btn ' + (plan === 'monthly' ? 'btn-primary' : 'btn-ghost');
    document.getElementById('plan-yearly').className = 'btn ' + (plan === 'yearly' ? 'btn-primary' : 'btn-ghost');

    if (plan === 'yearly') {
      document.getElementById('pro-price').textContent = '¥990';
      document.getElementById('pro-yearly-hint').style.display = 'block';
    } else {
      document.getElementById('pro-price').textContent = '¥99';
      document.getElementById('pro-yearly-hint').style.display = 'none';
    }
  }

  let pendingOrderNo = null;
  let pendingPaymentMethod = null;
  let pollTimer = null;

  async function purchaseTier(tierKey) {
    if (tierKey === 'enterprise') {
      showToast('企业版暂不开放，敬请期待', 'info'); return;
    }
    if (!state.token || state.token === 'demo-token') {
      showToast('请先登录', 'error'); return;
    }

    const prices = { pro: { monthly: 99, yearly: 990 } };
    const names = { pro: '专业版' };
    const plan = state.currentPlan;
    const amount = prices[tierKey][plan] || 0;
    const planName = plan === 'yearly' ? '年付' : '月付';

    document.getElementById('purchase-title').textContent = '💳 选择支付方式';
    document.getElementById('purchase-content').innerHTML = `
      <div style="text-align:center;padding:8px 0">
        <div style="font-size:28px;font-weight:800;color:var(--indigo);margin-bottom:2px">¥${amount}</div>
        <div style="color:var(--slate);font-size:13px">${names[tierKey]} · ${planName}</div>
      </div>
      <div style="display:flex;gap:12px;margin-top:20px">
        <div class="pay-method-card" onclick="selectPayment('wechat')" id="pay-card-wechat"
             style="flex:1;padding:20px 12px;border:2px solid #E2E8F0;border-radius:12px;text-align:center;cursor:pointer;transition:all 0.15s">
          <div style="font-size:36px;margin-bottom:8px">💚</div>
          <div style="font-size:15px;font-weight:700">微信支付</div>
          <div style="font-size:11px;color:var(--slate);margin-top:4px">推荐使用</div>
        </div>
        <div class="pay-method-card" onclick="selectPayment('alipay')" id="pay-card-alipay"
             style="flex:1;padding:20px 12px;border:2px solid #E2E8F0;border-radius:12px;text-align:center;cursor:pointer;transition:all 0.15s">
          <div style="font-size:36px;margin-bottom:8px">💙</div>
          <div style="font-size:15px;font-weight:700">支付宝</div>
          <div style="font-size:11px;color:var(--slate);margin-top:4px">安全便捷</div>
        </div>
      </div>
    `;
    document.getElementById('purchase-actions').style.display = 'none';
    document.getElementById('purchase-modal').classList.add('open');

    state.purchaseTierKey = tierKey;
    state.purchasePlan = plan;
    state.purchaseAmount = amount;
    pendingPaymentMethod = null;
  }

  function selectPayment(method) {
    pendingPaymentMethod = method;
    // 高亮选中卡片
    document.querySelectorAll('.pay-method-card').forEach(c => {
      c.style.borderColor = '#E2E8F0';
      c.style.background = '#fff';
    });
    const card = document.getElementById('pay-card-' + method);
    card.style.borderColor = 'var(--indigo)';
    card.style.background = '#EEF2FF';

    // 创建订单
    createAndShowOrder(method);
  }

  async function createAndShowOrder(method) {
    const data = await api('/payment/create-order', {
      method: 'POST',
      body: JSON.stringify({
        tier_key: state.purchaseTierKey,
        plan: state.purchasePlan,
        payment_method: method,
      })
    });
    if (data.error) { showToast(data.error, 'error'); return; }

    pendingOrderNo = data.order_no;
    const methodInfo = { wechat: { name: '微信支付', emoji: '💚', color: '#07C160' },
                        alipay: { name: '支付宝', emoji: '💙', color: '#1677FF' } };

    document.getElementById('purchase-title').textContent = '📱 扫码支付';
    document.getElementById('purchase-content').innerHTML = `
      <div style="text-align:center;padding:12px 0">
        <div style="font-size:20px;font-weight:700;margin-bottom:4px">
          ${methodInfo[method].emoji} ${methodInfo[method].name}
        </div>
        <div style="color:var(--slate);font-size:13px">请扫码完成支付</div>
      </div>
      <!-- 二维码占位区（正式接入后替换为真实二维码） -->
      <div style="width:180px;height:180px;margin:12px auto;border:2px dashed #E2E8F0;border-radius:16px;display:flex;flex-direction:column;align-items:center;justify-content:center;background:var(--bg)">
        <div style="font-size:48px">${methodInfo[method].emoji}</div>
        <div style="font-size:12px;color:var(--slate);margin-top:8px">${methodInfo[method].name}</div>
        <div style="font-size:11px;color:#94A3B8;margin-top:4px">扫码支付 ¥${state.purchaseAmount}</div>
      </div>
      <div style="text-align:center;margin-top:8px;color:var(--slate);font-size:12px">
        订单号：<span style="font-family:monospace;color:var(--indigo)">${data.order_no}</span>
      </div>
      <div style="text-align:center;margin-top:8px;color:#94A3B8;font-size:11px">
        💡 正式上线后将展示真实支付二维码<br>当前点击下方按钮即可模拟支付
      </div>
    `;

    document.getElementById('purchase-actions').innerHTML = `
      <button class="btn btn-ghost" style="flex:1;justify-content:center" onclick="closeModal('purchase-modal')">取消</button>
      <button class="btn btn-indigo" style="flex:2;justify-content:center" onclick="simulatePay()">
        ✅ 我已支付（模拟）
      </button>
    `;
    document.getElementById('purchase-actions').style.display = 'flex';
  }

  async function simulatePay() {
    if (!pendingOrderNo) return;
    document.getElementById('purchase-content').innerHTML = `
      <div style="text-align:center;padding:32px 0">
        <div style="font-size:32px;margin-bottom:12px">⏳</div>
        <div style="font-size:15px;font-weight:600">正在确认支付...</div>
      </div>
    `;
    document.getElementById('purchase-actions').style.display = 'none';

    const data = await api('/payment/simulate-pay/' + pendingOrderNo, { method: 'POST' });
    if (data.error) {
      showToast(data.error, 'error');
      closeModal('purchase-modal');
      return;
    }

    document.getElementById('purchase-content').innerHTML = `
      <div style="text-align:center;padding:24px 0">
        <div style="font-size:48px;margin-bottom:12px">🎉</div>
        <div style="font-size:18px;font-weight:700;color:var(--emerald)">支付成功！</div>
        <div style="color:var(--slate);font-size:14px;margin-top:6px">会员权益已即时激活</div>
      </div>
    `;
    document.getElementById('purchase-actions').innerHTML = `
      <button class="btn btn-indigo" style="flex:1;justify-content:center;width:100%" onclick="closeModal('purchase-modal');refreshUserState()">开始使用</button>
    `;
    document.getElementById('purchase-actions').style.display = 'flex';

    // 更新用户状态
    if (state.user) {
      state.user.membership_tier = state.purchaseTierKey || 'pro';
      updateUserDisplay();
    }
  }

  function closeModal(id) {
    document.getElementById(id).classList.remove('open');
    if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  }

  function updateUserDisplay() {
    const tierMap = { free: '免费版', pro: '专业版', enterprise: '企业版' };
    const tierName = tierMap[state.user.membership_tier] || '免费版';
    document.getElementById('header-tier').textContent = tierName;
    document.getElementById('current-tier-name').textContent = tierName;
    const badgeClass = { free: 'badge-free', pro: 'badge-pro', enterprise: 'badge-enterprise' };
    document.getElementById('profile-badge').className = 'badge ' + (badgeClass[state.user.membership_tier] || 'badge-free');
    document.getElementById('profile-badge').textContent = tierName;
  }

  async function refreshUserState() {
    const data = await api('/auth/me');
    if (data && !data.error) {
      state.user = data;
      updateUserDisplay();
    }
  }

  /* ===========================
     个人中心
  =========================== */
  async function saveProfile() {
    const data = await api('/auth/me', {
      method: 'PUT',
      body: JSON.stringify({
        username: document.getElementById('edit-username').value,
        phone: document.getElementById('edit-phone').value,
        email: document.getElementById('edit-phone').dataset.email || '',
        company: document.getElementById('edit-company').value,
        role: document.getElementById('edit-role').value
      })
    });
    if (data.error) { showToast(data.error, 'error'); return; }
    showToast('个人信息已更新', 'success');
  }

  async function changePassword() {
    const oldPwd = document.getElementById('old-pwd').value;
    const newPwd = document.getElementById('new-pwd').value;
    const confirmPwd = document.getElementById('confirm-pwd').value;
    if (!oldPwd || !newPwd) { showToast('请填写密码', 'error'); return; }
    if (newPwd !== confirmPwd) { showToast('两次密码不一致', 'error'); return; }
    const data = await api('/auth/password', {
      method: 'PUT',
      body: JSON.stringify({ oldPassword: oldPwd, newPassword: newPwd })
    });
    if (data.error) { showToast(data.error, 'error'); return; }
    showToast('密码修改成功', 'success');
    document.getElementById('old-pwd').value = '';
    document.getElementById('new-pwd').value = '';
    document.getElementById('confirm-pwd').value = '';
  }

  /* ===========================
     退出登录
  =========================== */
  function handleLogout() {
    state.token = null;
    state.user = null;
    localStorage.removeItem('ailang_token');
    showToast('已退出登录', 'info');
    showView('view-landing');
  }

  /* ===========================
     Toast 提示
  =========================== */
  function showToast(message, type = 'info') {
    const icons = { success: '✅', error: '❌', info: 'ℹ️' };
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `<span>${icons[type]}</span><span>${message}</span>`;
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 3500);
  }

  /* ===========================
     管理后台
  =========================== */
  let adminState = { tab: 'dashboard', userPage: 1, diagPage: 1, dashboardData: null };

  async function enterAdmin() {
    if (!state.user) { showToast('请先登录', 'error'); return; }
    // 检查是否是管理员
    const data = await api('/admin/dashboard');
    if (data.error) {
      showToast('无管理员权限：' + data.error, 'error');
      return;
    }
    showView('view-admin');
    document.getElementById('admin-avatar').textContent = (state.user.username || 'A')[0].toUpperCase();
    document.getElementById('admin-name').textContent = state.user.username || '管理员';
    adminSwitchTab('dashboard');
  }

  async function adminSwitchTab(tab) {
    adminState.tab = tab;
    document.querySelectorAll('.admin-nav-side').forEach(el => el.classList.remove('active'));
    const navEl = document.getElementById('admin-nav-' + tab);
    if (navEl) navEl.classList.add('active');

    document.querySelectorAll('[id^="admin-tab-"]').forEach(el => el.style.display = 'none');
    const tabEl = document.getElementById('admin-tab-' + tab);
    if (tabEl) tabEl.style.display = 'block';

    if (tab === 'dashboard') await adminLoadDashboard();
    if (tab === 'users') await adminLoadUsers();
    if (tab === 'diagnoses') await adminLoadDiagnoses();
    if (tab === 'orders') await adminLoadOrders();
    if (tab === 'knowledge') await adminLoadKnowledge();
  }

  async function adminLoadDashboard() {
    const data = await api('/admin/dashboard');
    if (data.error) { showToast(data.error, 'error'); return; }
    adminState.dashboardData = data;

    const ov = data.overview;
    const cards = document.getElementById('admin-stats-cards');
    cards.innerHTML = `
      <div class="admin-stat-card"><div class="stat-value" style="color:var(--indigo)">${ov.total_users}</div><div class="stat-label">总用户数</div></div>
      <div class="admin-stat-card"><div class="stat-value" style="color:var(--emerald)">${ov.total_diagnoses}</div><div class="stat-label">总诊断次数</div></div>
      <div class="admin-stat-card"><div class="stat-value" style="color:var(--amber)">${ov.total_orders}</div><div class="stat-label">总订单数</div></div>
      <div class="admin-stat-card"><div class="stat-value" style="color:var(--primary)">${ov.today_new_users}</div><div class="stat-label">今日新增用户</div></div>
    `;

    // Trend chart
    const trend = data.trend || [];
    const maxVal = Math.max(1, ...trend.map(t => Math.max(t.new_users, t.diagnoses)));
    const chart = document.getElementById('admin-trend-chart');
    chart.innerHTML = trend.map(t => {
      const h1 = Math.max(4, (t.new_users / maxVal) * 180);
      const h2 = Math.max(4, (t.diagnoses / maxVal) * 180);
      return `<div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px">
        <div style="display:flex;gap:4px;align-items:flex-end;height:200px">
          <div style="width:20px;background:var(--indigo);border-radius:4px 4px 0 0;height:${h1}px" title="新增用户: ${t.new_users}"></div>
          <div style="width:20px;background:var(--emerald);border-radius:4px 4px 0 0;height:${h2}px" title="诊断次数: ${t.diagnoses}"></div>
        </div>
        <span style="font-size:10px;color:var(--slate)">${t.date}</span>
      </div>`;
    }).join('');

    // Tier distribution
    const tier = data.tier_distribution || {};
    const tierChart = document.getElementById('admin-tier-chart');
    tierChart.innerHTML = `
      <div style="display:flex;flex-direction:column;gap:12px">
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span style="font-size:13px">🆓 免费版</span>
          <span style="font-size:13px;font-weight:700">${tier.free || 0}</span>
        </div>
        <div style="height:6px;background:#E2E8F0;border-radius:3px"><div style="height:100%;width:${Math.max(5, (tier.free||0) / Math.max(1, ov.total_users) * 100)}%;background:#94A3B8;border-radius:3px"></div></div>
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span style="font-size:13px">💎 专业版</span>
          <span style="font-size:13px;font-weight:700">${tier.pro || 0}</span>
        </div>
        <div style="height:6px;background:#E2E8F0;border-radius:3px"><div style="height:100%;width:${Math.max(5, (tier.pro||0) / Math.max(1, ov.total_users) * 100)}%;background:#6366F1;border-radius:3px"></div></div>
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span style="font-size:13px">👑 企业版</span>
          <span style="font-size:13px;font-weight:700">${tier.enterprise || 0}</span>
        </div>
        <div style="height:6px;background:#E2E8F0;border-radius:3px"><div style="height:100%;width:${Math.max(5, (tier.enterprise||0) / Math.max(1, ov.total_users) * 100)}%;background:#F59E0B;border-radius:3px"></div></div>
      </div>`;
  }

  async function adminLoadUsers(page = 1) {
    adminState.userPage = page;
    const search = document.getElementById('admin-user-search')?.value || '';
    const data = await api(`/admin/users?page=${page}&limit=15&search=${encodeURIComponent(search)}`);
    if (data.error) { showToast(data.error, 'error'); return; }

    document.getElementById('admin-user-count').textContent = `共 ${data.total} 条`;
    const tierBadges = { free: 'admin-badge-free', pro: 'admin-badge-pro', enterprise: 'admin-badge-enterprise' };
    const tbody = document.getElementById('admin-users-tbody');
    tbody.innerHTML = (data.users || []).map(u => `
      <tr>
        <td>${u.id}</td>
        <td>${u.phone || '-'}</td>
        <td>${u.username || '-'}</td>
        <td>${u.company || '-'}</td>
        <td><span class="admin-badge ${tierBadges[u.membership_tier] || 'admin-badge-free'}">${u.membership_tier === 'pro' ? '专业版' : u.membership_tier === 'enterprise' ? '企业版' : '免费版'}</span></td>
        <td style="font-size:12px;color:var(--slate)">${(u.created_at || '').substring(0, 10)}</td>
        <td>${u.is_disabled ? '<span style="color:var(--rose);font-size:12px">已禁用</span>' : '<span style="color:var(--emerald);font-size:12px">正常</span>'}</td>
        <td>
          <div class="admin-row-actions">
            <button class="btn btn-ghost btn-sm" onclick="adminEditUserTier(${u.id},'${u.membership_tier || 'free'}')">✏️</button>
            <button class="btn btn-ghost btn-sm" style="color:var(--rose)" onclick="adminToggleUser(${u.id},${u.is_disabled ? 0 : 1})">${u.is_disabled ? '启用' : '禁用'}</button>
          </div>
        </td>
      </tr>`).join('');

    // Pagination
    const pager = document.getElementById('admin-users-pager');
    let pHTML = '';
    for (let p = 1; p <= data.totalPages; p++) {
      pHTML += `<button class="btn btn-ghost btn-sm" style="min-width:32px;justify-content:center" onclick="adminLoadUsers(${p})" ${p === page ? 'style="background:var(--indigo);color:#fff;min-width:32px;justify-content:center"' : ''}>${p}</button>`;
    }
    pager.innerHTML = pHTML;
  }

  async function adminEditUserTier(userId, currentTier) {
    const newTier = prompt(`修改会员等级 (当前: ${currentTier})\n可选: free / pro / enterprise`, currentTier);
    if (!newTier || newTier === currentTier) return;
    const data = await api(`/admin/users/${userId}`, {
      method: 'PUT',
      body: JSON.stringify({ membership_tier: newTier })
    });
    if (data.ok) { showToast('会员等级已更新', 'success'); adminLoadUsers(adminState.userPage); }
    else { showToast(data.error || '操作失败', 'error'); }
  }

  async function adminToggleUser(userId, disable) {
    const data = await api(`/admin/users/${userId}`, {
      method: 'PUT',
      body: JSON.stringify({ is_disabled: disable })
    });
    if (data.ok) { showToast(disable ? '用户已禁用' : '用户已启用', 'success'); adminLoadUsers(adminState.userPage); }
    else { showToast(data.error || '操作失败', 'error'); }
  }

  async function adminLoadDiagnoses(page = 1) {
    adminState.diagPage = page;
    const data = await api(`/admin/diagnoses?page=${page}&limit=15`);
    if (data.error) { showToast(data.error, 'error'); return; }

    const tbody = document.getElementById('admin-diags-tbody');
    tbody.innerHTML = (data.diagnoses || []).map(d => `
      <tr>
        <td>${d.id}</td>
        <td>${d.user_name || d.user_phone || '-'}</td>
        <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${d.title || d.query?.substring(0, 30) || '-'}</td>
        <td style="font-size:11px">${d.dimensions_selected || '全维度'}</td>
        <td style="font-size:12px;color:var(--slate)">${(d.created_at || '').substring(0, 16)}</td>
        <td>
          <button class="btn btn-ghost btn-sm" onclick="adminViewDiagnosis(${d.id})">查看</button>
        </td>
      </tr>`).join('');

    const pager = document.getElementById('admin-diags-pager');
    let pHTML = '';
    for (let p = 1; p <= data.totalPages; p++) {
      pHTML += `<button class="btn btn-ghost btn-sm" style="min-width:32px;justify-content:center" onclick="adminLoadDiagnoses(${p})" ${p===page?'style="background:var(--indigo);color:#fff;min-width:32px;justify-content:center"':''}>${p}</button>`;
    }
    pager.innerHTML = pHTML;
  }

  async function adminViewDiagnosis(id) {
    const data = await api(`/diagnosis/detail/${id}`);
    if (data.error) { showToast(data.error, 'error'); return; }
    const r = data.record;
    try {
      const result = JSON.parse(r.result_json || '{}');
      alert(`诊断详情 #${r.id}\n\n主题：${r.title}\n维度：${r.dimensions_selected || '全维度'}\n\n总结：${result.summary || '无'}${result._meta ? '\n\n模型：' + result._meta.model + '\nTokens：' + result._meta.tokens_used : ''}`);
    } catch(e) {
      alert(`诊断详情 #${r.id}\n\n主题：${r.title}\n${r.query}`);
    }
  }

  async function adminLoadOrders() {
    const data = await api('/admin/orders');
    if (data.error) { showToast(data.error, 'error'); return; }

    const tbody = document.getElementById('admin-orders-tbody');
    tbody.innerHTML = (data.orders || []).map(o => `
      <tr>
        <td style="font-family:monospace;font-size:12px">${o.order_no || '-'}</td>
        <td>${o.user_name || o.user_phone || '-'}</td>
        <td>${o.tier_name || o.tier_key || '-'}</td>
        <td style="font-weight:700">¥${o.amount || 0}</td>
        <td><span style="font-size:12px;${o.status === 'paid' ? 'color:var(--emerald)' : 'color:var(--amber)'}">${o.status === 'paid' ? '已支付' : '待支付'}</span></td>
        <td style="font-size:12px;color:var(--slate)">${(o.created_at || '').substring(0, 16)}</td>
      </tr>`).join('');
  }

  /* ===========================
     知识库
  =========================== */
  let knowledgeState = {
    page: 1,
    editingId: null,
    view: 'list',  // list | form | detail
    uploadedFile: null  // { file_name, file_path, file_type, file_size, file_url, file_original_name, icon }
  };

  async function adminLoadKnowledge(page = 1) {
    knowledgeState.page = page;
    const search = document.getElementById('knowledge-search')?.value || '';
    const category = document.getElementById('knowledge-category-filter')?.value || '';

    const params = new URLSearchParams({ page, limit: 15 });
    if (search) params.set('search', search);
    if (category) params.set('category', category);

    // Load stats
    const statsData = await api('/admin/knowledge-stats');
    if (!statsData.error) {
      document.getElementById('knowledge-stats-bar').innerHTML = `
        <div class="admin-stat-card" style="flex:1"><div class="stat-value" style="color:var(--indigo);font-size:22px">${statsData.total}</div><div class="stat-label">总文章数</div></div>
        <div class="admin-stat-card" style="flex:1"><div class="stat-value" style="color:var(--emerald);font-size:22px">${statsData.materials}</div><div class="stat-label">原始素材</div></div>
        <div class="admin-stat-card" style="flex:1"><div class="stat-value" style="color:var(--amber);font-size:22px">${statsData.cases}</div><div class="stat-label">实战案例</div></div>
        <div class="admin-stat-card" style="flex:1"><div class="stat-value" style="color:var(--slate);font-size:14px;padding-top:8px">${statsData.recent_update ? statsData.recent_update.substring(0,10) : '暂无'}</div><div class="stat-label">最近更新</div></div>
      `;
    }

    const data = await api(`/admin/knowledge?${params.toString()}`);
    if (data.error) { showToast(data.error, 'error'); return; }

    document.getElementById('knowledge-count').textContent = `共 ${data.total} 条`;

    const fileIcons = { image: '🖼️', word: '📝', excel: '📊', ppt: '📽️', pdf: '📄', text: '📃' };
    const catLabels = { material: '📦 原始素材', case: '📋 实战案例' };
    const catColors = { material: 'var(--indigo)', case: 'var(--amber)' };

    const tbody = document.getElementById('knowledge-tbody');
    tbody.innerHTML = (data.articles || []).map(a => {
      const fileIcon = a.file_type ? `<span title="${escHtml(a.file_original_name||a.file_name||'')}" style="font-size:18px">${fileIcons[a.file_type] || '📎'}</span>` : '<span style="color:var(--slate);font-size:11px">—</span>';
      return `
      <tr>
        <td style="color:var(--slate);font-size:12px">${a.id}</td>
        <td>
          <a onclick="knowledgeViewDetail(${a.id})" style="cursor:pointer;color:var(--primary);font-weight:600;font-size:13px;text-decoration:none">${escHtml(a.title || '')}</a>
          <div style="font-size:11px;color:var(--slate);margin-top:2px">${(a.content || '').substring(0, 60)}${(a.content||'').length > 60 ? '...' : ''}</div>
        </td>
        <td style="text-align:center">${fileIcon}</td>
        <td><span style="font-size:12px;color:${catColors[a.category] || 'var(--slate)'};font-weight:600">${catLabels[a.category] || a.category}</span></td>
        <td style="max-width:140px"><span style="font-size:11px;color:var(--slate)">${(a.tags || '-').split(/[,，]/).slice(0,3).map(t => `<span style="display:inline-block;background:#F1F5F9;padding:2px 8px;border-radius:4px;margin:2px">${t.trim()}</span>`).join('')}</span></td>
        <td style="font-size:12px">${a.author_name || '-'}</td>
        <td style="font-size:12px;color:var(--slate)">${(a.updated_at || '').substring(0, 16)}</td>
        <td>
          <div class="admin-row-actions">
            <button class="btn btn-ghost btn-sm" onclick="knowledgeShowForm(true, ${a.id})">✏️</button>
            <button class="btn btn-ghost btn-sm" style="color:var(--rose)" onclick="knowledgeConfirmDelete(${a.id},'${escHtml((a.title||'').substring(0,20))}')">🗑</button>
          </div>
        </td>
      </tr>`}).join('') || '<tr><td colspan="8" style="text-align:center;padding:32px;color:var(--slate)">暂无知识库内容，点击「＋ 新建文章」开始沉淀</td></tr>';

    // Pagination
    const pager = document.getElementById('knowledge-pager');
    let pHTML = '';
    for (let p = 1; p <= data.totalPages; p++) {
      pHTML += `<button class="btn btn-ghost btn-sm" style="min-width:32px;justify-content:center" onclick="adminLoadKnowledge(${p})" ${p===page?'style="background:var(--indigo);color:#fff;min-width:32px;justify-content:center"':''}>${p}</button>`;
    }
    pager.innerHTML = pHTML;

    // Show list view
    document.getElementById('knowledge-list-view').style.display = '';
    document.getElementById('knowledge-form-view').style.display = 'none';
    document.getElementById('knowledge-detail-view').style.display = 'none';
    document.getElementById('knowledge-add-btn').style.display = '';
    knowledgeState.view = 'list';
  }

  function knowledgeShowForm(editMode, articleId) {
    knowledgeState.editingId = null;
    knowledgeState.uploadedFile = null;
    hideFilePreview();

    if (editMode && articleId) {
      knowledgeState.editingId = articleId;
      document.getElementById('knowledge-form-title').textContent = '编辑文章';
      document.getElementById('knowledge-delete-btn').style.display = '';
      // Fetch article data
      api(`/admin/knowledge/${articleId}`).then(data => {
        if (data.error) { showToast(data.error, 'error'); return; }
        document.getElementById('knowledge-edit-category').value = data.category || 'material';
        document.getElementById('knowledge-edit-title').value = data.title || '';
        document.getElementById('knowledge-edit-tags').value = data.tags || '';
        document.getElementById('knowledge-edit-content').value = data.content || '';
        // Restore file info if exists
        if (data.file_name) {
          knowledgeState.uploadedFile = {
            file_name: data.file_name,
            file_path: data.file_path,
            file_type: data.file_type,
            file_size: data.file_size,
            file_url: data.file_url,
            file_original_name: data.file_original_name || data.file_name
          };
          showFilePreview(knowledgeState.uploadedFile);
        }
      });
    } else {
      document.getElementById('knowledge-form-title').textContent = '新建文章';
      document.getElementById('knowledge-delete-btn').style.display = 'none';
      document.getElementById('knowledge-edit-category').value = 'material';
      document.getElementById('knowledge-edit-title').value = '';
      document.getElementById('knowledge-edit-tags').value = '';
      document.getElementById('knowledge-edit-content').value = '';
    }

    document.getElementById('knowledge-list-view').style.display = 'none';
    document.getElementById('knowledge-form-view').style.display = '';
    document.getElementById('knowledge-detail-view').style.display = 'none';
    document.getElementById('knowledge-add-btn').style.display = 'none';
    knowledgeState.view = 'form';
  }

  function knowledgeBackToList() {
    document.getElementById('knowledge-list-view').style.display = '';
    document.getElementById('knowledge-form-view').style.display = 'none';
    document.getElementById('knowledge-detail-view').style.display = 'none';
    document.getElementById('knowledge-add-btn').style.display = '';
    knowledgeState.view = 'list';
    knowledgeState.editingId = null;
  }

  /* ── 文件上传辅助函数 ── */

  function showFilePreview(fileInfo) {
    const preview = document.getElementById('knowledge-file-preview');
    const content = document.getElementById('knowledge-file-preview-content');
    const isImage = fileInfo.file_type === 'image';
    const sizeStr = fileInfo.file_size
      ? (fileInfo.file_size > 1048576 ? (fileInfo.file_size/1048576).toFixed(1)+' MB' : (fileInfo.file_size/1024).toFixed(1)+' KB')
      : '';
    const url = fileInfo.file_url || '#';

    if (isImage) {
      content.innerHTML = `
        <div style="width:80px;height:80px;border-radius:8px;overflow:hidden;flex-shrink:0;background:#E2E8F0">
          <img src="${url}" style="width:100%;height:100%;object-fit:cover" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 40 40%22><rect fill=%22%23CBD5E1%22 width=%2240%22 height=%2240%22/><text x=%2220%22 y=%2224%22 text-anchor=%22middle%22 font-size=%2216%22>🖼</text></svg>'">
        </div>
        <div style="flex:1;min-width:0">
          <div style="font-size:13px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${escHtml(fileInfo.file_original_name || fileInfo.file_name || '')}</div>
          <div style="font-size:11px;color:var(--slate);margin-top:2px">图片 · ${sizeStr}</div>
        </div>`;
    } else {
      const icons = { word: '📝', excel: '📊', ppt: '📽️', pdf: '📄', text: '📃' };
      const labels = { word: 'Word 文档', excel: 'Excel 表格', ppt: 'PPT 演示', pdf: 'PDF 文档', text: '文本文件' };
      content.innerHTML = `
        <div style="font-size:32px;flex-shrink:0">${icons[fileInfo.file_type] || '📎'}</div>
        <div style="flex:1;min-width:0">
          <div style="font-size:13px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${escHtml(fileInfo.file_original_name || fileInfo.file_name || '')}</div>
          <div style="font-size:11px;color:var(--slate);margin-top:2px">${labels[fileInfo.file_type] || '文件'} · ${sizeStr}</div>
        </div>`;
    }
    preview.style.display = '';
    document.getElementById('knowledge-upload-zone').style.display = 'none';
  }

  function hideFilePreview() {
    document.getElementById('knowledge-file-preview').style.display = 'none';
    document.getElementById('knowledge-upload-zone').style.display = '';
  }

  function knowledgeRemoveFile() {
    knowledgeState.uploadedFile = null;
    hideFilePreview();
    document.getElementById('knowledge-file-input').value = '';
  }

  async function uploadFileToServer(file) {
    const formData = new FormData();
    formData.append('file', file);
    try {
      const token = localStorage.getItem('ailang_token') || '';
      const resp = await fetch('/api/admin/knowledge/upload', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body: formData
      });
      const data = await resp.json();
      if (data.error) throw new Error(data.error);
      return data.file;
    } catch (e) {
      showToast('文件上传失败: ' + e.message, 'error');
      return null;
    }
  }

  async function knowledgeHandleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;
    await processSelectedFile(file);
  }

  async function knowledgeHandleFileDrop(event) {
    event.preventDefault();
    event.target.style.borderColor = 'var(--border)';
    event.target.style.background = 'var(--bg)';
    const file = event.dataTransfer.files[0];
    if (!file) return;
    await processSelectedFile(file);
  }

  async function processSelectedFile(file) {
    // Validate file size
    if (file.size > 50 * 1024 * 1024) {
      showToast('文件大小不能超过 50MB', 'error');
      return;
    }
    // Show uploading state
    const preview = document.getElementById('knowledge-file-preview');
    const content = document.getElementById('knowledge-file-preview-content');
    preview.style.display = '';
    document.getElementById('knowledge-upload-zone').style.display = 'none';
    content.innerHTML = `<div style="display:flex;align-items:center;gap:12px"><div style="font-size:24px;animation:spin 1s linear infinite">⏳</div><div style="font-size:13px;font-weight:600">正在上传 ${escHtml(file.name)}...</div></div>`;

    const fileInfo = await uploadFileToServer(file);
    if (!fileInfo) {
      hideFilePreview();
      return;
    }
    knowledgeState.uploadedFile = fileInfo;
    showFilePreview(fileInfo);
  }

  async function knowledgeSave() {
    const category = document.getElementById('knowledge-edit-category').value;
    const title = document.getElementById('knowledge-edit-title').value.trim();
    const tags = document.getElementById('knowledge-edit-tags').value.trim();
    const content = document.getElementById('knowledge-edit-content').value.trim();
    const file = knowledgeState.uploadedFile;

    if (!title) { showToast('请输入标题', 'error'); return; }
    if (!content && !file) { showToast('请填写文本内容或上传文件', 'error'); return; }

    const btn = document.getElementById('knowledge-save-btn');
    const origText = btn.textContent;
    btn.textContent = '⏳ 保存中...';
    btn.disabled = true;

    try {
      let data;
      const body = { category, title, tags, content };
      if (file) {
        Object.assign(body, {
          file_name: file.file_name,
          file_path: file.file_path,
          file_type: file.file_type,
          file_size: file.file_size,
          file_url: file.file_url,
          file_original_name: file.file_original_name
        });
      }

      if (knowledgeState.editingId) {
        data = await api(`/admin/knowledge/${knowledgeState.editingId}`, {
          method: 'PUT',
          body: JSON.stringify(body)
        });
      } else {
        data = await api('/admin/knowledge', {
          method: 'POST',
          body: JSON.stringify(body)
        });
      }

      if (data.error) {
        showToast(data.error, 'error');
      } else {
        showToast(knowledgeState.editingId ? '文章已更新' : '文章已创建', 'success');
        knowledgeState.uploadedFile = null;
        knowledgeBackToList();
        adminLoadKnowledge(knowledgeState.page);
      }
    } catch(e) {
      showToast('保存失败，请检查网络连接', 'error');
    } finally {
      btn.textContent = origText;
      btn.disabled = false;
    }
  }

  async function knowledgeViewDetail(articleId) {
    const data = await api(`/admin/knowledge/${articleId}`);
    if (data.error) { showToast(data.error, 'error'); return; }

    const catLabels = { material: '📦 原始素材', case: '📋 实战案例' };
    const fileIcons = { image: '🖼️', word: '📝', excel: '📊', ppt: '📽️', pdf: '📄', text: '📃' };
    const fileLabels = { image: '图片', word: 'Word', excel: 'Excel', ppt: 'PPT', pdf: 'PDF', text: '文本' };
    const tagsHTML = (data.tags || '').split(/[,，]/).filter(Boolean).map(t =>
      `<span style="display:inline-block;background:#F1F5F9;padding:3px 10px;border-radius:6px;font-size:12px;margin:2px">${t.trim()}</span>`
    ).join(' ') || '<span style="color:var(--slate)">无标签</span>';

    // Build file section
    let fileSection = '';
    if (data.file_name) {
      const isImage = data.file_type === 'image';
      const fileUrl = data.file_url || `/api/admin/knowledge/files/${data.file_name}`;
      const sizeStr = data.file_size ? (data.file_size > 1048576 ? (data.file_size/1048576).toFixed(1)+'MB' : (data.file_size/1024).toFixed(1)+'KB') : '';
      
      if (isImage) {
        fileSection = `
          <div style="margin-bottom:20px;border:1px solid var(--border);border-radius:12px;overflow:hidden;background:#F8FAFC">
            <div style="padding:10px 16px;background:#fff;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px">
              <span style="font-size:18px">🖼️</span>
              <span style="font-size:13px;font-weight:600;flex:1">${escHtml(data.file_original_name || data.file_name)}</span>
              <span style="font-size:11px;color:var(--slate)">${sizeStr}</span>
              <a href="${fileUrl}" target="_blank" class="btn btn-ghost btn-sm" style="text-decoration:none">🔗 查看原图</a>
              <a href="${fileUrl}" download="${escHtml(data.file_original_name||data.file_name)}" class="btn btn-ghost btn-sm" style="text-decoration:none">⬇ 下载</a>
            </div>
            <div style="padding:16px;text-align:center;max-height:500px;overflow:auto">
              <img src="${fileUrl}" alt="${escHtml(data.title)}" style="max-width:100%;max-height:460px;object-fit:contain;border-radius:8px" onerror="this.parentElement.innerHTML='<div style=padding:40px;color:var(--slate)>图片加载失败</div>'">
            </div>
          </div>`;
      } else {
        const icon = fileIcons[data.file_type] || '📎';
        fileSection = `
          <div style="margin-bottom:20px;padding:16px;background:linear-gradient(135deg,#F8FAFC,#EEF2FF);border:1px solid var(--border);border-radius:12px;display:flex;align-items:center;gap:14px">
            <div style="font-size:32px">${icon}</div>
            <div style="flex:1;min-width:0">
              <div style="font-size:14px;font-weight:600">${escHtml(data.file_original_name || data.file_name)}</div>
              <div style="font-size:11px;color:var(--slate);margin-top:2px">${fileLabels[data.file_type] || '文件'} · ${sizeStr}</div>
            </div>
            <a href="${fileUrl}" download="${escHtml(data.file_original_name||data.file_name)}" class="btn btn-indigo btn-sm" style="text-decoration:none">⬇ 下载文件</a>
          </div>`;
      }
    }

    document.getElementById('knowledge-detail-content').innerHTML = `
      <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
        <span style="font-size:13px;color:var(--slate)">${catLabels[data.category] || data.category}</span>
        <span style="font-size:12px;color:var(--slate)">· 作者：${data.author_name || '-'}</span>
        <span style="font-size:12px;color:var(--slate)">· 更新于：${(data.updated_at||'').substring(0,16)}</span>
      </div>
      <h2 style="font-size:22px;font-weight:800;margin-bottom:16px;letter-spacing:-0.5px">${escHtml(data.title || '')}</h2>
      <div style="margin-bottom:20px">${tagsHTML}</div>
      ${fileSection}
      <div style="border-top:1px solid var(--border);padding-top:20px;margin-top:20px;font-size:15px;line-height:2;white-space:pre-wrap;color:var(--text)">${escHtml(data.content || '') || '<span style="color:var(--slate)">（无文本内容）</span>'}</div>
    `;

    document.getElementById('knowledge-list-view').style.display = 'none';
    document.getElementById('knowledge-form-view').style.display = 'none';
    document.getElementById('knowledge-detail-view').style.display = '';
    document.getElementById('knowledge-add-btn').style.display = 'none';
    knowledgeState.view = 'detail';
  }

  async function knowledgeConfirmDelete(articleId, title) {
    if (!confirm(`确定删除文章「${title}」吗？此操作不可撤销。`)) return;
    const data = await api(`/admin/knowledge/${articleId}`, { method: 'DELETE' });
    if (data.error) { showToast(data.error, 'error'); return; }
    showToast('文章已删除', 'success');
    adminLoadKnowledge(knowledgeState.page);
  }

  async function knowledgeDelete() {
    if (!knowledgeState.editingId) return;
    const id = knowledgeState.editingId;
    const title = document.getElementById('knowledge-edit-title').value.trim() || '未命名';
    await knowledgeConfirmDelete(id, title);
    knowledgeBackToList();
  }

  function escHtml(str) {
    return String(str || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  }

  // 安全解析日期字符串（兼容 ISO 和 "YYYY-MM-DD HH:MM:SS" 格式）
  function parseDate(dateStr) {
    if (!dateStr) return null;
    // 尝试直接解析
    let d = new Date(dateStr);
    if (!isNaN(d.getTime())) return d;
    // 尝试将空格替换为 T
    d = new Date(String(dateStr).replace(' ', 'T'));
    if (!isNaN(d.getTime())) return d;
    return null;
  }

  // 相对时间显示
  function formatRelativeTime(dateStr) {
    const d = parseDate(dateStr);
    if (!d) return String(dateStr || '').substring(0, 19);
    const now = new Date();
    const diff = now - d;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days === 1) return '昨天 ' + d.toLocaleTimeString('zh-CN', {hour:'2-digit',minute:'2-digit'});
    if (days < 7) return `${days}天前 · ` + d.toLocaleTimeString('zh-CN', {hour:'2-digit',minute:'2-digit'});
    return d.toLocaleDateString('zh-CN') + ' ' + d.toLocaleTimeString('zh-CN', {hour:'2-digit',minute:'2-digit'});
  }

  // 按日期节点分组
  function groupByDate(list) {
    const today = new Date(); today.setHours(0,0,0,0);
    const yesterday = new Date(today); yesterday.setDate(yesterday.getDate() - 1);
    const weekStart = new Date(today); weekStart.setDate(weekStart.getDate() - 7);
    const groups = {};
    const order = [];
    list.forEach(item => {
      const d = parseDate(item.created_at);
      let key, label;
      if (!d) { key = 'unknown'; label = '历史记录'; }
      else {
        const dStart = new Date(d); dStart.setHours(0,0,0,0);
        if (dStart.getTime() === today.getTime()) { key = 'today'; label = '📌 今天'; }
        else if (dStart.getTime() === yesterday.getTime()) { key = 'yesterday'; label = '📌 昨天'; }
        else if (dStart >= weekStart) { key = 'week'; label = '📌 本周'; }
        else {
          key = dStart.toISOString().substring(0, 7); // YYYY-MM
          label = '📌 ' + d.getFullYear() + '年' + (d.getMonth()+1) + '月';
        }
      }
      if (!groups[key]) { groups[key] = { label, items: [] }; order.push(key); }
      groups[key].items.push(item);
    });
    return order.map(k => groups[k]);
  }

  /* ===========================
     工具诊断面板
  =========================== */
  let toolPanelState = { dim: '', dimName: '', toolName: '', toolDesc: '' };
  let savedProfiles = [];

  function openToolPanel(dim, dimName, name, desc) {
    toolPanelState = { dim, dimName, toolName: name, toolDesc: desc };
    document.getElementById('tool-panel-title').textContent = name;
    document.getElementById('tool-panel-desc').textContent = desc;
    const badge = document.getElementById('tool-panel-dim');
    badge.textContent = dimName;
    const colors = { product: '#2563EB', customer: '#10B981', channel: '#F59E0B', team: '#8B5CF6', finance: '#F43F5E' };
    const bgs = { product: '#EFF6FF', customer: '#F0FDF4', channel: '#FFFBEB', team: '#F5F3FF', finance: '#FFF1F2' };
    badge.style.background = bgs[dim] || '#F1F5F9';
    badge.style.color = colors[dim] || '#64748B';

    // 重置表单
    document.getElementById('tool-industry').value = '';
    document.getElementById('tool-product').value = '';
    document.getElementById('tool-customers').value = '';
    document.getElementById('tool-teamsize').value = '';
    document.getElementById('tool-extra').value = '';
    document.getElementById('tool-result').classList.remove('active');
    document.getElementById('tool-generating').classList.remove('active');
    document.getElementById('tool-ppt-btn').style.display = 'none';
    document.getElementById('tool-ppt-btn').disabled = false;
    document.getElementById('tool-ppt-btn').textContent = '📽️ 生成配套 PPT';
    document.getElementById('tool-submit-btn').style.display = '';
    document.getElementById('tool-submit-btn').disabled = false;
    document.getElementById('tool-submit-btn').textContent = '🪄 生成专属工具方案';

    // 重置档案选择
    document.getElementById('profile-select').value = '';
    document.getElementById('profile-preview').style.display = 'none';
    document.getElementById('btn-del-profile').classList.remove('visible');

    // 加载已保存的档案
    loadProfiles();

    document.getElementById('tool-panel-overlay').classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  function closeToolPanel() {
    document.getElementById('tool-panel-overlay').classList.remove('active');
    document.body.style.overflow = '';
  }

  // ========== 企业档案管理 ==========

  async function loadProfiles() {
    if (!state.token) { savedProfiles = []; renderProfileSelect(); return; }
    try {
      const data = await api('/company-profiles');
      savedProfiles = data.list || [];
      renderProfileSelect();
    } catch (e) {
      savedProfiles = [];
      renderProfileSelect();
    }
  }

  function renderProfileSelect() {
    const sel = document.getElementById('profile-select');
    sel.innerHTML = '<option value="">-- 选择已保存的企业信息快速填入 --</option>';
    savedProfiles.forEach((p, idx) => {
      const opt = document.createElement('option');
      opt.value = idx;
      opt.textContent = `${p.company_name}（${p.industry}）`;
      sel.appendChild(opt);
    });
    // 无档案时显示提示
    const picker = document.getElementById('profile-picker');
    if (savedProfiles.length === 0) {
      sel.insertAdjacentHTML('afterend', '<div class="profile-empty">暂无保存的企业档案，填写下方信息后可点击「💾 保存」</div>');
    } else {
      const hint = picker.querySelector('.profile-empty');
      if (hint) hint.remove();
    }
  }

  function selectProfile(idx) {
    const p = savedProfiles[idx];
    if (!p) {
      document.getElementById('profile-preview').style.display = 'none';
      document.getElementById('btn-del-profile').classList.remove('visible');
      return;
    }
    // 填入表单
    document.getElementById('tool-industry').value = p.industry || '';
    document.getElementById('tool-product').value = p.product || '';
    document.getElementById('tool-customers').value = p.customer_group || '';
    document.getElementById('tool-teamsize').value = p.team_size || '';
    document.getElementById('tool-extra').value = p.extra_info || '';

    // 显示预览
    const preview = document.getElementById('profile-preview');
    preview.innerHTML = `
      <span>🏢 ${escHtml(p.company_name)}</span>
      <span>📦 ${escHtml(p.industry)}</span>
      ${p.product ? `<span>🛒 ${escHtml(p.product)}</span>` : ''}
      ${p.team_size ? `<span>👥 ${escHtml(p.team_size)}</span>` : ''}
    `;
    preview.style.display = 'flex';
    document.getElementById('btn-del-profile').classList.add('visible');
    document.getElementById('btn-del-profile').dataset.profileIdx = idx;
    document.getElementById('btn-del-profile').dataset.profileId = p.id;
  }

  async function saveCurrentProfile() {
    const industry = document.getElementById('tool-industry').value.trim();
    const product = document.getElementById('tool-product').value.trim();
    if (!industry && !product) {
      showToast('请至少填写行业或产品信息后再保存', 'error');
      return;
    }

    // 自动生成企业名称（用户可自定义）
    let companyName = product || industry;
    if (product && industry) companyName = industry + '·' + product;
    // 截断过长的名称
    if (companyName.length > 30) companyName = companyName.substring(0, 30);

    try {
      const data = await api('/company-profiles', {
        method: 'POST',
        body: JSON.stringify({
          company_name: companyName,
          industry,
          product,
          customer_group: document.getElementById('tool-customers').value.trim(),
          team_size: document.getElementById('tool-teamsize').value,
          extra_info: document.getElementById('tool-extra').value.trim()
        })
      });

      if (data.ok) {
        showToast(data.action === 'updated' ? '企业档案已更新' : '企业档案已保存', 'success');
        await loadProfiles();
        // 自动选中刚保存的档案
        const idx = savedProfiles.findIndex(p => p.company_name === companyName);
        if (idx >= 0) {
          document.getElementById('profile-select').value = idx;
          selectProfile(idx);
        }
      } else {
        showToast(data.error || '保存失败', 'error');
      }
    } catch (e) {
      showToast('保存失败，请重试', 'error');
    }
  }

  async function deleteCurrentProfile() {
    const btn = document.getElementById('btn-del-profile');
    const id = btn.dataset.profileId;
    if (!id) return;

    if (!confirm('确定要删除这个企业档案吗？此操作不可撤销。')) return;

    try {
      const data = await api('/company-profiles/' + id, { method: 'DELETE' });
      if (data.ok) {
        showToast('档案已删除', 'success');
        document.getElementById('profile-select').value = '';
        document.getElementById('profile-preview').style.display = 'none';
        btn.classList.remove('visible');
        await loadProfiles();
      } else {
        showToast(data.error || '删除失败', 'error');
      }
    } catch (e) {
      showToast('删除失败，请重试', 'error');
    }
  }

  // 静默自动保存档案（不弹 toast，失败也忽略）
  async function autoSaveProfileSilent(industry, product) {
    if (!industry || !product || !state.token) return;
    try {
      await api('/company-profiles', {
        method: 'POST',
        body: JSON.stringify({
          company_name: industry + '·' + product,
          industry,
          product,
          customer_group: document.getElementById('tool-customers').value.trim(),
          team_size: document.getElementById('tool-teamsize').value,
          extra_info: document.getElementById('tool-extra').value.trim()
        })
      });
      // 静默刷新档案列表
      await loadProfiles();
    } catch (e) { /* 静默忽略 */ }
  }

  async function generateTool() {
    const industry = document.getElementById('tool-industry').value.trim();
    const product = document.getElementById('tool-product').value.trim();
    if (!industry || !product) {
      showToast('请填写行业和产品信息', 'error');
      return;
    }

    const btn = document.getElementById('tool-submit-btn');
    btn.disabled = true;
    btn.textContent = '⏳ 生成中...';
    document.getElementById('tool-generating').classList.add('active');
    document.getElementById('tool-result').classList.remove('active');

    try {
      const body = {
        tool_name: toolPanelState.toolName,
        tool_desc: toolPanelState.toolDesc,
        dimension: toolPanelState.dim,
        industry,
        product,
        customer_group: document.getElementById('tool-customers').value.trim(),
        team_size: document.getElementById('tool-teamsize').value,
        extra_needs: document.getElementById('tool-extra').value.trim()
      };

      const data = await api('/diagnosis/generate-tool-v2', {
        method: 'POST',
        body: JSON.stringify(body)
      });

      if (data.error) {
        showToast(data.error, 'error');
        btn.disabled = false;
        btn.textContent = '🪄 生成专属工具方案';
        document.getElementById('tool-generating').classList.remove('active');
        return;
      }

      // 显示结果（含Sheet预览）
      document.getElementById('tool-generating').classList.remove('active');
      document.getElementById('tool-result-title').textContent = '✅ ' + (data.title || '工具方案已生成');

      // 构建Sheet预览描述
      let sheetInfo = '';
      if (data.preview && data.preview.sheetNames) {
        const sheets = data.preview.sheetNames;
        const details = data.preview.sheetDetails || [];
        sheetInfo = sheets.map((name, i) => {
          const d = details[i] || {};
          return `📄 ${name}（${d.rowCount || '?'}行）`;
        }).join(' · ');
      }
      const descEl = document.getElementById('tool-result-desc');
      descEl.innerHTML = ['',
        '<span style="font-weight:bold;color:#1a3a5c;">🏷️ 专业工具 v3.0' + (data.pipeline === 'multi-pass' ? ' · 多阶段AI增强' : '') + '</span>',
        sheetInfo ? '<br><span style="font-size:13px;color:#718096;">' + sheetInfo + '</span>' : '',
        '<br><span style="font-size:13px;">点击下方按钮下载 Excel 工具方案，还可生成配套 PPT</span>'
      ].join('\n');
      const dlBtn = document.getElementById('tool-dl-btn');
      dlBtn.dataset.url = API + data.download_url;
      dlBtn.dataset.filename = data.filename;
      _dlFileState = { url: API + data.download_url, filename: data.filename };
      document.getElementById('tool-result').classList.add('active');
      // 显示 PPT 生成按钮
      const pptBtn = document.getElementById('tool-ppt-btn');
      pptBtn.style.display = '';
      pptBtn.dataset.toolName = toolPanelState.toolName;
      pptBtn.dataset.industry = industry;
      pptBtn.dataset.product = product;
      btn.style.display = 'none';

      // 自动保存企业档案（静默，失败不提示）
      autoSaveProfileSilent(industry, product);

      showToast('工具方案生成成功！', 'success');
    } catch (e) {
      showToast('网络错误，请重试', 'error');
      btn.disabled = false;
      btn.textContent = '🪄 生成专属工具方案';
      document.getElementById('tool-generating').classList.remove('active');
    }
  }

  // 下载工具文件（使用 fetch + blob，带 JWT 认证）
  let _dlFileState = { url: '', filename: '' };
  async function downloadToolFile(url, filename) {
    url = url || _dlFileState.url;
    filename = filename || _dlFileState.filename;
    if (!url) { showToast('没有可下载的文件', 'error'); return; }
    try {
      const headers = {};
      if (state.token) headers['Authorization'] = 'Bearer ' + state.token;
      const resp = await fetch(url, { headers });
      if (!resp.ok) { showToast('文件下载失败: ' + resp.status, 'error'); return; }
      const blob = await resp.blob();
      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = filename || 'tool.xlsx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(blobUrl);
      showToast('文件下载中...', 'success');
    } catch(e) {
      showToast('下载失败: ' + e.message, 'error');
    }
  }

  // 从我的文档列表下载
  function downloadMyTool(url, filename) {
    const fullUrl = API + url;
    downloadToolFile(fullUrl, filename);
  }

  // 为当前工具生成配套 PPT
  async function generatePptForTool() {
    const btn = document.getElementById('tool-ppt-btn');
    const toolName = btn.dataset.toolName || toolPanelState.toolName;
    const industry = btn.dataset.industry || '';
    const product = btn.dataset.product || '';

    btn.disabled = true;
    btn.textContent = '⏳ 生成中...';

    try {
      const data = await api('/ppt/generate', {
        method: 'POST',
        body: JSON.stringify({
          topic: `${industry}${product} - ${toolName} 工具方案`,
          type: 'tool',
          industry,
          product,
          audience: '企业管理层'
        })
      });

      if (data.error) {
        showToast(data.error, 'error');
        btn.disabled = false;
        btn.textContent = '📽️ 生成配套 PPT';
        return;
      }

      // 下载 PPT
      await downloadToolFile(API + data.download_url, data.filename);
      showToast(`PPT 已生成（${data.slide_count} 页），正在下载...`, 'success');
      btn.textContent = '✅ 已生成';
    } catch (e) {
      showToast('PPT 生成失败: ' + e.message, 'error');
      btn.disabled = false;
      btn.textContent = '📽️ 生成配套 PPT';
    }
  }

  // 批量导入文件到知识库
  function knowledgeBatchImport() {
    const input = document.createElement('input');
    input.type = 'file';
    input.multiple = true;
    input.accept = '.docx,.pdf,.pptx,.xlsx,.txt,.md,.csv,.json,.jpg,.jpeg,.png,.gif,.webp';
    input.onchange = async () => {
      const files = input.files;
      if (!files || files.length === 0) return;

      showToast(`正在导入 ${files.length} 个文件...`, 'info');

      const formData = new FormData();
      for (const f of files) formData.append('files', f);
      formData.append('category', document.getElementById('knowledge-category-filter').value || 'material');

      try {
        const headers = {};
        if (state.token) headers['Authorization'] = 'Bearer ' + state.token;
        const resp = await fetch(API + '/admin/knowledge/import-batch', {
          method: 'POST',
          headers,
          body: formData
        });
        const data = await resp.json();

        if (data.ok) {
          showToast(data.summary, 'success');
          adminLoadKnowledge();
        } else {
          showToast(data.error || '导入失败', 'error');
        }
      } catch (e) {
        showToast('导入失败: ' + e.message, 'error');
      }
    };
    input.click();
  }

  // 重建知识库向量检索索引
  async function knowledgeReindexAll() {
    if (!confirm('确定要重建所有知识库文章的搜索索引吗？此操作可能需要几分钟。')) return;

    showToast('正在重建索引...', 'info');
    try {
      const resp = await fetch(API + '/admin/knowledge/reindex-all', {
        method: 'POST',
        headers: state.token ? { 'Authorization': 'Bearer ' + state.token } : {}
      });
      const data = await resp.json();

      if (data.ok) {
        showToast(`索引重建完成！共 ${data.articles_indexed} 篇文章，${data.total_chunks} 个文本块`, 'success');
      } else {
        showToast(data.error || '重建失败', 'error');
      }
    } catch (e) {
      showToast('重建失败: ' + e.message, 'error');
    }
  }

  // 我的文档页面
  async function loadMyTools() {
    const data = await api('/diagnosis/my-tools');
    const list = data.list || [];
    const container = document.getElementById('my-tools-list');
    if (list.length === 0) {
      container.innerHTML = '<div style="text-align:center;padding:60px 20px;color:var(--slate)"><div style="font-size:48px;margin-bottom:16px">📭</div><p>还没有生成的工具方案</p><p style="font-size:13px">去诊断工作台选择工具，填写信息后即可生成专属方案</p></div>';
      return;
    }
    // 按日期分组并排序（最新在前）
    const grouped = groupByDate(list);
    container.innerHTML = grouped.map(group => {
      const items = group.items.map(r => {
        const hasFile = r.download_url && r.filename;
        return `
          <div class="my-tool-item" style="display:flex;align-items:center;justify-content:space-between;padding:14px 20px;background:var(--surface);border:1px solid var(--border);border-radius:10px;margin-bottom:8px;margin-left:28px;position:relative">
            <div style="position:absolute;left:-20px;top:50%;transform:translateY(-50%);width:10px;height:10px;border-radius:50%;background:var(--primary);border:2px solid var(--surface);box-shadow:0 0 0 1px var(--primary)"></div>
            <div>
              <div style="font-weight:600;font-size:14px;margin-bottom:3px">📊 ${escHtml(r.title)}</div>
              <div style="font-size:12px;color:var(--slate)">${formatRelativeTime(r.created_at)} · ${escHtml(r.industry || '')} ${escHtml(r.product || '')}</div>
            </div>
            <div>
              ${hasFile ? `<button class="btn btn-sm" data-url="${r.download_url}" data-filename="${escHtml(r.filename)}" onclick="downloadMyTool(this.dataset.url,this.dataset.filename)" style="font-size:12px;padding:6px 14px">📥 下载</button>` : '<span style="font-size:12px;color:var(--slate)">已过期</span>'}
            </div>
          </div>`;
      }).join('');
      return `
        <div class="date-group" style="margin-bottom:16px">
          <div class="date-node" style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
            <div class="date-node-line" style="width:4px;height:28px;background:var(--primary);border-radius:2px;flex-shrink:0"></div>
            <span style="font-size:13px;font-weight:700;color:var(--text)">${group.label}</span>
            <span style="font-size:11px;color:var(--slate);background:var(--gray-100);padding:1px 8px;border-radius:10px">${group.items.length}条记录</span>
          </div>
          ${items}
        </div>`;
    }).join('');
  }

  /* ===========================
     自动恢复登录
  =========================== */
  window.addEventListener('load', async () => {
    const token = localStorage.getItem('ailang_token');
    if (token) {
      state.token = token;
      const data = await api('/auth/me');
      if (data.user) {
        state.user = data.user;
        enterApp();
        return;
      } else {
        localStorage.removeItem('ailang_token');
        state.token = null;
      }
    }
    showView('view-landing');
  });
</script>

<!-- 工具诊断面板 -->
<div class="tool-panel-overlay" id="tool-panel-overlay" onclick="if(event.target===this)closeToolPanel()">
  <div class="tool-panel">
    <div class="tool-panel-header">
      <div>
        <h3 id="tool-panel-title">工具详情</h3>
        <span class="dim-badge" id="tool-panel-dim" style="margin-top:4px;display:inline-block"></span>
      </div>
      <button class="tool-panel-close" onclick="closeToolPanel()">✕</button>
    </div>
    <div class="tool-panel-body">
      <p id="tool-panel-desc" style="font-size:13px;color:var(--slate);margin-bottom:20px"></p>

      <!-- 企业档案快捷选择 -->
      <div class="profile-picker" id="profile-picker">
        <div class="profile-picker-header">
          <span>📋 企业档案</span>
          <div class="profile-picker-actions">
            <button class="btn-save-profile" onclick="saveCurrentProfile()" title="保存当前填写的信息">💾 保存</button>
            <button class="btn-del-profile" id="btn-del-profile" onclick="deleteCurrentProfile()" title="删除选中的档案">🗑 删除</button>
          </div>
        </div>
        <select class="profile-select" id="profile-select" onchange="selectProfile(this.value)">
          <option value="">-- 选择已保存的企业信息快速填入 --</option>
        </select>
        <div class="profile-preview" id="profile-preview" style="display:none"></div>
      </div>

      <div class="form-group">
        <label>1. 我的行业 <span class="required">*</span></label>
        <input type="text" id="tool-industry" placeholder="例如：餐饮、教育培训、电商零售、制造业..." />
        <div class="form-hint">你所在的具体行业领域</div>
      </div>
      <div class="form-group">
        <label>2. 我的产品/服务是？ <span class="required">*</span></label>
        <input type="text" id="tool-product" placeholder="例如：品牌女装、企业培训课程、SaaS软件..." />
        <div class="form-hint">你的核心产品线或服务类型</div>
      </div>
      <div class="form-group">
        <label>3. 我的客户群体是？</label>
        <input type="text" id="tool-customers" placeholder="例如：25-40岁职场女性、中小企业主、大学生..." />
        <div class="form-hint">目标客户画像，越具体诊断越精准</div>
      </div>
      <div class="form-group">
        <label>4. 团队有多少人？</label>
        <select id="tool-teamsize">
          <option value="">请选择</option>
          <option value="1-5人">1-5人（初创/个人）</option>
          <option value="6-20人">6-20人（小团队）</option>
          <option value="21-50人">21-50人（中小企业）</option>
          <option value="51-200人">51-200人（成长型企业）</option>
          <option value="200人以上">200人以上（规模企业）</option>
        </select>
      </div>
      <div class="form-group">
        <label>5. 其他诉求</label>
        <textarea id="tool-extra" placeholder="你有什么特别想解决的问题？或者期望工具重点关注的方向？"></textarea>
      </div>

      <div class="tool-generating" id="tool-generating">
        <div class="spinner-small"></div>
        <span>AI 正在生成专业级工具方案（v3.0 · 多Sheet模板）... 预计 20-40 秒</span>
      </div>

      <div class="tool-result-box" id="tool-result">
        <h4 id="tool-result-title">✅ 工具方案已生成</h4>
        <p style="font-size:12px;color:#166534;margin-bottom:12px" id="tool-result-desc"></p>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
          <button class="dl-btn" id="tool-dl-btn" onclick="downloadToolFile(this.dataset.url,this.dataset.filename)">
            📥 下载 Excel 工具方案
          </button>
          <button class="dl-btn" id="tool-ppt-btn" onclick="generatePptForTool()" style="background:var(--indigo);display:none">
            📽️ 生成配套 PPT
          </button>
        </div>
      </div>

      <button class="btn btn-primary tool-generate-btn" id="tool-submit-btn" onclick="generateTool()">
        🪄 生成专属工具方案
      </button>
    </div>
  </div>
</div>

</body>
</html>
