/* global React, PageHead, FilterBar, Icon, Button, SIDEBAR, ROLES */

const { useMemo, useState, useEffect } = React;

const FLOW_PAGE_URL = "/design-inspector/flow.html";

const openFlowPage = () => { window.open(FLOW_PAGE_URL, "_blank", "noopener"); };

const STATIC_ROUTES = [
  {
    groupLabel: "開發工具",
    routes: [
      {
        title: "Design System（元件展示）",
        path: "#/main-intro/design-system",
        kind: "hash",
        note: "Button、Tag、Form、Dialog 等共用元件與 token 範例",
      },
      {
        title: "Table 範例（表格樣式集）",
        path: "#/main-intro/table",
        kind: "hash",
        note: "排序、分組表頭、凍結欄、勾選批次、行內編輯、差異對照、分頁",
      },
      {
        title: "Flow 畫面總覽",
        path: FLOW_PAGE_URL,
        kind: "path",
        note: "全站模組截圖畫布，依 URL 分組平移縮放",
      },
      {
        title: "原型入口（本頁）",
        path: "#/main-intro",
        kind: "hash",
        note: "入口導覽與路由總覽",
      },
      {
        title: "原型首頁（預設模組）",
        path: "#/product/new",
        kind: "hash",
        note: "進入 Sidebar 後台原型",
      },
    ],
  },
];

const buildPrototypeRouteCatalog = () => {
  const groups = SIDEBAR.map(group => ({
    groupId: group.id,
    groupLabel: group.label,
    routes: (group.children || []).map(item => ({
      title: item.label,
      path: `#/${group.id}/${item.id}`,
      kind: "hash",
      roleOnly: item.roleOnly || group.roleOnly || null,
      approvable: !!item.approvable,
    })),
  }));
  return [...STATIC_ROUTES, ...groups];
};

const MainIntroTopbar = () => (
  <div className="main-intro__topbar">
    <img className="main-intro__topbar-logo" src="assets/uber-logo-horizontal-dark.svg" alt="Uber" />
    <div className="main-intro__topbar-name">DG SKU 管理系統 · 原型入口</div>
  </div>
);

const MainIntroHub = ({ onOpenRoutes, onOpenDesignSystem, onOpenTable, onEnterApp }) => {
  const entries = [
    {
      key: "design-system",
      icon: "layers",
      title: "Design System",
      desc: "共用元件展示：Button、Tag、Form、Dialog、token 色票與字級範例。",
      meta: "#/main-intro/design-system",
      onClick: onOpenDesignSystem,
    },
    {
      key: "table",
      icon: "list",
      title: "Table 範例",
      desc: "表格樣式集：排序、分組表頭、凍結欄、勾選批次、行內編輯、差異對照、分頁。",
      meta: "#/main-intro/table",
      onClick: onOpenTable,
    },
    {
      key: "flow",
      icon: "mapPin",
      title: "Flow 畫面總覽",
      desc: "全站模組截圖畫布，依 URL 分組；平移縮放瀏覽，點卡片跳轉原型頁。",
      meta: FLOW_PAGE_URL,
      onClick: openFlowPage,
    },
    {
      key: "routes",
      icon: "list",
      title: "路由總覽",
      desc: "列出原型內每一個 hash 路由、頁面標題與角色限制，可一鍵跳轉。",
      meta: "#/main-intro/routes",
      onClick: onOpenRoutes,
    },
    {
      key: "app",
      icon: "grid",
      title: "進入原型",
      desc: "開啟帶 Sidebar 的後台原型，從新商品建立單開始瀏覽各模組。",
      meta: "#/product/new",
      onClick: onEnterApp,
    },
  ];

  return (
    <div className="main-intro__inner">
      <PageHead
        title="原型入口"
        subtitle="DG SKU Hi-Fi 原型導覽。瀏覽 Design System、Flow 畫面總覽、路由總覽，或直接進入後台。"
      />
      <div className="main-intro__grid">
        {entries.map(entry => (
          <button key={entry.key} type="button" className="main-intro__card" onClick={entry.onClick}>
            <div className="main-intro__card-head">
              <div className="main-intro__card-icon"><Icon name={entry.icon} size={18} /></div>
              <div className="main-intro__card-title">{entry.title}</div>
            </div>
            <p className="main-intro__card-desc">{entry.desc}</p>
            <div className="main-intro__card-meta">{entry.meta}</div>
          </button>
        ))}
      </div>
    </div>
  );
};

const MainIntroRoutes = ({ onBack, onOpenSub, onOpenRoute }) => {
  const [q, setQ] = useState("");
  const catalog = useMemo(() => buildPrototypeRouteCatalog(), []);

  const filtered = useMemo(() => {
    const lq = q.trim().toLowerCase();
    if (!lq) return catalog;
    return catalog
      .map(group => ({
        ...group,
        routes: group.routes.filter(r =>
          r.title.toLowerCase().includes(lq)
          || r.path.toLowerCase().includes(lq)
          || (group.groupLabel || "").toLowerCase().includes(lq)
        ),
      }))
      .filter(g => g.routes.length > 0);
  }, [catalog, q]);

  const total = filtered.reduce((n, g) => n + g.routes.length, 0);

  const openRoute = (route) => {
    if (route.kind === "path") {
      window.open(route.path, "_blank", "noopener");
      return;
    }
    const introSub = route.path.match(/^#\/main-intro\/([^/?#]+)/);
    if (introSub) {
      onOpenSub(introSub[1]);
      return;
    }
    const m = route.path.match(/^#\/([^/]+)\/([^/?#]+)/);
    if (m) onOpenRoute(m[1], m[2]);
    else window.location.hash = route.path.replace(/^#/, "");
  };

  const roleLabel = (roleOnly) => {
    if (!roleOnly) return "—";
    return ROLES[roleOnly]?.label || roleOnly;
  };

  return (
    <div className="main-intro__inner">
      <PageHead
        crumbs={[
          { label: "原型入口", onClick: onBack },
          { label: "路由總覽", current: true },
        ]}
        title="路由總覽"
        subtitle={`共 ${total} 個入口（含 Design System、Flow 與 Sidebar ${SIDEBAR.reduce((n, g) => n + (g.children?.length || 0), 0)} 項）`}
        actions={<Button variant="default" onClick={onBack}>返回入口</Button>}
      />

      <FilterBar filters={[
        { type: "search", placeholder: "搜尋大分類、標題、路徑…", value: q, onChange: setQ },
      ]} />

      {filtered.map(group => (
        <section key={group.groupLabel} className="main-intro__group">
          <h2 className="main-intro__group-title">{group.groupLabel}</h2>
          <div className="card">
            <div className="tbl-wrap">
              <table className="tbl">
                <thead>
                  <tr>
                    <th>頁面標題</th>
                    <th style={{ width: 280 }}>網址</th>
                    <th style={{ width: 100 }}>角色限制</th>
                    <th style={{ width: 80 }} className="center">功能</th>
                  </tr>
                </thead>
                <tbody>
                  {group.routes.map(route => (
                    <tr key={route.path + route.title}>
                      <td>
                        <a className="main-intro__route-link" onClick={() => openRoute(route)}>
                          {route.title}
                        </a>
                        {route.note && (
                          <div style={{ fontSize: "var(--fs-12)", color: "var(--fg-4)", marginTop: 4 }}>{route.note}</div>
                        )}
                        {route.approvable && (
                          <div style={{ fontSize: "var(--fs-12)", color: "var(--fg-4)", marginTop: 2 }}>含審核流程</div>
                        )}
                      </td>
                      <td className="main-intro__route-url">
                        {route.kind === "path"
                          ? `${window.location.origin}${route.path}`
                          : `${window.location.origin}/${route.path}`}
                      </td>
                      <td className="main-intro__route-role">{roleLabel(route.roleOnly)}</td>
                      <td className="center">
                        <button type="button" className="row-act" onClick={() => openRoute(route)}>開啟</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </section>
      ))}
    </div>
  );
};

const MainIntroPage = ({ subView, onOpenSub, onOpenRoute, onEnterApp }) => {
  useEffect(() => {
    if (subView === "flow") window.location.replace(FLOW_PAGE_URL);
  }, [subView]);

  if (subView === "flow") return null;

  return (
  <div className="main-intro">
    <MainIntroTopbar />
    {subView === "routes" ? (
      <MainIntroRoutes
        onBack={() => onOpenSub(null)}
        onOpenSub={onOpenSub}
        onOpenRoute={onOpenRoute}
      />
    ) : subView === "design-system" ? (
      <MainIntroDesignSystem onBack={() => onOpenSub(null)} />
    ) : subView === "table" ? (
      <MainIntroTableGallery onBack={() => onOpenSub(null)} />
    ) : (
      <MainIntroHub
        onOpenRoutes={() => onOpenSub("routes")}
        onOpenDesignSystem={() => onOpenSub("design-system")}
        onOpenTable={() => onOpenSub("table")}
        onEnterApp={onEnterApp}
      />
    )}
  </div>
  );
};

Object.assign(window, { MainIntroPage, buildPrototypeRouteCatalog });
