// extra.jsx — PostPlay, Login, Language sheet, Search, status screens.
(function () {
  const T = window.T, { Btn, Eyebrow, ImgSlot, IconBtn, Chip } = window;
  const { useState } = React;

  // ── PostPlay ────────────────────────────────────────────────
  function PostPlay({ go, app, params, set }) {
    const s = window.siteById(params.id) || window.SITES[0];
    const { v } = window.pickVoice(app);
    const [fb, setFb] = useState(null);
    const [saved, setSaved] = useState(app.saved?.includes(s.id));
    const nearby = window.SITES.filter(x => x.id !== s.id && x.dist <= 1000).slice(0, 2);
    const more = window.SITES.filter(x => x.id !== s.id && x.dist > 1000).slice(0, 2);
    return (
      <div style={{ position: 'absolute', inset: 0, background: T.canvas, overflow: 'hidden',
        display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '12px 16px 0' }}>
          <IconBtn name="x" onClick={() => go('home')} /></div>
        <div style={{ flex: 1, overflowY: 'auto', scrollbarWidth: 'none', padding: '4px 24px 24px' }}>
          <div style={{ width: 56, height: 56, borderRadius: 18, background: T.teal, display: 'grid',
            placeItems: 'center', boxShadow: 'inset 0 0 0 1.5px ' + T.gold, marginBottom: 16 }}>
            <Icon name="check" size={28} color={T.gold} stroke={2.2} /></div>
          <Eyebrow color={T.goldDim}>이야기를 다 들었어요</Eyebrow>
          <h1 style={{ fontFamily: T.display, fontSize: 28, letterSpacing: -.7, color: T.ink, margin: '10px 0 6px' }}>
            {s.full}</h1>
          <p style={{ fontFamily: T.sans, fontSize: 14.5, color: T.muted, margin: 0 }}>
            {v.name}의 목소리로 들은 이야기 · 약 6분</p>

          {/* feedback */}
          <div style={{ marginTop: 24, background: T.soft, border: '1px solid ' + T.hairlineSoft,
            borderRadius: T.r.lg, padding: '18px 18px' }}>
            <div style={{ fontFamily: T.display, fontSize: 18, letterSpacing: -.3, color: T.ink,
              textAlign: 'center', marginBottom: 14 }}>이 이야기, 어떠셨어요?</div>
            <div style={{ display: 'flex', gap: 10 }}>
              {[['good', '좋았어요', 'heart'], ['meh', '아쉬워요', 'flag']].map(([id, label, ic]) => (
                <button key={id} onClick={() => setFb(id)} style={{ flex: 1, cursor: 'pointer',
                  padding: '14px 0', borderRadius: T.r.md, background: fb === id ? T.teal : T.canvas,
                  border: '1px solid ' + (fb === id ? T.teal : T.hairline), display: 'flex',
                  flexDirection: 'column', alignItems: 'center', gap: 7, transition: 'all .16s' }}>
                  <Icon name={ic} size={22} color={fb === id ? T.gold : T.muted}
                    fill={fb === id && ic === 'heart' ? T.gold : 'none'} />
                  <span style={{ fontFamily: T.sans, fontSize: 13.5, fontWeight: 600,
                    color: fb === id ? T.onDark : T.body }}>{label}</span>
                </button>
              ))}
            </div>
            {fb && <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, textAlign: 'center',
              marginTop: 12, animation: 'munaFade .3s' }}>의견 고마워요. 다음 이야기에 반영할게요.</div>}
          </div>

          {/* actions */}
          <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
            <Btn full kind={saved ? 'soft' : 'primary'} icon="bookmark"
              onClick={() => { setSaved(true); set({ saved: [...new Set([...(app.saved || []), s.id])] }); }}>
              {saved ? '보관함에 있음' : '보관함에 저장'}</Btn>
            <IconBtn name="share" size={54} style={{ borderRadius: 12 }} />
          </div>

          {/* next */}
          <div style={{ marginTop: 28 }}>
            <div style={{ fontFamily: T.display, fontSize: 19, letterSpacing: -.4, color: T.ink, marginBottom: 4 }}>
              이어서 듣기 좋은 곳</div>
            <div style={{ fontFamily: T.sans, fontSize: 13, color: T.muted, marginBottom: 14 }}>
              바로 곁에 있어요</div>
            {nearby.map(x => <NextRow key={x.id} site={x} go={go} tag="가까움" />)}
            <div style={{ fontFamily: T.sans, fontSize: 13, color: T.muted, margin: '18px 0 14px' }}>
              관심사로 이어지는 이야기</div>
            {more.map(x => <NextRow key={x.id} site={x} go={go} tag="추천" />)}
          </div>
        </div>
      </div>
    );
  }
  function NextRow({ site, go, tag }) {
    const col = window.TAG_COLORS[site.c];
    return (
      <button onClick={() => go('detail', { id: site.id })} style={{ width: '100%', textAlign: 'left',
        cursor: 'pointer', background: 'none', border: 'none', padding: '10px 0', display: 'flex',
        alignItems: 'center', gap: 13, borderBottom: '1px solid ' + T.hairlineSoft }}>
        <ImgSlot label="" h={56} style={{ width: 56, flexShrink: 0 }} r={13} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <span style={{ fontFamily: T.display, fontSize: 16.5, letterSpacing: -.3, color: T.ink, whiteSpace: 'nowrap' }}>{site.name}</span>
            <span style={{ fontFamily: T.sans, fontSize: 10.5, fontWeight: 700, color: col.bg,
              background: col.soft, padding: '2px 7px', borderRadius: 99, whiteSpace: 'nowrap' }}>{tag}</span>
          </div>
          <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, marginTop: 2, whiteSpace: 'nowrap' }}>
            {site.type} · {site.dist >= 1000 ? (site.dist / 1000).toFixed(1) + 'km' : site.dist + 'm'}</div>
        </div>
        <div style={{ width: 38, height: 38, borderRadius: 99, background: T.teal, display: 'grid',
          placeItems: 'center', flexShrink: 0 }}>
          <Icon name="play" size={16} color={T.gold} fill={T.gold} /></div>
      </button>
    );
  }

  // ── Login ───────────────────────────────────────────────────
  function Login({ go }) {
    return (
      <div style={{ position: 'absolute', inset: 0, background: T.canvas, overflow: 'hidden',
        display: 'flex', flexDirection: 'column', padding: '14px 26px 30px' }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <IconBtn name="x" onClick={() => go('back')} /></div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <window.Logo size={40} />
          <h1 style={{ fontFamily: T.display, fontSize: 28, letterSpacing: -.7, color: T.ink, margin: '22px 0 10px' }}>
            발자취를 잃지 않게<br/>저장해 둘까요?</h1>
          <p style={{ fontFamily: T.sans, fontSize: 15, lineHeight: 1.6, color: T.body, margin: '0 0 28px' }}>
            로그인하면 보관함과 관심사가 계정에 연동돼, 기기를 바꿔도 그대로 이어집니다.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
            <Btn full kind="primary" onClick={() => go('home')}>휴대폰 번호로 계속</Btn>
            <Btn full kind="outline" onClick={() => go('home')}>이메일로 계속</Btn>
            <Btn full kind="soft" onClick={() => go('home')}>Apple로 계속</Btn>
          </div>
        </div>
        <button onClick={() => go('back')} style={{ background: 'none', border: 'none', cursor: 'pointer',
          fontFamily: T.sans, fontSize: 14.5, fontWeight: 600, color: T.muted, padding: 8 }}>
          로그인 없이 둘러보기</button>
      </div>
    );
  }

  // ── Language sheet (overlay) ────────────────────────────────
  function LangPick({ go, app, set }) {
    return (
      <div onClick={() => go('back')} style={{ position: 'absolute', inset: 0, zIndex: 40,
        background: 'rgba(24,30,26,.42)', display: 'flex', alignItems: 'flex-end', animation: 'munaFade .2s' }}>
        <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxHeight: '78%', background: T.canvas,
          borderRadius: '22px 22px 0 0', display: 'flex', flexDirection: 'column', animation: 'munaRise .3s ease' }}>
          <div style={{ padding: '12px 24px 8px', flexShrink: 0 }}>
            <div style={{ width: 40, height: 5, borderRadius: 9, background: T.hairline, margin: '0 auto 14px' }} />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <h3 style={{ fontFamily: T.display, fontSize: 22, letterSpacing: -.5, color: T.ink, margin: 0 }}>청취 언어</h3>
              <IconBtn name="x" size={38} ic={18} onClick={() => go('back')} /></div>
            <p style={{ fontFamily: T.sans, fontSize: 13, color: T.muted, margin: '6px 0 0' }}>
              해설과 자막이 선택한 언어로 제공돼요</p>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', scrollbarWidth: 'none', padding: '8px 16px 26px' }}>
            {window.LANGS.map(l => {
              const on = (app.lang || 'ko') === l.code;
              return (
                <button key={l.code} onClick={() => { set({ lang: l.code }); go('back'); }} style={{ width: '100%',
                  cursor: 'pointer', background: on ? T.soft : 'none', border: '1px solid ' + (on ? T.hairline : 'transparent'),
                  borderRadius: T.r.md, padding: '13px 14px', display: 'flex', alignItems: 'center', gap: 12,
                  marginBottom: 2 }}>
                  <span style={{ flex: 1, textAlign: 'left' }}>
                    <span style={{ fontFamily: T.sans, fontSize: 15.5, fontWeight: 600, color: T.ink }}>{l.native}</span>
                    <span style={{ fontFamily: T.sans, fontSize: 13, color: T.mutedSoft, marginLeft: 8 }}>{l.label}</span>
                  </span>
                  {on && <Icon name="check" size={20} color={T.teal} stroke={2.4} />}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ── Search ──────────────────────────────────────────────────
  function Search({ go }) {
    const [q, setQ] = useState('');
    const recent = ['경복궁', '종묘', '북촌'];
    const res = q ? window.SITES.filter(s => s.full.includes(q) || s.name.includes(q)) : [];
    return (
      <div style={{ position: 'absolute', inset: 0, background: T.canvas, overflow: 'hidden',
        display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '14px 18px 12px', display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
          <IconBtn name="chevronL" onClick={() => go('back')} bg={T.soft} />
          <div style={{ flex: 1, height: 48, borderRadius: 99, background: T.soft, border: '1px solid ' + T.hairline,
            display: 'flex', alignItems: 'center', gap: 10, padding: '0 16px' }}>
            <Icon name="search" size={19} color={T.muted} />
            <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="유산 이름으로 찾기"
              style={{ flex: 1, border: 'none', outline: 'none', background: 'none', fontFamily: T.sans,
                fontSize: 15, color: T.ink }} />
            {q && <button onClick={() => setQ('')} style={{ background: 'none', border: 'none', cursor: 'pointer' }}>
              <Icon name="x" size={17} color={T.mutedSoft} /></button>}
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', scrollbarWidth: 'none', padding: '8px 22px 24px' }}>
          {!q ? (
            <>
              <div style={{ fontFamily: T.sans, fontSize: 13, fontWeight: 700, color: T.muted, margin: '8px 0 12px' }}>
                최근 검색</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {recent.map(r => <Chip key={r} size="sm" onClick={() => setQ(r)}>{r}</Chip>)}
              </div>
              <div style={{ fontFamily: T.sans, fontSize: 13, fontWeight: 700, color: T.muted, margin: '24px 0 6px' }}>
                인기 유산</div>
              {window.SITES.slice(0, 4).map(s => <ResRow key={s.id} s={s} go={go} />)}
            </>
          ) : res.length ? (
            res.map(s => <ResRow key={s.id} s={s} go={go} />)
          ) : (
            <div style={{ textAlign: 'center', padding: '60px 20px' }}>
              <Icon name="search" size={34} color={T.mutedSoft} style={{ margin: '0 auto 12px' }} />
              <div style={{ fontFamily: T.sans, fontSize: 15, color: T.muted }}>‘{q}’ 검색 결과가 없어요</div>
            </div>
          )}
        </div>
      </div>
    );
  }
  function ResRow({ s, go }) {
    return (
      <button onClick={() => go('detail', { id: s.id })} style={{ width: '100%', textAlign: 'left',
        cursor: 'pointer', background: 'none', border: 'none', padding: '11px 0', display: 'flex',
        alignItems: 'center', gap: 13, borderBottom: '1px solid ' + T.hairlineSoft }}>
        <ImgSlot label="" h={50} style={{ width: 50, flexShrink: 0 }} r={12} />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: T.display, fontSize: 16.5, letterSpacing: -.3, color: T.ink }}>{s.full}</div>
          <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, marginTop: 2 }}>{s.type} · {s.region}</div>
        </div>
        <Icon name="arrowR" size={18} color={T.mutedSoft} />
      </button>
    );
  }

  Object.assign(window, { PostPlay, Login, LangPick, Search });
})();
