// ===== ui.jsx =====
// Shared UI primitives: Navbar, Footer, Button, Badge, AnimatedNumber, etc.

const { useEffect, useRef, useState, useMemo, useCallback } = React;

// ----- Animated number (rAF-based count up) -----
function AnimatedNumber({ value, duration = 1200, decimals = 0, className = '', prefix = '', suffix = '' }) {
  const [n, setN] = useState(0);
  const startRef = useRef(null);
  const fromRef = useRef(0);

  useEffect(() => {
    fromRef.current = n;
    startRef.current = null;
    let raf;
    const step = (ts) => {
      if (!startRef.current) startRef.current = ts;
      const t = Math.min(1, (ts - startRef.current) / duration);
      // easeOutCubic
      const e = 1 - Math.pow(1 - t, 3);
      setN(fromRef.current + (value - fromRef.current) * e);
      if (t < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line
  }, [value, duration]);

  const formatted = decimals > 0
    ? n.toFixed(decimals)
    : Math.round(n).toLocaleString('en-US');
  return <span className={`tnum ${className}`}>{prefix}{formatted}{suffix}</span>;
}

// ----- Button -----
function Button({ as: As = 'button', kind = 'primary', size = 'md', className = '', children, icon, iconRight, ...rest }) {
  const base = 'inline-flex items-center justify-center gap-2 font-medium rounded-lg transition-all duration-150 select-none';
  const sizes = { sm: 'h-8 px-3 text-sm', md: 'h-10 px-4 text-[14px]', lg: 'h-12 px-6 text-[15px]' };
  const kinds = {
    primary:   'bg-brand-600 text-white hover:bg-blue-700 active:bg-blue-800 shadow-sm',
    secondary: 'bg-white text-navy-900 ring-1 ring-ink-200 hover:bg-ink-50 hover:ring-ink-300',
    ghost:     'text-ink-700 hover:bg-ink-100',
    dark:      'bg-navy-900 text-white hover:bg-navy-800',
    danger:    'bg-bad-500 text-white hover:bg-bad-600',
  };
  return (
    <As className={`${base} ${sizes[size]} ${kinds[kind]} ${className}`} {...rest}>
      {icon ? <span className="-ml-0.5">{icon}</span> : null}
      {children}
      {iconRight ? <span className="-mr-0.5">{iconRight}</span> : null}
    </As>
  );
}

// ----- Badge -----
function Badge({ children, tone = 'ink', className = '' }) {
  const tones = {
    ink:   'bg-ink-100 text-ink-700',
    brand: 'bg-brand-50 text-brand-600 ring-1 ring-brand-100',
    ok:    'bg-ok-50 text-ok-600 ring-1 ring-ok-100',
    warn:  'bg-warn-50 text-warn-600 ring-1 ring-warn-100',
    bad:   'bg-bad-50 text-bad-600 ring-1 ring-bad-100',
    navy:  'bg-navy-900 text-white',
  };
  return <span className={`inline-flex items-center gap-1.5 h-6 px-2.5 rounded-full text-[12px] font-medium ${tones[tone]} ${className}`}>{children}</span>;
}

// ----- Card -----
function Card({ className = '', children, ...rest }) {
  return <div className={`bg-white rounded-2xl ring-1 ring-ink-200 shadow-card ${className}`} {...rest}>{children}</div>;
}

// ----- Status pill (also for Order) -----
function StatusPill({ status }) {
  const s = MOCK.ORDER_STATUSES[status];
  if (!s) return null;
  return (
    <span className={`inline-flex items-center gap-2 h-7 px-2.5 rounded-full text-[12.5px] font-medium ${s.badgeClass}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${s.dotClass} ${status === 'processing' ? 'pulse-dot' : ''}`} />
      {s.label}
    </span>
  );
}

// ----- Navbar -----
function Navbar({ route, navigate }) {
  const items = [
    { key: 'home',   label: '产品' },
    { key: 'home#pricing', label: '定价' },
    { key: 'home#faq',     label: '帮助' },
  ];
  return (
    <header className="sticky top-0 z-40 backdrop-blur bg-white/85 border-b border-ink-200">
      <div className="max-w-[1200px] mx-auto h-16 px-6 lg:px-8 flex items-center justify-between">
        <button onClick={() => navigate('home')} className="flex items-center gap-2.5 group">
          <I.Logo size={30} />
          <div className="leading-tight">
            <div className="font-semibold text-navy-900 text-[15px] tracking-tight">墨鉴 · Mojian</div>
            <div className="text-[10.5px] text-ink-500 -mt-0.5 tracking-wide">ACADEMIC AI DETECTOR</div>
          </div>
        </button>
        <nav className="hidden md:flex items-center gap-1">
          {items.map(it => (
            <a key={it.key} href={`#${it.key.split('#')[1] || ''}`} onClick={(e) => { e.preventDefault(); navigate('home', { hash: it.key.includes('#') ? it.key.split('#')[1] : null }); }}
               className="h-9 px-3 inline-flex items-center text-[14px] text-ink-700 hover:text-navy-900 rounded-md hover:bg-ink-100">
              {it.label}
            </a>
          ))}
        </nav>
        <div className="flex items-center gap-2">
          <Button kind="ghost" size="sm" onClick={() => navigate('trial')} className="hidden md:inline-flex">免费试用</Button>
          <Button kind="ghost" size="sm" onClick={() => navigate('report', { id: 'r-1085' })} className="hidden sm:inline-flex">查看示例</Button>
          <Button
            kind="dark" size="sm"
            onClick={() => navigate('upload')}
            iconRight={<I.ArrowRight size={14} />}
            className="!h-9 !px-4 shadow-soft">
            立即检测
          </Button>
        </div>
      </div>
    </header>
  );
}

// ----- Footer -----
function Footer({ navigate }) {
  return (
    <footer className="border-t border-ink-200 mt-24 bg-white">
      <div className="max-w-[1200px] mx-auto px-6 lg:px-8 py-12 grid md:grid-cols-12 gap-10">
        <div className="md:col-span-5">
          <div className="flex items-center gap-2.5">
            <I.Logo size={32} />
            <div className="leading-tight">
              <div className="font-semibold text-navy-900 text-[15px]">墨鉴 · Mojian</div>
              <div className="text-[11px] text-ink-500 tracking-wide">ACADEMIC AI DETECTOR</div>
            </div>
          </div>
          <p className="mt-4 text-[13.5px] text-ink-500 max-w-sm leading-relaxed">学术写作 · AI 智能鉴定。基于困惑度与突发性多维度统计分析，覆盖主流大模型生成特征。</p>
          <div className="mt-6 flex items-center gap-3 text-[12.5px] text-ink-500">
            <I.Mail size={14} />
            <a href="mailto:support@mojian.ai" className="hover:text-navy-900">support@mojian.ai</a>
            <span className="text-ink-300">·</span>
            <I.Globe size={14} />
            <span>ruyijingu.top</span>
          </div>
          <div className="mt-3 text-[12px] text-ink-400">ICP 备案中 · 服务于学术自查场景</div>
        </div>

        <div className="md:col-span-3">
          <div className="text-[12.5px] font-semibold text-navy-900 uppercase tracking-wide">产品</div>
          <ul className="mt-3 space-y-2 text-[13.5px] text-ink-500">
            <li><a onClick={() => navigate('upload')}      className="hover:text-navy-900 cursor-pointer">立即检测</a></li>
            <li><a onClick={() => navigate('report', { id: 'r-1085' })} className="hover:text-navy-900 cursor-pointer">示例报告</a></li>
            <li><a onClick={() => navigate('home', { hash: 'pricing' })} className="hover:text-navy-900 cursor-pointer">定价方案</a></li>
            <li><a onClick={() => navigate('home', { hash: 'faq' })}     className="hover:text-navy-900 cursor-pointer">常见问题</a></li>
          </ul>
        </div>

        <div className="md:col-span-4">
          <div className="text-[12.5px] font-semibold text-navy-900 uppercase tracking-wide">重要声明</div>
          <p className="mt-3 text-[12.5px] text-ink-500 leading-relaxed">
            本平台提供学术写作辅助参考，检测结果仅供作者自查改进使用，<span className="text-ink-700 font-medium">不构成最终学术鉴定</span>。请以所在机构官方查重系统结果为准。本平台不保留用户论文原文，所有上传文件在检测完成 24 小时内自动删除。
          </p>
        </div>
      </div>
      <div className="border-t border-ink-200">
        <div className="max-w-[1200px] mx-auto px-6 lg:px-8 h-12 flex items-center justify-between text-[12px] text-ink-400">
          <div>© 2026 Mojian Academic AI Detector. All rights reserved.</div>
          <div className="hidden md:flex items-center gap-4">
            <span>服务协议</span>
            <span>隐私政策</span>
            <span>数据安全</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ----- Section helper -----
function Section({ id, eyebrow, title, subtitle, children, className = '', dark = false }) {
  return (
    <section id={id} className={`${dark ? 'bg-navy-950 text-white' : ''} ${className}`}>
      <div className="max-w-[1200px] mx-auto px-6 lg:px-8 py-20">
        {(eyebrow || title) && (
          <div className="max-w-3xl mb-12">
            {eyebrow && <div className={`text-[12px] font-semibold tracking-[0.18em] uppercase ${dark ? 'text-brand-500' : 'text-brand-600'} mb-3`}>{eyebrow}</div>}
            {title && <h2 className={`text-[34px] sm:text-[40px] leading-[1.1] font-bold ${dark ? 'text-white' : 'text-navy-900'} tracking-tight`}>{title}</h2>}
            {subtitle && <p className={`mt-4 text-[16px] leading-relaxed ${dark ? 'text-ink-300' : 'text-ink-500'} max-w-2xl`}>{subtitle}</p>}
          </div>
        )}
        {children}
      </div>
    </section>
  );
}

// Visibility-triggered fade-up
function Reveal({ children, delay = 0, as: As = 'div', className = '' }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setShown(true); io.disconnect(); } }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <As ref={ref} className={className} style={{ opacity: shown ? 1 : 0, transform: shown ? 'none' : 'translateY(10px)', transition: `opacity .6s ease ${delay}ms, transform .6s ease ${delay}ms` }}>
      {children}
    </As>
  );
}

Object.assign(window, { AnimatedNumber, Button, Badge, Card, StatusPill, Navbar, Footer, Section, Reveal });
