/* 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`
  };
})());

// =========================================================
// Shared: page-level hero band
// =========================================================
const PageHero = ({ eyebrow, title, sub, accent = 'var(--brand)' }) => (
  <section className="sp-hero">
    <div className="container sp-hero-inner">
      {eyebrow && <span className="eyebrow" style={{ color: accent }}><Icon name="bolt" size={12}/> {eyebrow}</span>}
      <h1 className="display-1 sp-hero-title">{title}</h1>
      {sub && <p className="sp-hero-sub">{sub}</p>}
    </div>
    <div className="sp-hero-grid"/>
  </section>
);

// =========================================================
// ABOUT — 关于我们 / 招聘 / 媒体 / 法律
// =========================================================
const AboutPage = () => {
  const pillars = [
    { i: 'target', c: '#1677FF', t: '使命', d: '让全球供应链的每一次决策,都基于实时、可信、可追溯的数据。' },
    { i: 'flame',  c: '#00D4AA', t: '相信',  d: '物流行业的下一个十年,属于把人工经验沉淀成可复制系统的人。' },
    { i: 'shield', c: '#7C5CFF', t: '原则',  d: '数据可解释,模型可追溯,价格可比对。我们不卖黑箱。' }
  ];
  const team = [
    { n: 'JD Liu',     r: 'Co-founder & CEO',  bio: '前 Maersk 数字化战略,15 年货代与船公司经历' },
    { n: 'Wang Lei',   r: 'Co-founder & CTO',  bio: '前 Cargowise 工程负责人,主导多区域 EDI 平台' },
    { n: 'Chen Hua',   r: 'Chief Data Officer', bio: '前 IHS Markit 海运分析,SCFI/CCFI 数据合作' },
    { n: 'Sara Park',  r: 'VP Product',         bio: '前 Flexport 产品总监,跨境 SaaS 设计 8 年' },
    { n: 'Mark Yu',    r: 'VP Engineering',     bio: '前阿里云 PaaS,擅长流式计算与可观测性' },
    { n: 'Helen Tan',  r: 'Head of Customer',   bio: '前 Kuehne+Nagel 中国区销售运营负责人' }
  ];
  const investors = ['Sequoia China', 'IDG Capital', 'ZhenFund', 'Lightspeed', 'GGV', 'GSR Ventures'];
  const milestones = [
    { y: '2022 Q3', t: '公司成立,A 轮 Seed' },
    { y: '2023 Q2', t: 'FreightIQ Rates 1.0 上线,首批 30 客户' },
    { y: '2024 Q1', t: 'A 轮 1,800 万美元,Sequoia 领投' },
    { y: '2024 Q4', t: 'Foresight 数据情报产品发布' },
    { y: '2025 Q3', t: 'B 轮 4,500 万美元,IDG 领投' },
    { y: '2026 Q1', t: '客户突破 1,200 家,覆盖 28 个市场' }
  ];
  const jobs = [
    { dept: '工程',   t: '高级前端工程师 (React / 数据可视化)', loc: '上海 / 远程', tag: 'Full-time' },
    { dept: '工程',   t: '数据平台工程师 (Flink / Kafka)',     loc: '深圳',         tag: 'Full-time' },
    { dept: '产品',   t: '产品经理 — 抢单与策略引擎',           loc: '上海',         tag: 'Full-time' },
    { dept: '商务',   t: '解决方案专家 — 大客户',                loc: '北京 / 上海',   tag: 'Full-time' },
    { dept: '客成',   t: '客户成功经理 (英语必备)',              loc: '新加坡',       tag: 'Full-time' },
    { dept: '设计',   t: '高级产品设计师',                       loc: '上海 / 远程',   tag: 'Full-time' }
  ];
  const press = [
    { src: '36Kr',          d: '2025-11-08', t: 'FreightIQ 完成 4,500 万美元 B 轮融资,IDG 领投' },
    { src: 'TechCrunch',    d: '2025-09-22', t: 'How FreightIQ is reshaping freight rate intelligence in Asia' },
    { src: 'Lloyd’s List', d: '2025-08-14', t: 'Chinese startup launches AI freight forecasting platform' },
    { src: '中国航务周刊',   d: '2025-06-30', t: 'FreightIQ 与中远海运签署数据合作协议' },
    { src: 'Splash247',     d: '2025-04-02', t: 'FreightIQ Foresight enters beta with 28 carriers onboarded' }
  ];

  return (
    <>
      <PageHero
        eyebrow="关于我们"
        title={<>把全球物流的决策,<br/>从经验交给数据。</>}
        sub="FreightIQ 成立于 2022 年,总部上海,在深圳、新加坡、鹿特丹设有团队。我们为全球 1,200+ 货代、船公司、跨境品牌提供运价、预测、抢舱、情报一体化的智能中枢。"
      />

      {/* Pillars */}
      <section className="section">
        <div className="container">
          <div className="grid grid-3">
            {pillars.map(p => (
              <div key={p.t} className="card" style={{ padding: 28 }}>
                <div style={{ width: 44, height: 44, borderRadius: 12, background: `linear-gradient(135deg, ${p.c}, ${p.c}cc)`, color: '#fff', display:'flex', alignItems:'center', justifyContent:'center', boxShadow: `0 8px 18px ${p.c}33`, marginBottom: 18 }}>
                  <Icon name={p.i} size={20}/>
                </div>
                <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>{p.t}</div>
                <p style={{ fontSize: 14, lineHeight: 1.6 }}>{p.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Milestones */}
      <section className="section" style={{ background: 'var(--surface-2)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div style={{ textAlign: 'center', marginBottom: 48 }}>
            <span className="eyebrow"><Icon name="clock" size={12}/> 历程</span>
            <h2 className="display-2" style={{ marginTop: 16 }}>四年,从一个原型到 1,200 个客户</h2>
          </div>
          <div className="sp-timeline">
            {milestones.map((m, i) => (
              <div key={i} className="sp-timeline-row">
                <div className="sp-timeline-year mono">{m.y}</div>
                <div className="sp-timeline-dot"/>
                <div className="sp-timeline-text">{m.t}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Team */}
      <section className="section">
        <div className="container">
          <div style={{ textAlign: 'center', marginBottom: 48 }}>
            <span className="eyebrow"><Icon name="users" size={12}/> 团队</span>
            <h2 className="display-2" style={{ marginTop: 16 }}>把行业老兵与工程师放进同一间办公室</h2>
          </div>
          <div className="sp-team-grid">
            {team.map(p => (
              <div key={p.n} className="sp-team-card">
                <div className="sp-team-avatar mono">{p.n.split(' ').map(s=>s[0]).join('')}</div>
                <div className="sp-team-name">{p.n}</div>
                <div className="sp-team-role">{p.r}</div>
                <div className="sp-team-bio">{p.bio}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Investors */}
      <section style={{ padding: '64px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)', background: 'var(--surface-2)' }}>
        <div className="container">
          <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 24 }}>
            投资人 / Investors
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 48, opacity: 0.7 }}>
            {investors.map(v => (
              <span key={v} style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink-3)', letterSpacing: '-0.01em' }}>{v}</span>
            ))}
          </div>
        </div>
      </section>

      {/* Careers */}
      <section className="section" id="careers">
        <div className="container">
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 32, gap: 24, flexWrap: 'wrap' }}>
            <div>
              <span className="eyebrow"><Icon name="bolt" size={12}/> 招聘</span>
              <h2 className="display-2" style={{ marginTop: 16 }}>{jobs.length} 个开放职位</h2>
              <p style={{ marginTop: 8, fontSize: 15 }}>简历投递:<a href="mailto:talent@freightiq.ai" style={{ color: 'var(--brand)', fontWeight: 500 }}>talent@freightiq.ai</a></p>
            </div>
            <a className="btn btn-ghost btn-sm" href="/contact?type=careers">投递简历 <Icon name="arrow" size={12}/></a>
          </div>
          <div className="sp-jobs">
            {jobs.map((j, i) => (
              <a key={i} className="sp-job-row" href={`mailto:talent@freightiq.ai?subject=${encodeURIComponent('应聘:' + j.t)}`}>
                <div className="sp-job-dept">{j.dept}</div>
                <div className="sp-job-title">{j.t}</div>
                <div className="sp-job-loc"><Icon name="globe" size={11}/> {j.loc}</div>
                <div><span className="chip">{j.tag}</span></div>
                <div className="sp-job-arr"><Icon name="arrow" size={14}/></div>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Press */}
      <section className="section" id="press" style={{ background: 'var(--surface-2)', borderTop: '1px solid var(--line)' }}>
        <div className="container">
          <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginBottom: 32, gap: 24, flexWrap: 'wrap' }}>
            <div>
              <span className="eyebrow"><Icon name="doc" size={12}/> 媒体资源</span>
              <h2 className="display-2" style={{ marginTop: 16 }}>新闻 & 媒体提及</h2>
              <p style={{ marginTop: 8, fontSize: 15 }}>媒体联系:<a href="mailto:press@freightiq.ai" style={{ color: 'var(--brand)', fontWeight: 500 }}>press@freightiq.ai</a> · 品牌资源包: <a href="#" style={{ color: 'var(--brand)', fontWeight: 500 }}>下载 ↓</a></p>
            </div>
          </div>
          <div className="card" style={{ overflow: 'hidden' }}>
            {press.map((p, i) => (
              <div key={i} className="sp-press-row">
                <span className="sp-press-src mono">{p.src}</span>
                <span className="sp-press-date mono" style={{ color: 'var(--ink-5)' }}>{p.d}</span>
                <span className="sp-press-title">{p.t}</span>
                <Icon name="arrow" size={12} color="var(--ink-5)"/>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Legal */}
      <section className="section" id="legal">
        <div className="container">
          <div style={{ textAlign: 'center', marginBottom: 36 }}>
            <span className="eyebrow"><Icon name="shield" size={12}/> 法律</span>
            <h2 className="display-2" style={{ marginTop: 16 }}>合规 & 政策</h2>
          </div>
          <div className="grid grid-4">
            {[
              { id: 'privacy',  t: '隐私政策',     d: '我们如何收集、处理、保护数据' },
              { id: 'terms',    t: '服务条款',     d: '使用 FreightIQ 服务的法律约定' },
              { id: 'cookie',   t: 'Cookie 政策',  d: 'Cookie 类型与可选项设置' },
              { id: 'security', t: '安全白皮书',   d: 'SOC2 · GDPR · 数据隔离详情' }
            ].map(L => (
              <a key={L.id} id={L.id} className="card card-hov" style={{ padding: 22, display: 'block' }} href={`mailto:legal@freightiq.ai?subject=${encodeURIComponent(L.t)}`}>
                <Icon name="doc" size={18} color="var(--brand)"/>
                <div style={{ fontSize: 15, fontWeight: 600, marginTop: 12 }}>{L.t}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 6 }}>{L.d}</div>
                <div style={{ fontSize: 11, color: 'var(--brand)', marginTop: 14, display: 'flex', gap: 4, alignItems: 'center' }}>查看完整文本 <Icon name="arrow" size={11}/></div>
              </a>
            ))}
          </div>
        </div>
      </section>
    </>
  );
};

// =========================================================
// CONTACT — 联系销售 / Demo / 试用 / 合作
// =========================================================
const ContactPage = () => {
  const params = (typeof window !== 'undefined' && new URLSearchParams(window.location.search)) || new URLSearchParams();
  const initialType = params.get('type') || 'sales';
  const [form, setForm] = React.useState({
    type: initialType,
    name: '', company: '', role: '', email: '', phone: '', size: '', msg: ''
  });
  const [sent, setSent] = React.useState(false);
  const set = (k, v) => setForm(s => ({ ...s, [k]: v }));
  const submit = (e) => { e.preventDefault(); setSent(true); };

  const types = [
    { k: 'sales',    l: '联系销售',   d: '了解定价与方案',   i: 'bolt' },
    { k: 'demo',     l: '预约 Demo',   d: '解决方案专家 1:1', i: 'play' },
    { k: 'trial',    l: '免费试用',    d: '14 天全功能开通',   i: 'check' },
    { k: 'partner',  l: '商务合作',    d: '渠道 / 数据 / 集成', i: 'plug' },
    { k: 'careers',  l: '招聘咨询',    d: '加入 FreightIQ',   i: 'users' }
  ];
  const offices = [
    { city: '上海',     addr: '徐汇区肇嘉浜路 1065 号飞雕国际大厦 7F',  tz: 'GMT+8',  ph: '+86 21 5588 8888' },
    { city: '深圳',     addr: '南山区粤海街道科技园 T7 25F',           tz: 'GMT+8',  ph: '+86 755 2233 1188' },
    { city: '新加坡',    addr: '6 Battery Rd #16-01, Singapore 049909', tz: 'GMT+8',  ph: '+65 6303 8088' },
    { city: '鹿特丹',   addr: 'Wilhelminakade 909, 3072 AP Rotterdam', tz: 'GMT+1',  ph: '+31 10 880 2700' }
  ];

  return (
    <>
      <PageHero
        eyebrow="联系我们"
        title={<>有人 24 小时<br/>守在另一头。</>}
        sub="销售 / 解决方案 / 合作 / 招聘 — 选一项,30 秒填好,我们会在一个工作日内回复。"
      />

      <section style={{ padding: '0 0 96px' }}>
        <div className="container">
          <div className="sp-contact-grid">
            {/* Left — form */}
            <form className="sp-form card" onSubmit={submit}>
              {sent ? (
                <div style={{ padding: 56, textAlign: 'center' }}>
                  <div style={{ width: 64, height: 64, borderRadius: 16, background: 'color-mix(in srgb, var(--accent) 16%, transparent)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
                    <Icon name="check" size={32} color="var(--accent)"/>
                  </div>
                  <h3 className="display-3" style={{ marginBottom: 10 }}>已收到,谢谢!</h3>
                  <p style={{ maxWidth: 440, margin: '0 auto', fontSize: 14 }}>
                    我们会在一个工作日内通过邮件 / 电话联系你 ({form.email || '邮箱'})。如急,直接拨 <a className="mono" href="tel:+862155888888" style={{ color: 'var(--brand)' }}>+86 21 5588 8888</a>。
                  </p>
                  <button type="button" className="btn btn-ghost btn-sm" style={{ marginTop: 22 }} onClick={() => setSent(false)}>再提交一份</button>
                </div>
              ) : (
                <>
                  <div className="sp-form-head">
                    <h2 style={{ fontSize: 22, marginBottom: 6 }}>30 秒填好</h2>
                    <p style={{ fontSize: 13 }}>带 <span style={{ color: 'var(--danger)' }}>*</span> 是必填,其余可空。</p>
                  </div>

                  <div className="sp-form-types">
                    {types.map(t => (
                      <label key={t.k} className={`sp-form-type ${form.type === t.k ? 'on' : ''}`}>
                        <input type="radio" name="type" value={t.k} checked={form.type === t.k} onChange={e => set('type', e.target.value)} hidden/>
                        <Icon name={t.i} size={14}/>
                        <div>
                          <div style={{ fontSize: 13, fontWeight: 600 }}>{t.l}</div>
                          <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 2 }}>{t.d}</div>
                        </div>
                      </label>
                    ))}
                  </div>

                  <div className="sp-form-row sp-form-2col">
                    <Field label="姓名" req v={form.name} on={v => set('name', v)} ph="张三"/>
                    <Field label="公司" req v={form.company} on={v => set('company', v)} ph="某某物流"/>
                  </div>
                  <div className="sp-form-row sp-form-2col">
                    <Field label="职务" v={form.role} on={v => set('role', v)} ph="销售总监 / 运营 / IT"/>
                    <Field label="团队规模" v={form.size} on={v => set('size', v)} ph="如 50 人 / 10 名销售" select={['1–10','11–50','51–200','201–1000','1000+']}/>
                  </div>
                  <div className="sp-form-row sp-form-2col">
                    <Field label="工作邮箱" req v={form.email} on={v => set('email', v)} ph="you@company.com" type="email"/>
                    <Field label="电话 / WeChat" v={form.phone} on={v => set('phone', v)} ph="+86 138 …"/>
                  </div>
                  <div className="sp-form-row">
                    <label className="sp-form-label">留言 <span style={{ color: 'var(--ink-4)', fontWeight: 400 }}>(可选)</span></label>
                    <textarea className="sp-form-input" rows="4" value={form.msg} onChange={e => set('msg', e.target.value)} placeholder="想了解的产品 / 业务场景 / 当前用什么系统..."/>
                  </div>

                  <div className="sp-form-foot">
                    <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>
                      <Icon name="lock" size={12}/> 你的信息仅用于销售跟进,不会用于营销或转售。
                    </span>
                    <button type="submit" className="btn btn-primary btn-lg" style={{ minWidth: 160, justifyContent: 'center' }}>
                      提交 <Icon name="arrow" size={14}/>
                    </button>
                  </div>
                </>
              )}
            </form>

            {/* Right — alt channels */}
            <aside className="sp-contact-aside">
              <div className="sp-channel-card">
                <Icon name="bolt" size={16} color="var(--brand)"/>
                <div className="sp-channel-t">销售热线</div>
                <a className="sp-channel-v mono" href="tel:+862155888888">+86 21 5588 8888</a>
                <div className="sp-channel-meta">工作日 09:00 – 22:00</div>
              </div>
              <div className="sp-channel-card">
                <Icon name="users" size={16} color="var(--accent)"/>
                <div className="sp-channel-t">销售邮箱</div>
                <a className="sp-channel-v" href="mailto:sales@freightiq.ai">sales@freightiq.ai</a>
                <div className="sp-channel-meta">回复 SLA 24h</div>
              </div>
              <div className="sp-channel-card">
                <Icon name="plug" size={16} color="#7C5CFF"/>
                <div className="sp-channel-t">合作 / 数据集成</div>
                <a className="sp-channel-v" href="mailto:partners@freightiq.ai">partners@freightiq.ai</a>
                <div className="sp-channel-meta">数据源 / 渠道 / OEM</div>
              </div>
              <div className="sp-channel-card">
                <Icon name="settings" size={16} color="var(--amber)"/>
                <div className="sp-channel-t">技术支持 / 客户服务</div>
                <a className="sp-channel-v" href="mailto:support@freightiq.ai">support@freightiq.ai</a>
                <div className="sp-channel-meta">付费客户 7×24,SLA P1 30 分钟</div>
              </div>
            </aside>
          </div>

          {/* Offices */}
          <div style={{ marginTop: 64, paddingTop: 48, borderTop: '1px solid var(--line)' }}>
            <div style={{ fontSize: 13, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.12em', fontWeight: 600, marginBottom: 24 }}>办公室 / Offices</div>
            <div className="grid grid-4">
              {offices.map(o => (
                <div key={o.city} className="sp-office">
                  <div className="sp-office-city">{o.city} <span className="mono" style={{ fontSize: 11, color: 'var(--ink-5)', marginLeft: 6 }}>{o.tz}</span></div>
                  <div className="sp-office-addr">{o.addr}</div>
                  <a className="mono sp-office-ph" href={`tel:${o.ph.replace(/\s/g,'')}`}>{o.ph}</a>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

const Field = ({ label, req, v, on, ph, type='text', select }) => (
  <div className="sp-form-row" style={{ margin: 0 }}>
    <label className="sp-form-label">{label}{req && <span style={{ color: 'var(--danger)' }}> *</span>}</label>
    {select ? (
      <select className="sp-form-input" value={v} onChange={e => on(e.target.value)} required={req}>
        <option value="">{ph || '请选择'}</option>
        {select.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
    ) : (
      <input className="sp-form-input" type={type} value={v} onChange={e => on(e.target.value)} placeholder={ph} required={req}/>
    )}
  </div>
);

// =========================================================
// SOLUTIONS — 5 行业 hub
// =========================================================
const SolutionsPage = () => {
  const inds = [
    {
      id: 'forwarder', name: '货代 / Freight Forwarder', icon: 'ship', color: '#1677FF',
      pain: [
        '20+ 船公司询价靠人工,旺季每天 6 小时',
        '订舱抢不到 / 抢错价 / 老客户跑单',
        '毛利 / 客户 / 销售看不清,凭感觉调价'
      ],
      sol: '把 50+ 船公司运价、舱位、订舱接口聚合到一个工作台,加上 AI 抢单与策略库,加上一套销售 / 客户 / 毛利 BI 看板。',
      stack: ['Rates · 实时运价', 'Rates · 抢舱订舱', 'Rates · 运营 BI'],
      quote: '原本 3 位销售每天 6 小时询价,现在 1 人 1 小时,订单毛利 +2.4%。',
      who: '张经理 · COSCO 华南区销售总监',
      kpi: [{ v: '−83%', l: '询价时间' }, { v: '+2.4pp', l: '订单毛利' }, { v: '+480 柜', l: '抢单/月' }]
    },
    {
      id: 'carrier', name: '船公司 / Carrier', icon: 'globe', color: '#00D4AA',
      pain: [
        '运价、舱位、燃油、舆情数据散在不同系统',
        '航线 / 港口 / 风险信号分析依赖外部分析师',
        '内部 BI 报表周期长 (T+7),无法支撑实时调价'
      ],
      sol: 'Foresight 一图整合 AIS、运价指数、海关、燃油、新闻情报与气候数据,提供运价预测、风险预警、SRI 结构性风险指数。',
      stack: ['Foresight · 智能问答', 'Foresight · 数据洞察', 'Foresight · 智能预警'],
      quote: '把 AIS、港口、燃油、舆情一张图看完,以前要 5 个分析师,现在 Foresight 替我们做。',
      who: 'Chen Li · MAERSK 东北亚数据分析主管',
      kpi: [{ v: '−5 名', l: '人工分析师' }, { v: '94 分钟', l: '预警提前' }, { v: '94.3%', l: '预测准确' }]
    },
    {
      id: 'ecommerce', name: '跨境电商 / Cross-border E-commerce', icon: 'cube', color: '#7C5CFF',
      pain: [
        '黑五 / 旺季舱位/价格剧烈波动,补货节奏踩不准',
        '物流费占毛利 8–15%,缺乏单 SKU 物流成本核算',
        '多 3PL / 货代报价不透明,无法快速比对'
      ],
      sol: 'Rates 比价 + Foresight 趋势预测 + Prospect 拓客组合,从选品 → 询价 → 出货 → 补货 全链路给数据。',
      stack: ['Rates · 实时运价', 'Rates · 抢舱订舱', 'Foresight · 趋势分析'],
      quote: '把舱位预测和补货节奏挂上 Foresight,我们 Q4 备货节省了 12% 物流支出。',
      who: '王总 · 某 DTC 品牌创始人',
      kpi: [{ v: '−12%', l: '物流支出' }, { v: '−18%', l: '滞港' }, { v: '+22%', l: '准时交付' }]
    },
    {
      id: 'manufacturer', name: '制造业出口 / Manufacturer Export', icon: 'cpu', color: '#FFB020',
      pain: [
        '业务部门询价多,合同价 / 现货价对不上账',
        'L/C 与提单时效要求苛刻,船期变动手忙脚乱',
        'CFO 需要按合同 / 客户 / 项目核算物流成本'
      ],
      sol: 'Rates 合同管理 + Foresight 船期/到港预警 + 与 SAP / Kingdee / 自研 ERP 双向同步,把物流费用入账自动化。',
      stack: ['Rates · 合同与现货', 'Foresight · 船期预警', 'API · ERP 集成'],
      quote: '从询价到合同入账的链路从 5 个系统 / 12 步压到一个看板 / 3 步。',
      who: '李 CFO · 某汽车零部件出口企业',
      kpi: [{ v: '−72%', l: '财务对账' }, { v: '−4 天', l: '提单延迟' }, { v: '+1 名', l: '编制释放' }]
    },
    {
      id: 'sct', name: '供应链团队 / Supply Chain Team', icon: 'flow', color: '#FF5A4E',
      pain: [
        '海运 / 空运 / 卡车多模态成本无法横向比对',
        '风险监控全靠新闻 + 微信群,信号滞后',
        '应急预案没有数据支撑,只能凭经验'
      ],
      sol: 'Foresight 全模态数据汇总 + 智能预警 + 抢单工作台联动,真正做到"看到信号就有动作"。',
      stack: ['Foresight · 智能问答', 'Foresight · 智能预警', 'Rates · 抢舱工作台'],
      quote: '红海事件爆发当天,Foresight 比我们的舆情群快了 3 小时,我们抢回了 14 个柜的舱位。',
      who: '某 500 强供应链总监',
      kpi: [{ v: '+3 小时', l: '信号提前' }, { v: '14 柜', l: '抢回' }, { v: '−$280K', l: '风险损失' }]
    }
  ];

  return (
    <>
      <PageHero
        eyebrow="解决方案"
        title={<>5 个行业,<br/>5 套打法。</>}
        sub="货代、船公司、跨境电商、制造业、供应链团队 — 不同岗位用 FreightIQ 的方式不一样。下面是按行业整理的真实部署。"
      />

      {/* Anchor nav */}
      <div className="sp-sol-anchors">
        <div className="container" style={{ display: 'flex', gap: 6, overflowX: 'auto', padding: '14px 24px' }}>
          {inds.map(i => (
            <a key={i.id} href={`#${i.id}`} className="sp-sol-anchor">
              <Icon name={i.icon} size={12} color={i.color}/> {i.name.split(' / ')[0]}
            </a>
          ))}
        </div>
      </div>

      {inds.map((I, idx) => (
        <section key={I.id} id={I.id} className="section sp-industry" style={{ background: idx % 2 === 1 ? 'var(--surface-2)' : 'transparent' }}>
          <div className="container">
            <div className="sp-industry-head">
              <div className="sp-industry-icon" style={{ background: `linear-gradient(135deg, ${I.color}, ${I.color}99)`, boxShadow: `0 14px 32px ${I.color}33` }}>
                <Icon name={I.icon} size={24}/>
              </div>
              <div>
                <span className="eyebrow" style={{ color: I.color }}>{idx + 1 < 10 ? `0${idx+1}` : idx+1} · 行业</span>
                <h2 className="display-2" style={{ marginTop: 8 }}>{I.name}</h2>
              </div>
            </div>

            <div className="sp-industry-body">
              <div>
                <div className="sp-block-h">现状痛点</div>
                <ul className="sp-pain-list">
                  {I.pain.map((p, j) => (
                    <li key={j}>
                      <span className="sp-pain-dot" style={{ background: I.color }}/>
                      <span>{p}</span>
                    </li>
                  ))}
                </ul>
              </div>
              <div>
                <div className="sp-block-h">FreightIQ 怎么解</div>
                <p style={{ fontSize: 16, lineHeight: 1.7, color: 'var(--ink-2)' }}>{I.sol}</p>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 16 }}>
                  {I.stack.map(s => <span key={s} className="chip" style={{ background: `${I.color}14`, color: I.color, border: `1px solid ${I.color}33` }}>{s}</span>)}
                </div>
              </div>
            </div>

            <div className="sp-industry-bottom">
              <div className="sp-industry-quote card" style={{ padding: 24, borderLeft: `3px solid ${I.color}` }}>
                <div style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--ink-1)', fontWeight: 500 }}>"{I.quote}"</div>
                <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 14 }}>{I.who}</div>
              </div>
              <div className="sp-industry-kpis">
                {I.kpi.map(k => (
                  <div key={k.l} className="sp-industry-kpi">
                    <div className="mono" style={{ fontSize: 26, fontWeight: 600, color: I.color, letterSpacing: '-0.02em' }}>{k.v}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 4 }}>{k.l}</div>
                  </div>
                ))}
              </div>
            </div>

            <div style={{ marginTop: 28, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <a className="btn btn-primary btn-sm" href={`/contact?type=demo&industry=${I.id}`}>预约 {I.name.split(' / ')[0]} 方案 Demo <Icon name="arrow" size={12}/></a>
              <a className="btn btn-ghost btn-sm" href="#cases">查看完整客户案例</a>
            </div>
          </div>
        </section>
      ))}
    </>
  );
};

// =========================================================
// BLOG — 文章 / Webinar
// =========================================================
const BlogPage = () => {
  const featured = {
    cat: '产品发布', date: '2026-04-28', read: '6 分钟',
    t: 'FreightIQ Foresight 2.0 发布:把 AIS、运价、舆情、燃油融为一个 SRI',
    d: '过去半年我们与 28 家船公司 + 6 个港口运营商一起验证了一个想法 — 物流行业需要一个像 VIX 之于股市那样的实时风险指数。',
    img: 'linear-gradient(135deg, #00D4AA 0%, #1677FF 70%, #7C5CFF 110%)'
  };
  const posts = [
    { cat: '行业洞察', date: '2026-04-22', read: '5 分钟', t: '红海危机第 18 个月:航线、运价、保费的连锁反应', img: '#FF5A4E' },
    { cat: '工程实践', date: '2026-04-15', read: '8 分钟', t: '从 5 分钟刷新到 12 秒推送:运价数据流的重构之路', img: '#1677FF' },
    { cat: '客户故事', date: '2026-04-08', read: '4 分钟', t: 'COSCO 华南:用 Rates 把销售人效提升 6 倍的细节', img: '#7C5CFF' },
    { cat: 'AI / 模型', date: '2026-03-31', read: '7 分钟', t: 'SCFI 预测准确率 94.3%:我们做对了什么,还有什么没做对', img: '#00D4AA' },
    { cat: '产品发布', date: '2026-03-22', read: '3 分钟', t: '抢舱工作台 1.5:策略库 + 多账号池 + 风险熔断', img: '#FFB020' },
    { cat: '行业洞察', date: '2026-03-14', read: '6 分钟', t: '中欧班列 2026:数据告诉我们的三件事', img: '#0A2A5C' }
  ];
  const webinars = [
    { date: '2026-05-22', time: '14:00 GMT+8', t: 'Foresight 2.0 实战:从 SRI 到智能预警', host: 'Chen Li, CDO', seats: '146 / 500' },
    { date: '2026-06-04', time: '10:00 GMT+8', t: '货代抢舱工作台:策略库设计 6 招',          host: 'Sara Park, VP Product', seats: '88 / 300' },
    { date: '2026-06-18', time: '15:00 GMT+1', t: 'European Shippers Roundtable: Smart Carrier Mix', host: 'JD Liu, CEO', seats: '32 / 100' }
  ];
  const [email, setEmail] = React.useState('');
  const [subbed, setSubbed] = React.useState(false);

  return (
    <>
      <PageHero
        eyebrow="博客 & 资源"
        title={<>FreightIQ 怎么想,<br/>FreightIQ 怎么做。</>}
        sub="产品发布 / 客户故事 / 行业洞察 / 工程实践 / Webinar 直播 — 一个地方更新。"
      />

      {/* Featured */}
      <section style={{ padding: '0 0 64px' }}>
        <div className="container">
          <a className="sp-blog-featured card" href="#" style={{ background: 'var(--surface)' }}>
            <div className="sp-blog-featured-img" style={{ background: featured.img }}>
              <span className="chip" style={{ background: 'rgba(255,255,255,0.2)', color: '#fff', border: '1px solid rgba(255,255,255,0.3)' }}>精选</span>
            </div>
            <div className="sp-blog-featured-body">
              <div style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 12, color: 'var(--ink-4)', marginBottom: 12 }}>
                <span className="chip">{featured.cat}</span>
                <span className="mono">{featured.date}</span>
                <span>·</span>
                <span>{featured.read}</span>
              </div>
              <h3 className="display-3">{featured.t}</h3>
              <p style={{ marginTop: 14, fontSize: 15, lineHeight: 1.65, color: 'var(--ink-3)' }}>{featured.d}</p>
              <div style={{ marginTop: 22, color: 'var(--brand)', fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
                阅读全文 <Icon name="arrow" size={12}/>
              </div>
            </div>
          </a>
        </div>
      </section>

      {/* Post grid */}
      <section style={{ padding: '0 0 64px' }}>
        <div className="container">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, gap: 16, flexWrap: 'wrap' }}>
            <h2 style={{ fontSize: 22, fontWeight: 600 }}>最新文章</h2>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {['全部', '产品发布', '客户故事', '行业洞察', '工程实践', 'AI / 模型'].map((t, i) => (
                <button key={t} className={i === 0 ? 'chip chip-brand' : 'chip'} style={{ cursor: 'pointer' }}>{t}</button>
              ))}
            </div>
          </div>
          <div className="sp-blog-grid">
            {posts.map((p, i) => (
              <a key={i} href="#" className="sp-blog-card card card-hov">
                <div className="sp-blog-card-img" style={{ background: `linear-gradient(135deg, ${p.img}, ${p.img}99)` }}>
                  <span className="mono" style={{ color: '#fff', fontSize: 11, opacity: 0.8 }}>{p.cat}</span>
                </div>
                <div style={{ padding: '20px 22px 22px' }}>
                  <div className="sp-blog-meta">
                    <span className="mono">{p.date}</span><span>·</span><span>{p.read}</span>
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 600, lineHeight: 1.4, marginTop: 8 }}>{p.t}</div>
                </div>
              </a>
            ))}
          </div>
          <div style={{ textAlign: 'center', marginTop: 32 }}>
            <button className="btn btn-ghost btn-sm">加载更多 <Icon name="arrowDown" size={12}/></button>
          </div>
        </div>
      </section>

      {/* Webinars */}
      <section className="section" id="webinars" style={{ background: 'var(--surface-2)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div style={{ marginBottom: 32 }}>
            <span className="eyebrow"><Icon name="play" size={12}/> Webinar</span>
            <h2 className="display-2" style={{ marginTop: 16 }}>即将举办的直播</h2>
            <p style={{ marginTop: 8, fontSize: 15, maxWidth: 600 }}>线上 1 小时,讲一个具体场景,带演示和问答。免费报名,回放 24 小时上线。</p>
          </div>
          <div className="card" style={{ overflow: 'hidden' }}>
            {webinars.map((w, i) => (
              <div key={i} className="sp-webinar-row">
                <div className="sp-webinar-date">
                  <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>{w.date}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>{w.time}</div>
                </div>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink-1)' }}>{w.t}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 4 }}>{w.host}</div>
                </div>
                <div className="sp-webinar-seats mono">{w.seats}</div>
                <button className="btn btn-primary btn-sm">立即报名</button>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Newsletter */}
      <section className="section">
        <div className="container">
          <div className="sp-news-card">
            <div>
              <h3 style={{ fontSize: 22, fontWeight: 600, marginBottom: 8 }}>每两周一封,只发干货</h3>
              <p style={{ fontSize: 14 }}>产品发布 · 行业洞察 · Webinar 提醒。已有 8,400+ 物流从业者订阅。随时退订。</p>
            </div>
            {subbed ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--accent)', fontWeight: 500 }}>
                <Icon name="check" size={18}/> 已订阅,首封将在周一发到 <span className="mono">{email}</span>
              </div>
            ) : (
              <form className="sp-news-form" onSubmit={e => { e.preventDefault(); setSubbed(true); }}>
                <input className="sp-form-input" type="email" required placeholder="you@company.com" value={email} onChange={e => setEmail(e.target.value)}/>
                <button type="submit" className="btn btn-primary">订阅 <Icon name="arrow" size={12}/></button>
              </form>
            )}
          </div>
        </div>
      </section>
    </>
  );
};

// =========================================================
// LOGIN — 登录 / SSO / 注册占位
// =========================================================
// LOGIN — Split-screen brand panel + form
// =========================================================
const LOGIN_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "layout": "split",
  "brandTheme": "ocean",
  "showProductSwitcher": true
}/*EDITMODE-END*/;

const LoginBrandPanel = ({ theme = 'ocean' }) => {
  // animated route counter
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setTick(x => x + 1), 1800);
    return () => clearInterval(t);
  }, []);
  const rates = [
    { lane: 'SHA → LAX', val: 2580, delta: -42 },
    { lane: 'NGB → RTM', val: 1845, delta: +18 },
    { lane: 'SZX → HAM', val: 1920, delta: -8  },
    { lane: 'QIN → NYC', val: 3120, delta: +96 }
  ];
  const liveLane = rates[tick % rates.length];

  return (
    <aside className={`sp-login-brand sp-login-brand-${theme}`}>
      <div className="sp-login-brand-bg" aria-hidden="true">
        {/* World-map dot grid */}
        <svg className="sp-login-brand-svg" viewBox="0 0 600 800" preserveAspectRatio="xMidYMid slice">
          <defs>
            <radialGradient id="lp-glow" cx="50%" cy="40%" r="60%">
              <stop offset="0%" stopColor="rgba(255,255,255,0.18)"/>
              <stop offset="100%" stopColor="rgba(255,255,255,0)"/>
            </radialGradient>
            <linearGradient id="lp-route" x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="rgba(255,255,255,0)"/>
              <stop offset="50%" stopColor="rgba(255,255,255,0.9)"/>
              <stop offset="100%" stopColor="rgba(255,255,255,0)"/>
            </linearGradient>
          </defs>
          <rect width="600" height="800" fill="url(#lp-glow)"/>
          {/* Dot grid (lightweight world hint) */}
          <g fill="rgba(255,255,255,0.08)">
            {Array.from({ length: 22 }).map((_, r) =>
              Array.from({ length: 18 }).map((_, c) => (
                <circle key={r + '-' + c} cx={32 + c * 32} cy={56 + r * 32} r={1.4}/>
              ))
            )}
          </g>
          {/* Three flowing arcs (shipping lanes) */}
          {[
            { d: 'M 60 540 Q 300 200 540 480', delay: 0 },
            { d: 'M 80 320 Q 320 600 520 280', delay: 1.2 },
            { d: 'M 100 660 Q 380 380 560 620', delay: 2.4 }
          ].map((arc, i) => (
            <g key={i}>
              <path d={arc.d} stroke="rgba(255,255,255,0.25)" strokeWidth="1.2" fill="none" strokeDasharray="4 6"/>
              <path d={arc.d} stroke="url(#lp-route)" strokeWidth="2.2" fill="none" strokeDasharray="80 1000"
                style={{ animation: `sp-login-flow 6s linear infinite`, animationDelay: `${arc.delay}s` }}/>
            </g>
          ))}
        </svg>
      </div>

      <div className="sp-login-brand-inner">
        <a href="/" className="sp-login-brand-logo">
          <span className="sp-login-brand-mark"/>
          <span>全集</span>
          <span className="sp-login-brand-tag">FreightIQ</span>
        </a>

        <div className="sp-login-brand-body">
          <h1 className="sp-login-brand-h1">
            全球航运数据,<br/>
            <span className="sp-login-brand-h1-em">统一登录入口</span>
          </h1>
          <p className="sp-login-brand-lead">
            一个账号 · 贯穿 Rates 运价 · Foresight 预测 · Prospect 拓客<br/>
            连接全球 28 家船司、92 个港口、2.4亿条历史数据
          </p>

          {/* Live ticker — proves the platform is "alive" */}
          <div className="sp-login-ticker">
            <div className="sp-login-ticker-dot"/>
            <div className="sp-login-ticker-body">
              <div className="sp-login-ticker-label">实时运价</div>
              <div className="sp-login-ticker-row">
                <span className="sp-login-ticker-lane mono">{liveLane.lane}</span>
                <span className="sp-login-ticker-val mono">${liveLane.val.toLocaleString()}</span>
                <span className={`sp-login-ticker-delta ${liveLane.delta < 0 ? 'down' : 'up'} mono`}>
                  {liveLane.delta > 0 ? '+' : ''}{liveLane.delta}
                </span>
              </div>
            </div>
          </div>

          {/* Customer logos strip */}
          <div className="sp-login-trust">
            <div className="sp-login-trust-label">已被 320+ 物流企业选用</div>
            <div className="sp-login-trust-logos">
              {['MAERSK', 'COSCO', 'MSC', 'CMA CGM', 'EVERGREEN'].map(n => (
                <span key={n} className="sp-login-trust-logo">{n}</span>
              ))}
            </div>
          </div>
        </div>

        <div className="sp-login-brand-foot">
          <a href="/about" className="sp-login-brand-link">关于我们</a>
          <span>·</span>
          <a href="/solutions" className="sp-login-brand-link">解决方案</a>
          <span>·</span>
          <a href="/contact" className="sp-login-brand-link">联系销售</a>
        </div>
      </div>
    </aside>
  );
};

const LoginPage = () => {
  const [tweaks, setTweaks] = React.useState(() => {
    try { return { ...LOGIN_TWEAK_DEFAULTS, ...JSON.parse(localStorage.getItem('lp-tweaks') || '{}') }; }
    catch { return LOGIN_TWEAK_DEFAULTS; }
  });
  const setTweak = (k, v) => setTweaks(s => {
    const next = { ...s, [k]: v };
    try { localStorage.setItem('lp-tweaks', JSON.stringify(next)); } catch {}
    return next;
  });

  // ── Flow state ──────────────────────────────
  // step: 'identify' → 'verify' → 'workspace' → 'done'
  const [step, setStep] = React.useState('identify');
  const [method, setMethod] = React.useState('email');     // 'email' | 'phone'
  const [identifier, setIdentifier] = React.useState('');
  const [phoneRegion, setPhoneRegion] = React.useState('+86');
  const [code, setCode] = React.useState(['', '', '', '', '', '']);
  const [countdown, setCountdown] = React.useState(0);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState('');

  // workspace setup state
  const [isFirstTime, setIsFirstTime] = React.useState(false);
  const [ssoUser, setSsoUser] = React.useState(null);     // { name, email, avatar } from Google
  const [workspace, setWorkspace] = React.useState('');
  const [displayName, setDisplayName] = React.useState('');

  const codeRefs = React.useRef([]);

  // countdown timer
  React.useEffect(() => {
    if (countdown <= 0) return;
    const t = setTimeout(() => setCountdown(c => c - 1), 1000);
    return () => clearTimeout(t);
  }, [countdown]);

  // Validate identifier
  const isValidIdentifier = () => {
    if (method === 'email') return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(identifier);
    return /^1[3-9]\d{9}$/.test(identifier);
  };

  // ── Submit handlers ──────────────────────────
  const handleSendCode = (e) => {
    e?.preventDefault?.();
    setErr('');
    if (!isValidIdentifier()) {
      setErr(method === 'email' ? '请输入有效的邮箱地址' : '请输入有效的 11 位手机号');
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      setStep('verify');
      setCountdown(60);
      setCode(['', '', '', '', '', '']);
      setTimeout(() => codeRefs.current[0]?.focus(), 50);
    }, 600);
  };

  const handleVerify = (codeArr) => {
    const fullCode = (codeArr || code).join('');
    if (fullCode.length !== 6) return;
    setLoading(true);
    setErr('');
    setTimeout(() => {
      setLoading(false);
      // Demo: code "000000" or any 6 digits → success
      // Determine first-time by checking localStorage
      const knownUsers = JSON.parse(localStorage.getItem('fiq-known-users') || '[]');
      const isNew = !knownUsers.includes(identifier);
      setIsFirstTime(isNew);
      if (isNew) {
        setStep('workspace');
      } else {
        setStep('done');
      }
    }, 700);
  };

  const handleCodeInput = (idx, val) => {
    if (!/^\d?$/.test(val)) return;
    const next = [...code];
    next[idx] = val;
    setCode(next);
    if (val && idx < 5) codeRefs.current[idx + 1]?.focus();
    if (next.every(d => d !== '')) {
      // Auto-submit when all 6 digits filled
      handleVerify(next);
    }
  };

  const handleCodeKey = (idx, e) => {
    if (e.key === 'Backspace' && !code[idx] && idx > 0) {
      codeRefs.current[idx - 1]?.focus();
    } else if (e.key === 'ArrowLeft' && idx > 0) {
      codeRefs.current[idx - 1]?.focus();
    } else if (e.key === 'ArrowRight' && idx < 5) {
      codeRefs.current[idx + 1]?.focus();
    }
  };

  const handleCodePaste = (e) => {
    e.preventDefault();
    const pasted = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, 6);
    if (pasted.length === 0) return;
    const next = ['', '', '', '', '', ''];
    for (let i = 0; i < pasted.length; i++) next[i] = pasted[i];
    setCode(next);
    if (pasted.length === 6) handleVerify(next);
    else codeRefs.current[pasted.length]?.focus();
  };

  const handleResend = () => {
    setCountdown(60);
    setCode(['', '', '', '', '', '']);
    setErr('');
    codeRefs.current[0]?.focus();
  };

  const handleGoogle = () => {
    setErr('');
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      // Simulate Google OAuth returning user info
      const fakeUser = { name: 'Su Yang', email: 'suyang@example.com', avatar: 'S' };
      setSsoUser(fakeUser);
      setIdentifier(fakeUser.email);
      setDisplayName(fakeUser.name);
      const knownUsers = JSON.parse(localStorage.getItem('fiq-known-users') || '[]');
      const isNew = !knownUsers.includes(fakeUser.email);
      setIsFirstTime(isNew);
      if (isNew) {
        setStep('workspace');
      } else {
        setStep('done');
      }
    }, 800);
  };

  const handleWorkspaceFinish = (e) => {
    e?.preventDefault?.();
    if (!workspace.trim()) {
      setErr('请为您的工作区取个名字');
      return;
    }
    setLoading(true);
    setTimeout(() => {
      // Remember this user for next time
      const known = JSON.parse(localStorage.getItem('fiq-known-users') || '[]');
      if (!known.includes(identifier)) {
        known.push(identifier);
        localStorage.setItem('fiq-known-users', JSON.stringify(known));
      }
      setLoading(false);
      setStep('done');
    }, 600);
  };

  const handleSkip = () => {
    // Skip workspace name → just mark known and go done
    const known = JSON.parse(localStorage.getItem('fiq-known-users') || '[]');
    if (!known.includes(identifier)) {
      known.push(identifier);
      localStorage.setItem('fiq-known-users', JSON.stringify(known));
    }
    setStep('done');
  };

  const handleBack = () => {
    setErr('');
    if (step === 'verify') {
      setStep('identify');
      setCode(['', '', '', '', '', '']);
    }
  };

  const resetDemo = () => {
    localStorage.removeItem('fiq-known-users');
    setStep('identify');
    setIdentifier('');
    setCode(['', '', '', '', '', '']);
    setWorkspace('');
    setDisplayName('');
    setSsoUser(null);
    setIsFirstTime(false);
    setErr('');
  };

  // Tweaks panel
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e?.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const isSplit  = tweaks.layout === 'split';
  const isCenter = tweaks.layout === 'centered';
  const isHero   = tweaks.layout === 'hero';

  // ── Card content based on step ──────────────
  const maskedIdentifier = method === 'email'
    ? identifier.replace(/^(.{2}).*(@.*)$/, '$1***$2')
    : identifier.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');

  const stepIdentify = (
    <>
      <div className="sp-login-head">
        <div>
          <h2 className="sp-login-title">登录 / 注册</h2>
          <p className="sp-login-sub">输入邮箱或手机号,获取验证码即可一键进入</p>
        </div>
        {tweaks.showProductSwitcher && (
          <div className="sp-login-prods" title="账号通用于以下产品">
            {[
              { l: 'R', c: '#1677FF' }, { l: 'F', c: '#8B5CF6' }, { l: 'P', c: '#10B981' }
            ].map((p, i) => (
              <span key={i} className="sp-login-prod mono" style={{ background: p.c }}>{p.l}</span>
            ))}
          </div>
        )}
      </div>

      <div className="sp-login-pill" role="tablist">
        <button role="tab" className={method === 'email' ? 'on' : ''}
          onClick={() => { setMethod('email'); setIdentifier(''); setErr(''); }}>邮箱</button>
        <button role="tab" className={method === 'phone' ? 'on' : ''}
          onClick={() => { setMethod('phone'); setIdentifier(''); setErr(''); }}>手机</button>
        <span className="sp-login-pill-thumb" style={{ transform: method === 'phone' ? 'translateX(100%)' : 'translateX(0)' }}/>
      </div>

      <form onSubmit={handleSendCode} className="sp-login-form">
        {method === 'email' ? (
          <Field label="工作邮箱" req v={identifier} on={setIdentifier}
            ph="you@company.com" type="email"/>
        ) : (
          <div className="sp-form-row">
            <label className="sp-form-label">手机号 <span style={{ color: 'var(--danger)' }}>*</span></label>
            <div className="sp-login-phone">
              <select className="sp-login-region" value={phoneRegion} onChange={e => setPhoneRegion(e.target.value)}>
                <option value="+86">🇨🇳 +86</option>
                <option value="+852">🇭🇰 +852</option>
                <option value="+853">🇲🇴 +853</option>
                <option value="+886">🇹🇼 +886</option>
                <option value="+1">🇺🇸 +1</option>
                <option value="+44">🇬🇧 +44</option>
                <option value="+81">🇯🇵 +81</option>
                <option value="+82">🇰🇷 +82</option>
                <option value="+65">🇸🇬 +65</option>
              </select>
              <input className="sp-form-input" type="tel" required
                value={identifier} onChange={e => setIdentifier(e.target.value.replace(/\D/g, '').slice(0, 11))}
                placeholder="请输入手机号" inputMode="numeric"/>
            </div>
          </div>
        )}

        {err && <div className="sp-login-err"><Icon name="bell" size={12}/> {err}</div>}

        <button type="submit" className="btn btn-primary btn-lg sp-login-submit" disabled={loading || !identifier}>
          {loading ? <span className="sp-login-spin"/> : null}
          {loading ? '发送中…' : '发送验证码'}
          {!loading && <Icon name="arrow" size={14}/>}
        </button>
      </form>

      <div className="sp-sso-divider"><span>或使用第三方登录</span></div>

      <button type="button" className="sp-sso-google" onClick={handleGoogle} disabled={loading}>
        <span className="sp-sso-mark-v2" style={{ background: '#fff' }}><SsoG/></span>
        <span>使用 Google 账号继续</span>
      </button>

      <div className="sp-login-legal">
        登录即表示同意 <a href="/about#terms">服务条款</a> 与 <a href="/about#privacy">隐私政策</a>
        {' '}· <a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer">津ICP备2023005990号-2</a>
      </div>
    </>
  );

  const stepVerify = (
    <>
      <div className="sp-login-head" style={{ alignItems: 'center' }}>
        <button type="button" className="sp-login-back-btn" onClick={handleBack} aria-label="返回">
          <Icon name="arrow" size={16} stroke={2}/>
        </button>
        <div style={{ flex: 1 }}>
          <h2 className="sp-login-title">输入验证码</h2>
          <p className="sp-login-sub">
            6 位验证码已发送至 <strong className="mono">{method === 'phone' ? phoneRegion + ' ' : ''}{maskedIdentifier}</strong>
          </p>
        </div>
      </div>

      <div className="sp-otp-row" onPaste={handleCodePaste}>
        {code.map((d, i) => (
          <input key={i}
            ref={el => codeRefs.current[i] = el}
            className="sp-otp-box"
            type="text" inputMode="numeric" maxLength={1}
            value={d}
            onChange={e => handleCodeInput(i, e.target.value)}
            onKeyDown={e => handleCodeKey(i, e)}
            aria-label={`验证码第 ${i + 1} 位`}/>
        ))}
      </div>

      {err && <div className="sp-login-err"><Icon name="bell" size={12}/> {err}</div>}

      <div className="sp-otp-resend">
        {countdown > 0 ? (
          <span style={{ color: 'var(--ink-4)' }}>
            <Icon name="clock" size={12}/> {countdown}s 后可重新发送
          </span>
        ) : (
          <a onClick={handleResend}>重新发送验证码</a>
        )}
      </div>

      <button type="button" className="btn btn-primary btn-lg sp-login-submit"
        onClick={() => handleVerify()} disabled={loading || code.some(d => !d)}>
        {loading ? <span className="sp-login-spin"/> : null}
        {loading ? '验证中…' : '验证并进入'}
        {!loading && <Icon name="arrow" size={14}/>}
      </button>

      <div className="sp-otp-hint">
        没有收到? <a onClick={handleBack}>更换{method === 'email' ? '邮箱' : '手机号'}</a>
        {' '}· <a href="/contact">联系我们</a>
      </div>
    </>
  );

  const stepWorkspace = (
    <>
      {ssoUser && (
        <div className="sp-ws-userpill">
          <div className="sp-ws-avatar">{ssoUser.avatar}</div>
          <div>
            <div className="sp-ws-name">{ssoUser.name}</div>
            <div className="sp-ws-email mono">{ssoUser.email}</div>
          </div>
          <span className="sp-ws-source">via Google</span>
        </div>
      )}

      <div className="sp-login-head" style={{ marginTop: ssoUser ? 16 : 0 }}>
        <div>
          <h2 className="sp-login-title">👋 给您的工作区取个名字</h2>
          <p className="sp-login-sub">
            一个工作区贯穿 Rates · Foresight · Prospect 三大产品,常见取法:公司名 / 团队名 / 项目名
          </p>
        </div>
      </div>

      <form onSubmit={handleWorkspaceFinish} className="sp-login-form">
        <div className="sp-form-row">
          <label className="sp-form-label">工作区名称 <span style={{ color: 'var(--danger)' }}>*</span></label>
          <div className="sp-ws-input-wrap">
            <input className="sp-form-input" autoFocus
              value={workspace}
              onChange={e => setWorkspace(e.target.value)}
              placeholder="如:全集物流、东方海运、Acme Logistics"
              maxLength={40}/>
            <span className="sp-ws-count mono">{workspace.length}/40</span>
          </div>
          {workspace && (
            <div className="sp-ws-preview">
              工作区地址: <span className="mono">app.freightiq.com/<strong>{workspace.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-').replace(/^-|-$/g, '') || 'workspace'}</strong></span>
            </div>
          )}
        </div>

        {!ssoUser && (
          <div className="sp-form-row">
            <label className="sp-form-label">您的称呼 <span style={{ color: 'var(--ink-5)', fontWeight: 400 }}>(可跳过)</span></label>
            <input className="sp-form-input"
              value={displayName} onChange={e => setDisplayName(e.target.value)}
              placeholder="如:王经理 / Alice"/>
          </div>
        )}

        {err && <div className="sp-login-err"><Icon name="bell" size={12}/> {err}</div>}

        <button type="submit" className="btn btn-primary btn-lg sp-login-submit" disabled={loading}>
          {loading ? <span className="sp-login-spin"/> : null}
          {loading ? '创建中…' : '进入工作区'}
          {!loading && <Icon name="arrow" size={14}/>}
        </button>

        <button type="button" className="sp-login-skip" onClick={handleSkip}>
          稍后再说,先进去看看
        </button>
      </form>

      <div className="sp-login-legal">
        您可以稍后在 <strong>设置 · 工作区</strong> 中修改名称与权限
        {' '}· <a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer">津ICP备2023005990号-2</a>
      </div>
    </>
  );

  const stepDone = (
    <div className="sp-login-done">
      <div className="sp-login-done-icon">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 6 9 17l-5-5"/>
        </svg>
      </div>
      <h2 className="sp-login-title" style={{ textAlign: 'center' }}>
        {isFirstTime ? '工作区创建成功' : '欢迎回来'}
      </h2>
      <p className="sp-login-sub" style={{ textAlign: 'center', marginTop: 8 }}>
        {workspace ? <>正在进入 <strong>{workspace}</strong>…</> : '正在跳转到您的工作台…'}
      </p>
      <div className="sp-login-done-actions">
        <a href={FIQ_APP_LINKS.rates} target="_blank" rel="noopener noreferrer" className="btn btn-primary btn-lg">
          进入 Rates 运价 <Icon name="arrow" size={14}/>
        </a>
        <a href={FIQ_APP_LINKS.foresight} target="_blank" rel="noopener noreferrer" className="btn btn-ghost btn-lg">
          进入 Foresight 预测
        </a>
        <a href={FIQ_APP_LINKS.prospect} target="_blank" rel="noopener noreferrer" className="btn btn-ghost btn-lg">
          进入 Prospect 拓客
        </a>
        <a href="/workspace" className="btn btn-ghost btn-lg">
          进入项目工作台
        </a>
      </div>
      <button type="button" onClick={resetDemo} className="sp-login-reset">
        🔄 重置 Demo(再次体验首次登录)
      </button>
    </div>
  );

  const formCard = (
    <div className={`sp-login-card ${isCenter ? 'card' : ''}`}>
      {step === 'identify' && stepIdentify}
      {step === 'verify' && stepVerify}
      {step === 'workspace' && stepWorkspace}
      {step === 'done' && stepDone}
    </div>
  );

  return (
    <section className={`sp-login-v2 sp-login-v2-${tweaks.layout} sp-login-theme-${tweaks.brandTheme}`}>
      <div className="sp-login-utility">
        <a href="/" className="sp-login-back">
          <Icon name="arrow" size={14}/> 返回官网
        </a>
        <div className="sp-login-util-right">
          <div className="sp-login-lang">
            <span>🌐</span>
            <select defaultValue="zh-CN" aria-label="语言">
              <option value="zh-CN">简体中文</option>
              <option value="en">English</option>
            </select>
          </div>
          <span className="sp-login-help">
            需要帮助? <a href="/contact">联系我们</a>
          </span>
        </div>
      </div>

      {isHero && (<>
        <LoginBrandPanel theme={tweaks.brandTheme}/>
        <div className="sp-login-hero-form-wrap">{formCard}</div>
      </>)}

      {isSplit && (
        <div className="sp-login-split">
          <LoginBrandPanel theme={tweaks.brandTheme}/>
          <main className="sp-login-formpane">
            <div className="sp-login-formpane-inner">{formCard}</div>
          </main>
        </div>
      )}

      {isCenter && (
        <div className="sp-login-center">
          <div className="sp-login-center-bg"/>
          <div className="sp-login-center-inner">
            <a href="/" className="logo" style={{ marginBottom: 24, justifyContent: 'center' }}>
              <span className="logo-mark"/> 全集
            </a>
            {formCard}
          </div>
        </div>
      )}

      {tweaksOpen && (
        <div className="sp-login-tweaks">
          <div className="sp-login-tweaks-head">
            <strong>Tweaks</strong>
            <button onClick={() => { setTweaksOpen(false); window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*'); }}>×</button>
          </div>
          <div className="sp-login-tweaks-body">
            <div className="sp-login-tweak-sec">
              <div className="sp-login-tweak-lbl">布局</div>
              <div className="sp-login-tweak-seg">
                {[{v:'split',l:'分屏'},{v:'centered',l:'居中'},{v:'hero',l:'Hero'}].map(o => (
                  <button key={o.v} className={tweaks.layout === o.v ? 'on' : ''} onClick={() => setTweak('layout', o.v)}>{o.l}</button>
                ))}
              </div>
            </div>
            <div className="sp-login-tweak-sec">
              <div className="sp-login-tweak-lbl">品牌主题</div>
              <div className="sp-login-tweak-seg">
                {[{v:'ocean',l:'海蓝'},{v:'night',l:'深夜'},{v:'sunset',l:'日落'}].map(o => (
                  <button key={o.v} className={tweaks.brandTheme === o.v ? 'on' : ''} onClick={() => setTweak('brandTheme', o.v)}>{o.l}</button>
                ))}
              </div>
            </div>
            <div className="sp-login-tweak-sec">
              <label className="sp-login-tweak-toggle">
                <input type="checkbox" checked={tweaks.showProductSwitcher}
                  onChange={e => setTweak('showProductSwitcher', e.target.checked)}/>
                显示产品矩阵标记
              </label>
            </div>
            <div className="sp-login-tweak-sec">
              <button className="sp-login-tweak-reset" onClick={resetDemo}>🔄 重置首次登录状态</button>
            </div>
          </div>
        </div>
      )}
    </section>
  );
};

// ---- Inline SSO brand glyphs ----
const SsoG = () => (
  <svg width="14" height="14" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
);
const SsoM = () => (
  <svg width="13" height="13" viewBox="0 0 23 23"><path fill="#f25022" d="M0 0h11v11H0z"/><path fill="#7fba00" d="M12 0h11v11H12z"/><path fill="#00a4ef" d="M0 12h11v11H0z"/><path fill="#ffb900" d="M12 12h11v11H12z"/></svg>
);
const SsoW = () => <span style={{ fontWeight: 700, fontSize: 11 }}>企</span>;
const SsoF = () => <span style={{ fontWeight: 700, fontSize: 11 }}>飞</span>;
const Eye = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>
);
const EyeOff = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19c-7 0-10-7-10-7a19.43 19.43 0 0 1 4.06-5.94M9.9 4.24A10.94 10.94 0 0 1 12 4c7 0 10 7 10 7a19.4 19.4 0 0 1-2.18 3.19m-5.32 1.27a3 3 0 1 1-4.24-4.24"/><line x1="2" y1="2" x2="22" y2="22"/></svg>
);

const PwStrength = ({ value = '' }) => {
  const score = React.useMemo(() => {
    let s = 0;
    if (value.length >= 8) s++;
    if (/[A-Z]/.test(value)) s++;
    if (/[0-9]/.test(value)) s++;
    if (/[^A-Za-z0-9]/.test(value)) s++;
    return s;
  }, [value]);
  if (!value) return null;
  const labels = ['很弱', '一般', '良好', '强', '极强'];
  const colors = ['#EF4444', '#F59E0B', '#F59E0B', '#10B981', '#059669'];
  return (
    <div className="sp-login-strength">
      <div className="sp-login-strength-bars">
        {[0,1,2,3].map(i => (
          <span key={i} style={{ background: i < score ? colors[score - 1] : 'var(--line)' }}/>
        ))}
      </div>
      <span style={{ color: colors[score - 1] || 'var(--ink-5)' }}>{labels[score]}</span>
    </div>
  );
};

Object.assign(window, { PageHero, AboutPage, ContactPage, SolutionsPage, BlogPage, LoginPage, Field });
