// 송세훈 (달의 이성) 시네마틱 슬라이드 인트로 — 고려대 AMP 특별강연
const { useState, useEffect, useRef, useMemo } = React;
const D = window.SONGSEHUN;

const PALETTES = {
  moon: { name: '문라이트', shadow: '#1c1610', highlight: '#d4c89a', accent: '#e8c97a', bg: 'radial-gradient(ellipse at 50% 45%, #14110b 0%, #06050a 60%, #02010a 100%)' },
  azure: { name: '아주르', shadow: '#0a1830', highlight: '#a8c2e8', accent: '#7ab8e8', bg: 'radial-gradient(ellipse at 50% 45%, #0a1228 0%, #050816 60%, #01020a 100%)' },
  pine: { name: '딥파인', shadow: '#0a1f1a', highlight: '#a3d7c5', accent: '#c9a94d', bg: 'radial-gradient(ellipse at 50% 45%, #0f2e25 0%, #07140f 60%, #02060a 100%)' },
  ember: { name: '엠버', shadow: '#1a0a08', highlight: '#e8b89a', accent: '#e8a15a', bg: 'radial-gradient(ellipse at 50% 45%, #1a0a08 0%, #080403 60%, #02010a 100%)' },
  ivory: { name: '아이보리', shadow: '#5a4d2e', highlight: '#f5ecd0', accent: '#d4ba6e', bg: 'radial-gradient(ellipse at 50% 45%, #1f1810 0%, #0a0805 60%, #02010a 100%)' },
};

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "paletteKey": "moon",
  "rotationSpeed": 0.05,
  "glow": 1.0,
  "intensity": 1.0,
  "slideDuration": 8000,
  "autoplay": true
}/*EDITMODE-END*/;

// ── Eyebrow ─────────────────────────────────────────
const Eyebrow = ({ children }) => <div className="eyebrow gold">{children}</div>;

// ── Moon background scene (persistent) ──────────────
function MoonBackdrop({ tweaks, slideIdx }) {
  const mountRef = useRef(null);
  const stateRef = useRef({});
  stateRef.current = {
    glow: tweaks.glow,
    intensity: tweaks.intensity,
    rotationSpeed: tweaks.rotationSpeed,
    palette: PALETTES[tweaks.paletteKey] || PALETTES.moon,
  };
  useEffect(() => {
    if (!mountRef.current) return;
    window.MoonScene({ mount: mountRef.current, getState: () => stateRef.current, onActivePillar: () => {} });
  }, []);
  // moon parallax: shifts position based on slide
  const positions = [
    { x: '0%', y: '0%', scale: 1 },     // hero
    { x: '-22%', y: '8%', scale: 0.78 },  // titles
    { x: '20%', y: '5%', scale: 0.72 },   // pillars
    { x: '-15%', y: '-8%', scale: 0.65 }, // creativities
    { x: '18%', y: '-12%', scale: 0.55 }, // books
    { x: '-22%', y: '10%', scale: 0.6 },  // projects
    { x: '0%', y: '12%', scale: 0.5 },    // timeline
    { x: '0%', y: '0%', scale: 1.1 },     // manifesto
  ];
  const pos = positions[Math.min(slideIdx, positions.length - 1)] || positions[0];
  return (
    <div className="moon-backdrop"
         style={{ transform: `translate(${pos.x}, ${pos.y}) scale(${pos.scale})` }}>
      <div className="moon-mount" ref={mountRef}/>
    </div>
  );
}

// ── Slide 1 — Hero ──────────────────────────────────
function SlideHero() {
  return (
    <div className="slide-content hero-content">
      <div className="kicker">고려대 AMP 특별강연 · KOREA UNIVERSITY AMP</div>
      <div className="name-en gold-shimmer">REASON OF MOON</div>
      <div className="name-divider"/>
      <div className="name-ko">
        <span className="name-char">달</span>
        <span className="name-char">의</span>
        <span className="name-char-spacer"/>
        <span className="name-char">이</span>
        <span className="name-char">성</span>
      </div>
      <div className="name-person">송세훈 · SEHUN SONG</div>
      <div className="hero-tag">
        <span>인공지능 시대,</span>
        <span className="gold">'어떻게 질문할 것인가'</span>
        <span>를 가르치는 사람.</span>
      </div>
      <div className="hero-stats">
        <div className="hs"><b>{D.career}</b><span>교육 현장</span></div>
        <div className="hs-divider"/>
        <div className="hs"><b>{D.books.length}</b><span>출간 저서</span></div>
        <div className="hs-divider"/>
        <div className="hs"><b>{D.titles.length}</b><span>현재 직함</span></div>
      </div>
    </div>
  );
}

// ── Slide 2 — Current Roles ─────────────────────────
function SlideTitles() {
  return (
    <div className="slide-content titles-content">
      <div className="slide-head">
        <Eyebrow>NOW · 현재의 활동</Eyebrow>
        <h2 className="slide-h">7개의 역할로 동시에 살다</h2>
        <p className="slide-sub">출판인 · 교육자 · 개발자 · 엔지니어 · 교수 · 기자 · 강연자</p>
      </div>
      <div className="titles-list">
        {D.titles.map((t, i) => (
          <div className="title-item" key={i} style={{ animationDelay: `${i * 0.08 + 0.2}s` }}>
            <div className="title-num">0{i + 1}</div>
            <div>
              <div className="title-ko">{t.ko}</div>
              <div className="title-en">{t.en} · since {t.since}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Slide 3 — Four Pillars ──────────────────────────
function SlidePillars() {
  return (
    <div className="slide-content pillars-content">
      <div className="slide-head">
        <Eyebrow>FOUR PILLARS · 네 개의 기둥</Eyebrow>
        <h2 className="slide-h"><span className="nowrap">달의 이성을 떠받치는</span> <span className="nowrap">네 기둥</span></h2>
        <p className="slide-sub">연결 · 창조 · 학습 · 설계 — 메타프롬프트 사고법의 골격</p>
      </div>
      <div className="pillar-quad">
        {D.pillars.map((p, i) => (
          <div key={p.id} className="pillar-tile" style={{ animationDelay: `${i * 0.15 + 0.2}s`, '--accent': p.color }}>
            <div className="pillar-glyph">
              <div className="pillar-num">0{i + 1}</div>
            </div>
            <div className="pillar-ko">{p.ko}</div>
            <div className="pillar-en">{p.en}</div>
            <div className="pillar-desc">{p.desc}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Slide 4 — Creativities ──────────────────────────
function SlideCreativities() {
  return (
    <div className="slide-content creat-content">
      <div className="slide-head">
        <Eyebrow>THREE CREATIVITIES · 세 가지 창의성</Eyebrow>
        <h2 className="slide-h"><span className="nowrap">기존 결합 · 가능성 탐색</span><br/><span className="nowrap">패러다임 변형</span></h2>
        <p className="slide-sub">Margaret Boden의 창의성 분류로 설계된 학습 프레임</p>
      </div>
      <div className="creat-grid">
        {D.creativities.map((c, i) => (
          <div className="creat-card big" key={i} style={{ animationDelay: `${i * 0.18 + 0.2}s` }}>
            <div className="creat-glyph">{c.glyph}</div>
            <div className="creat-ko">{c.ko}</div>
            <div className="creat-en">{c.en}</div>
            <div className="creat-desc">{c.desc}</div>
          </div>
        ))}
      </div>
      <div className="quote-strip">
        "프롬프트에 대한 프롬프트 = 어떻게 질문할 것인가에 대한 질문"
      </div>
    </div>
  );
}

// ── Slide 5 — Books ─────────────────────────────────
function SlideBooks() {
  return (
    <div className="slide-content books-content">
      <div className="slide-head">
        <Eyebrow>BOOKS · 저서</Eyebrow>
        <h2 className="slide-h">프롬프트의 언어로 4권을 쓰다</h2>
        <p className="slide-sub">2023년부터 매해 새로운 프롬프트 사고법 출간</p>
      </div>
      <div className="books-stack">
        {D.books.map((b, i) => (
          <div className="book" key={i} style={{ animationDelay: `${i * 0.12 + 0.3}s` }}>
            <div className="book-spine">
              <div className="book-title">{b.ko}</div>
              <div className="book-sub">{b.sub}</div>
              <div className="book-year">{b.year}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Slide 6 — Projects ──────────────────────────────
function SlideProjects() {
  return (
    <div className="slide-content proj-content">
      <div className="slide-head">
        <Eyebrow>PROJECTS · 최근 프로젝트</Eyebrow>
        <h2 className="slide-h">교육 · AI · 언어를 잇는 6개의 실험실</h2>
        <p className="slide-sub">2021 데이터바우처부터 2025 UPMD 프롬프트 언어까지</p>
      </div>
      <div className="proj-grid">
        {D.projects.map((p, i) => (
          <div className="proj-card" key={i} style={{ animationDelay: `${i * 0.08 + 0.2}s` }}>
            <div className="proj-year">{p.year}</div>
            <div className="proj-name">{p.ko}</div>
            <div className="proj-desc">{p.desc}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Slide 7 — Timeline ──────────────────────────────
function SlideTimeline() {
  const [played, setPlayed] = useState(0);
  const trackRef = useRef(null);
  const total = D.timeline.length;
  useEffect(() => {
    setPlayed(0);
    const startDelay = 600;  // wait for slide-in
    const perStep = 110;     // ms between reveals
    const t0 = setTimeout(() => {
      let i = 0;
      const id = setInterval(() => {
        i += 1;
        setPlayed(i);
        if (i >= total) clearInterval(id);
      }, perStep);
      // store for cleanup
      trackRef.current && (trackRef.current._intervalId = id);
    }, startDelay);
    return () => {
      clearTimeout(t0);
      if (trackRef.current?._intervalId) clearInterval(trackRef.current._intervalId);
    };
  }, [total]);
  // auto-scroll head as it plays
  useEffect(() => {
    if (!trackRef.current) return;
    const nodes = trackRef.current.querySelectorAll('.tl-node');
    const idx = Math.min(played, nodes.length - 1);
    if (idx < 0 || !nodes[idx]) return;
    const target = nodes[idx];
    const left = target.offsetLeft - trackRef.current.clientWidth * 0.55;
    trackRef.current.scrollTo({ left: Math.max(0, left), behavior: 'smooth' });
  }, [played]);
  return (
    <div className="slide-content tl-content">
      <div className="slide-head">
        <Eyebrow>TIMELINE · 발자취</Eyebrow>
        <h2 className="slide-h">1994 → 2026, 30년의 궤적</h2>
        <p className="slide-sub">영문학도에서 프롬프트 엔지니어로 — <span className="tl-progress-txt">{Math.min(played, total)} / {total}</span></p>
      </div>
      <div className="tl-track" ref={trackRef}>
        <div className="tl-fill" style={{ width: `${(played / total) * 100}%` }}/>
        {D.timeline.map((y, i) => (
          <div className={`tl-node ${i < played ? 'lit' : ''} ${i === played - 1 ? 'now' : ''}`} key={i}>
            <div className="tl-year">{y.year}</div>
            <div className="tl-dot"/>
            <div className="tl-text">{y.ko}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Slide 8 — Manifesto ─────────────────────────────
function SlideManifesto() {
  return (
    <div className="slide-content manif-content">
      <div className="manifesto">
        <div className="manif-line l1">{D.manifesto.line1}</div>
        <div className="manif-line l2 gold-shimmer">{D.manifesto.line2}</div>
        <div className="manif-line l3">{D.manifesto.line3}</div>
        <div className="manif-sub">{D.manifesto.sub}</div>
      </div>
      <div className="gh-footer">
        <div className="gh-mark">⌂</div>
        <div>
          <div className="gh-lbl">GITHUB</div>
          <div className="gh-url">{D.github}</div>
        </div>
        <div className="gh-mark right">☾</div>
      </div>
      <div className="closing-thanks">
        <span className="ct-line"/>
        <span>고려대 AMP 특별강연 · 감사합니다</span>
        <span className="ct-line"/>
      </div>
    </div>
  );
}

const SLIDES = [
  { id: 'hero',    name: 'HERO',         label: '강연자',   Comp: SlideHero },
  { id: 'titles',  name: 'NOW',          label: '현재 활동', Comp: SlideTitles },
  { id: 'pillars', name: 'FOUR PILLARS', label: '네 기둥',   Comp: SlidePillars },
  { id: 'creat',   name: 'CREATIVITY',   label: '창의성',   Comp: SlideCreativities },
  { id: 'books',   name: 'BOOKS',        label: '저서',     Comp: SlideBooks },
  { id: 'proj',    name: 'PROJECTS',     label: '프로젝트',  Comp: SlideProjects },
  { id: 'tl',      name: 'TIMELINE',     label: '발자취',   Comp: SlideTimeline },
  { id: 'manif',   name: 'MANIFESTO',    label: '맺음',     Comp: SlideManifesto },
];

// ── Tweaks panel ────────────────────────────────────
function TweaksPanel({ visible, tweaks, setTweaks, onClose }) {
  if (!visible) return null;
  return (
    <div className="tweaks-panel">
      <div className="tw-head">
        <Eyebrow>TWEAKS</Eyebrow>
        <button className="tw-close" onClick={onClose}>✕</button>
      </div>
      <div className="tw-row">
        <label>슬라이드 시간 <span className="dim">{(tweaks.slideDuration / 1000).toFixed(1)}초</span></label>
        <input type="range" min="3000" max="20000" step="500" value={tweaks.slideDuration} onChange={e => setTweaks({ slideDuration: +e.target.value })}/>
      </div>
      <div className="tw-row">
        <label>달 회전 속도 <span className="dim">{tweaks.rotationSpeed.toFixed(2)}</span></label>
        <input type="range" min="0" max="0.4" step="0.01" value={tweaks.rotationSpeed} onChange={e => setTweaks({ rotationSpeed: +e.target.value })}/>
      </div>
      <div className="tw-row">
        <label>글로우 강도 <span className="dim">{tweaks.glow.toFixed(2)}</span></label>
        <input type="range" min="0" max="2.5" step="0.05" value={tweaks.glow} onChange={e => setTweaks({ glow: +e.target.value })}/>
      </div>
      <div className="tw-row">
        <label>표면 밝기 <span className="dim">{tweaks.intensity.toFixed(2)}</span></label>
        <input type="range" min="0.4" max="1.6" step="0.05" value={tweaks.intensity} onChange={e => setTweaks({ intensity: +e.target.value })}/>
      </div>
      <div className="tw-row">
        <label>자동 재생</label>
        <div className="toggle-row">
          <button className={`toggle-chip ${tweaks.autoplay ? 'on' : ''}`} onClick={() => setTweaks({ autoplay: !tweaks.autoplay })}>
            {tweaks.autoplay ? '재생 중' : '정지'}
          </button>
        </div>
      </div>
      <div className="tw-row">
        <label>팔레트</label>
        <div className="palette-picker">
          {Object.entries(PALETTES).map(([k, p]) => (
            <button key={k} className={`pal-sw ${tweaks.paletteKey === k ? 'on' : ''}`} onClick={() => setTweaks({ paletteKey: k })}>
              <span className="sw" style={{ background: p.shadow }}/>
              <span className="sw" style={{ background: p.highlight }}/>
              <span className="sw" style={{ background: p.accent }}/>
              <span className="pal-name">{p.name}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Root ────────────────────────────────────────────
function App() {
  const [tweaks, setTweaksState] = useState(DEFAULTS);
  const [tweaksVisible, setTV] = useState(false);
  const [slideIdx, setSlideIdx] = useState(0);
  const [progress, setProgress] = useState(0);
  const [paused, setPaused] = useState(false);

  const setTweaks = (partial) => setTweaksState((t) => ({ ...t, ...partial }));

  const playing = tweaks.autoplay && !paused;

  // auto-advance
  useEffect(() => {
    if (!playing) return;
    const startTime = performance.now();
    let raf;
    const tick = (now) => {
      const elapsed = now - startTime;
      const p = elapsed / tweaks.slideDuration;
      setProgress(p);
      if (p >= 1) {
        setSlideIdx((i) => (i + 1) % SLIDES.length);
        setProgress(0);
      } else {
        raf = requestAnimationFrame(tick);
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [slideIdx, playing, tweaks.slideDuration]);

  // keyboard nav
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowRight' || e.key === ' ') { setSlideIdx((i) => (i + 1) % SLIDES.length); setProgress(0); }
      if (e.key === 'ArrowLeft') { setSlideIdx((i) => (i - 1 + SLIDES.length) % SLIDES.length); setProgress(0); }
      if (e.key.toLowerCase() === 'p') { setPaused((p) => !p); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // edit mode
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTV(true);
      if (e.data?.type === '__deactivate_edit_mode') setTV(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);
  useEffect(() => { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: tweaks }, '*'); }, [tweaks]);

  const palette = PALETTES[tweaks.paletteKey] || PALETTES.moon;
  const Slide = SLIDES[slideIdx].Comp;

  return (
    <div className="stage" style={{ background: palette.bg }}>
      <div className="bg-grain"/>
      <div className="bg-vignette"/>

      {/* persistent moon scene */}
      <MoonBackdrop tweaks={tweaks} slideIdx={slideIdx}/>

      {/* corner decor */}
      <div className="corner tl"/><div className="corner tr"/>
      <div className="corner bl"/><div className="corner br"/>

      {/* topbar */}
      <header className="topbar">
        <div className="brand">
          <div className="logo-glyph">☾</div>
          <div>
            <div className="brand-name">달의 이성 · Reason of Moon</div>
            <div className="brand-sub">고려대 AMP 특별강연 · 강연자 소개</div>
          </div>
        </div>
        <div className="topbar-right">
          <div className="slide-counter">
            <span className="sc-num">{String(slideIdx + 1).padStart(2, '0')}</span>
            <span className="sc-sep">/</span>
            <span className="sc-tot">{String(SLIDES.length).padStart(2, '0')}</span>
            <span className="sc-name">{SLIDES[slideIdx].name}</span>
          </div>
          <button className="tw-btn" onClick={() => setTV(v => !v)}>Tweaks</button>
        </div>
      </header>

      {/* slide stage */}
      <main className="slide-stage">
        {SLIDES.map((s, i) => (
          <div key={s.id} className={`slide-frame ${i === slideIdx ? 'on' : i < slideIdx ? 'past' : 'future'}`}>
            {i === slideIdx && <Slide/>}
          </div>
        ))}
      </main>

      {/* progress bar */}
      <div className="prog-rail">
        <div className="prog-fill" style={{ width: `${(slideIdx + progress) / SLIDES.length * 100}%` }}/>
      </div>

      {/* slide chapters */}
      <nav className="chapter-nav">
        {SLIDES.map((s, i) => (
          <button key={s.id} className={`ch-btn ${i === slideIdx ? 'on' : ''} ${i < slideIdx ? 'done' : ''}`}
                  onClick={() => { setSlideIdx(i); setProgress(0); }}>
            <span className="ch-num">{String(i + 1).padStart(2, '0')}</span>
            <span className="ch-label">{s.label}</span>
            {i === slideIdx && (
              <span className="ch-prog" style={{ width: `${progress * 100}%` }}/>
            )}
          </button>
        ))}
      </nav>

      {/* play/pause control */}
      <div className="play-control">
        <button className="pp-btn" onClick={() => setPaused(p => !p)} title={paused ? '재생' : '일시정지'}>
          {paused || !tweaks.autoplay ? (
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M7 5v14l12-7z"/></svg>
          ) : (
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
          )}
        </button>
        <button className="pp-btn small" onClick={() => { setSlideIdx((i) => (i - 1 + SLIDES.length) % SLIDES.length); setProgress(0); }}>◀</button>
        <button className="pp-btn small" onClick={() => { setSlideIdx((i) => (i + 1) % SLIDES.length); setProgress(0); }}>▶</button>
        <div className="kbd-hint">←/→ 이동 · 스페이스 다음 · P 일시정지</div>
      </div>

      <TweaksPanel visible={tweaksVisible} tweaks={tweaks} setTweaks={setTweaks} onClose={() => setTV(false)}/>
    </div>
  );
}

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