/* === Main App === */
/* global React, ReactDOM, ToastProvider, Sidebar, Topbar, ProductDetailDrawer, InfoDrawer,
   PageProductPool, PageProductDetail, PageProductCompare,
   PageMgrOverview, PageMgrStrategy, PageMgrTactical, PageMgrSelection,
   PageWarnOverview, PageRiskWarning, PageSOP,
   PageOperationOverview, PageOperationUser, PageOperationBatch, PageOperationRule, PageOperationProduct, PageOperationData, PageOperationProbe, PageOperationDict, PageOperationIndicator,
   PageDashboard */
const { useState, useEffect } = React;

const ROUTES = {
  "pool-list":    { title: "产品池", crumb: "产品池" },
  "pool-detail":  { title: "产品详情", crumb: "产品池 / 产品详情" },
  "pool-compare": { title: "产品对比", crumb: "产品池 / 产品对比" },
  "mgr-overview": { title: "管理人分析", crumb: "管理人分析" },
  "mgr-strategy": { title: "策略配置能力", crumb: "管理人分析 / 策略配置能力" },
  "mgr-tactical": { title: "战术配置能力", crumb: "管理人分析 / 战术配置能力" },
  "mgr-selection":{ title: "选基能力", crumb: "管理人分析 / 选基能力" },
  "warn-overview":{ title: "预警和售后", crumb: "预警和售后" },
  "warn-risk":    { title: "风险事件预警", crumb: "预警和售后 / 风险事件预警" },
  "warn-sop":     { title: "售后 SOP", crumb: "预警和售后 / 售后 SOP" },
  "operation-overview":{ title: "运营管理", crumb: "运营管理" },
  "operation-user":{ title: "用户权限", crumb: "运营管理 / 用户权限" },
  "operation-batch":{ title: "批量任务", crumb: "运营管理 / 批量任务" },
  "operation-rule":{ title: "规则策略", crumb: "运营管理 / 规则策略" },
  "operation-product":{ title: "产品维护", crumb: "运营管理 / 产品维护" },
  "operation-data":{ title: "数据接入", crumb: "运营管理 / 数据接入" },
  "operation-indicator":{ title: "指标计算", crumb: "运营管理 / 指标计算" },
  "operation-probe":{ title: "数据探查", crumb: "运营管理 / 数据探查" },
  "operation-dict":{ title: "数据字典", crumb: "运营管理 / 数据字典" },
  "dashboard":    { title: "视图看板", crumb: "视图看板" },
  "system":       { title: "系统设置", crumb: "系统设置" },
};

function App() {
  const [route, setRoute] = useState("pool-list");
  const [productId, setProductId] = useState("A108");
  const [mgrId, setMgrId] = useState("M01");
  const [compareIds, setCompareIds] = useState(["A108", "P005", "P009", "C3"]);
  const [drawer, setDrawer] = useState(null); // { kind: 'product'|'info', id?, payload? }
  const [dataLoaded, setDataLoaded] = useState(false);
  const [loadError, setLoadError] = useState(null);

  useEffect(() => {
    // 检查数据是否加载完成
    const checkData = () => {
      if (window.IRDATA && window.IRDATA.products && window.IRDATA.products.length > 0) {
        setDataLoaded(true);
        return true;
      }
      return false;
    };

    if (!checkData()) {
      // 如果数据还没加载，等待一下再检查
      const timer = setTimeout(() => {
        if (!checkData()) {
          setLoadError("数据加载超时，请刷新页面重试");
        }
      }, 3000);

      return () => clearTimeout(timer);
    }
  }, []);

  const [watchState, setWatchState] = useState([]);
  const [watchlistLoaded, setWatchlistLoaded] = useState(false);

  useEffect(() => {
    if (route.startsWith('warn-') || route === 'warn-overview') {
      if (!watchlistLoaded) {
        window.IRDATA.loadWatchlist().then(data => {
          setWatchState(Array.isArray(data) ? data.map(e => ({ ...e })) : []);
          setWatchlistLoaded(true);
        });
      }
    }
  }, [route, watchlistLoaded]);

  const onNav = (r, extras) => {
    setRoute(r);
    if (extras?.productId) setProductId(extras.productId);
    if (extras?.mgrId) setMgrId(extras.mgrId);
  };

  const openDrawer = (d) => setDrawer(d);
  const closeDrawer = () => setDrawer(null);

  const addToCompare = (id) => {
    setCompareIds(ids => ids.includes(id) ? ids : (ids.length >= 6 ? ids : [...ids, id]));
  };

  const setStage = (eid, stage) => {
    setWatchState(prev => prev.map(e => e.id === eid ? { ...e, stage } : e));
  };

  const meta = ROUTES[route] || ROUTES["pool-list"];

  const renderPage = () => {
    if (!dataLoaded && !loadError) {
      return (
        <div className="card">
          <div className="card-body" style={{ padding: "80px 20px", textAlign: "center" }}>
            <div className="coming-soon-icon">⏳</div>
            <h3>数据加载中...</h3>
            <p>请稍候</p>
          </div>
        </div>
      );
    }

    if (loadError) {
      return (
        <div className="card">
          <div className="card-body" style={{ padding: "80px 20px", textAlign: "center" }}>
            <div className="coming-soon-icon">⚠️</div>
            <h3>加载出错</h3>
            <p>{loadError}</p>
            <button className="btn btn-primary" onClick={() => window.location.reload()}>
              刷新页面
            </button>
          </div>
        </div>
      );
    }

    switch (route) {
      case "pool-list":
        return <PageProductPool onNav={onNav} openDrawer={openDrawer}
          compareIds={compareIds} addToCompare={addToCompare} />;
      case "pool-detail":
        return <PageProductDetail productId={productId} setProductId={setProductId}
          onNav={onNav} openDrawer={openDrawer} />;
      case "pool-compare":
        return <PageProductCompare compareIds={compareIds} setCompareIds={setCompareIds}
          openDrawer={openDrawer} onNav={onNav} />;
      case "mgr-overview":
        return <PageMgrOverview mgrId={mgrId} setMgrId={setMgrId} onNav={onNav} openDrawer={openDrawer} />;
      case "mgr-strategy":
        return <PageMgrStrategy mgrId={mgrId} setMgrId={setMgrId} openDrawer={openDrawer} />;
      case "mgr-tactical":
        return <PageMgrTactical mgrId={mgrId} setMgrId={setMgrId} openDrawer={openDrawer} />;
      case "mgr-selection":
        return <PageMgrSelection mgrId={mgrId} setMgrId={setMgrId} />;
      case "warn-overview":
        return <PageWarnOverview onNav={onNav} watchState={watchState} setStage={setStage} />;
      case "warn-risk":
        return <PageRiskWarning openDrawer={openDrawer} onNav={onNav}
          watchState={watchState} setStage={setStage} />;
      case "warn-sop":
        return <PageSOP openDrawer={openDrawer} watchState={watchState} setStage={setStage} />;
      case "operation-overview":
        return <PageOperationOverview onNav={onNav} />;
      case "operation-user":
        return <PageOperationUser />;
      case "operation-batch":
        return <PageOperationBatch />;
      case "operation-rule":
        return <PageOperationRule />;
      case "operation-product":
        return <PageOperationProduct />;
      case "operation-data":
        return <PageOperationData />;
      case "operation-indicator":
        return <PageOperationIndicator />;
      case "operation-probe":
        return <PageOperationProbe />;
      case "operation-dict":
        return <PageOperationDict />;
      case "dashboard":
        return <PageDashboard />;
      default:
        return <div className="card"><div className="card-body">页面未找到</div></div>;
    }
  };

  return (
    <ToastProvider>
      <div className="app">
        <Sidebar route={route} onNav={onNav} />
        <div className="main">
          <Topbar
            title={meta.title}
            crumb={meta.crumb}
            onNav={onNav}
            openDrawer={openDrawer}
          />
          <div className="content">{renderPage()}</div>
        </div>
      </div>
      {drawer?.kind === "product" && (
        <ProductDetailDrawer id={drawer.id} onClose={closeDrawer} onNav={onNav} />
      )}
      {drawer?.kind === "info" && (
        <InfoDrawer payload={drawer.payload} onClose={closeDrawer} />
      )}
    </ToastProvider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
