import { AnimatePresence, motion } from 'framer-motion'
import { useEffect, useState } from 'react'
import { assetPath } from './assetPath'
import { StudioLogo } from './components/StudioLogo'
import type { IntroPhase, Locale, LocalizedText } from './types'
import { reveal, siteCopy, studioFacts, teamRoles, projectModules, workflowPoints, proofCards, contactInfo } from './data'
import { IntroOverlay } from './components/IntroOverlay'
import { SignalMiniGame } from './components/SignalMiniGame'

function t(locale: Locale, text: LocalizedText) {
  return text[locale]
}

function multiline(text: string) {
  return text.split('\n').map((line, index) => (
    <span key={`${line}-${index}`}>
      {line}
      {index < text.split('\n').length - 1 ? <br /> : null}
    </span>
  ))
}

function Eyebrow({ children }: { children: string }) {
  return (
    <span className="eyebrow">
      <span className="eyebrow-line" aria-hidden="true" />
      <span className="eyebrow-copy">{children}</span>
    </span>
  )
}

function HeroTitle({ title }: { title: string }) {
  const lines = title.split(/\s+/).length > 2 ? title.split(/\s+/) : title.split('\n')
  const rendered = lines.length > 1 ? lines : title.split(/(?<=夜)(?=工)|(?<=No Stay)(?= Night Studio)/)
  return (
    <h1 className="hero-title-glitch" aria-label="止夜工作室">
      <span className="hero-title-main">
        {rendered.map((line, index) => (
          <span key={`${line}-${index}`}>
            {line}
            {index < rendered.length - 1 ? <br /> : null}
          </span>
        ))}
      </span>
    </h1>
  )
}

function ProofCarousel({ locale }: { locale: Locale }) {
  const [activeIndex, setActiveIndex] = useState(0)
  const [direction, setDirection] = useState(1)
  const activeCard = proofCards[activeIndex]

  const showCard = (nextIndex: number) => {
    const total = proofCards.length
    const normalized = (nextIndex + total) % total
    setDirection(normalized > activeIndex || (activeIndex === total - 1 && normalized === 0) ? 1 : -1)
    setActiveIndex(normalized)
  }

  useEffect(() => {
    const autoTimer = window.setInterval(() => {
      setDirection(1)
      setActiveIndex((current) => (current + 1) % proofCards.length)
    }, 4600)

    return () => window.clearInterval(autoTimer)
  }, [])

  return (
    <div className="proof-carousel">
      <div className="proof-carousel-stage">
        <div className="proof-carousel-media">
          <AnimatePresence mode="wait" initial={false}>
            <motion.img
              key={activeCard.image}
              src={activeCard.image}
              alt={t(locale, activeCard.alt)}
              custom={direction}
              initial={{ opacity: 0, scale: 1.06, x: direction > 0 ? 48 : -48 }}
              animate={{ opacity: 1, scale: 1, x: 0 }}
              exit={{ opacity: 0, scale: 0.98, x: direction > 0 ? -36 : 36 }}
              transition={{ duration: 0.62, ease: [0.22, 1, 0.36, 1] }}
            />
          </AnimatePresence>
          <div className="proof-carousel-media-glow" aria-hidden="true" />
        </div>
        <div className="proof-carousel-copy">
          <AnimatePresence mode="wait" initial={false}>
            <motion.div
              key={t(locale, activeCard.title)}
              className="proof-carousel-copy-inner"
              custom={direction}
              initial={{ opacity: 0, y: 26, x: direction > 0 ? 18 : -18 }}
              animate={{ opacity: 1, y: 0, x: 0 }}
              exit={{ opacity: 0, y: -18, x: direction > 0 ? -12 : 12 }}
              transition={{ duration: 0.44, ease: [0.22, 1, 0.36, 1] }}
            >
              <span>{activeCard.tag}</span>
              <strong>{t(locale, activeCard.title)}</strong>
              <p>{t(locale, activeCard.note)}</p>
            </motion.div>
          </AnimatePresence>
          <div className="proof-carousel-controls">
            <button type="button" className="proof-nav-button" onClick={() => showCard(activeIndex - 1)} aria-label={t(locale, siteCopy.proof.previous)}>
              {t(locale, siteCopy.proof.previous)}
            </button>
            <div className="proof-carousel-progress" aria-hidden="true">
              {proofCards.map((card, index) => (
                <span key={t(locale, card.title)} className={index === activeIndex ? 'is-active' : ''} />
              ))}
            </div>
            <button type="button" className="proof-nav-button" onClick={() => showCard(activeIndex + 1)} aria-label={t(locale, siteCopy.proof.next)}>
              {t(locale, siteCopy.proof.next)}
            </button>
          </div>
        </div>
      </div>

      <div className="proof-carousel-rail" role="tablist" aria-label={t(locale, siteCopy.proof.railLabel)}>
        {proofCards.map((card, index) => (
          <button
            key={t(locale, card.title)}
            type="button"
            role="tab"
            aria-selected={index === activeIndex}
            className={`proof-rail-card${index === activeIndex ? ' is-active' : ''}`}
            onClick={() => showCard(index)}
          >
            <div className="proof-rail-thumb">
              <img src={card.image} alt="" />
            </div>
            <div className="proof-rail-copy">
              <span>{card.tag}</span>
              <strong>{t(locale, card.title)}</strong>
            </div>
          </button>
        ))}
      </div>
    </div>
  )
}

const INTRO_CLOSE_AT_MS = 2200

function App() {
  const [introPhase, setIntroPhase] = useState<IntroPhase>('intro')
  const [locale, setLocale] = useState<Locale>('zh')
  const workflowBoardAsset = assetPath('assets/workflow-board.jpg')

  const requestCloseIntro = () => {
    setIntroPhase((current) => (current === 'intro' ? 'closing' : current))
  }

  useEffect(() => {
    const closeTimer = window.setTimeout(() => requestCloseIntro(), INTRO_CLOSE_AT_MS)
    return () => { window.clearTimeout(closeTimer) }
  }, [])

  useEffect(() => {
    const prev = document.body.style.overflow
    document.body.style.overflow = introPhase === 'hidden' ? '' : 'hidden'
    return () => { document.body.style.overflow = prev }
  }, [introPhase])

  const handleIntroComplete = () => {
    setIntroPhase('hidden')
  }

  useEffect(() => {
    if (introPhase === 'hidden') return
    const onWheel = (e: WheelEvent) => {
      if (e.deltaY > 0) {
        requestCloseIntro()
      }
    }
    window.addEventListener('wheel', onWheel, { passive: true, once: true })
    return () => window.removeEventListener('wheel', onWheel)
  }, [introPhase])

  return (
    <div className="site-root">
      <IntroOverlay phase={introPhase} onSkip={requestCloseIntro} onComplete={handleIntroComplete} />

      <div className="page-shell page-shell-visible">
        <header className="topbar">
          <a className="brand" href="#hero">
            <span className="brand-mark">
              <StudioLogo title="止夜工作室 logo" />
            </span>
            <span className="brand-copy">
              <strong>止夜工作室</strong>
              <span>No Stay Night Studio</span>
            </span>
          </a>
          <div className="topbar-actions">
            <nav className="nav" aria-label={locale === 'zh' ? '主导航' : 'Main navigation'}>
              <a href="#about">{t(locale, siteCopy.nav.about)}</a>
              <a href="#project">{t(locale, siteCopy.nav.project)}</a>
              <a href="#workflow">{t(locale, siteCopy.nav.workflow)}</a>
              <a href="#proof">{t(locale, siteCopy.nav.proof)}</a>
              <a href="#contact">{t(locale, siteCopy.nav.contact)}</a>
            </nav>
            <div className="locale-switch" aria-label={locale === 'zh' ? '语言切换' : 'Language switch'}>
              <button type="button" className={locale === 'zh' ? 'is-active' : ''} onClick={() => setLocale('zh')}>中</button>
              <button type="button" className={locale === 'en' ? 'is-active' : ''} onClick={() => setLocale('en')}>EN</button>
            </div>
          </div>
        </header>

        <main>
          <motion.section className="section hero content-hero" id="hero" {...reveal}>
            <div className="content-hero-layout">
              <div className="hero-side-rail" aria-hidden="true">
                <span className="hero-rail-text">NO STAY NIGHT STUDIO</span>
                <span className="hero-rail-line" />
                <span className="hero-rail-year">EST. 2024</span>
              </div>

              <div className="content-hero-copy">
                <Eyebrow>{t(locale, siteCopy.hero.eyebrow)}</Eyebrow>
                <HeroTitle title={t(locale, siteCopy.hero.title)} />
                <p className="content-hero-tagline">{t(locale, siteCopy.hero.tagline)}</p>
                <p className="content-hero-description">
                  {t(locale, siteCopy.hero.description)}
                </p>
                <div className="hero-meta-strip">
                  {siteCopy.hero.meta.map((item) => (
                    <span key={t(locale, item)}>{t(locale, item)}</span>
                  ))}
                </div>
              </div>

              <div className="content-hero-visual" aria-hidden="true">
                <StudioLogo className="hero-logo-display" title="" />
              </div>
            </div>
          </motion.section>

          <motion.section className="section section-about" id="about" {...reveal}>
            <div className="about-header">
              <span className="section-index">01</span>
              <Eyebrow>{t(locale, siteCopy.about.eyebrow)}</Eyebrow>
              <h2>{multiline(t(locale, siteCopy.about.heading))}</h2>
            </div>
            <div className="about-statement-full">
              <p className="statement-lead">{t(locale, siteCopy.about.statementLead)}</p>
              <div className="about-body-cols">
                {siteCopy.about.body.map((paragraph) => (
                  <p key={t(locale, paragraph)}>{t(locale, paragraph)}</p>
                ))}
              </div>
            </div>
            <div className="about-data-strip">
              {studioFacts.map((fact) => (
                <div key={t(locale, fact.label)} className="data-cell">
                  <span className="data-label">{t(locale, fact.label)}</span>
                  <strong className="data-value">{t(locale, fact.value)}</strong>
                  <p className="data-note">{t(locale, fact.note)}</p>
                </div>
              ))}
              <div className="data-divider" />
              {teamRoles.map((role) => (
                <div key={t(locale, role.role)} className="data-cell">
                  <span className="data-label">{t(locale, role.role)}</span>
                  <strong className="data-value">{t(locale, role.count)}</strong>
                  <p className="data-note">{t(locale, role.note)}</p>
                </div>
              ))}
            </div>
          </motion.section>

          <motion.section className="section section-project" id="project" {...reveal}>
            <div className="project-masthead">
              <span className="section-index">02</span>
              <div className="project-masthead-copy">
                <Eyebrow>{t(locale, siteCopy.project.eyebrow)}</Eyebrow>
                <h2>{t(locale, siteCopy.project.title)}</h2>
                <p className="project-sub">{t(locale, siteCopy.project.subtitle)}</p>
              </div>
              <div className="project-status-strip">
                {siteCopy.project.status.map((item) => (
                  <span key={t(locale, item)}>{t(locale, item)}</span>
                ))}
              </div>
            </div>
            <div className="project-modules-row">
              {projectModules.map((item) => (
                <article key={item.index} className="project-module-item">
                  <span className="module-index">{item.index}</span>
                  <h3>{t(locale, item.title)}</h3>
                  <p>{t(locale, item.note)}</p>
                </article>
              ))}
            </div>
            <SignalMiniGame locale={locale} />
          </motion.section>

          <motion.section className="section section-workflow" id="workflow" {...reveal}>
            <div className="workflow-header">
              <span className="section-index">03</span>
              <Eyebrow>{t(locale, siteCopy.workflow.eyebrow)}</Eyebrow>
            </div>
            <div className="workflow-asymmetric">
              <div className="workflow-text-col">
                <h2>{t(locale, siteCopy.workflow.heading)}</h2>
                <div className="workflow-points">
                  {workflowPoints.map((item) => (
                    <div key={`${item.id}-${locale}`} className="workflow-point">
                      <span className="wp-id">{item.id}</span>
                      <div>
                        <h3>{t(locale, item.title)}</h3>
                        <p>{t(locale, item.note)}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              <div className="workflow-image-col">
                <article className="framed-image framed-image-large">
                  <div className="image-caption">
                    <span>{t(locale, siteCopy.workflow.boardTag)}</span>
                    <strong>{t(locale, siteCopy.workflow.boardTitle)}</strong>
                  </div>
                  <img src={workflowBoardAsset} alt={t(locale, siteCopy.workflow.boardAlt)} />
                </article>
              </div>
            </div>
          </motion.section>

          <motion.section className="section section-proof" id="proof" {...reveal}>
            <div className="proof-header">
              <span className="section-index">04</span>
              <Eyebrow>{t(locale, siteCopy.proof.eyebrow)}</Eyebrow>
              <h2>{t(locale, siteCopy.proof.heading)}</h2>
            </div>
            <ProofCarousel locale={locale} />
          </motion.section>

          <motion.section className="section contact-section section-contact" id="contact" {...reveal}>
            <div className="contact-raw">
              <span className="section-index">05</span>
              <Eyebrow>{t(locale, siteCopy.contact.eyebrow)}</Eyebrow>
              <p className="contact-invite">{t(locale, siteCopy.contact.invite)}</p>
              <div className="contact-raw-list">
                {contactInfo.map((item) =>
                  item.href ? (
                    <a key={t(locale, item.label)} className="contact-raw-item" href={item.href}>
                      <span>{t(locale, item.label)}</span>
                      <strong>{item.value}</strong>
                    </a>
                  ) : (
                    <div key={t(locale, item.label)} className="contact-raw-item">
                      <span>{t(locale, item.label)}</span>
                      <strong>{item.value}</strong>
                    </div>
                  )
                )}
              </div>
            </div>
          </motion.section>
        </main>

        <footer className="site-footer">{t(locale, siteCopy.footer)}</footer>
      </div>
    </div>
  )
}

export default App
