import { useEffect, useRef, useState } from 'react'
import { createRoot } from 'react-dom/client'
import './styles.css'
import BorderGlow from './BorderGlow'

const works = [
  { id:'01', title:'NEON CIRCUIT', category:'BRAND FILM / 3D', year:'2025', image:'', video:'/videos/neon-circuit-wechat-v2.mp4', preview:true, size:'wide' },
  { id:'02', title:'FUTURE FREQUENCY', category:'MOTION IDENTITY', year:'2024', image:'', video:'/videos/future-frequency.mp4', preview:true, size:'tall' },
  { id:'03', title:'LIMITLESS PLAY', category:'ESPORTS VISUAL', year:'2023', image:'', video:'/videos/limitless-play.mp4', preview:true, size:'tall' },
  { id:'04', title:'SIGNAL / 07', category:'TITLE SEQUENCE', year:'2022', image:'', video:'/videos/central-bank.mp4', preview:true, size:'wide' },
]

const strengths = [
  ['01', '动态叙事', '以节奏、镜头与情绪建立可被记住的视觉表达。', '↗'],
  ['02', '三维创作', '从概念到 C4D / Octane 渲染，完成具有空间感的世界。', '◇'],
  ['03', '品牌视觉', '将策略、识别与动态语言统一为清晰的品牌体验。', '◌'],
  ['04', '创意落地', '兼顾沟通、节奏与制作细节，让创意被准确实现。', '✳'],
]

function App() {
  const [menuOpen, setMenuOpen] = useState(false)
  const [active, setActive] = useState('首页')
  const [isFloatingNav, setIsFloatingNav] = useState(false)
  const [playingProject, setPlayingProject] = useState(null)
  const projectVideoRefs = useRef({})
  const nav = [['首页','home'],['经历','about'],['项目','work'],['能力','strengths']]

  useEffect(() => {
    const sections = [...document.querySelectorAll('[data-section]')]
    const observer = new IntersectionObserver((items) => {
      const hit = items.find((item) => item.isIntersecting)
      if (hit) setActive(hit.target.dataset.section)
    }, { rootMargin:'-45% 0px -45% 0px' })
    sections.forEach((section) => observer.observe(section))
    return () => observer.disconnect()
  }, [])

  useEffect(() => {
    document.documentElement.classList.add('motion-ready')
    const targets = [...document.querySelectorAll('.reveal-section')]
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-revealed')
          observer.unobserve(entry.target)
        }
      })
    }, { threshold: 0.16, rootMargin: '0px 0px -8%' })
    targets.forEach((target) => observer.observe(target))

    const parallax = [...document.querySelectorAll('.parallax-image')]
    let frame = 0
    const updateParallax = () => {
      frame = 0
      parallax.forEach((image) => {
        const rect = image.getBoundingClientRect()
        const progress = (innerHeight * .5 - (rect.top + rect.height * .5)) / innerHeight
        image.style.setProperty('--parallax-y', (progress * -5).toFixed(2) + '%')
      })
    }
    const requestParallax = () => { if (!frame) frame = requestAnimationFrame(updateParallax) }
    updateParallax()
    addEventListener('scroll', requestParallax, { passive:true })
    addEventListener('resize', requestParallax, { passive:true })
    return () => { observer.disconnect(); removeEventListener('scroll', requestParallax); removeEventListener('resize', requestParallax); if (frame) cancelAnimationFrame(frame) }
  }, [])

  useEffect(() => {
    let frame = 0
    const updateNav = () => {
      frame = 0
      setIsFloatingNav(window.scrollY >= window.innerHeight * 0.76)
    }
    const requestUpdate = () => { if (!frame) frame = requestAnimationFrame(updateNav) }
    updateNav()
    window.addEventListener('scroll', requestUpdate, { passive: true })
    return () => { window.removeEventListener('scroll', requestUpdate); if (frame) cancelAnimationFrame(frame) }
  }, [])

  const go = (id) => {
    document.getElementById(id)?.scrollIntoView({ behavior:'smooth' })
    setMenuOpen(false)
  }
  const playProject = (id) => {
    Object.entries(projectVideoRefs.current).forEach(([key, video]) => { if (key !== id) video?.pause() })
    setPlayingProject(id)
    requestAnimationFrame(() => projectVideoRefs.current[id]?.play().catch(() => {}))
  }

  return <main>
    <header className={'site-header ' + (isFloatingNav ? 'is-floating' : '')}>
      <button className="brand" type="button" onClick={() => go('home')} aria-label="返回首页">LC<span>®</span></button>
      <nav className={menuOpen ? 'nav-open' : ''}>
        {nav.map(([label,id]) => <button type="button" className={active === label ? 'active' : ''} onClick={() => go(id)} key={id}>{label}</button>)}
      </nav>
      <a className="header-contact" href="mailto:717943726@qq.com">LET'S TALK <b>↗</b></a>
      <button className="menu-button" type="button" onClick={() => setMenuOpen(!menuOpen)} aria-label="打开菜单">{menuOpen ? '×' : '☰'}</button>
    </header>

    <section className="hero hero-opening" id="home" data-section="首页">
      <video className="hero-video" autoPlay muted loop playsInline preload="metadata" poster="https://images.unsplash.com/photo-1634017839464-5c339ebe3cb4?auto=format&fit=crop&w=1800&q=90">
        <source src="https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260702_081042_df7202bf-bd80-4b2b-bbc6-1f09ba2870e9.mp4" type="video/mp4" />
      </video>
      <div className="hero-grid" />
      <div className="hero-gradient" />
      <p className="hero-side">MOTION / 3D / VISUAL DESIGN</p>
      <div className="opening-curtain" /><div className="hero-copy">
        <div className="hero-topline"><span>2015 — 2026</span><span>SELECTED PORTFOLIO</span></div>
        <p className="hero-label">李晨 / 动效设计师 &amp; 3D 设计师</p>
        <h1>LI CHEN<br /><i>SHOWREEL</i></h1>
        <p className="hero-intro">用动态、空间与想象力，<br />为品牌创造能被感知的视觉时刻。</p>
        <div className="hero-actions"><button type="button" onClick={() => go('work')}>EXPLORE WORK <b>↓</b></button><a href="mailto:717943726@qq.com">START A PROJECT <b>↗</b></a></div>
      </div>
      <div className="hero-code"><span>01 / 05</span><i /><span>SCROLL TO EXPLORE</span></div>
    </section>

    <section className="about section reveal-section" id="about" data-section="经历">
      <div className="layout">
        <p className="section-id">01 / ABOUT</p>
        <div className="about-layout">
          <div className="about-portrait"><img src="/images/li-chen-portrait-bw.jpg" alt="李晨个人肖像" /><span>AVAILABLE FOR<br />SELECTED PROJECTS</span></div>
          <div className="about-text">
            <p className="about-lead">你好，我是 <em>李晨</em>，一名关注质感、秩序与运动的动效 / 三维设计师。</p>
            <p>拥有十年以上视觉设计与项目执行经验，服务过电视栏目、品牌传播、娱乐内容及数字体验项目。擅长将策略转译成具备情绪、节奏和记忆点的视觉系统。</p>
            <a className="email-link" href="mailto:717943726@qq.com">717943726@qq.com <b>↗</b></a>
            <div className="data-row"><div><strong>10<span>+</span></strong><small>年行业经验</small></div><div><strong>40<span>+</span></strong><small>完成项目</small></div><div><strong>06</strong><small>核心工具</small></div></div>
          </div>
        </div>
      </div>
    </section>

    <section className="work section reveal-section" id="work" data-section="项目">
      <div className="layout">
        <div className="work-heading"><p className="section-id">02 / SELECTED WORKS</p><h2>精选<i>项目</i></h2><p>每一个画面，都是概念、技术和直觉共同产生的结果。<br />作品图片将在下一阶段替换为真实项目素材。</p></div>
        <div className="works-grid">{works.map((work) => <BorderGlow className={work.size + (playingProject === work.id ? ' is-playing' : '')} key={work.id}><article className="work-card">{work.video ? <><video ref={(node) => { projectVideoRefs.current[work.id] = node }} className="parallax-image project-video" src={work.preview || playingProject === work.id ? work.video : undefined} poster={work.preview ? undefined : work.image} preload={work.preview ? 'metadata' : 'none'} muted loop playsInline onPlay={() => setPlayingProject(work.id)} onPause={() => setPlayingProject(null)} onClick={(event) => { event.currentTarget.paused ? event.currentTarget.play() : event.currentTarget.pause() }} />{playingProject !== work.id && <button className="project-play" type="button" onClick={() => playProject(work.id)} aria-label="播放项目视频">▶</button>}</> : <img className="parallax-image" src={work.image} alt={work.title} loading="lazy" />}<div className="work-shadow" /><div className="work-meta"><span>{work.id}</span><span>{work.year}</span></div><div className="work-title"><p>{work.category}</p><h3>{work.title}</h3></div><button type="button" aria-label={'查看 ' + work.title}>↗</button></article></BorderGlow>)}</div>
      </div>
    </section>

    <section className="strengths section reveal-section" id="strengths" data-section="能力">
      <div className="layout">
        <div className="strengths-heading"><p className="section-id">03 / WHAT I DO</p><h2>让技术成为<br />想象力的<span>引力</span>。</h2></div>
        <div className="strength-grid">{strengths.map(([number,title,body,mark]) => <article className="strength-card" key={number}><span>{number}</span><b>{mark}</b><h3>{title}</h3><p>{body}</p><i>↗</i></article>)}</div>
        <div className="tools"><span>TOOLS I USE</span><p>AFTER EFFECTS <b>·</b> CINEMA 4D <b>·</b> OCTANE <b>·</b> PREMIERE <b>·</b> UNREAL ENGINE</p></div>
      </div>
    </section>

    <section className="contact reveal-section" id="contact">
      <div className="contact-orb" /><div className="contact-grid" />
      <div className="layout contact-content"><p><i /> LET'S CREATE SOMETHING MEMORABLE</p><h2>HAVE A<br /><i>VISION?</i></h2><a href="mailto:717943726@qq.com">717943726@qq.com <b>↗</b></a><footer><span>© 2026 LI CHEN. ALL RIGHTS RESERVED.</span><span>CHENGDU, CHINA / 177 4422 0926</span></footer></div>
    </section>
  </main>
}

createRoot(document.getElementById('root')).render(<App />)
