/* =========================================================================
   골라주 — 골라주 tool page
   ========================================================================= */
const { Button: GButton, Card: GCard, Badge: GBadge, DoodleIcon: GDoodle } = window.MarginaliaDesignSystem_fe27e0;
const { MOODS, TIMES, OTTS, HERO_COPY } = window.GollageData;

/* Platform → search URL builder */
const PLATFORM_SEARCH = {
  '넷플릭스':      (t) => `https://www.netflix.com/search?q=${encodeURIComponent(t)}`,
  '디즈니+':       (t) => `https://www.disneyplus.com/search?q=${encodeURIComponent(t)}`,
  'Apple TV+':    (t) => `https://tv.apple.com/search?term=${encodeURIComponent(t)}`,
  'Amazon Prime': (t) => `https://www.primevideo.com/search/ref=atv_nb_sr?phrase=${encodeURIComponent(t)}`,
  '왓챠':          (t) => `https://watcha.com/search?query=${encodeURIComponent(t)}`,
  '웨이브':         (t) => `https://www.wavve.com/search?keyword=${encodeURIComponent(t)}`,
  '티빙':           (t) => `https://www.tving.com/search?keyword=${encodeURIComponent(t)}`,
};

/* ---------------- Nav ---------------- */
function ToolNav() {
  return (
    <header className="nav">
      <nav className="nav-inner" aria-label="주 내비게이션">
        <a href="index.html" className="nav-logo">
          <GDoodle name="star" size={28} tilt={-10} aria-hidden="true" />
          <span className="nav-logo-text">gollage</span>
        </a>
        <div className="nav-text-links">
          <a href="index.html">골라주가 뭐야?</a>
        </div>
      </nav>
    </header>
  );
}

/* ---------------- Tool section ---------------- */
function ToolSection({ copy, tool }) {
  const { mood, time, setTime, otts, setOtts, 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" className="tool-card-inner" style={{ transition: 'none' }}>
            <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} />
              <OttRow label="플랫폼" options={OTTS} value={otts} onChange={setOtts} />
            </div>

            <div aria-live="polite" aria-atomic="true" className="sr-only">
              {phase === 'curating' && '추천 영상을 찾고 있어요.'}
              {phase === 'result' && pick && `${pick.title} 추천 완료.`}
              {phase === 'error' && '추천을 찾지 못했어요. 다시 시도해보세요.'}
            </div>

            {phase !== 'idle' && (
              <div className="tool-result-area">
                {phase === 'curating' && <Curating mood={mood} />}
                {phase === 'error' && <FetchError onRetry={tool.reroll} />}
                {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>
  );
}

/* ---------------- Error state ---------------- */
function FetchError({ onRetry }) {
  return (
    <div className="curating">
      <GDoodle name="bird" size={36} aria-hidden="true" />
      <div>
        <div className="curating-title">추천을 못 찾았어.</div>
        <div className="curating-sub">네트워크 상태를 확인하고 다시 시도해봐.</div>
      </div>
      <GButton variant="secondary" size="sm" onClick={onRetry}>다시 시도</GButton>
    </div>
  );
}

/* ---------------- 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>
  );
}

/* ---------------- Curator note (with mobile expand) ---------------- */
function CuratorNote({ reason }) {
  const [expanded, setExpanded] = React.useState(false);
  const [needsClamp, setNeedsClamp] = React.useState(false);
  const textRef = React.useRef(null);

  React.useEffect(() => {
    setExpanded(false);
    setNeedsClamp(false);
    const id = setTimeout(() => {
      const el = textRef.current;
      if (!el) return;
      // 클램핑된 높이 측정
      const clampedH = el.clientHeight;
      // 클램프 해제 후 전체 높이 측정
      el.style.display = 'block';
      el.style.overflow = 'visible';
      el.style.webkitLineClamp = 'unset';
      const fullH = el.scrollHeight;
      // 복원
      el.style.display = '';
      el.style.overflow = '';
      el.style.webkitLineClamp = '';
      setNeedsClamp(fullH > clampedH);
    }, 0);
    return () => clearTimeout(id);
  }, [reason]);

  return (
    <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 }} />
        <div style={{ flex: 1 }}>
          <p ref={textRef} className={`result-curator-text${!expanded ? ' result-curator-text--clamped' : ''}`}>{reason}</p>
          {needsClamp && !expanded && (
            <button className="result-curator-expand" onClick={() => setExpanded(true)}>더보기</button>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------------- Result block ---------------- */
function Result({ copy, tool }) {
  const { pick, mood, time } = tool;
  const t = (TIMES.find(x => x.id === time) || {}).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.year ? ` · ${pick.year}` : ''}{pick.runtime ? ` · ${pick.runtime}` : ''}</div>
        {pick.reason && <CuratorNote reason={pick.reason} />}
        <div className="result-meta-row">
          <span className="result-where-label">어디서 봐</span>
          {pick.platform
            ? <PlatformBadge name={pick.platform} />
            : <span className="result-where-none">직접 검색</span>}
          {t && <span className="result-criteria">· {t} 기준으로 골랐어</span>}
        </div>
        <div className="result-actions">
          <GButton variant="accent"
            onClick={() => {
              const url = pick.platform && PLATFORM_SEARCH[pick.platform]?.(pick.title);
              url ? window.open(url, '_blank', 'noopener,noreferrer') : 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>
  );
}

/* ---------------- Toast ---------------- */
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>
  );
}

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

  const [mood, setMood] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [otts, setOtts] = React.useState([]);
  const [phase, setPhase] = React.useState('idle');
  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, selectedOtts) => {
    const gen = ++callGen.current;
    setPhase('curating');
    setShowGollage(false);
    try {
      const result = await window.TMDB.fetchByMood(m.id, t, selectedOtts);
      if (gen !== callGen.current) return;
      result.color = m.poster;
      setPick(result);
      setPhase('result');
    } catch (_) {
      if (gen !== callGen.current) return;
      setPhase('error');
    }
  };

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

  const handleTimeChange = (t) => {
    const next = time === t ? null : t;
    setTime(next);
    if (mood) runCurate(mood, next, otts);
  };

  const handleOttChange = (next) => {
    setOtts(next);
    if (mood) runCurate(mood, time, next);
  };

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

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

  const onShare = (where) => {
    if (where === 'pick')        flashToast(copy.saved);
    else if (where === '저장')   flashToast('카드 저장 완료.');
    else if (where === '인스타')      flashToast('인스타 공유 완료!');
    else if (where === '인스타-에러') flashToast('공유 실패. 저장 버튼을 써봐.');
    else if (where === 'X')          flashToast('X 공유 완료!');
    else if (where === 'X-에러')     flashToast('공유 실패. 저장 버튼을 써봐.');
    else if (where === '카톡')       flashToast('카톡 공유 완료!');
    else if (where === '카톡-에러')  flashToast('공유 실패. 저장 버튼을 써봐.');
  };

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

  const tool = { mood, time, setTime: handleTimeChange, otts, setOtts: handleOttChange, phase, pick, showGollage, choose, reroll, makeGollage, onShare };

  return (
    <div className="app">
      <ToolNav />
      <main id="main-content">
        <ToolSection copy={copy} tool={tool} />
      </main>
<Toast msg={toast} />
    </div>
  );
}

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