// 共享组件库
// 导航栏、印章、分隔符、卡片等通用组件

const { useState, useEffect } = React;

// ====== 主题管理（全局共享） ======
// 三态：light / dark / auto
const ThemeManager = {
  key: 'theme-mode',
  order: ['light', 'dark', 'auto'],
  getMode() {
    try { return localStorage.getItem(this.key) || 'auto'; } catch(e) { return 'auto'; }
  },
  setMode(mode) {
    const root = document.documentElement;
    root.classList.add('theme-transitioning');
    setTimeout(() => root.classList.remove('theme-transitioning'), 400);
    root.setAttribute('data-theme', mode);
    if (mode === 'auto') {
      try { localStorage.removeItem(this.key); } catch(e) {}
    } else {
      try { localStorage.setItem(this.key, mode); } catch(e) {}
    }
  },
  cycle() {
    const current = this.getMode();
    const idx = this.order.indexOf(current);
    const next = this.order[(idx + 1) % this.order.length];
    this.setMode(next);
    return next;
  },
  isDark() {
    const mode = this.getMode();
    if (mode === 'dark') return true;
    if (mode === 'light') return false;
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  }
};

// ====== 主题图标 ======
function ThemeIcon({ mode }) {
  if (mode === 'dark') {
    // 月（深色模式）
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>
      </svg>
    );
  }
  if (mode === 'light') {
    // 日（浅色模式）
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="4"/>
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
      </svg>
    );
  }
  // auto：半阴半阳（跟随系统）
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M12 3a9 9 0 1 0 0 18 4.5 4.5 0 0 1 0-9 4.5 4.5 0 0 0 0-9z"/>
    </svg>
  );
}

function themeLabel(mode) {
  if (mode === 'light') return '浅色';
  if (mode === 'dark') return '深色';
  return '自动';
}

function themeLabelFull(mode) {
  if (mode === 'light') return '浅色模式';
  if (mode === 'dark') return '深色模式';
  return '跟随系统';
}

// ====== 主题切换 hook ======
function useTheme() {
  const [mode, setModeState] = useState(ThemeManager.getMode());
  const [dark, setDark] = useState(ThemeManager.isDark());

  useEffect(() => {
    const syncFromDOM = () => {
      setModeState(ThemeManager.getMode());
      setDark(ThemeManager.isDark());
    };
    // 监听 localStorage 变化（多标签同步）
    const onStorage = (e) => {
      if (e.key === ThemeManager.key) syncFromDOM();
    };
    window.addEventListener('storage', onStorage);
    // 监听系统主题变化（auto 模式下）
    const mql = window.matchMedia('(prefers-color-scheme: dark)');
    const onMedia = () => {
      if (ThemeManager.getMode() === 'auto') setDark(mql.matches);
    };
    if (mql.addEventListener) mql.addEventListener('change', onMedia);
    else if (mql.addListener) mql.addListener(onMedia);

    // 轮询 data-theme 属性（兜底：当被外部脚本切换时也能同步）
    let lastTheme = document.documentElement.getAttribute('data-theme');
    const timer = setInterval(() => {
      const cur = document.documentElement.getAttribute('data-theme');
      if (cur !== lastTheme) {
        lastTheme = cur;
        syncFromDOM();
      }
    }, 500);

    return () => {
      window.removeEventListener('storage', onStorage);
      if (mql.removeEventListener) mql.removeEventListener('change', onMedia);
      else if (mql.removeListener) mql.removeListener(onMedia);
      clearInterval(timer);
    };
  }, []);

  const cycle = () => {
    ThemeManager.cycle();
    setModeState(ThemeManager.getMode());
    setDark(ThemeManager.isDark());
  };

  return { mode, dark, cycle, setMode: (m) => { ThemeManager.setMode(m); setModeState(m); setDark(ThemeManager.isDark()); } };
}

// ====== 主题切换按钮（桌面端：胶囊形图标+文字） ======
function ThemeToggle({ className = "" }) {
  const { mode, cycle } = useTheme();
  return (
    <button
      type="button"
      className={`theme-toggle ${className}`}
      onClick={cycle}
      title={`当前：${themeLabelFull(mode)}，点击切换`}
      aria-label="切换主题"
    >
      <ThemeIcon mode={mode} />
      <span>{themeLabel(mode)}</span>
    </button>
  );
}

// ====== 主题切换（移动端：横条按钮） ======
function MobileThemeToggle() {
  const { mode, cycle } = useTheme();
  return (
    <div className="nav-mobile-theme">
      <span>主题模式</span>
      <button
        type="button"
        className="nav-mobile-theme-btn"
        onClick={cycle}
      >
        <ThemeIcon mode={mode} />
        <span>{themeLabelFull(mode)}</span>
      </button>
    </div>
  );
}

// ====== 祥云 SVG 图标 ======
function CloudIcon({ className = "", size = 24 }) {
  return (
    <svg 
      className={className} 
      width={size} 
      height={size} 
      viewBox="0 0 24 24" 
      fill="currentColor"
      aria-hidden="true"
    >
      <path d="M12 4c-2.5 0-4.5 1.5-5.5 3.5C4 7.5 2 9.5 2 12c0 2.5 2 4.5 4.5 4.5h11c2.5 0 4.5-2 4.5-4.5 0-2.5-2-4.5-4.5-4.5-1-2-3-3.5-5.5-3.5zm0 2c1.5 0 2.8.8 3.5 2h-7c.7-1.2 2-2 3.5-2zm-6 4h12c1.4 0 2.5 1.1 2.5 2.5S19.4 15 18 15H6c-1.4 0-2.5-1.1-2.5-2.5S4.6 10 6 10z"/>
    </svg>
  );
}

// ====== 印章组件 ======
function SealStamp({ text, size = "md", className = "", animate = false }) {
  const sizeClass = size === "sm" ? "small" : size === "lg" ? "large" : "";
  return (
    <div className={`seal-stamp ${sizeClass} ${className} ${animate ? "seal-animate" : ""}`}>
      {text}
    </div>
  );
}

// ====== 祥云分隔符 ======
function CloudDivider() {
  return (
    <div className="cloud-divider">
      <CloudIcon className="cloud-icon" size={18} />
    </div>
  );
}

// ====== 导航栏 ======
function NavBar({ currentPage, onNavigate }) {
  const [toolsOpen, setToolsOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const toolsRef = React.useRef(null);

  const handleNav = (path) => {
    onNavigate(path);
    setToolsOpen(false);
    setMobileOpen(false);
  };

  // 点击下拉外部关闭
  useEffect(() => {
    function handleClickOutside(e) {
      if (toolsRef.current && !toolsRef.current.contains(e.target)) {
        setToolsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const navItems = teamData.nav.filter(item => item.label !== "交互工具");
  const toolItem = teamData.nav.find(item => item.label === "交互工具");

  return (
    <header className="nav-bar">
      <div className="nav-inner">
        <a className="nav-brand" onClick={() => handleNav("home")}>
          <div className="nav-seal">文</div>
          <div>
            <div className="nav-brand-text">{teamData.site.name}</div>
            <div className="nav-brand-sub">{teamData.site.englishName}</div>
          </div>
        </a>

        <nav className="nav-links">
          {navItems.map(item => (
            <a
              key={item.path}
              className={`nav-link ${currentPage === item.path ? "active" : ""}`}
              onClick={() => handleNav(item.path)}
            >
              {item.label}
            </a>
          ))}
          <div 
            ref={toolsRef}
            className="nav-link nav-tools"
            onMouseEnter={() => setToolsOpen(true)}
            onMouseLeave={() => setToolsOpen(false)}
          >
            <span
              onClick={(e) => {
                e.stopPropagation();
                setToolsOpen(v => !v);
              }}
              style={{ cursor: 'pointer' }}
            >交互工具 ▾</span>
            {toolsOpen && (
              <div className="nav-tools-menu">
                {toolItem.children.map(child => (
                  <div
                    key={child.path}
                    className="menu-item"
                    onClick={() => handleNav(child.path)}
                  >
                    {child.label}
                  </div>
                ))}
              </div>
            )}
          </div>
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
          <ThemeToggle />
          <div 
            className="nav-hamburger"
            onClick={() => setMobileOpen(!mobileOpen)}
          >
            <span className="hamburger-label">{mobileOpen ? "关闭" : "菜单"}</span>
            <div className="hamburger-icon">
              <span style={{ transform: mobileOpen ? "rotate(45deg) translate(5px, 5px)" : "" }}></span>
              <span style={{ opacity: mobileOpen ? 0 : 1 }}></span>
              <span style={{ transform: mobileOpen ? "rotate(-45deg) translate(5px, -5px)" : "" }}></span>
            </div>
          </div>
        </div>
      </div>

      {mobileOpen && (
        <div className="nav-mobile open">
          {navItems.map(item => (
            <a
              key={item.path}
              className={`nav-link ${currentPage === item.path ? "active" : ""}`}
              onClick={() => handleNav(item.path)}
            >
              {item.label}
            </a>
          ))}
          <div className="nav-section-title">交互工具</div>
          {toolItem.children.map(child => (
            <a
              key={child.path}
              className={`nav-link ${currentPage === child.path ? "active" : ""}`}
              onClick={() => handleNav(child.path)}
            >
              {child.label}
            </a>
          ))}
          <MobileThemeToggle />
        </div>
      )}
    </header>
  );
}

// ====== 章节标题 ======
function SectionHead({ eyebrow, title, subtitle, children }) {
  return (
    <div className="section-head fade-in-up">
      {eyebrow && <div className="section-eyebrow">{eyebrow}</div>}
      {title && <h2 className="section-title">{title}</h2>}
      <CloudDivider />
      {subtitle && <p className="section-subtitle">{subtitle}</p>}
      {children}
    </div>
  );
}

// ====== 古风卡片 ======
function GuCard({ kicker, title, desc, corner, onClick, children }) {
  return (
    <div className="gu-card" onClick={onClick}>
      {corner && <div className="card-corner">{corner}</div>}
      {kicker && <div className="card-kicker">{kicker}</div>}
      {title && <h3 className="card-title">{title}</h3>}
      {desc && <p className="card-desc">{desc}</p>}
      {children}
    </div>
  );
}

// ====== Hero 区 ======
function HeroSection({ title, sealText, subtitle, quote, leftVertical, rightVertical, children }) {
  return (
    <section className="hero">
      {leftVertical && (
        <div className="hero-vertical-text left">{leftVertical}</div>
      )}
      {rightVertical && (
        <div className="hero-vertical-text">{rightVertical}</div>
      )}
      <div className="fade-in-up">
        <h1 className="hero-title">
          {title}
          {sealText && <span className="seal-mark">{sealText}</span>}
        </h1>
        {subtitle && <div className="hero-subtitle">{subtitle}</div>}
        {quote && <p className="hero-quote">{quote}</p>}
        {children}
      </div>
    </section>
  );
}

// ====== 竹简时间线 ======
function BambooTimeline({ items }) {
  return (
    <div className="bamboo-timeline">
      {items.map((item, idx) => (
        <div key={idx} className="bamboo-item fade-in-up" style={{ animationDelay: `${idx * 0.1}s` }}>
          <div className="bamboo-year">
            <div>{item.year}</div>
            <div style={{ fontSize: "13px", color: "var(--ink-faint)", fontFamily: "var(--font-song)", letterSpacing: "0.1em" }}>
              {item.yearAD}
            </div>
          </div>
          <div className="bamboo-content">
            <h4>{item.title}</h4>
            {item.date && <div style={{ fontSize: "13px", color: "var(--ink-faint)", marginBottom: "8px", fontFamily: "var(--font-body)" }}>{item.date}</div>}
            <p>{item.desc}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

// ====== 卷轴容器 ======
function ScrollContainer({ children, className = "" }) {
  return (
    <div className={`scroll-container ${className}`}>
      {children}
    </div>
  );
}

// ====== 页脚 ======
function Footer() {
  return (
    <footer>
      <div className="main-wrap">
        <div className="footer-seal">
          <SealStamp text="新文明" size="sm" />
        </div>
        <div className="footer-brand">{teamData.site.name}</div>
        <div className="footer-meta">
          重铸文字之精魄 · 续写文明之薪火<br/>
          <span style={{ fontFamily: "var(--font-brush)", fontSize: "14px", color: "var(--seal)", letterSpacing: "0.2em" }}>
            {teamData.site.updated}
          </span>
        </div>
      </div>
    </footer>
  );
}

// ====== 工具页头部 ======
function ToolHeader({ title, subtitle, icon }) {
  return (
    <div style={{ textAlign: "center", padding: "48px 16px 32px" }}>
      <div style={{ 
        fontSize: "clamp(48px, 15vw, 64px)", 
        fontFamily: "var(--font-brush)", 
        color: "var(--seal)",
        marginBottom: "12px",
        lineHeight: "1"
      }}>
        {icon}
      </div>
      <h1 style={{ 
        fontFamily: "var(--font-brush)", 
        fontSize: "clamp(24px, 7vw, 38px)", 
        color: "var(--ink)",
        letterSpacing: "0.15em",
        marginBottom: "12px",
        padding: "0 8px",
        wordBreak: "keep-all"
      }}>
        {title}
      </h1>
      <CloudDivider />
      <p style={{ 
        fontFamily: "var(--font-body)", 
        fontSize: "clamp(13px, 3.5vw, 16px)", 
        color: "var(--ink-light)",
        maxWidth: "600px",
        margin: "0 auto",
        lineHeight: "1.8",
        padding: "0 8px"
      }}>
        {subtitle}
      </p>
    </div>
  );
}

// ====== 返回按钮 ======
function BackButton({ onNavigate }) {
  return (
    <div style={{ marginTop: "32px", textAlign: "center" }}>
      <button className="btn" onClick={() => onNavigate("home")}>
        ← 返回首页
      </button>
    </div>
  );
}

// 导出到全局
Object.assign(window, {
  CloudIcon,
  SealStamp,
  CloudDivider,
  NavBar,
  SectionHead,
  GuCard,
  HeroSection,
  BambooTimeline,
  ScrollContainer,
  Footer,
  ToolHeader,
  BackButton
});
