/* global React, Icon */
var FIQ_APP_LINKS = window.FIQ_APP_LINKS || (window.FIQ_APP_LINKS = (() => {
  const hostname = window.location.hostname;
  const base = (hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1')
    ? 'http://127.0.0.1:3000'
    : (hostname === 'test.tradedata-ai.com' || hostname.indexOf('test.') === 0)
      ? 'https://test.app.tradedata-ai.com'
      : 'https://app.tradedata-ai.com';
  return {
    home: base,
    leads: `${base}/leads/dashboard`,
    rates: `${base}/rates`,
    foresight: `${base}/foresight`,
    prospect: `${base}/leads/dashboard`,
    login: `${base}/login`,
    register: `${base}/register`
  };
})());

// ═══════════════════════════════════════════════════════════════
// Shared Nav + Footer for Rates 产品站 - 多页面结构
// 用法:<RatesNav current="home | quotes | booking | trends | integrations | pricing"/>
// ═══════════════════════════════════════════════════════════════

const NAV_ITEMS = [
  { k: 'quotes',       t: '实时运价', href: '/products/soptallkinds/quotes' },
  { k: 'booking',      t: '抢舱订舱', href: '/products/soptallkinds/booking' },
  { k: 'trends',       t: '趋势分析', href: '/products/soptallkinds/trends' },
  { k: 'integrations', t: '集成',     href: '/products/soptallkinds/integrations' },
  { k: 'pricing',      t: '定价',     href: '/products/soptallkinds/pricing' },
];

const SOPTALLKINDS_ROUTES = window.SOPTALLKINDS_ROUTES || (window.SOPTALLKINDS_ROUTES = {
  home: '/products/soptallkinds',
  quotes: '/products/soptallkinds/quotes',
  booking: '/products/soptallkinds/booking',
  bookingConsole: '/products/soptallkinds/booking/console',
  trends: '/products/soptallkinds/trends',
  trendsBi: '/products/soptallkinds/trends/bi',
  integrations: '/products/soptallkinds/integrations',
  pricing: '/products/soptallkinds/pricing',
  foresight: '/FreightIQ-Foresight',
});

const WEBSITE_LANGS = [
  { code: 'zh-CN', short: '中', label: '简体中文' },
  { code: 'en', short: 'EN', label: 'English' },
];
const DEFAULT_LANG = 'zh-CN';
const LANG_STORAGE_KEY = 'fiq-lang';
const normalizeLang = (code) => WEBSITE_LANGS.some((l) => l.code === code) ? code : DEFAULT_LANG;

const RatesNav = ({ current = 'home' }) => {
  const [lang, setLang] = React.useState(() => normalizeLang(localStorage.getItem(LANG_STORAGE_KEY)));
  const [langOpen, setLangOpen] = React.useState(false);
  const currentLang = WEBSITE_LANGS.find((item) => item.code === lang) || WEBSITE_LANGS[0];
  const pickLang = (code) => {
    const next = normalizeLang(code);
    setLang(next);
    setLangOpen(false);
    localStorage.setItem(LANG_STORAGE_KEY, next);
    document.documentElement.setAttribute('lang', next);
  };
  React.useEffect(() => {
    document.documentElement.setAttribute('lang', lang);
  }, [lang]);
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href={SOPTALLKINDS_ROUTES.home} className="logo" style={{ cursor: 'pointer' }}>
          <span className="logo-mark"/>
          <span style={{ color: 'var(--brand)' }}>Soptallkinds</span>
        </a>
        <div className="nav-links">
          {NAV_ITEMS.map(n => (
            <a key={n.k} className={`nav-link ${current === n.k ? 'active' : ''}`} href={n.href}>
              {n.t}
            </a>
          ))}
          <a className="nav-link" href="/" style={{ color: 'var(--ink-4)' }}>
            <Icon name="arrow" size={12} stroke={2}/> 返回官网
          </a>
        </div>
        <div className="nav-cta">
          <div style={{ position: 'relative' }}>
            <button className="btn btn-ghost btn-sm" onClick={() => setLangOpen(o => !o)} style={{ padding: '6px 10px', gap: 6 }}>
              <Icon name="globe" size={14}/>
              <span style={{ fontSize: 12, fontWeight: 600 }}>{currentLang.short}</span>
            </button>
            {langOpen && (
              <div style={{
                position: 'absolute', top: 'calc(100% + 8px)', right: 0,
                minWidth: 160, padding: 6,
                background: 'var(--surface)', border: '1px solid var(--line)',
                borderRadius: 10, boxShadow: 'var(--shadow-lg)', zIndex: 120,
              }} onMouseLeave={() => setLangOpen(false)}>
                {WEBSITE_LANGS.map(l => (
                  <button key={l.code} onClick={() => pickLang(l.code)}
                    style={{ width: '100%', padding: '8px 10px', border: 'none', background: 'transparent',
                             textAlign: 'left', fontSize: 13, borderRadius: 6, cursor: 'pointer',
                             color: lang === l.code ? 'var(--brand)' : 'var(--ink-2)',
                             fontWeight: lang === l.code ? 600 : 500 }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-3)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    {l.label}
                  </button>
                ))}
              </div>
            )}
          </div>
          <span style={{ width: 1, height: 20, background: 'var(--line)' }}/>
          <a className="btn btn-ghost btn-sm" href={FIQ_APP_LINKS.login}>登录</a>
          <a className="btn btn-brand btn-sm" href={FIQ_APP_LINKS.register}>免费试用 <Icon name="arrow" size={12}/></a>
        </div>
      </div>
    </nav>
  );
};

// ─────────────────────────────────────────────────
// Page sub-header — 二级导航条,用于非首页的页面
// ─────────────────────────────────────────────────
const RatesPageHeader = ({ eyebrow, title, subtitle, current }) => (
  <section style={{
    padding: '72px 0 40px',
    background: 'linear-gradient(180deg, var(--surface) 0%, var(--bg) 100%)',
    borderBottom: '1px solid var(--line)',
    position: 'relative', overflow: 'hidden',
  }}>
    {/* subtle grid */}
    <div style={{
      position: 'absolute', inset: 0, opacity: 0.3, pointerEvents: 'none',
      backgroundImage: 'linear-gradient(rgba(22,119,255,0.08) 1px, transparent 1px), linear-gradient(90deg, rgba(22,119,255,0.08) 1px, transparent 1px)',
      backgroundSize: '48px 48px',
      maskImage: 'radial-gradient(ellipse at 30% 50%, #000 10%, transparent 70%)',
      WebkitMaskImage: 'radial-gradient(ellipse at 30% 50%, #000 10%, transparent 70%)',
    }}/>
    <div className="container" style={{ position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-4)', marginBottom: 14 }}>
        <a href={SOPTALLKINDS_ROUTES.home} style={{ color: 'inherit' }}>Soptallkinds</a>
        <span>›</span>
        <span style={{ color: 'var(--ink-2)', fontWeight: 500 }}>{eyebrow}</span>
      </div>
      <h1 className="display-2" style={{ maxWidth: 720, marginBottom: 12 }}>{title}</h1>
      <p className="lead" style={{ maxWidth: 640, fontSize: 17 }}>{subtitle}</p>
    </div>
  </section>
);

// ─────────────────────────────────────────────────
// Shared Footer
// ─────────────────────────────────────────────────
const RatesFooter = () => {
  const cols = [
    { t: '产品', l: [
      { t: '实时运价', h: SOPTALLKINDS_ROUTES.quotes },
      { t: '抢舱订舱', h: SOPTALLKINDS_ROUTES.booking },
      { t: '趋势分析', h: SOPTALLKINDS_ROUTES.trends },
      { t: '集成',     h: SOPTALLKINDS_ROUTES.integrations },
      { t: '定价',     h: SOPTALLKINDS_ROUTES.pricing },
    ]},
    { t: '其他产品线', l: [
      { t: 'FreightIQ 官网 ↗', h: '/' },
      { t: 'Foresight AI →',   h: '/FreightIQ-Foresight' },
      { t: 'Prospect 拓客 ↗',  h: FIQ_APP_LINKS.prospect,  ext: true },
      { t: 'AgenticX 平台 ↗',  h: '#' },
    ]},
    { t: '资源',  l: [
      { t: '文档',       h: SOPTALLKINDS_ROUTES.integrations },
      { t: 'API 参考',   h: SOPTALLKINDS_ROUTES.integrations },
      { t: '更新日志',   h: '#' }, { t: '状态页',    h: '#' },
      { t: '客户故事',   h: '/#cases' },
    ]},
    { t: '关于',  l: [
      { t: '公司介绍',   h: '#' }, { t: '招聘',      h: '#' },
      { t: '联系销售',   h: '#' }, { t: '合作伙伴',  h: '#' },
    ]},
  ];
  return (
    <footer className="footer">
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr repeat(4, 1fr)', gap: 32, marginBottom: 48 }}>
          <div>
            <div className="logo" style={{ marginBottom: 14 }}>
              <span className="logo-mark"/>
              <span style={{ color: 'var(--brand)' }}>Soptallkinds</span>
            </div>
            <p style={{ fontSize: 13, color: 'var(--ink-4)', maxWidth: 300 }}>
              全球运价聚合与抢舱订舱。FreightIQ 产品矩阵中的运价业务线。
            </p>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-5)', marginTop: 16 }}>
              rates.freightiq.ai
            </div>
          </div>
          {cols.map(c => (
            <div key={c.t}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 14, color: 'var(--ink-2)' }}>{c.t}</div>
              {c.l.map(x => (
                <a key={x.t} href={x.h} {...(x.ext ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>{x.t}</a>
              ))}
            </div>
          ))}
        </div>
        <div style={{ paddingTop: 28, borderTop: '1px solid var(--line)', display: 'flex', justifyContent:'space-between', fontSize: 12, color: 'var(--ink-4)', flexWrap:'wrap', gap: 12 }}>
          <span>© 2026 FreightIQ Technologies. 保留所有权利.</span>
          <a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer" style={{ color: 'inherit' }}>
            备案编号：津ICP备2023005990号-2
          </a>
          <span style={{ display:'flex', gap: 16 }}>
            <a href="#">隐私</a><a href="#">条款</a><a href="#">Cookie</a><a href="#">安全</a>
            <a href="/" style={{ color: 'var(--brand)', fontWeight: 500 }}>← 返回 FreightIQ 官网</a>
          </span>
        </div>
      </div>
    </footer>
  );
};

// ─────────────────────────────────────────────────
// CTA — 可复用,几乎每个页面底部都放
// ─────────────────────────────────────────────────
const RatesCTA = () => (
  <section style={{ padding: '96px 0' }}>
    <div className="container">
      <div style={{
        position: 'relative', overflow: 'hidden',
        padding: '64px 56px', borderRadius: 28,
        background: 'linear-gradient(135deg, #001E3C 0%, #0A2A5C 50%, #1677FF 130%)',
        color: '#fff',
      }}>
        <div style={{
          position:'absolute', inset: 0, opacity: 0.5, pointerEvents: 'none',
          backgroundImage: 'radial-gradient(circle at 80% 20%, rgba(0,212,170,0.3) 0%, transparent 40%), radial-gradient(circle at 20% 80%, rgba(79,163,255,0.35) 0%, transparent 40%)',
        }}/>
        <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 40, alignItems: 'center' }}>
          <div>
            <h2 className="display-2" style={{ color: '#fff', marginBottom: 12 }}>
              把一周的询价,<br/>压缩到一杯咖啡。
            </h2>
            <p style={{ fontSize: 17, color: 'rgba(255,255,255,0.75)', maxWidth: 560 }}>
              14 天免费试用 · 全功能解锁 · 无需信用卡。加入 1,200+ 货代团队,让数据替你工作。
            </p>
          </div>
          <div style={{ display:'flex', flexDirection: 'column', gap: 10, alignItems:'flex-start' }}>
            <a href={FIQ_APP_LINKS.register} className="btn btn-lg" style={{ background: '#fff', color: '#001E3C', width: '100%', justifyContent: 'center', fontWeight: 600 }}>
              免费开始 <Icon name="arrow" size={14}/>
            </a>
            <a href="/contact" className="btn btn-lg" style={{ width: '100%', justifyContent: 'center', background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.25)', color: '#fff' }}>
              预约专属演示
            </a>
          </div>
        </div>
      </div>
    </div>
  </section>
);

// ─────────────────────────────────────────────────
// 抢舱订舱 · 二级页签 (在 RatesNav 与具体子页面之间)
// 用法:<BookingSubtabs current="overview | console | strategy | history | accounts"/>
// ─────────────────────────────────────────────────
const BookingSubtabs = ({ current = 'overview' }) => {
  const tabs = [
    { k: 'overview', t: '产品概览', href: SOPTALLKINDS_ROUTES.booking, icon: 'doc' },
    { k: 'console',  t: '抢单工作台', href: SOPTALLKINDS_ROUTES.bookingConsole, icon: 'bolt', running: true },
    { k: 'strategy', t: '策略库',     href: `${SOPTALLKINDS_ROUTES.booking}#strategy`, icon: 'shield' },
    { k: 'history',  t: '历史订单',   href: '#', icon: 'clock' },
    { k: 'accounts', t: '账户中心',   href: '#', icon: 'users' },
  ];
  return (
    <div className="console-subtabs">
      <div className="console-subtabs-inner">
        <span className="console-subtab" style={{ color: 'var(--ink-2)', fontWeight: 600, padding: '6px 6px 6px 0', cursor: 'default' }}>
          抢舱订舱
        </span>
        <span className="console-subtab-divider"/>
        {tabs.map(t => (
          <a key={t.k} href={t.href} className={`console-subtab ${current === t.k ? 'active' : ''}`}>
            <Icon name={t.icon} size={13}/>
            {t.t}
            {t.running && current === t.k && (
              <span style={{
                width: 5, height: 5, borderRadius: '50%', background: '#00D4AA',
                boxShadow: '0 0 0 3px color-mix(in srgb, #00D4AA 30%, transparent)',
                marginLeft: 4,
              }}/>
            )}
          </a>
        ))}
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--ink-4)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%', background: '#00D4AA',
              boxShadow: '0 0 0 3px color-mix(in srgb, #00D4AA 30%, transparent)',
            }}/>
            5 个任务运行中
          </span>
          <span className="console-subtab-divider" style={{ margin: 0 }}/>
          <span className="mono">最近同步 2s 前</span>
        </div>
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────
// 趋势分析 / 运营 BI · 页内二级导航(锚点跳转)
// 用法:<TrendsSubtabs current="forecast | overview | margin | carriers | sales | customers | alerts"/>
// ─────────────────────────────────────────────────
const TrendsSubtabs = ({ current = 'forecast' }) => {
  const [active, setActive] = React.useState(current);
  const tabs = [
    { k: 'forecast',  t: '运价趋势', href: '#forecast',  icon: 'chart' },
    { k: 'overview',  t: '经营概览', href: '#overview',  icon: 'radar' },
    { k: 'margin',    t: '毛利分析', href: '#margin',    icon: 'flame' },
    { k: 'carriers',  t: '承运占比', href: '#carriers',  icon: 'ship' },
    { k: 'sales-kpi', t: '销售 KPI', href: '#sales-kpi', icon: 'target' },
    { k: 'customers', t: '客户洞察', href: '#customers', icon: 'users' },
    { k: 'alerts',    t: '智能预警', href: '#alerts',    icon: 'sparkAi' },
  ];

  React.useEffect(() => {
    const ids = tabs.map(t => t.k);
    const opts = { rootMargin: '-30% 0px -60% 0px', threshold: 0 };
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting && ids.includes(e.target.id)) setActive(e.target.id); });
    }, opts);
    ids.forEach(id => { const el = document.getElementById(id); if (el) obs.observe(el); });
    return () => obs.disconnect();
  }, []);

  return (
    <div className="console-subtabs">
      <div className="console-subtabs-inner">
        <span className="console-subtab" style={{ color: 'var(--ink-2)', fontWeight: 600, padding: '6px 6px 6px 0', cursor: 'default' }}>
          趋势 · 运营 BI
        </span>
        <span className="console-subtab-divider"/>
        {tabs.map(t => (
          <a key={t.k} href={t.href} className={`console-subtab ${active === t.k ? 'active' : ''}`}>
            <Icon name={t.icon} size={13}/>
            {t.t}
          </a>
        ))}
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--ink-4)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%', background: '#00D4AA',
              boxShadow: '0 0 0 3px color-mix(in srgb, #00D4AA 30%, transparent)',
            }}/>
            数据实时同步
          </span>
          <span className="console-subtab-divider" style={{ margin: 0 }}/>
          <span className="mono">最近刷新 12s 前</span>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { RatesNav, RatesPageHeader, RatesFooter, RatesCTA, BookingSubtabs, TrendsSubtabs });
