import { useEffect, useState, type FormEvent, type MouseEvent } from 'react'
import boyaLogo from './assets/boya-logo.png'
import './OfficialHomePage.css'

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'

const capabilities: Array<[string, string, string]> = [
  ['结构化量表体系', '覆盖症状自评、情绪、人格、危机识别四大类核心量表，均经临床团队针对中文语境与本土数据校准。', '30+ 套量表 · 支持按场景组合发放'],
  ['结构化报告', '报告同时输出指标分数、维度解读、风险标签与处置建议，关键结果触发人工复核，可生成 PDF / Word / Excel。', '个人版 / 团体版 两类封面与模板'],
  ['项目化运营', '多项目隔离，独立访问路径与项目管理员，支持批量邀请码、按组织或部门拆分、按项目导出。', '多项目并行 · 数据互不可见'],
  ['合规与审计', '端到端 TLS、敏感数据脱敏、全链路审计日志，面向个人信息保护和数据安全要求设计。', '可选私有化部署 · 数据不出域'],
  ['团体分析', '支持按维度、人群、时间序列交叉分析，自动识别高风险群体，输出可用于汇报的可视化指标。', '分组对比 / 趋势复盘'],
  ['临床复核与回访', '对临界与异常结果，可转入持证心理咨询师复核队列，支持一对一陪伴介入与回访闭环。', '持证咨询师一线经验支持'],
]

const assessments: Array<[string, string, string, string, string]> = [
  ['SCL-90', '症状自评量表', 'Symptom Checklist-90', '9 大症状维度的全面筛查，适合作为整体心理健康状态评估的入口。', '90 题 · 约 20 分钟'],
  ['SAS', '焦虑自评量表', 'Self-Rating Anxiety Scale', '面向焦虑情绪状态的快速筛查，适合纳入年度体检与压力监测流程。', '20 题 · 约 5 分钟'],
  ['SDS', '抑郁自评量表', 'Self-Rating Depression Scale', '面向抑郁情绪状态的快速筛查，临床场景中与 SAS 常作为组合使用。', '20 题 · 约 5 分钟'],
]

const flows: Array<[string, string, string]> = [
  ['01', '项目配置', '由平台超级管理员创建项目，再由项目管理员配置邀请码、协议版本与参测人员。'],
  ['02', '参测作答', '参测人通过项目 slug 进入独立空间，在标准化环境下完成全部题项。'],
  ['03', '评分与复核', '系统按量表规则评分，异常或临界结果进入人工复核与陪伴流程。'],
  ['04', '报告与归档', '输出结构化报告，写入审计日志，支持项目级全量导出。'],
]

const audiences: Array<[string, string[]]> = [
  ['政府与公共机构', ['公务员心理健康年度筛查', '突发事件后人员心理评估', '重大会议人员状态监测']],
  ['大型企业', ['员工 EAP 项目入口', '高强度岗位定期评估', '组织变革期情绪监测']],
  ['高校与教育机构', ['新生入学心理普查', '学业危机预警', '毕业季压力管理']],
  ['医疗与卫生机构', ['临床心理科入院评估', '慢病管理心理共病筛查', '医务人员压力监测']],
]

function OfficialHomePage() {
  const [appointmentOpen, setAppointmentOpen] = useState(false)
  const [appointmentMessage, setAppointmentMessage] = useState('')
  const [submittingAppointment, setSubmittingAppointment] = useState(false)
  const [appointmentForm, setAppointmentForm] = useState({
    name: '',
    organization: '',
    phone: '',
    wechat: '',
    city: '',
  })

  useEffect(() => {
    const revealObserver = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return
        entry.target.classList.add('show')
        revealObserver.unobserve(entry.target)
      })
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' })

    document.querySelectorAll('.official-home .reveal').forEach((item) => revealObserver.observe(item))

    const animateCount = (element: Element, target: number) => {
      const duration = 1200
      const start = performance.now()
      const ease = (value: number) => 1 - Math.pow(1 - value, 3)
      const step = (now: number) => {
        const progress = Math.min(1, (now - start) / duration)
        const value = Math.floor(ease(progress) * target)
        element.textContent = value.toLocaleString('en-US')
        if (progress < 1) requestAnimationFrame(step)
        else element.textContent = target.toLocaleString('en-US')
      }
      requestAnimationFrame(step)
    }

    const countObserver = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return
        entry.target.querySelectorAll('[data-count]').forEach((item) => {
          animateCount(item, Number.parseInt(item.getAttribute('data-count') || '0', 10))
        })
        countObserver.unobserve(entry.target)
      })
    }, { threshold: 0.4 })

    document.querySelectorAll('.official-home .hero-meta, .official-home .stats').forEach((item) => countObserver.observe(item))

    return () => {
      revealObserver.disconnect()
      countObserver.disconnect()
    }
  }, [])

  const handleAnchorClick = (event: MouseEvent<HTMLAnchorElement>) => {
    const href = event.currentTarget.getAttribute('href')
    if (!href?.startsWith('#') || href.length < 2) return
    const target = document.querySelector(href)
    if (!target) return
    event.preventDefault()
    const top = target.getBoundingClientRect().top + window.scrollY - 60
    window.scrollTo({ top, behavior: 'smooth' })
  }

  const openAppointment = () => {
    setAppointmentMessage('')
    setAppointmentOpen(true)
  }

  const submitAppointment = async (event: FormEvent) => {
    event.preventDefault()
    setSubmittingAppointment(true)
    setAppointmentMessage('')
    try {
      const response = await fetch(`${API_BASE}/appointments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...appointmentForm, sourcePath: window.location.pathname || '/' }),
      })
      const raw = await response.text()
      const data = raw ? JSON.parse(raw) : null
      if (!response.ok) throw new Error(data?.message || '预约提交失败')
      setAppointmentMessage('预约已提交，我们会尽快联系您。')
      setAppointmentForm({ name: '', organization: '', phone: '', wechat: '', city: '' })
    } catch (error) {
      setAppointmentMessage(error instanceof Error ? error.message : '预约提交失败')
    } finally {
      setSubmittingAppointment(false)
    }
  }

  return (
    <main className="official-home">
      <nav className="official-topbar">
        <a className="official-brand" href="/" aria-label="博雅心理测评首页">
          <img src={boyaLogo} alt="博雅" />
        </a>
        <div className="official-nav-actions">
          <div className="official-nav-links">
            <a href="#capability" onClick={handleAnchorClick}>平台能力</a>
            <a href="#bank" onClick={handleAnchorClick}>量表矩阵</a>
            <a href="#flow" onClick={handleAnchorClick}>测评流程</a>
            <a href="#compliance" onClick={handleAnchorClick}>合规与安全</a>
            <a href="#audience" onClick={handleAnchorClick}>服务对象</a>
          </div>
        </div>
      </nav>

      <section className="official-hero">
        <div className="official-hero-copy">
          <h1>面向政企与机构的<br /><span>专业心理测评</span>平台</h1>
          <p className="official-lead">
            围绕国际会议、政府机关、大型企业、高校与医疗机构的真实使用场景，
            博雅提供国际通用量表、本土常模、结构化报告与可审计的数据治理，
            帮助组织识别压力水平、适应状态与支持需求。
          </p>
          <div className="official-hero-actions">
            <button className="official-hero-cta" type="button" onClick={openAppointment}>预约演示</button>
          </div>
          <div className="hero-meta">
            <div><b data-count="12">0</b>临床心理研究</div>
            <div><b><span data-count="30">0</span><span className="u">+</span></b>国际通用量表</div>
            <div><b><span data-count="50000">0</span><span className="u">+</span></b>累计完成测评</div>
            <div><b><span data-count="120">0</span><span className="u">+</span></b>合作机构</div>
          </div>
        </div>
        <aside className="official-cred">
          <div className="official-cred-box">
            <div className="official-cred-title">平台亮点</div>
            <ul>
              <li>覆盖 SCL-90 / SAS / SDS 等核心量表，按本土语境复核</li>
              <li>独立项目空间，支持私有化部署与多租户隔离</li>
              <li>结构化测评报告，审计日志可追溯</li>
              <li>支持团体测评、批量邀请码、项目级导出</li>
            </ul>
          </div>
        </aside>
      </section>

      <div className="official-wrap official-stats-wrap">
        <div className="stats reveal">
          <div><div className="stat-num"><span data-count="12">0</span><span className="u">年</span></div><div className="stat-label">临床心理研究与服务经验</div></div>
          <div><div className="stat-num"><span data-count="30">0</span><span className="u">+ 套</span></div><div className="stat-label">国际通用心理测评量表</div></div>
          <div><div className="stat-num"><span data-count="50000">0</span><span className="u">+ 人次</span></div><div className="stat-label">累计完成的标准化测评</div></div>
          <div><div className="stat-num"><span data-count="99">0</span><span className="u">.9%</span></div><div className="stat-label">数据完整性与可审计率</div></div>
        </div>
      </div>

      <section className="official-block" id="capability">
        <div className="official-wrap">
          <div className="official-section-head">
            <h2 className="reveal">平台能力</h2>
            <p className="reveal d1">以标准化、可治理为核心，在量表、报告、流程、合规四个方向同时为机构提供能力支撑。</p>
          </div>
          <div className="official-capability">
            {capabilities.map((item, index) => (
              <article className={`reveal d${index % 3}`} key={item[0]}>
                <div className="official-cap-index">{String(index + 1).padStart(2, '0')}</div>
                <h3>{item[0]}</h3>
                <p>{item[1]}</p>
                <div className="official-cap-meta">{item[2]}</div>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="official-block alt" id="bank">
        <div className="official-wrap">
          <div className="official-section-head">
            <h2 className="reveal">量表矩阵</h2>
            <p className="reveal d1">以下为平台内最常被机构启用的量表，可按机构场景组合配置。</p>
          </div>
          <div className="official-bank reveal">
            <div className="official-bank-head">
              <div>量表代码</div><div>名称</div><div>主要用途</div><div>题量 · 耗时</div>
            </div>
            {assessments.map((item) => (
              <div className="official-bank-row" key={item[0]}>
                <div className="official-bank-code">{item[0]}</div>
                <div className="official-bank-name">{item[1]}<small>{item[2]}</small></div>
                <div className="official-bank-desc">{item[3]}</div>
                <div className="official-bank-num">{item[4]}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="official-block" id="flow">
        <div className="official-wrap">
          <div className="official-section-head">
            <h2 className="reveal">测评流程</h2>
            <p className="reveal d1">每一步都对应平台中可追溯的操作记录，机构端可在后台实时看到当前进度。</p>
          </div>
          <div className="official-flow">
            {flows.map((item, index) => (
              <article className={`reveal d${index}`} key={item[0]}>
                <div className="official-step-num">{item[0]}</div>
                <h3>{item[1]}</h3>
                <p>{item[2]}</p>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="official-block alt" id="compliance">
        <div className="official-wrap">
          <div className="official-section-head">
            <h2 className="reveal">合规与安全</h2>
            <p className="reveal d1">我们将数据安全视为平台核心能力，而非附加项。所有数据处理流程均面向个人信息保护和数据安全合规设计。</p>
          </div>
          <div className="official-compliance">
            <article className="reveal"><h3>数据安全</h3><p>端到端 TLS 传输、敏感字段后台脱敏展示，支持密钥分层托管与轮换。</p><span>符合等保与审计要求</span></article>
            <article className="reveal d1"><h3>个人信息保护</h3><p>明确告知、最小必要、可撤回的同意机制，完整保留每一次协议版本记录。</p><span>符合个人信息安全规范</span></article>
            <article className="reveal d2"><h3>部署形态</h3><p>公有云 SaaS、专有 VPC、机构自有 IDC 三种形态均可交付。</p><span>支持数据不出机构内网</span></article>
          </div>
        </div>
      </section>

      <section className="official-block" id="audience">
        <div className="official-wrap">
          <div className="official-section-head">
            <h2 className="reveal">服务对象</h2>
            <p className="reveal d1">平台已在多种典型组织场景中落地，可根据既有最佳实践快速配置。</p>
          </div>
          <div className="official-audience">
            {audiences.map((item, index) => (
              <article className={`reveal d${index}`} key={item[0]}>
                <h3>{item[0]}</h3>
                <ul>{item[1].map((text) => <li key={text}>{text}</li>)}</ul>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="official-cta" id="cta">
        <div className="official-wrap">
          <div>
            <h2>准备好把心理测评纳入你的组织流程？</h2>
            <p>我们可以基于你机构的真实场景，提供量表组合建议与试点方案。</p>
          </div>
          <button type="button" onClick={openAppointment}>预约演示</button>
        </div>
      </section>

      <footer className="official-footer">
        <div className="official-footer-grid">
          <section>
            <p>大连博雅人力资源咨询有限公司</p>
            <p>大连市大数据研究院</p>
            <p className="muted">面向政企与机构的专业心理测评平台</p>
          </section>
          <section><h3>平台</h3><a href="#capability" onClick={handleAnchorClick}>平台能力</a><a href="#bank" onClick={handleAnchorClick}>量表矩阵</a><a href="#flow" onClick={handleAnchorClick}>测评流程</a></section>
          <section><h3>联系我们</h3><p>商务合作：boyaxzgh@163.com</p><p>联系方式：0411-84791865</p><p>工作时间：周一至周五 09:00-18:00</p></section>
          <section><h3>机构信息</h3><p>博雅学业职业发展研究中心</p><p>大连市大数据研究院</p></section>
        </div>
        <div className="official-footer-bottom">© 2026 大连博雅人力资源咨询有限公司 · 大连市大数据研究院</div>
      </footer>

      {appointmentOpen && (
        <div className="official-modal-backdrop" onMouseDown={(event) => {
          if (event.target === event.currentTarget) setAppointmentOpen(false)
        }}>
          <section className="official-appointment-modal" role="dialog" aria-modal="true" aria-label="预约演示">
            <div className="official-modal-head">
              <div>
                <h2>预约演示</h2>
                <p>留下基本信息，我们会尽快联系你确认演示安排。</p>
              </div>
              <button type="button" onClick={() => setAppointmentOpen(false)}>关闭</button>
            </div>
            <form className="official-appointment-form" onSubmit={submitAppointment}>
              <label>姓名<input required value={appointmentForm.name} onChange={(event) => setAppointmentForm({ ...appointmentForm, name: event.target.value })} /></label>
              <label>机构<input required value={appointmentForm.organization} onChange={(event) => setAppointmentForm({ ...appointmentForm, organization: event.target.value })} /></label>
              <label>电话号<input required inputMode="tel" value={appointmentForm.phone} onChange={(event) => setAppointmentForm({ ...appointmentForm, phone: event.target.value })} /></label>
              <label>微信号<input required value={appointmentForm.wechat} onChange={(event) => setAppointmentForm({ ...appointmentForm, wechat: event.target.value })} /></label>
              <label>城市<input required value={appointmentForm.city} onChange={(event) => setAppointmentForm({ ...appointmentForm, city: event.target.value })} /></label>
              {appointmentMessage && <p className="official-appointment-message">{appointmentMessage}</p>}
              <div className="official-modal-actions">
                <button type="button" onClick={() => setAppointmentOpen(false)}>取消</button>
                <button className="official-submit" type="submit" disabled={submittingAppointment}>{submittingAppointment ? '提交中...' : '提交预约'}</button>
              </div>
            </form>
          </section>
        </div>
      )}
    </main>
  )
}

export default OfficialHomePage
