const { useEffect, useMemo, useState } = React;

function Icon({ d, size = 16 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d={d}></path>
    </svg>
  );
}

const ICONS = {
  workbench: "M4 4h7v7H4zM13 4h7v4h-7zM13 10h7v10h-7zM4 13h7v7H4z",
  member: "M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2M12 11a4 4 0 100-8 4 4 0 000 8z",
  merchant: "M3 21V8l9-5 9 5v13M9 21v-8h6v8",
  data: "M4 19V5M10 19V9M16 19V3M22 19H2",
  content: "M4 4h16v16H4zM8 8h8M8 12h8M8 16h5",
  marketing: "M12 3l2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5z",
  parking: "M5 4h9a5 5 0 010 10H9v6H5z",
  system: "M12 15a3 3 0 100-6 3 3 0 000 6zM19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8.3 1.7 1.7 0 00-1 1.5V21a2 2 0 01-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.8-.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 010-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 014 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9c.3.6.9 1 1.6 1H21a2 2 0 010 4h-.1a1.7 1.7 0 00-1.5 1z",
  settle: "M4 7h16v12H4zM8 7V5h8v2M8 12h8M8 16h5",
  opinion: "M21 15a4 4 0 01-4 4H8l-5 3V7a4 4 0 014-4h10a4 4 0 014 4z",
  survey: "M9 11l3 3L22 4M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11",
  sp: "M12 2l3 7h7l-5.5 4.5L18 21l-6-4-6 4 1.5-7.5L2 9h7z",
  fold: "M4 6h10M4 12h16M4 18h10M18 8l4 4-4 4",
  unfold: "M4 6h16M4 12h10M4 18h16M14 8l-4 4 4 4",
  chevronDown: "M6 9l6 6 6-6",
};

/** 一级菜单：除 SP营销 外仅展示一级 */
const PRIMARY_MENUS = [
  { id: "workbench", label: "工作台", icon: "workbench" },
  { id: "member", label: "会员中心", icon: "member" },
  { id: "merchant", label: "商户中心", icon: "merchant" },
  { id: "datacenter", label: "数据中心", icon: "data" },
  { id: "content", label: "内容中心", icon: "content" },
  { id: "marketing", label: "营销中心", icon: "marketing" },
  { id: "parking", label: "停车服务", icon: "parking" },
  { id: "system", label: "系统配置", icon: "system" },
  { id: "trade", label: "交易结算", icon: "settle" },
  { id: "opinion", label: "意见箱", icon: "opinion" },
  { id: "survey", label: "问卷调查", icon: "survey" },
  { id: "sp", label: "SP营销", icon: "sp", hasChildren: true },
];

/** SP营销：二级 + 三级 */
const SP_MENUS = [
  {
    id: "activity-group",
    label: "活动管理",
    children: [{ id: "activity", label: "活动管理", path: "sp/activity" }],
  },
  {
    id: "rules-group",
    label: "规则配置",
    children: [{ id: "rules", label: "全局规则配置", path: "sp/rules" }],
  },
  { id: "recon", label: "对账单管理", path: "sp/recon" },
  { id: "settle", label: "结算单管理", path: "sp/settle" },
];

const ROUTE_META = {
  "sp/activity": { crumbs: ["SP营销", "活动管理", "活动管理"], title: "活动管理" },
  "sp/activity/create": { crumbs: ["SP营销", "活动管理", "活动管理", "新建"], title: "新建" },
  "sp/rules": { crumbs: ["SP营销", "规则配置", "全局规则配置"], title: "全局规则配置" },
  "sp/activity-data": { crumbs: ["SP营销", "活动管理", "活动管理", "活动数据"], title: "活动数据" },
  "sp/activity-data/tasks": { crumbs: ["SP营销", "活动管理", "活动管理", "我的任务"], title: "我的任务" },
  "sp/recon": { crumbs: ["SP营销", "对账单管理"], title: "对账单管理" },
  "sp/recon/tasks": { crumbs: ["SP营销", "对账单管理", "我的任务"], title: "我的任务" },
  "sp/settle": { crumbs: ["SP营销", "结算单管理"], title: "结算单管理" },
  "sp/settle/tasks": { crumbs: ["SP营销", "结算单管理", "我的任务"], title: "我的任务" },
};

function resolveCrumbs(route) {
  if (ROUTE_META[route]) return ROUTE_META[route].crumbs;
  if (route.startsWith("sp/activity-data/board/")) return ["SP营销", "活动管理", "活动管理", "活动数据"];
  if (route === "sp/activity-data" || route.startsWith("sp/activity-data/")) {
    return ["SP营销", "活动管理", "活动管理", "活动数据"];
  }
  if (route.startsWith("sp/activity/view/")) return ["SP营销", "活动管理", "活动管理", "详情"];
  if (route.startsWith("sp/activity/edit/")) return ["SP营销", "活动管理", "活动管理", "修改"];
  if (route.startsWith("sp/activity/") && !route.startsWith("sp/activity-data")) {
    return ["SP营销", "活动管理", "活动管理"];
  }
  return null;
}

function isMenuPathActive(route, path) {
  return route === path || route.startsWith(path + "/");
}

function isActivityMenuActive(route) {
  return (
    route === "sp/activity" ||
    route.startsWith("sp/activity/") ||
    route === "sp/activity-data" ||
    route.startsWith("sp/activity-data/")
  );
}

function parseHash() {
  const raw = (location.hash || "#sp/activity").replace(/^#/, "");
  return raw || "sp/activity";
}

function navigate(path) {
  location.hash = path;
}

function useHashRoute() {
  const [route, setRoute] = useState(parseHash);
  useEffect(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener("hashchange", onHash);
    if (!location.hash) location.hash = "sp/activity";
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

function useStore() {
  const [state, setState] = useState(() => SPData.load());
  const update = (updater) => {
    setState((prev) => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      const synced = SPData.applyAutoArchive(next);
      SPData.save(synced);
      return synced;
    });
  };
  return [state, update];
}

const STATUS_TAG_COLOR = {
  draft: "default",
  reviewing: "processing",
  rejected: "error",
  pending: "warning",
  active: "success",
  paused: "warning",
  ended: "default",
  archived: "default",
  deleted: "default",
};

function StatusTag({ status }) {
  const meta = SPData.STATUS[status] || { label: status, tone: "draft" };
  return (
    <antd.Tag color={STATUS_TAG_COLOR[status] || STATUS_TAG_COLOR[meta.tone] || "default"}>
      {meta.label}
    </antd.Tag>
  );
}

function AdminShell({ children, density = "regular", accent = "#006eff" }) {
  const route = useHashRoute();
  const [collapsed, setCollapsed] = useState(false);
  const [openGroups, setOpenGroups] = useState({ "activity-group": true, "rules-group": false });

  const isSp = route.startsWith("sp/");
  const primaryId = isSp ? "sp" : route.split("/")[0];

  useEffect(() => {
    document.documentElement.style.setProperty("--accent", accent);
    document.documentElement.style.setProperty("--aside-active", accent);
    document.documentElement.style.setProperty("--sub-active", accent);
    document.documentElement.style.setProperty("--accent-hover", accent);
    document.documentElement.style.setProperty("--density-pad", density === "compact" ? "12px" : density === "comfy" ? "22px" : "16px");
  }, [accent, density]);

  useEffect(() => {
    if (isActivityMenuActive(route) || route === "sp/rules") {
      setOpenGroups((g) => ({
        ...g,
        "activity-group": isActivityMenuActive(route) ? true : g["activity-group"],
        "rules-group": route === "sp/rules" ? true : g["rules-group"],
      }));
    }
  }, [route]);

  const crumbs = useMemo(() => {
    if (isSp) return resolveCrumbs(route) || ["SP营销"];
    const item = PRIMARY_MENUS.find((m) => m.id === primaryId);
    return item ? [item.label] : ["工作台"];
  }, [isSp, route, primaryId]);

  const shellClass = [
    "app-shell",
    isSp ? "has-sub" : "",
    collapsed ? "collapsed" : "",
  ].filter(Boolean).join(" ");

  return (
    <div className={shellClass} data-screen-label="admin-shell">
      {/* 左侧深色一级栏：通高，含 Logo */}
      <aside className="aside" data-screen-label="primary-menu">
        <div className="aside-brand">
          {!collapsed ? <img className="brand-logo" src="logo.png" alt="WANDA PLAZA"></img> : null}
          <button
            className="collapse-btn"
            type="button"
            title={collapsed ? "展开菜单" : "折叠菜单"}
            onClick={() => setCollapsed((v) => !v)}
          >
            <Icon d={collapsed ? ICONS.unfold : ICONS.fold} size={16}></Icon>
          </button>
        </div>
        <div className="aside-menu">
          {PRIMARY_MENUS.map((item) => (
            <button
              key={item.id}
              type="button"
              className={"aside-item" + (primaryId === item.id ? " active" : "")}
              title={item.label}
              onClick={() => navigate(item.hasChildren ? "sp/activity" : item.id)}
            >
              <span className="aside-icon"><Icon d={ICONS[item.icon]} size={16}></Icon></span>
              {!collapsed ? <span className="aside-label">{item.label}</span> : null}
            </button>
          ))}
        </div>
      </aside>

      {/* 右侧：顶栏 +（二级菜单 | 内容） */}
      <div className="workspace">
        <header className="topbar">
          <div className="topbar-right">
            <a className="topbar-link" href="https://center.wandawic.com" target="_blank" rel="noreferrer">新版小程序知识库</a>
            <span className="topbar-divider"></span>
            <span className="topbar-org">珠海万达商业管理集团股份有限公司</span>
            <span className="topbar-divider"></span>
            <div className="user-chip">
              <span className="user-avatar">韩</span>
              <span>韩金宇</span>
            </div>
          </div>
        </header>

        <div className="workspace-body">
          {isSp ? (
            <nav className="submenu" data-screen-label="sp-submenu">
              {SP_MENUS.map((item) => {
                if (item.children) {
                  const opened = !!openGroups[item.id];
                  return (
                    <div className="submenu-group" key={item.id}>
                      <button
                        type="button"
                        className="submenu-group-title"
                        onClick={() => setOpenGroups((g) => ({ ...g, [item.id]: !g[item.id] }))}
                      >
                        <span>{item.label}</span>
                        <span className={"chev-down" + (opened ? " open" : "")}>
                          <Icon d={ICONS.chevronDown} size={12}></Icon>
                        </span>
                      </button>
                      {opened ? (
                        <div className="submenu-children">
                          {item.children.map((child) => {
                            const active = child.path === "sp/activity"
                              ? isActivityMenuActive(route)
                              : route === child.path;
                            return (
                              <button
                                key={child.id}
                                type="button"
                                className={"submenu-item child" + (active ? " active" : "")}
                                onClick={() => navigate(child.path)}
                              >
                                {child.label}
                              </button>
                            );
                          })}
                        </div>
                      ) : null}
                    </div>
                  );
                }
                return (
                  <button
                    key={item.id}
                    type="button"
                    className={"submenu-item" + (isMenuPathActive(route, item.path) ? " active" : "")}
                    onClick={() => navigate(item.path)}
                  >
                    {item.label}
                  </button>
                );
              })}
            </nav>
          ) : null}

          <main className="main">
            <div className="breadcrumb">
              {crumbs.map((c, i) => {
                const isLast = i === crumbs.length - 1;
                let href = null;
                if (!isLast) {
                  if (c === "活动数据") href = "sp/activity-data";
                  else if (c === "对账单管理") href = "sp/recon";
                  else if (c === "结算单管理") href = "sp/settle";
                  else if (c === "活动管理") href = "sp/activity";
                  else if (c === "规则配置") href = "sp/rules";
                  else if (c === "SP营销") href = "sp/activity";
                }
                return (
                  <React.Fragment key={c + i}>
                    {i > 0 ? <span className="sep">/</span> : null}
                    {href ? (
                      <button type="button" className="crumb-link" onClick={() => navigate(href)}>{c}</button>
                    ) : (
                      <span className={isLast ? "current" : ""}>{c}</span>
                    )}
                  </React.Fragment>
                );
              })}
            </div>
            <div className="content">{typeof children === "function" ? children({ route, navigate }) : children}</div>
            <div className="footer-note">© 2026 万达广场小程序</div>
          </main>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Icon,
  ICONS,
  PRIMARY_MENUS,
  SP_MENUS,
  AdminShell,
  useHashRoute,
  useStore,
  StatusTag,
  navigate,
});
