import React, { useEffect, useRef, useState } from 'react'
import { flushSync } from 'react-dom'
import { createRoot } from 'react-dom/client'
import 'pretendard/dist/web/variable/pretendardvariable-dynamic-subset.css'
import './styles.css'
import { cityTime, isTime, matchCity, restoreTimes, returnPlan, signed } from './sleep.js'

const guides = [
  { title: '시차 적응법', text: '도착지 시간에 맞춰 식사와 수면 시간을 정해 보세요. 이동 전부터 일정에 맞춰 잠드는 시각을 조금씩 옮기면 한 번에 바꿔야 하는 폭을 줄일 수 있어요.', source: 'https://www.cdc.gov/yellow-book/hcp/travel-air-sea/jet-lag-disorder.html', credit: 'CDC' },
  { title: '귀국 후 첫 주 루틴', text: '한국 시간으로 기상 시각을 정하고 식사와 가벼운 활동도 그 시간표에 맞춰 보세요. 밤에 잠들기 어렵다면 낮에 길게 자는 일을 피하고, 필요할 때는 짧게 쉬세요.', source: 'https://www.nhs.uk/conditions/jet-lag/', credit: 'NHS' },
  { title: '아침 햇빛', text: '기상한 뒤 해가 떠 있다면 잠깐 밖에 나가 보세요. 아직 어두우면 해가 뜬 뒤로 산책을 잡아도 좋아요. 실제 여행에서는 이동 방향과 시차에 따라 빛을 쬐기 좋은 시간이 달라져요.', source: 'https://www.cdc.gov/yellow-book/hcp/travel-air-sea/jet-lag-disorder.html', credit: 'CDC' },
  { title: '수면 위생', text: '일어나는 시간을 일정하게 유지해 보세요. 잠자기 전에는 화면 밝기와 실내 조명을 낮추고, 저녁에는 카페인을 피하세요. 침실은 조용하고 어둡게 유지하세요.', source: 'https://www.cdc.gov/sleep/about/index.html', credit: 'CDC' },
]

const barcodePattern = [1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1]

function TimeField({ name, label, value, onChange }) {
  return (
    <label className="time-field">
      <span>{label}</span>
      <input type="time" name={name} lang="en-GB" required value={value} onChange={onChange} />
    </label>
  )
}

function BoardingPass({ city, times, now }) {
  const verdict = city.airport === 'ICN'
    ? '당신의 몸은 서울 시간에 살고 있어요'
    : `당신의 몸은 이미 ${city.korean}에 삽니다`

  return (
    <div className="ticket">
      <div className="ticket-head">
        <span><i className="signal" aria-hidden="true" /> 수면 보딩패스</span>
        <span className="mono badge">UTC{signed(city.offset)}</span>
      </div>
      <div className="ticket-route">
        <div className="airport">
          <span className="airport-name mono">SEOUL</span>
          <strong className="airport-code">ICN</strong>
        </div>
        <div className="flight-path" aria-hidden="true"><span>✈</span></div>
        <div className="airport destination">
          <span className="airport-name mono">{city.name}</span>
          <strong className="airport-code">{city.airport}</strong>
        </div>
      </div>
      <p className="verdict">{verdict}</p>
      <div className="ticket-stub">
        <dl className="ticket-details">
          <div><dt>현지 시각</dt><dd className="mono">{cityTime(now, city.offset)}</dd></div>
          <div><dt>서울과 시차</dt><dd>{signed(city.offset - 9)}시간</dd></div>
          <div><dt>탑승자</dt><dd>당신의 몸</dd></div>
          <div><dt>좌석</dt><dd className="mono">{times.sleep}-{times.wake}</dd></div>
        </dl>
        <div className="stamp" aria-hidden="true">
          <span>ARRIVED</span>
          <strong>{city.name}</strong>
          <span>✦</span>
        </div>
      </div>
      <div className="ticket-foot">
        <div className="barcode" aria-hidden="true">
          {barcodePattern.map((bar, index) => <i key={index} className={bar ? 'bar' : undefined} />)}
        </div>
        <span className="mono">@sukkuppi</span>
      </div>
    </div>
  )
}

function ReturnPlan({ times, now, onChange }) {
  const { days, steps } = returnPlan(times, now)
  const headline = days > 7 ? '지금은 시차 적응 중' : days ? `목표까지 ${days}일` : '목표 시간에 도착했어요'
  return (
    <section className="plan" aria-labelledby="plan-title">
      <div className="plan-head">
        <div className="plan-mark" aria-hidden="true">↶</div>
        <div>
          <h2 id="plan-title">한국인 복귀 플랜</h2>
          <p>{headline}</p>
        </div>
      </div>
      <div className="time-grid">
        <TimeField name="ts" label="목표 취침" value={times.ts} onChange={onChange} />
        <TimeField name="tw" label="목표 기상" value={times.tw} onChange={onChange} />
      </div>
      <ol className="timeline">
        {steps.map((step) => (
          <li key={step.label}>
            <span className="timeline-dot" aria-hidden="true" />
            <div className="step-head">
              <strong>{step.label}</strong>
              <time dateTime={step.date}>{step.shortDate}</time>
              <span className="countdown mono">{step.countdown}</span>
            </div>
            <div className="step-times">
              <span>취침 <strong>{step.bedtime}</strong></span>
              <span>기상 <strong>{step.wakeTime}</strong></span>
            </div>
            <p className="sunlight"><span aria-hidden="true">☀</span> 아침 햇빛 {step.sunlight}분</p>
          </li>
        ))}
      </ol>
      <p className="plan-note">하루 45~60분씩 앞당기고, 마지막 날은 남은 차이만 맞춰요. 날짜는 한국 시간 기준이에요.</p>
    </section>
  )
}

function App() {
  const [times, setTimes] = useState(() => restoreTimes(window.location.search))
  const [now, setNow] = useState(() => new Date())
  const [saving, setSaving] = useState(false)
  const [story, setStory] = useState(null)
  const [notice, setNotice] = useState('')
  const [shareUrl, setShareUrl] = useState('')
  const storyRef = useRef(null)
  const privacyRef = useRef(null)
  const city = matchCity(times.sleep, times.wake)

  useEffect(() => {
    const tick = () => setNow(new Date())
    const timer = window.setInterval(tick, 1000 * 15)
    const restore = () => setTimes(restoreTimes(window.location.search))
    window.addEventListener('popstate', restore)
    document.addEventListener('visibilitychange', tick)
    return () => {
      window.clearInterval(timer)
      window.removeEventListener('popstate', restore)
      document.removeEventListener('visibilitychange', tick)
    }
  }, [])

  function updateTime(event) {
    const { name, value } = event.currentTarget
    if (!isTime(value)) return
    const next = { ...times, [name]: value }
    setTimes(next)
    const url = new URL(window.location.href)
    for (const [key, time] of Object.entries(next)) url.searchParams.set(key, time)
    window.history.replaceState(null, '', url)
    setShareUrl('')
    setNotice('')
  }

  async function copyLink() {
    const url = new URL(window.location.pathname, window.location.origin)
    url.search = Object.entries(times).map(([key, time]) => `${key}=${time}`).join('&')
    try {
      await navigator.clipboard.writeText(url.href)
      setShareUrl('')
      setNotice('공유 링크를 복사했어요.')
    } catch {
      setShareUrl(url.href)
      setNotice('아래의 공유 링크를 복사해 주세요.')
    }
  }

  async function saveStory() {
    if (saving) return
    setSaving(true)
    flushSync(() => setStory({ city, times, now: new Date() }))
    setNotice('')
    try {
      const { default: html2canvas } = await import('html2canvas')
      await document.fonts.ready
      const canvas = await html2canvas(storyRef.current, {
        backgroundColor: '#0b1020', width: 360, height: 640, scale: 3, logging: false,
      })
      const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
      if (!blob) throw new Error('PNG export failed')
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `sleep-jetlag-${city.airport.toLowerCase()}.png`
      document.body.append(link)
      link.click()
      link.remove()
      window.setTimeout(() => URL.revokeObjectURL(url), 60_000)
      setNotice('스토리 이미지 다운로드를 시작했어요.')
    } catch {
      setNotice('이미지를 저장하지 못했어요. 다시 시도해 주세요.')
    } finally {
      setStory(null)
      setSaving(false)
    }
  }

  return (
    <div className="site">
      <header className="site-header">
        <div className="brand"><span className="brand-mark" aria-hidden="true">✈</span> SleepJetlag</div>
        <span className="mono header-code">ICN <span aria-hidden="true">↗</span> KST</span>
      </header>
      <main>
        <section className="hero" aria-labelledby="page-title" data-enter>
          <h1 id="page-title">수면시차 계산기</h1>
          <p>내 몸은 지금 어느 시간대에 있을까?</p>
        </section>

        <section className="input-panel" aria-labelledby="input-title">
          <h2 id="input-title">요즘 수면 시간</h2>
          <div className="time-grid">
            <TimeField name="sleep" label="취침" value={times.sleep} onChange={updateTime} />
            <TimeField name="wake" label="기상" value={times.wake} onChange={updateTime} />
          </div>
        </section>

        <section className="result" aria-label="수면시차 결과">
          {city.duration > 0
            ? <BoardingPass city={city} times={times} now={now} />
            : <p className="empty-ticket" role="status">수면 시간을 계산할 수 있도록 취침과 기상 시각을 다르게 입력해 주세요.</p>}
          <div className="actions">
            <button className="save" type="button" disabled={saving || city.duration === 0} onClick={saveStory}>
              <span aria-hidden="true">⇩</span> {saving ? '이미지 만드는 중…' : '스토리 PNG 저장'}
            </button>
            <button className="share" type="button" onClick={copyLink}>
              <span aria-hidden="true">↗</span> 링크 복사
            </button>
          </div>
          <p className="feedback" role="status">{notice}</p>
          {shareUrl && <input className="share-url" aria-label="공유 링크" value={shareUrl} readOnly onFocus={(event) => event.currentTarget.select()} />}
        </section>

        <ReturnPlan times={times} now={now} onChange={updateTime} />

        <section className="guides" aria-labelledby="guide-title">
          <h2 id="guide-title">수면시차 가이드</h2>
          {guides.map(({ title, text, source, credit }) => (
            <details key={title} name="sleep-guides">
              <summary>{title}</summary>
              <p>{text} <a href={source} target="_blank" rel="noreferrer">{credit} 자료</a></p>
            </details>
          ))}
        </section>
      </main>

      <footer className="site-footer">
        <span>SleepJetlag · 표준 UTC 오프셋 기준</span>
        <button type="button" onClick={() => privacyRef.current.showModal()}>개인정보처리방침</button>
      </footer>
      <dialog ref={privacyRef} aria-labelledby="privacy-title">
        <h2 id="privacy-title">개인정보처리방침</h2>
        <p>입력값은 브라우저에서 계산하며, 앱이 입력값을 별도 서버에 전송하거나 저장하지 않습니다. 바꾼 시각은 브라우저의 현재 주소와 복사한 공유 링크의 URL 파라미터에 남습니다.</p>
        <p>공유 링크를 받은 사람은 시각을 볼 수 있습니다. 해당 주소를 열면 파라미터가 호스팅 서버에 전달될 수 있습니다. 스토리 이미지는 브라우저에서 만들어 기기에 저장됩니다.</p>
        <form method="dialog"><button type="submit">닫기</button></form>
      </dialog>

      {story && <div className="story-offscreen" aria-hidden="true">
        <div className="story" ref={storyRef}>
          <div className="story-brand"><span aria-hidden="true">✈</span> SleepJetlag</div>
          <div className="story-intro">
            <p>내 몸은 지금 어느 시간대에 있을까?</p>
            <strong>수면시차 계산기</strong>
          </div>
          <BoardingPass {...story} />
          <div className="story-route mono">ICN <span aria-hidden="true">→</span> {story.city.airport}</div>
        </div>
      </div>}
    </div>
  )
}

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