/* =========================================================================
   골라주 — main app  (landing + inline mood→result tool)
   ========================================================================= */
const { Button: GButton, Card: GCard, Badge: GBadge, DoodleIcon: GDoodle } = window.MarginaliaDesignSystem_fe27e0;
const { MOODS, TIMES, COMPANY, PICKS, HERO_COPY } = window.GollageData;

/* Smooth-scroll helper — updates URL hash and scrolls without page jump */
function scrollTo(id) {
  history.pushState(null, '', '#' + id);
  document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });
}

/* ---------------- Nav ---------------- */
function Nav({ copy }) {
  const links = [['tool', '골라줘'], ['how', '어떻게'], ['why', '왜 골라주'], ['signature', 'Gollage Card']];
  return (
    <header className="nav">
      <nav className="nav-inner" aria-label="주 내비게이션">
        <a href="#top" className="nav-logo">
          <GDoodle name="star" size={28} tilt={-10} aria-hidden="true" />
          <span className="nav-logo-text">gollage</span>
        </a>
        <div className="nav-actions">
          <div className="nav-text-links">
            {links.map(([id, label]) => (
              <a key={id} href={`#${id}`}>{label}</a>
            ))}
          </div>
          <GButton variant="primary" size="sm" onClick={() => scrollTo('tool')} className="nav-cta">
            지금 {copy.cta}
          </GButton>
        </div>
      </nav>
    </header>
  );
}

/* ---------------- Hero (full viewport) ---------------- */
function Hero({ copy }) {
  return (
    <section id="top" className="hero" aria-labelledby="hero-title">
      <StarScatter items={[
        { name: 'star',         size: 32, top: '14%',    left: '6%',   tilt: -12, opacity: 0.8 },
        { name: 'sparkle',      size: 28, top: '22%',    right: '9%',  tilt: 8,   opacity: 0.7 },
        { name: 'star-pointed', size: 22, top: '55%',    left: '13%',  tilt: 14,  opacity: 0.5 },
        { name: 'star',         size: 20, bottom: '18%', right: '16%', tilt: -6,  opacity: 0.45 },
        { name: 'sparkle',      size: 18, bottom: '10%', left: '30%',  tilt: 10,  opacity: 0.35 },
      ]} />
      <div className="hero-inner">
        <div className="hero-content">
          <div className="hero-eyebrow">
            <GBadge stamp tone="coral">{copy.eyebrow}</GBadge>
          </div>
          <h1 className="hero-title" id="hero-title">{copy.title}</h1>
          <p className="hero-sub">{copy.sub}</p>
          <GButton variant="primary" size="lg"
            leftIcon={<GDoodle name="sparkle" size={20} aria-hidden="true" />}
            onClick={() => scrollTo('tool')}>
            지금 {copy.cta}
          </GButton>
        </div>
        <div aria-hidden="true" className="hero-scroll-hint">
          <span className="hero-scroll-label">골라줘</span>
          <svg width="16" height="20" viewBox="0 0 16 20" fill="none" className="hero-scroll-arrow">
            <path d="M8 2v14M2 10l6 6 6-6" stroke="var(--ink-300)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Tool section ---------------- */
function ToolSection({ copy, tool }) {
  const { mood, time, setTime, company, setCompany, phase, pick, showGollage } = tool;
  return (
    <section id="tool" className="tool-section" aria-labelledby="tool-heading">
      <div className="section-inner">
        <div className="tool-card-wrap">
          <GCard variant="inked" style={{ transition: 'none', borderRadius: '18px', padding: '28px' }}>
            <div className="tool-header">
              <GDoodle name="mug" size={26} tilt={-6} aria-hidden="true" />
              <h2 id="tool-heading">{copy.ask}</h2>
            </div>

            <div className="mood-grid" role="group" aria-label="무드 선택">
              {MOODS.map((m) => (
                <MoodChip key={m.id} mood={m} active={mood && mood.id === m.id} onClick={() => tool.choose(m.id)} />
              ))}
            </div>

            <div className="tool-refiners">
              <PillRow label="시간" options={TIMES} value={time} onChange={setTime} />
              <PillRow label="누구랑" options={COMPANY} value={company} onChange={setCompany} />
            </div>

            {/* Screen-reader announcement for phase transitions */}
            <div aria-live="polite" aria-atomic="true" className="sr-only">
              {phase === 'curating' && '추천 영상을 찾고 있어요.'}
              {phase === 'result' && pick && `${pick.title} 추천 완료.`}
            </div>

            {phase !== 'idle' && (
              <div className="tool-result-area">
                {phase === 'curating' && <Curating mood={mood} />}
                {phase === 'result' && pick && <Result copy={copy} tool={tool} />}
                {phase === 'result' && showGollage && pick && (
                  <div className="tool-gollage">
                    <div className="tool-gollage-header">
                      <span className="tool-gollage-label">오늘 밤의 기분, 남겨둬 —</span>
                    </div>
                    <GollageCard pick={pick} mood={mood} copy={copy} onShare={tool.onShare} />
                  </div>
                )}
              </div>
            )}
          </GCard>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Curating state ---------------- */
function Curating({ mood }) {
  return (
    <div className="curating" aria-busy="true">
      <span className="bob"><GDoodle name={mood ? mood.doodle : 'star'} size={36} aria-hidden="true" /></span>
      <div>
        <div className="curating-title">골라주는 중…</div>
        <div className="curating-sub">플랫폼 다 뒤져서 딱 한 편만 가져올게.</div>
      </div>
    </div>
  );
}

/* ---------------- Result block ---------------- */
function Result({ copy, tool }) {
  const { pick, mood, time, company } = tool;
  const t = (TIMES.find(x => x.id === time) || {}).label;
  const c = (COMPANY.find(x => x.id === company) || {}).label;
  return (
    <div className="result">
      <div className="result-poster">
        <PosterThumb pick={pick} width={188} tilt={-2.5} />
      </div>
      <div className="result-info">
        <div className="result-badge-row">
          <GBadge tone={mood.tone}>{mood.label}</GBadge>
          <span className="result-meta-label">오늘의 한 편</span>
        </div>
        <h3 className="result-title">{pick.title}</h3>
        <div className="result-genre">{pick.genre}{pick.runtime ? ` · ${pick.runtime}` : ''}</div>
        <div className="result-curator-note">
          <div className="result-curator-note-inner">
            <GDoodle name="star" size={20} tilt={-8} aria-hidden="true" style={{ flexShrink: 0, marginTop: 2 }} />
            <p className="result-curator-text">{pick.reason}</p>
          </div>
        </div>
        <div className="result-meta-row">
          <span className="result-where-label">어디서 봐</span>
          {pick.platform
            ? <PlatformBadge name={pick.platform} />
            : <span className="result-where-none">직접 검색</span>}
          <span className="result-criteria">· {t}, {c} 기준으로 골랐어</span>
        </div>
        <div className="result-actions">
          <GButton variant="accent" onClick={() => tool.onShare('pick')} leftIcon={<GDoodle name="sparkle" size={18} aria-hidden="true" />}>{copy.pick}</GButton>
          <GButton variant="secondary" onClick={tool.reroll}>{copy.again}</GButton>
          {!tool.showGollage && (
            <GButton variant="ghost" onClick={tool.makeGollage} leftIcon={<GDoodle name="flower" size={18} aria-hidden="true" />}>Gollage Card로 남기기</GButton>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------------- Problem section ---------------- */
function Problem() {
  return (
    <section className="section-problem" aria-labelledby="problem-heading">
      <StarScatter items={[{ name: 'bird', size: 30, top: 40, right: '8%', tilt: 6, opacity: 0.35 }]} />
      <div className="section-inner section-inner--elevated">
        <SectionHead align="center" eyebrow="고르는 데 지쳤잖아" doodle="bird" headingId="problem-heading"
          title="30분 스크롤, 결국 보던 거 또."
          sub="넷플릭스, 디즈니+, 웨이브, 티빙, 쿠팡플레이… 플랫폼만 다섯 개. 각자 수천 편. 진짜 문제는 콘텐츠가 아니라 '결정 피로'야." />
        <div className="problem-stats">
          {[
            { big: '5개+', small: '깔아둔 OTT 구독', d: 'mug' },
            { big: '23분', small: '뭐 볼지 고르는 평균 시간', d: 'cat' },
            { big: '또 그거', small: '결국 보던 거 다시 재생', d: 'guitar' },
          ].map((s, i) => (
            <GCard key={i} variant="soft" drawn tilt={i % 2 ? 1 : -1} style={{ textAlign: 'center', padding: '26px 18px' }}>
              <GDoodle name={s.d} size={34} tilt={i % 2 ? 6 : -6} aria-hidden="true" />
              <div className="stat-big">{s.big}</div>
              <div className="stat-small">{s.small}</div>
            </GCard>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- How it works ---------------- */
function How() {
  const steps = [
    { n: '하나', doodle: 'mug', title: '기분을 골라', d: '"오늘 기분이 어때?" 무드 하나만 톡 찍으면 돼. 시간·누구랑은 거들 뿐.' },
    { n: '둘', doodle: 'sparkle', title: '골라주가 골라줌', d: '플랫폼 가리지 않고, 지금 너한테 딱 맞는 단 한 편. 왜 골랐는지도 말해줘.' },
    { n: '셋', doodle: 'flower', title: 'Gollage Card로 남겨', d: '오늘 밤의 무드를 한 장 카드로. 마음에 들면 친구한테 바로 공유.' },
  ];
  return (
    <section id="how" className="section-how" aria-labelledby="how-heading">
      <div className="section-inner">
        <SectionHead eyebrow="어떻게 골라줘" doodle="star" headingId="how-heading"
          title="딱 세 번이면, 오늘 밤이 정해져."
          sub="회원가입도, 끝없는 스크롤도 없어. 들어오자마자 위에서 바로 해봐." />
        <ol className="how-steps" aria-label="이용 방법">
          {steps.map((s, i) => (
            <li key={i}>
              <GCard variant="inked" style={{ padding: '26px', borderRadius: 'var(--radius-doodle)', position: 'relative' }}>
                <div className="step-num" aria-hidden="true">{i + 1}</div>
                <GDoodle name={s.doodle} size={42} tilt={-6} aria-hidden="true" />
                <div className="step-eyebrow">STEP {s.n}</div>
                <h3 className="step-title">{s.title}</h3>
                <p className="step-body">{s.d}</p>
              </GCard>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/* ---------------- Why 골라주 (comparison) ---------------- */
function Why() {
  const cols = [
    { name: 'OTT 알고리즘', tone: 'neutral', rows: ['본 것만 또 추천', '자사 플랫폼만', '무한 스크롤', '왜인지 모름'], muted: true },
    { name: '지인 추천', tone: 'neutral', rows: ['취향 안 맞을 때도', '아는 것만 추천', '빠르지만 가끔 빗나감', '"그냥 재밌어"'], muted: true },
    { name: '골라주', tone: 'coral', rows: ['지금 무드 기반', '전 플랫폼 통합', '즉각, 단 한 편', '왜 골랐는지 설명'], muted: false },
  ];
  const labels = ['개인화', '추천 범위', '결정 속도', '신뢰'];
  return (
    <section id="why" className="section-why" aria-labelledby="why-heading">
      <div className="section-inner">
        <SectionHead align="center" eyebrow="왜 골라주" doodle="cat" headingId="why-heading"
          title="알고리즘도, 친구도 아닌."
          sub="골라주는 지금 이 순간 네 무드를 읽고, 이유까지 말해주는 큐레이터야." />
        <div className="why-cols">
          {cols.map((col, ci) => (
            <div key={ci} className={col.muted ? 'why-col why-col--muted' : 'why-col why-col--featured'}>
              <GCard variant={col.muted ? 'soft' : 'inked'} drawn={!col.muted} tilt={col.muted ? 0 : -1}
                style={{ padding: '24px', ...(col.muted ? {} : { background: 'var(--surface-raised)' }) }}>
                <div className="why-col-header">
                  {!col.muted && <GDoodle name="star" size={22} tilt={-8} aria-hidden="true" />}
                  <span className="why-col-name">{col.name}</span>
                </div>
                <dl className="why-rows">
                  {col.rows.map((r, ri) => (
                    <div key={ri}>
                      <dt className="why-row-label">{labels[ri]}</dt>
                      <dd className="why-row-value">{r}</dd>
                    </div>
                  ))}
                </dl>
              </GCard>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Gollage showcase ---------------- */
function Showcase() {
  const samples = [
    { title: '느린 마을의 우체부', genre: '힐링 드라마', color: '#5C7A4A', kw: ['잔잔', '위로'], doodle: 'mug', tone: 'sage' },
    { title: '여름의 끝, 너에게', genre: '로맨스', color: '#C97B86', kw: ['설렘', '여름'], doodle: 'flower', tone: 'blush' },
    { title: '13층의 목격자', genre: '스릴러', color: '#2F3A52', kw: ['긴장', '몰입'], doodle: 'cat', tone: 'blue' },
  ];
  return (
    <section id="signature" className="section-showcase" aria-labelledby="showcase-heading">
      <StarScatter items={[
        { name: 'sparkle', size: 28, top: 56, left: '6%', tilt: -10, opacity: 0.5 },
        { name: 'star', size: 22, bottom: 80, right: '10%', tilt: 8, opacity: 0.45 },
      ]} />
      <div className="section-inner section-inner--elevated">
        <div className="showcase-grid">
          <SectionHead align="center" eyebrow="시그니처 — Gollage Card" doodle="flower" headingId="showcase-heading"
            title="취향을 카드로. 골라주 + 콜라주."
            sub="큐레이션이 끝나면, 오늘의 무드·색감·키워드를 모아 세상에 하나뿐인 카드를 만들어줘. 공유하면 친구도 같이 보게 됨." />
          <div className="showcase-row" aria-label="Gollage Card 예시">
            {samples.map((s, i) => (
              <div key={i} className="showcase-card">
                <GollageCard pick={s} mood={{ doodle: s.doodle, tone: s.tone, label: s.genre }} copy={HERO_COPY} onShare={() => {}} hideShare />
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Footer CTA ---------------- */
function Footer({ copy }) {
  return (
    <footer className="footer" aria-label="시작하기">
      <StarScatter items={[
        { name: 'star', size: 28, top: 50, left: '12%', tilt: -12, opacity: 0.6 },
        { name: 'star-pointed', size: 24, top: 80, right: '14%', tilt: 10, opacity: 0.5 },
      ]} />
      <div className="section-inner section-inner--elevated">
        <GDoodle name="star" size={48} tilt={-8} aria-hidden="true" />
        <h2 className="footer-title">나 대신 골라주.</h2>
        <p className="footer-sub">이 한 마디가 골라주의 전부야. 오늘 밤은 고민 말고, 위로 올라가서 기분만 하나 찍어.</p>
        <GButton variant="primary" size="lg"
          leftIcon={<GDoodle name="sparkle" size={20} aria-hidden="true" />}
          onClick={() => scrollTo('tool')}>
          지금 {copy.cta}
        </GButton>
        <div className="footer-bottom">
          <span className="footer-brand">gollage</span>
          <span className="footer-tagline">Gollage · 오늘 뭐 볼지, 골라주.</span>
          <span className="footer-copyright">© {new Date().getFullYear()} Webtexture</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- Toast (always in DOM for aria-live to work) ---------------- */
function Toast({ msg }) {
  return (
    <div role="status" aria-live="polite" aria-atomic="true" style={{ display: 'contents' }}>
      {msg && (
        <div className="toast">
          <GDoodle name="star" size={18} aria-hidden="true" />{msg}
        </div>
      )}
    </div>
  );
}

/* ---------------- App ---------------- */
function App() {
  const copy = HERO_COPY;

  // tool state
  const [mood, setMood] = React.useState(null);
  const [time, setTime] = React.useState('mid');
  const [company, setCompany] = React.useState('alone');
  const [phase, setPhase] = React.useState('idle'); // idle | curating | result
  const [pick, setPick] = React.useState(null);
  const [showGollage, setShowGollage] = React.useState(false);
  const [toast, setToast] = React.useState('');
  const callGen = React.useRef(0);
  const toastTimer = React.useRef(null);

  const flashToast = (m) => {
    setToast(m);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(''), 2200);
  };

  const runCurate = async (m, t, c) => {
    const gen = ++callGen.current;
    setPhase('curating');
    setShowGollage(false);
    try {
      const result = await window.TMDB.fetchByMood(m.id, t, c);
      if (gen !== callGen.current) return;
      result.color = m.poster;
      setPick(result);
      setPhase('result');
    } catch (_) {
      if (gen !== callGen.current) return;
      const pool = PICKS[m.id];
      const fallback = pool[Math.floor(Math.random() * pool.length)];
      setPick(fallback);
      setPhase('result');
    }
  };

  const choose = (id) => {
    const m = MOODS.find(x => x.id === id);
    setMood(m);
    runCurate(m, time, company);
  };

  const reroll = () => {
    if (mood) runCurate(mood, time, company);
  };

  const makeGollage = () => { setShowGollage(true); flashToast('Gollage Card 만들었어!'); };

  const onShare = (where) => {
    if (where === 'pick') flashToast(copy.saved);
    else if (where === '저장') flashToast('카드 저장 완료.');
    else flashToast(`${where}로 공유 — 같이 보게 됨.`);
  };

  React.useEffect(() => () => { clearTimeout(toastTimer.current); }, []);

  const tool = { mood, time, setTime, company, setCompany, phase, pick, showGollage, choose, reroll, makeGollage, onShare };

  return (
    <div className="app">
      <Nav copy={copy} />
      <main id="main-content">
        <Hero copy={copy} />
        <ToolSection copy={copy} tool={tool} />
        <Problem />
        <How />
        <Why />
        <Showcase />
      </main>
      <Footer copy={copy} />
      <Toast msg={toast} />
    </div>
  );
}

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