/* ============================================================
   Beacon CS — App shell (dark slate nav · knowledge ops sections · top bar · router)
   ============================================================ */
const { useState, useEffect, useRef } = React;
window.PROTOTYPE_STATE = window.PROTOTYPE_STATE || {
  skillDraftReady: false,
  testSuitePassed: false,
  publishedVersions: {},
};

const SECTIONS = [
  { id: "analyze", label: "分析", ico: "analyze", group: "持续优化",
    sub: "结果与缺口" },
  { id: "train", label: "训练", ico: "train", group: "持续优化",
    sub: "文章、问答与流程" },
  { id: "test", label: "测试", ico: "test", group: "持续优化",
    sub: "发布前验证" },
  { id: "deploy", label: "发布", ico: "deploy", group: "持续优化",
    sub: "发布版本" },
  { id: "settings", label: "设置", ico: "settings", group: "系统配置",
    sub: "连接与权限" },
];

const VIEWS = {
  analyze: () => window.AnalyzeView,
  train: () => window.TrainView,
  test: () => window.TestView,
  deploy: () => window.DeployView,
  settings: () => window.SettingsView,
};

const resetContentScroll = () => {
  requestAnimationFrame(() => document.querySelector(".content")?.scrollTo({ top: 0, left: 0, behavior: "auto" }));
};

function App() {
  const [active, setActive] = useState(() => {
    const saved = localStorage.getItem("beacon.section");
    return SECTIONS.some(s => s.id === saved) ? saved : "train";
  });
  const [viewIntents, setViewIntents] = useState({});
  const [widgetOpen, setWidgetOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const activeRef = useRef(active);
  const viewIntentsRef = useRef(viewIntents);
  const Icons = window.Icons;

  useEffect(() => { localStorage.setItem("beacon.section", active); }, [active]);
  useEffect(() => {
    window.BeaconNav = {
      go: (section, intent = {}) => {
        if (!SECTIONS.some(s => s.id === section)) return;
        setViewIntents(prev => {
          const next = { ...prev, [section]: { ...(prev[section] || {}), ...intent } };
          viewIntentsRef.current = next;
          return next;
        });
        if (section !== activeRef.current) {
          setLoading(true);
          activeRef.current = section;
          setActive(section);
          setTimeout(() => { setLoading(false); resetContentScroll(); }, 260);
        } else resetContentScroll();
      },
      intent: (section) => viewIntentsRef.current[section] || {},
    };
    return () => { if (window.BeaconNav?.intent) window.BeaconNav = null; };
  }, []);

  const go = (id) => {
    if (id === activeRef.current) {
      resetContentScroll();
      return;
    }
    setViewIntents(prev => {
      const next = { ...prev, [id]: {} };
      viewIntentsRef.current = next;
      return next;
    });
    activeRef.current = id;
    setLoading(true); setActive(id);
    setTimeout(() => { setLoading(false); resetContentScroll(); }, 360);
  };

  const meta = SECTIONS.find(s => s.id === active);
  const View = VIEWS[active] ? VIEWS[active]() : null;

  // grouped nav
  const groups = [];
  SECTIONS.forEach(s => {
    let g = groups.find(x => x.name === s.group);
    if (!g) { g = { name: s.group, items: [] }; groups.push(g); }
    g.items.push(s);
  });

  return (
    <div className="app">
      {/* ---- dark slate nav ---- */}
      <nav className="nav">
        <div className="nav-brand">
          <div className="nav-logo">B</div>
          <div>
            <div className="nav-brand-name">Beacon CS</div>
            <div className="nav-brand-sub">BitMart · 客服系统</div>
          </div>
        </div>
        <div className="nav-sections">
          {groups.map(g => (
            <div key={g.name}>
              <div className="nav-group-label">{g.name}</div>
              {g.items.map(s => {
                const Ico = Icons[s.ico];
                return (
                  <button key={s.id}
                    className={"nav-item" + (active === s.id ? " active" : "")}
                    aria-label={`打开${s.label}`}
                    aria-current={active === s.id ? "page" : undefined}
                    onClick={() => go(s.id)}>
                    <Ico className="nav-ico" s={17} />
                    <span>{s.label}</span>
                    {s.badge ? <span className={"nav-badge" + (s.badgeRed ? " red" : "")}>{s.badge}</span> : null}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
        <div className="nav-foot">
          <button className="nav-widget-btn" data-testid="preview-widget" aria-label="预览客户聊天窗口" onClick={() => setWidgetOpen(true)}>
            <Icons.msg s={16} />
            <span>预览客户聊天窗口</span>
          </button>
        </div>
      </nav>

      {/* ---- main column ---- */}
      <div className="main">
        <header className="topbar">
          <div className="row" style={{ gap: 10 }}>
            <span className="topbar-title">{meta.label}</span>
            <span className="topbar-crumb">· {meta.sub}</span>
          </div>
          <div className="topbar-search">
            <Icons.search s={15} />
            <input aria-label="搜索文章、常见问答和处理流程" placeholder="搜索文章、问答或流程..." />
          </div>
          <div className="agent-status">
            <span className="agent-dot"></span>
            <span>就绪</span>
            <span className="agent-av">ED</span>
          </div>
        </header>

        <main className="content">
          {loading ? <window.SectionSkeleton /> : (View ? <View key={active} intent={viewIntents[active] || {}} /> : <div className="content-pad">暂未开放。</div>)}
        </main>
      </div>

      {/* ---- customer widget overlay ---- */}
      {widgetOpen && window.WidgetApp ? <window.WidgetApp onClose={() => setWidgetOpen(false)} /> : null}
    </div>
  );
}

window.__BeaconApp = App;
