const TopBar = ({ route = "overview", onRoute }) => {
  const isMobile = useIsMobile();

  const nav = [
    { key: "overview", zh: "總覽", jp: "ダッシュボード", href: "/home.html" },
    { key: "products", zh: "商品", jp: "商品一覧", href: "/products/", hasSubmenu: true },
    { key: "popup",    zh: "Pop-up", jp: "期間限定店", href: "/popup/" },
    { key: "about",    zh: "About", jp: "について", href: "/about/" },
  ];

  // Sub-menu for 商品 — grouped by series
  const productGroups = [
    {
      label_zh: "擴充包", label_jp: "拡張パック",
      items: [
        { slug: "ninja-spinner",  zh: "忍者飛旋",   jp: "ニンジャスピナー",   release: "2026-03-13", badge: "即將發售" },
        { slug: "mega-brave",     zh: "超級勇氣",  jp: "メガブレイブ",       release: "2025-08-01" },
        { slug: "mega-symphonia", zh: "超級交響樂",jp: "メガシンフォニア",   release: "2025-08-01" },
        { slug: "battle-partners",zh: "對戰搭檔",   jp: "バトルパートナーズ", release: "2025-01-24" },
        { slug: "crimson-haze",   zh: "緋紅薄霧",   jp: "クリムゾンヘイズ",   release: "2024-03-22" },
      ],
    },
    {
      label_zh: "挑戰牌組", label_jp: "スターターセット",
      items: [
        { slug: "start-deck-ex-2026", zh: "超級 ex 挑戰牌組", jp: "スターターセット MEGA", release: "2025-08-01" },
      ],
    },
  ];
  // Submenu — desktop: hover opens, click-when-open navigates (two-tap pattern).
  const [submenuOpen, setSubmenuOpen] = React.useState(false);
  // Mobile drawer — hamburger host
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  // Mobile drawer: products accordion — first tap expands, second tap on 商品 navigates.
  const [productsExpanded, setProductsExpanded] = React.useState(false);
  React.useEffect(() => { if (!isMobile) { setDrawerOpen(false); setProductsExpanded(false); } else setSubmenuOpen(false); }, [isMobile]);

  // MVP: fake refresh — spin 1.2s, then bump lastScraped to now + toast.
  // Persisted via localStorage so navigating between pages preserves it.
  const LS_KEY = "ptcg.lastScraped";
  const DEFAULT_SCRAPED = "2026-04-22T04:15:00+09:00";
  const [lastScraped, setLastScrapedState] = React.useState(() => {
    try {
      const saved = localStorage.getItem(LS_KEY);
      return new Date(saved || DEFAULT_SCRAPED);
    } catch { return new Date(DEFAULT_SCRAPED); }
  });
  const setLastScraped = (d) => {
    setLastScrapedState(d);
    try { localStorage.setItem(LS_KEY, d.toISOString()); } catch (_) {}
  };
  const [refreshing, setRefreshing] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  const fmtJST = React.useCallback((d) => {
    const parts = new Intl.DateTimeFormat("ja-JP", {
      timeZone: "Asia/Tokyo",
      year: "numeric", month: "2-digit", day: "2-digit",
      hour: "2-digit", minute: "2-digit", hour12: false,
    }).formatToParts(d).reduce((a, p) => (a[p.type] = p.value, a), {});
    return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
  }, []);

  const handleRefresh = () => {
    if (refreshing) return;
    setRefreshing(true);
    setTimeout(() => {
      setLastScraped(new Date());
      setRefreshing(false);
      setToast("已同步 · 剛剛");
      setTimeout(() => setToast(null), 2200);
    }, 1200);
  };

  // --- Shared styles ---
  const navBtnStyle = (active) => ({
    background: active ? "var(--ink-50)" : "transparent",
    color: active ? "var(--fg-1)" : "var(--fg-2)",
    border: "none", padding: "6px 12px", borderRadius: 6,
    font: "500 13px/1 var(--font-body)", cursor: "pointer",
    display: "flex", alignItems: "baseline", gap: 6,
    transition: "background 120ms",
    textDecoration: "none",
  });

  // --- Mobile drawer contents (same submenu data) ---
  const MobileDrawer = () => (
    <>
      {/* scrim */}
      <div onClick={() => setDrawerOpen(false)} style={{
        position: "fixed", inset: 0, zIndex: 1800,
        background: "rgba(17, 17, 17, 0.45)",
        animation: "tb-scrim-in 160ms var(--ease-out)",
      }}/>
      {/* panel */}
      <div style={{
        position: "fixed", top: 0, right: 0, bottom: 0,
        width: "min(86vw, 340px)",
        background: "#fff", zIndex: 1900,
        display: "flex", flexDirection: "column",
        boxShadow: "-12px 0 32px rgba(0,0,0,0.18)",
        animation: "tb-drawer-in 200ms var(--ease-out)",
        overflowY: "auto",
      }}>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "14px 16px", borderBottom: "1px solid var(--border-1)",
          position: "sticky", top: 0, background: "#fff",
        }}>
          <span style={{ font: "600 15px var(--font-jp)", color: "var(--fg-1)" }}>選單</span>
          <button onClick={() => setDrawerOpen(false)}
            aria-label="關閉選單"
            style={{
              width: 44, height: 44, borderRadius: 8, border: "none",
              background: "transparent", cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
            <Icon name="x" size={20} color="var(--fg-1)" />
          </button>
        </div>
        <nav style={{ padding: "8px 8px 16px", display: "flex", flexDirection: "column" }}>
          {nav.map(n => {
            const isSubmenu = n.hasSubmenu;
            // 商品: two-tap pattern — first tap expands sub-list; second tap navigates.
            if (isSubmenu) {
              return (
                <React.Fragment key={n.key}>
                  <a href={n.href}
                    onClick={e => {
                      if (!productsExpanded) { e.preventDefault(); setProductsExpanded(true); }
                    }}
                    style={{
                      display: "flex", alignItems: "center", gap: 8,
                      padding: "12px 12px", minHeight: 44,
                      borderRadius: 8, textDecoration: "none",
                      color: route === n.key ? "var(--fg-1)" : "var(--fg-2)",
                      font: "500 15px var(--font-body)",
                      background: route === n.key ? "var(--ink-50)" : "transparent",
                    }}>
                    <span>{n.zh}</span>
                    <span className="jp-sub" style={{ fontSize: 11 }}>{n.jp}</span>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round"
                      style={{ marginLeft: "auto", opacity: 0.6, transform: productsExpanded ? "rotate(180deg)" : "none", transition: "transform 160ms" }}>
                      <path d="m6 9 6 6 6-6"/>
                    </svg>
                  </a>
                  {productsExpanded && (
                    <div style={{
                      margin: "2px 0 6px",
                      paddingLeft: 4, borderLeft: "2px solid var(--border-1)",
                      animation: "tb-accordion-in 180ms var(--ease-out)",
                    }}>
                      {productGroups.map((g, gi) => (
                        <div key={gi} style={{ marginBottom: gi === 0 ? 6 : 0 }}>
                          <div style={{
                            padding: "6px 12px 4px",
                            fontSize: 10.5, color: "var(--fg-3)",
                            fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase",
                          }}>{g.label_zh} · <span className="jp-sub" style={{ fontSize: 10 }}>{g.label_jp}</span></div>
                          {g.items.map(it => (
                            <a key={it.slug} href={`/product/?slug=${it.slug}`} style={{
                              display: "flex", alignItems: "center", gap: 10,
                              padding: "10px 12px", minHeight: 44,
                              borderRadius: 8, textDecoration: "none",
                              color: "var(--fg-1)",
                            }}>
                              <div style={{ flex: 1, minWidth: 0 }}>
                                <div style={{ font: "500 14px var(--font-body)" }}>{it.zh}</div>
                                <div className="jp-sub" style={{ fontSize: 11, marginTop: 2 }}>
                                  {it.jp} · <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" }}>{it.release}</span>
                                </div>
                              </div>
                              {it.badge && (
                                <span style={{
                                  fontSize: 10, fontWeight: 600, padding: "3px 7px",
                                  background: "var(--red-50)", color: "var(--red-700)",
                                  borderRadius: 4, whiteSpace: "nowrap",
                                }}>{it.badge}</span>
                              )}
                            </a>
                          ))}
                        </div>
                      ))}
                    </div>
                  )}
                </React.Fragment>
              );
            }
            // Plain nav link
            return (
              <a key={n.key} href={n.href} style={{
                display: "flex", alignItems: "baseline", gap: 8,
                padding: "12px 12px", minHeight: 44,
                borderRadius: 8, textDecoration: "none",
                color: route === n.key ? "var(--fg-1)" : "var(--fg-2)",
                font: "500 15px var(--font-body)",
                background: route === n.key ? "var(--ink-50)" : "transparent",
              }}>
                {n.zh}
                <span className="jp-sub" style={{ fontSize: 11 }}>{n.jp}</span>
              </a>
            );
          })}
          {/* Last-scraped + refresh inside drawer */}
          <div style={{
            marginTop: "auto", paddingTop: 16,
            borderTop: "1px solid var(--border-1)",
            display: "flex", flexDirection: "column", gap: 10,
          }}>
            <div style={{ display: "flex", flexDirection: "column", padding: "0 12px" }}>
              <span style={{ fontSize: 11, color: "var(--fg-3)" }}>最後更新 · Last scraped</span>
              <span style={{ font: "500 13px var(--font-mono)", color: "var(--fg-1)" }}>
                {fmtJST(lastScraped)} JST
              </span>
            </div>
            <button onClick={handleRefresh} disabled={refreshing}
              style={{
                display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                margin: "0 12px", minHeight: 44, borderRadius: 8,
                border: "1px solid var(--border-2)", background: "#fff",
                color: refreshing ? "var(--fg-3)" : "var(--fg-1)",
                font: "500 14px var(--font-body)", cursor: refreshing ? "wait" : "pointer",
              }}>
              <span className={refreshing ? "tb-spin" : ""} style={{ display: "inline-flex" }}>
                <Icon name="refresh" size={16} />
              </span>
              {refreshing ? "同步中…" : "重新整理"}
            </button>
          </div>
        </nav>
      </div>
    </>
  );

  return (
    <>
      <header style={{
        height: 64, flexShrink: 0,
        background: "#fff", borderBottom: "1px solid var(--border-1)",
        display: "flex", alignItems: "center",
        padding: isMobile ? "0 12px" : "0 20px",
        gap: isMobile ? 8 : 24,
        whiteSpace: "nowrap",
      }}>
        {/* Logo — compact on mobile */}
        <a href="/home.html" style={{ display: "flex", alignItems: "center", gap: 9, textDecoration: "none" }}>
          <div style={{ width: 18, height: 18, borderRadius: 999, background: "var(--red-500)", position: "relative" }}>
            <div style={{ position: "absolute", inset: 5, background: "#fff", borderRadius: 999 }} />
          </div>
          <span style={{ font: "700 17px/1 var(--font-jp)", color: "var(--fg-1)", letterSpacing: "-0.005em" }}>ポケカ情報</span>
          {!isMobile && (
            <span style={{ fontSize: 12, color: "var(--fg-3)", marginLeft: 6, paddingLeft: 12, borderLeft: "1px solid var(--border-1)" }}>
              PTCG Dashboard
            </span>
          )}
        </a>

        {!isMobile && (
          <nav style={{ display: "flex", gap: 4 }}>
            {nav.map(n => {
              const active = route === n.key;
              const isProductsMenu = n.hasSubmenu;
              if (isProductsMenu) {
                return (
                  <div key={n.key}
                    onMouseEnter={() => setSubmenuOpen(true)}
                    onMouseLeave={() => setSubmenuOpen(false)}
                    style={{ position: "relative" }}>
                    <a href={n.href}
                      onClick={e => {
                        // Two-tap pattern: first click when submenu is closed just opens it.
                        // Only when submenu is already open does clicking navigate to /products/.
                        if (!submenuOpen) { e.preventDefault(); setSubmenuOpen(true); }
                      }}
                      style={navBtnStyle(active)}>
                      {n.zh}
                      <span className="jp-sub" style={{ fontSize: 10.5, opacity: active ? 0.7 : 0.55 }}>{n.jp}</span>
                      <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 2, opacity: 0.6, transform: submenuOpen ? "rotate(180deg)" : "none", transition: "transform 120ms" }}>
                        <path d="m6 9 6 6 6-6"/>
                      </svg>
                    </a>
                    {submenuOpen && (
                      <div style={{
                        position: "absolute", top: "calc(100% + 4px)", left: 0,
                        background: "#fff", border: "1px solid var(--border-1)",
                        borderRadius: 10, boxShadow: "var(--shadow-3)",
                        minWidth: 280, padding: "8px 0",
                        zIndex: 2000,
                        animation: "tb-menu-in 140ms var(--ease-out)",
                      }}>
                        {productGroups.map((g, gi) => (
                          <div key={gi} style={{ padding: gi > 0 ? "4px 0" : 0 }}>
                            {gi > 0 && <div style={{ height: 1, background: "var(--border-1)", margin: "4px 12px" }}/>}
                            <div style={{
                              padding: "6px 16px 4px",
                              fontSize: 10.5, color: "var(--fg-3)",
                              fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase",
                              display: "flex", alignItems: "baseline", gap: 8,
                            }}>
                              <span>{g.label_zh}</span>
                              <span className="jp-sub" style={{ fontSize: 10 }}>{g.label_jp}</span>
                            </div>
                            {g.items.map(it => (
                              <a key={it.slug} href={`/product/?slug=${it.slug}`}
                                style={{
                                  display: "flex", alignItems: "center", gap: 10,
                                  padding: "7px 16px",
                                  textDecoration: "none", color: "var(--fg-1)",
                                  fontSize: 13, fontWeight: 500,
                                  transition: "background 100ms",
                                }}
                                onMouseEnter={e => e.currentTarget.style.background = "var(--ink-50)"}
                                onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                                <div style={{ flex: 1, minWidth: 0 }}>
                                  <div style={{ font: "500 13px var(--font-body)", color: "var(--fg-1)" }}>{it.zh}</div>
                                  <div className="jp-sub" style={{ fontSize: 10.5, marginTop: 1 }}>{it.jp} · <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" }}>{it.release}</span></div>
                                </div>
                                {it.badge && (
                                  <span style={{
                                    fontSize: 10, fontWeight: 600, padding: "2px 6px",
                                    background: "var(--red-50)", color: "var(--red-700)",
                                    borderRadius: 4, whiteSpace: "nowrap",
                                  }}>{it.badge}</span>
                                )}
                              </a>
                            ))}
                          </div>
                        ))}
                        <div style={{ height: 1, background: "var(--border-1)", margin: "4px 12px" }}/>
                        <a href="/products/" style={{
                          display: "block", padding: "8px 16px",
                          fontSize: 12, color: "var(--fg-3)",
                          textDecoration: "none", fontWeight: 500,
                        }}
                          onMouseEnter={e => { e.currentTarget.style.background = "var(--ink-50)"; e.currentTarget.style.color = "var(--fg-1)"; }}
                          onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--fg-3)"; }}>
                          看全部 ({productGroups.reduce((n, g) => n + g.items.length, 0)}) →
                        </a>
                      </div>
                    )}
                  </div>
                );
              }
              return (
                <a key={n.key} href={n.href} style={navBtnStyle(active)}>
                  {n.zh}
                  <span className="jp-sub" style={{ fontSize: 10.5, opacity: active ? 0.7 : 0.55 }}>{n.jp}</span>
                </a>
              );
            })}
          </nav>
        )}

        {/* Right cluster — desktop only */}
        {!isMobile && (
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end" }}>
              <span style={{ fontSize: 11, color: "var(--fg-3)", whiteSpace: "nowrap" }}>最後更新 · Last scraped</span>
              <span style={{ font: "500 12px var(--font-mono)", color: "var(--fg-1)", whiteSpace: "nowrap" }}>
                {fmtJST(lastScraped)} JST
              </span>
            </div>
            <button
              onClick={handleRefresh}
              disabled={refreshing}
              style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                font: "500 13px/1 var(--font-body)",
                border: "1px solid transparent", borderRadius: 8,
                padding: "6px 10px",
                background: "transparent",
                color: refreshing ? "var(--fg-3)" : "var(--fg-2)",
                cursor: refreshing ? "wait" : "pointer",
                transition: "all 120ms var(--ease-out)",
                whiteSpace: "nowrap",
              }}
              onMouseEnter={e => { if (!refreshing) { e.currentTarget.style.background = "var(--ink-50)"; e.currentTarget.style.color = "var(--fg-1)"; } }}
              onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = refreshing ? "var(--fg-3)" : "var(--fg-2)"; }}
            >
              <span className={refreshing ? "tb-spin" : ""} style={{ display: "inline-flex" }}>
                <Icon name="refresh" size={14} />
              </span>
              {refreshing ? "同步中…" : "重新整理"}
            </button>
            <div style={{ width: 1, height: 24, background: "var(--border-1)" }} />
            <button style={{
              width: 32, height: 32, borderRadius: 6, border: "1px solid var(--border-1)",
              background: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
            }}><Icon name="info" size={16} color="var(--fg-2)" /></button>
          </div>
        )}

        {/* Hamburger — mobile only */}
        {isMobile && (
          <button
            onClick={() => setDrawerOpen(true)}
            aria-label="開啟選單"
            style={{
              marginLeft: "auto",
              width: 44, height: 44, borderRadius: 8,
              border: "none", background: "transparent",
              display: "flex", alignItems: "center", justifyContent: "center",
              cursor: "pointer",
            }}>
            <Icon name="menu" size={22} color="var(--fg-1)" />
          </button>
        )}
      </header>

      {/* Mobile drawer */}
      {isMobile && drawerOpen && <MobileDrawer/>}

      {/* Toast — anchored under topbar, auto-fades */}
      {toast && (
        <div style={{
          position: "fixed", top: 76, right: 20, zIndex: 1000,
          background: "#1C1917", color: "#fff",
          padding: "8px 14px", borderRadius: 8,
          font: "500 13px/1.2 var(--font-body)",
          boxShadow: "0 10px 24px rgba(0,0,0,0.18), 0 2px 6px rgba(0,0,0,0.08)",
          animation: "tb-toast-in 180ms var(--ease-out)",
          display: "flex", alignItems: "center", gap: 8,
        }}>
          <span style={{ color: "#10B981" }}>●</span>
          {toast}
        </div>
      )}

      <style>{`
        @keyframes tb-spin-kf { to { transform: rotate(360deg); } }
        .tb-spin { animation: tb-spin-kf 900ms linear infinite; }
        @keyframes tb-toast-in {
          from { opacity: 0; transform: translateY(-4px); }
          to { opacity: 1; transform: none; }
        }
        @keyframes tb-menu-in {
          from { opacity: 0; transform: translateY(-4px); }
          to { opacity: 1; transform: none; }
        }
        @keyframes tb-drawer-in {
          from { transform: translateX(100%); }
          to { transform: none; }
        }
        @keyframes tb-scrim-in {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes tb-accordion-in {
          from { opacity: 0; transform: translateY(-4px); }
          to { opacity: 1; transform: none; }
        }
      `}</style>
    </>
  );
};

window.TopBar = TopBar;
