/* global React, ReactDOM */
// ============================================================
// PandaKit · Main app shell
// ============================================================

const { useState: aUseState, useEffect: aUseEffect, useMemo: aUseMemo, useRef: aUseRef } = React;

function TopNav({ section, setSection, onOpenShowcase }) {
  const { t, lang, setLang } = useI18n();
  const items = [
    { value: "quick", label: t("nav.quick") },
    { value: "col",   label: t("nav.collection") },
    { value: "story", label: t("nav.story") },
  ];
  // 在 PandaKit 文字上 triple-click 进 showcase（之前在齿轮上，现在齿轮已删）
  const clickRef = aUseRef({ count: 0, timer: null });
  const onLogoClick = (e) => {
    e.preventDefault();
    setSection("quick");
    clickRef.current.count += 1;
    clearTimeout(clickRef.current.timer);
    clickRef.current.timer = setTimeout(() => {
      if (clickRef.current.count >= 3) onOpenShowcase();
      clickRef.current.count = 0;
    }, 600);
  };

  return (
    <header className="pk-glass" style={{
      position: "sticky", top: 0, zIndex: 100,
      borderBottom: "1px solid var(--border)",
      padding: "12px 28px",
      display: "flex", alignItems: "center", gap: 24,
    }}>
      <a href="#" onClick={onLogoClick}
         style={{
           display: "flex", alignItems: "center", gap: 10,
           textDecoration: "none", color: "var(--text)",
           minWidth: 200,  // 防中英切换时 tagline 长度变化导致 nav 抖动
         }}>
        <img src="assets/logo.png" alt="PandaHead" draggable={false}
          style={{ width: 36, height: 36, objectFit: "contain", display: "block" }} />
        <div className="pk-brand-text" style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
          <span style={{ fontWeight: 700, fontSize: 16, letterSpacing: "-0.01em" }}>PandaHead</span>
          <span style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>{t("app.tagline")}</span>
        </div>
      </a>

      <div style={{ flex: 1, display: "flex", justifyContent: "center" }}>
        <Tabs value={section} onChange={setSection} items={items} />
      </div>

      {/* lang 切换：单 button "中/EN"，desktop / mobile 都用同一个，CSS 缩 mobile 尺寸 */}
      <div style={{ display: "flex", alignItems: "center", gap: 4, minWidth: 200, justifyContent: "flex-end" }}>
        <button
          onClick={() => setLang(lang === "zh" ? "en" : "zh")}
          className="pk-focus-ring pk-lang-toggle"
          aria-label={t("lang.toggle")}
          style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            height: 32, padding: "0 14px",
            background: "transparent", border: "1px solid var(--border-strong)",
            borderRadius: 999, fontSize: 13,
            cursor: "pointer", color: "var(--text)",
          }}
        >
          <span style={{
            fontWeight: lang === "zh" ? 700 : 400,
            opacity: lang === "zh" ? 1 : 0.45,
            transition: "all 160ms var(--ease)",
          }}>中</span>
          <span style={{ opacity: 0.35, fontWeight: 300 }}>/</span>
          <span style={{
            fontWeight: lang === "en" ? 700 : 400,
            opacity: lang === "en" ? 1 : 0.45,
            transition: "all 160ms var(--ease)",
          }}>EN</span>
        </button>
      </div>
    </header>
  );
}

function Footer() {
  const { lang } = useI18n();
  return (
    <footer style={{
      borderTop: "1px solid var(--border)",
      padding: "20px 28px",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      fontSize: 12, color: "var(--text-faint)",
      flexWrap: "wrap", gap: 8,
    }}>
      <div>© 2026 PandaHead · {lang === "zh" ? "仅供学习与个人使用" : "For research & personal use"} · pandahead.fun</div>
    </footer>
  );
}

// URL ↔ section 映射（支持 /collection /story 路径）
const PATH_TO_SECTION = { '/': 'quick', '/quick': 'quick', '/collection': 'col', '/story': 'story' };
const SECTION_TO_PATH = { quick: '/', col: '/collection', story: '/story' };

function readSectionFromURL() {
  if (typeof window === 'undefined') return 'quick';
  // normalize trailing slash（CF Pages 偶尔 add 或 remove trailing /）
  let path = window.location.pathname || '/';
  if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1);
  // 兼容 hash routing：#/collection
  let hash = (window.location.hash || '').replace(/^#/, '');
  if (hash.length > 1 && hash.endsWith('/')) hash = hash.slice(0, -1);
  return PATH_TO_SECTION[hash] || PATH_TO_SECTION[path] || 'quick';
}

function App() {
  const [section, setSectionInternal] = aUseState(() => readSectionFromURL());
  const [prevSection, setPrev] = aUseState(() => readSectionFromURL());
  const [showcase, setShowcase] = aUseState(false);

  // popstate 同步（浏览器前进后退按钮）
  aUseEffect(() => {
    const onPop = () => setSectionInternal(readSectionFromURL());
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // Persisted favorites — keyed by trait JSON
  // Schema check：旧 fav key 是 trait JSON（含 face/pose），新 key 是 shellId|faceId|... 形式
  const [favs, setFavs] = aUseState(() => {
    try {
      const m = JSON.parse(localStorage.getItem("pk-favs") || "{}");
      // 旧 schema 检测：value.traits 不含 shellId → 整体清掉
      const hasOldSchema = Object.values(m).some((v) => v?.traits && !v.traits.shellId);
      if (hasOldSchema) { localStorage.removeItem("pk-favs"); return {}; }
      return m;
    } catch { return {}; }
  });
  aUseEffect(() => {
    try { localStorage.setItem("pk-favs", JSON.stringify(favs)); } catch {}
  }, [favs]);

  // Collection — 默认空（用户：合集应该让用户自己加载，不预填模板）
  const [collection, setCollection] = aUseState(() => {
    try {
      const stored = localStorage.getItem("pk-collection");
      if (stored) {
        const parsed = JSON.parse(stored);
        if (Array.isArray(parsed) && parsed.every((it) => it?.traits?.shellId)) {
          return parsed;
        }
        localStorage.removeItem("pk-collection");
      }
    } catch {}
    return [];
  });
  aUseEffect(() => {
    try { localStorage.setItem("pk-collection", JSON.stringify(collection)); } catch {}
  }, [collection]);

  const order = ["quick", "col", "story"];
  const setSection = (next) => {
    setPrev(section);
    setSectionInternal(next);
    // 同步 URL（pushState 不重载）
    const path = SECTION_TO_PATH[next] || '/';
    if (typeof window !== 'undefined' && window.location.pathname !== path) {
      try { window.history.pushState({}, '', path); } catch {}
    }
  };
  const direction = order.indexOf(section) >= order.indexOf(prevSection) ? "right" : "left";

  const pushToCollection = (item) => {
    setCollection((c) => {
      if (c.some((x) => x.id === item.id)) return c;
      const next = [
        {
          id: item.id,
          traits: item.traits,
          caption: item.traits?.text || (new Date()).toLocaleDateString("zh-CN"),
          tilt: ((Math.random() * 8) - 4),
        },
        ...c,
      ];
      return next;
    });
  };

  const sectionEl = aUseMemo(() => {
    if (section === "quick") return <QuickSection favs={favs} setFavs={setFavs} pushToCollection={pushToCollection} />;
    if (section === "col")   return <CollectionSection collection={collection} setCollection={setCollection} />;
    if (section === "story") return <StorySection />;
    return null;
  }, [section, favs, collection]);

  return (
    <I18nProvider>
      <ToastProvider>
        <Inner
          section={section} setSection={setSection}
          showcase={showcase} setShowcase={setShowcase}
          direction={direction} sectionEl={sectionEl}
        />
      </ToastProvider>
    </I18nProvider>
  );
}

// Inner — needs to live inside providers to use hooks
function Inner({ section, setSection, showcase, setShowcase, direction, sectionEl }) {
  const { t } = useI18n();
  const kbd = section === "quick"
    ? [
        { k: "R", label: t("kbd.r") },
        { k: "C", label: t("kbd.c") },
        { k: "D", label: t("kbd.d") },
        // F 收藏已删（用户要求）
      ]
    : [];

  return (
    <div style={{ minHeight: "100%", display: "flex", flexDirection: "column" }}>
      <TopNav section={section} setSection={setSection} onOpenShowcase={() => setShowcase(true)} />

      <main style={{
        flex: 1, padding: "32px 28px 24px",
        maxWidth: 1180, margin: "0 auto", width: "100%",
        overflowX: "hidden",
      }}>
        <SectionSwap k={section} direction={direction}>{sectionEl}</SectionSwap>
        <SectionFooterNav current={section} setSection={setSection} />
      </main>

      <Footer />

      {kbd.length > 0 && <KbdTip items={kbd} />}

      {showcase && (
        <div
          onClick={() => setShowcase(false)}
          style={{
            position: "fixed", inset: 0, zIndex: 300,
            background: "rgba(40,34,28,0.36)", animation: "pk-fade-in 180ms var(--ease)",
            display: "flex", alignItems: "stretch", justifyContent: "flex-end",
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              width: "min(960px, 96vw)", height: "100%",
              background: "var(--bg)",
              animation: "pk-slide-in-right 240ms var(--ease)",
              overflowY: "auto", padding: "28px 32px",
              borderLeft: "1px solid var(--border)",
              boxShadow: "var(--shadow-lg)",
            }}
          >
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--text-soft)" }}>
                /showcase · 隐藏路由
              </div>
              <IconButton label="close" onClick={() => setShowcase(false)}><Icon name="x" /></IconButton>
            </div>
            <ShowcaseSection />
          </div>
        </div>
      )}
    </div>
  );
}

// 板块底部跳转：上一节 / 下一节，方便顺序浏览
function SectionFooterNav({ current, setSection }) {
  const { lang } = useI18n();
  const order = ["quick", "col", "story"];
  const labels = {
    quick: lang === "zh" ? "快速生图" : "Quick",
    col:   lang === "zh" ? "我的合集" : "Collection",
    story: lang === "zh" ? "故事" : "Story",
  };
  const idx = order.indexOf(current);
  if (idx === -1) return null;
  const prev = idx > 0 ? order[idx - 1] : null;
  const next = idx < order.length - 1 ? order[idx + 1] : null;
  return (
    <div style={{
      marginTop: 40, padding: "20px 0 12px",
      borderTop: "1px solid var(--border)",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      gap: 12,
    }}>
      {prev ? (
        <button onClick={() => setSection(prev)}
          className="pk-focus-ring"
          style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "10px 16px", borderRadius: 999,
            background: "var(--card)", border: "1px solid var(--border)",
            color: "var(--text-soft)", fontSize: 13, fontWeight: 600,
            cursor: "pointer", transition: "all 160ms var(--ease)",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.color = "var(--text)"; e.currentTarget.style.borderColor = "var(--border-strong)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.color = "var(--text-soft)"; e.currentTarget.style.borderColor = "var(--border)"; }}
        >
          <Icon name="arrowLeft" size={14} />
          <span>{lang === "zh" ? "上一节 · " : "Prev · "}{labels[prev]}</span>
        </button>
      ) : <div />}
      {next ? (
        <button onClick={() => setSection(next)}
          className="pk-focus-ring"
          style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "10px 16px", borderRadius: 999,
            background: "var(--primary-soft)", border: "1px solid var(--primary-deep)",
            color: "var(--text)", fontSize: 13, fontWeight: 600,
            cursor: "pointer", transition: "all 160ms var(--ease)",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.transform = "translateX(2px)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.transform = "translateX(0)"; }}
        >
          <span>{lang === "zh" ? "下一节 · " : "Next · "}{labels[next]}</span>
          <Icon name="arrowRight" size={14} />
        </button>
      ) : <div />}
    </div>
  );
}

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