// main-tabs.jsx — Explore, QR scan, Library, MyPage.
(function () {
  const T = window.T, { Btn, Chip, Eyebrow, ImgSlot, IconBtn, Logo } = window;
  const { useState } = React;

  function ScreenHead({ eyebrow, title, sub, right }) {
    return (
      <div style={{ padding: '18px 22px 12px', display: 'flex', alignItems: 'flex-start',
        justifyContent: 'space-between', gap: 12 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          {eyebrow && <Eyebrow color={T.gold}>{eyebrow}</Eyebrow>}
          <h1 style={{ fontFamily: T.display, fontSize: 27, letterSpacing: -.6, lineHeight: 1.18, color: T.ink,
            margin: eyebrow ? '8px 0 0' : 0 }}>{title}</h1>
          {sub && <p style={{ fontFamily: T.sans, fontSize: 13.5, color: T.muted, margin: '5px 0 0' }}>{sub}</p>}
        </div>
        {right}
      </div>
    );
  }
  window.ScreenHead = ScreenHead;

  // ── Explore ─────────────────────────────────────────────────
  function Explore({ go }) {
    const [cat, setCat] = useState('테마');
    const cats = ['테마', '지역', '시대'];
    const themes = ['궁궐', '성곽·문', '사당·제례', '정원·정자', '마을', '공예'];
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.canvas, overflow: 'hidden' }}>
        <ScreenHead eyebrow="둘러보기" title="여행을 미리 그려봐요"
          sub="위치와 상관없이 테마·지역·시대로 찾아보세요"
          right={<IconBtn name="search" onClick={() => go('search')} />} />
        <div style={{ display: 'flex', gap: 8, padding: '4px 22px 14px', flexShrink: 0 }}>
          {cats.map(c => <Chip key={c} active={cat === c} onClick={() => setCat(c)}>{c}</Chip>)}
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '0 22px 24px', scrollbarWidth: 'none' }}>
          {/* featured */}
          <button onClick={() => go('detail', { id: 'jongmyo' })} style={{ width: '100%', textAlign: 'left',
            cursor: 'pointer', border: 'none', borderRadius: T.r.xl, overflow: 'hidden', padding: 0,
            position: 'relative', marginBottom: 18, background: T.teal }}>
            <ImgSlot label="추천 컬렉션 대표 이미지" h={170} r={0} tone="dark" />
            <div style={{ position: 'absolute', inset: 0, background:
              'linear-gradient(to top, rgba(24,48,42,.92), transparent 65%)' }} />
            <div style={{ position: 'absolute', left: 18, right: 18, bottom: 16 }}>
              <Eyebrow color={T.gold}>이주의 컬렉션</Eyebrow>
              <div style={{ fontFamily: T.display, fontSize: 22, color: T.onDark, letterSpacing: -.4,
                marginTop: 6 }}>왕의 하루를 따라 걷기</div>
              <div style={{ fontFamily: T.sans, fontSize: 13, color: T.onDarkMuted, marginTop: 3 }}>
                7곳 · 도보 코스 약 2시간</div>
            </div>
          </button>

          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 18 }}>
            {themes.map((t, i) => (
              <Chip key={t} size="sm" color={window.TAG_COLORS[i % 6].bg}
                active={i === 0} onClick={() => {}}>{t}</Chip>
            ))}
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {window.SITES.map(s => {
              const col = window.TAG_COLORS[s.c];
              return (
                <button key={s.id} onClick={() => go('detail', { id: s.id })} style={{ textAlign: 'left',
                  cursor: 'pointer', background: T.soft, border: '1px solid ' + T.hairlineSoft,
                  borderRadius: T.r.lg, overflow: 'hidden', padding: 0 }}>
                  <ImgSlot label={s.name} h={96} r={0} />
                  <div style={{ padding: '10px 12px 12px' }}>
                    <div style={{ fontFamily: T.display, fontSize: 16, letterSpacing: -.3, color: T.ink }}>{s.name}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 4 }}>
                      <span style={{ width: 6, height: 6, borderRadius: 9, background: col.bg }} />
                      <span style={{ fontFamily: T.sans, fontSize: 11.5, color: T.muted }}>{s.era} · {s.region}</span>
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ── QR Scan ─────────────────────────────────────────────────
  function QRScan({ go }) {
    const [err, setErr] = useState(false);
    return (
      <div style={{ position: 'absolute', inset: 0, background: '#10120f', overflow: 'hidden',
        display: 'flex', flexDirection: 'column' }}>
        {/* camera placeholder */}
        <div style={{ position: 'absolute', inset: 0, background:
          'radial-gradient(120% 80% at 50% 40%, #2b2f26, #121410)' }}>
          <div style={{ position: 'absolute', inset: 0, background:
            'repeating-linear-gradient(115deg, rgba(255,255,255,.025) 0 18px, transparent 18px 40px)' }} />
        </div>
        {/* top bar */}
        <div style={{ position: 'relative', zIndex: 3, display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', padding: '14px 18px' }}>
          <IconBtn name="x" onClick={() => go('home')} bg="rgba(255,255,255,.12)" border="transparent"
            color={T.onDark} />
          <span style={{ fontFamily: T.display, fontSize: 17, color: T.onDark, letterSpacing: -.3 }}>QR 스캔</span>
          <IconBtn name="flash" bg="rgba(255,255,255,.12)" border="transparent" color={T.onDark} />
        </div>
        {/* scan frame */}
        <div style={{ position: 'relative', zIndex: 3, flex: 1, display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', gap: 26, marginTop: -30 }}>
          <div style={{ width: 232, height: 232, position: 'relative' }}>
            {[['top','left'],['top','right'],['bottom','left'],['bottom','right']].map((c, i) => (
              <div key={i} style={{ position: 'absolute', [c[0]]: 0, [c[1]]: 0, width: 42, height: 42,
                [`border${c[0][0].toUpperCase()+c[0].slice(1)}`]: '3px solid ' + (err ? T.clay : T.gold),
                [`border${c[1][0].toUpperCase()+c[1].slice(1)}`]: '3px solid ' + (err ? T.clay : T.gold),
                [`border${c[0]==='top'?'TopLeftRadius':''}`]: undefined,
                borderRadius: c[0]==='top'&&c[1]==='left'?'14px 0 0 0':c[0]==='top'?'0 14px 0 0':c[1]==='left'?'0 0 0 14px':'0 0 14px 0' }} />
            ))}
            {!err && <div style={{ position: 'absolute', left: 8, right: 8, top: 0, height: 2.5,
              background: 'linear-gradient(90deg, transparent, ' + T.gold + ', transparent)',
              borderRadius: 2, animation: 'munaScan 2.2s ease-in-out infinite' }} />}
          </div>
          <div style={{ textAlign: 'center', padding: '0 40px' }}>
            <div style={{ fontFamily: T.sans, fontSize: 15, fontWeight: 600,
              color: err ? T.claySoft : T.onDark }}>
              {err ? '인식할 수 없는 코드예요' : '안내판의 QR 코드를 비춰주세요'}</div>
            <div style={{ fontFamily: T.sans, fontSize: 13, color: 'rgba(246,240,227,.55)', marginTop: 5 }}>
              {err ? 'Muna 코드가 맞는지 확인해 주세요' : '코드를 비추면 그 자리에서 바로 청취가 시작돼요'}</div>
          </div>
        </div>
        {/* bottom actions */}
        <div style={{ position: 'relative', zIndex: 3, padding: '0 22px 30px',
          display: 'flex', flexDirection: 'column', gap: 10 }}>
          {err ? (
            <Btn full kind="gold" onClick={() => setErr(false)}>다시 스캔하기</Btn>
          ) : (
            <Btn full kind="gold" icon="sparkle" onClick={() => go('detail', { id: 'geun' })}>스캔 성공 (데모)</Btn>
          )}
          <button onClick={() => setErr(!err)} style={{ background: 'none', border: 'none', cursor: 'pointer',
            fontFamily: T.sans, fontSize: 13.5, fontWeight: 600, color: 'rgba(246,240,227,.6)', padding: 6 }}>
            {err ? '' : '인식 실패 화면 보기'}</button>
        </div>
      </div>
    );
  }

  // ── Library ─────────────────────────────────────────────────
  function Library({ go, app }) {
    const [tab, setTab] = useState('visited');
    const visited = ['geun', 'gwang', 'hyang'].map(window.siteById);
    const saved = ['jongmyo', 'bukchon', 'injeong'].map(window.siteById);
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.canvas, overflow: 'hidden' }}>
        <ScreenHead eyebrow="나의 발자취" title="보관함"
          sub="다녀온 곳과 담아둔 이야기를 모아봐요" />
        {/* recap card */}
        <div style={{ padding: '4px 22px 14px', flexShrink: 0 }}>
          <div style={{ background: T.teal, borderRadius: T.r.xl, padding: '16px 18px', display: 'flex',
            alignItems: 'center', gap: 16 }}>
            <div>
              <div style={{ fontFamily: T.sans, fontSize: 12, fontWeight: 700, color: T.gold,
                letterSpacing: 1, textTransform: 'uppercase' }}>2026년, 지금까지</div>
              <div style={{ fontFamily: T.display, fontSize: 21, color: T.onDark, letterSpacing: -.3,
                marginTop: 4 }}>유산 12곳 · 이야기 18편</div>
              <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.onDarkMuted, marginTop: 3 }}>
                들은 시간 2시간 41분</div>
            </div>
            <div style={{ marginLeft: 'auto' }}>
              <IconBtn name="trail" color={T.gold} bg={T.tealEl} border="transparent" /></div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, padding: '0 22px 14px', flexShrink: 0 }}>
          <Chip active={tab === 'visited'} onClick={() => setTab('visited')}>다녀온 곳</Chip>
          <Chip active={tab === 'saved'} onClick={() => setTab('saved')}>담아둔 이야기</Chip>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '0 22px 24px', scrollbarWidth: 'none' }}>
          {(tab === 'visited' ? visited : saved).map((s, i) => (
            <button key={s.id} onClick={() => go('detail', { id: s.id })} style={{ width: '100%',
              textAlign: 'left', cursor: 'pointer', background: 'none', border: 'none', padding: '13px 0',
              borderBottom: '1px solid ' + T.hairlineSoft, display: 'flex', alignItems: 'center', gap: 14 }}>
              <ImgSlot label="" h={62} style={{ width: 62, flexShrink: 0 }} r={14} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: T.display, fontSize: 17, letterSpacing: -.3, color: T.ink }}>{s.name}</div>
                <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, marginTop: 3 }}>
                  {tab === 'visited' ? `${3 - i}일 전 청취 · ${s.min}분` : `담아둠 · ${s.type}`}</div>
              </div>
              <Icon name={tab === 'visited' ? 'play' : 'bookmark'} size={19}
                color={tab === 'visited' ? T.teal : T.gold} fill={tab === 'saved' ? T.gold : 'none'} />
            </button>
          ))}
        </div>
      </div>
    );
  }

  // ── MyPage ──────────────────────────────────────────────────
  function MyPage({ go, app }) {
    const selNames = app.interests.map(id => window.INTERESTS.find(i => i.id === id)).filter(Boolean);
    const lang = window.LANGS.find(l => l.code === app.lang) || window.LANGS[0];
    const rows = [
      { ic: 'globe', t: '청취 언어', v: lang.native, act: () => go('langPick') },
      { ic: 'bookmark', t: '보관함', v: '18편', act: () => go('library') },
      { ic: 'sound', t: '재생 설정', v: '자동 재생 · 배속 1.0x' },
      { ic: 'gear', t: '알림 · 권한', v: '근접 알림 켜짐' },
      { ic: 'grid', t: '상태 화면 미리보기', v: '', act: () => go('states') },
    ];
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.canvas, overflow: 'hidden' }}>
        <div style={{ flex: 1, overflowY: 'auto', scrollbarWidth: 'none', paddingBottom: 24 }}>
          {/* profile */}
          <div style={{ padding: '22px 22px 18px', display: 'flex', alignItems: 'center', gap: 15 }}>
            <div style={{ width: 62, height: 62, borderRadius: 99, background: T.strong, flexShrink: 0,
              display: 'grid', placeItems: 'center', border: '1px solid ' + T.hairline }}>
              <Icon name="user" size={28} color={T.muted} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: T.display, fontSize: 21, letterSpacing: -.4, color: T.ink }}>여행자님</div>
              <div style={{ fontFamily: T.sans, fontSize: 13, color: T.muted, marginTop: 2 }}>
                로그인하면 발자취가 안전하게 보관돼요</div>
            </div>
          </div>
          <div style={{ padding: '0 22px' }}>
            <Btn full kind="primary" size="md" onClick={() => go('login')}>로그인 / 회원가입</Btn>
          </div>

          {/* interests */}
          <div style={{ padding: '24px 22px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontFamily: T.sans, fontSize: 13, fontWeight: 700, color: T.muted, letterSpacing: .3 }}>
              관심사</span>
            <button onClick={() => go('interest', { edit: true })} style={{ background: 'none', border: 'none',
              cursor: 'pointer', fontFamily: T.sans, fontSize: 13.5, fontWeight: 600, color: T.teal }}>수정</button>
          </div>
          <div style={{ padding: '0 22px', display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {selNames.length ? selNames.map(it => {
              const col = window.TAG_COLORS[it.c];
              return <span key={it.id} style={{ fontFamily: T.sans, fontSize: 13.5, fontWeight: 600,
                color: col.bg, background: col.soft, padding: '7px 13px', borderRadius: 99 }}>{it.label}</span>;
            }) : <span style={{ fontFamily: T.sans, fontSize: 13.5, color: T.mutedSoft }}>선택한 관심사가 없어요</span>}
          </div>

          {/* settings list */}
          <div style={{ padding: '24px 22px 0' }}>
            <div style={{ background: T.soft, borderRadius: T.r.lg, border: '1px solid ' + T.hairlineSoft,
              overflow: 'hidden' }}>
              {rows.map((r, i) => (
                <button key={r.t} onClick={r.act} style={{ width: '100%', textAlign: 'left',
                  cursor: r.act ? 'pointer' : 'default', background: 'none',
                  border: 'none', borderTop: i ? '1px solid ' + T.hairlineSoft : 'none',
                  padding: '15px 16px', display: 'flex', alignItems: 'center', gap: 13 }}>
                  <Icon name={r.ic} size={20} color={T.teal} />
                  <span style={{ flex: 1, fontFamily: T.sans, fontSize: 15, fontWeight: 500, color: T.ink }}>{r.t}</span>
                  <span style={{ fontFamily: T.sans, fontSize: 13, color: T.muted }}>{r.v}</span>
                  {r.act && <Icon name="chevronR" size={17} color={T.mutedSoft} />}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  Object.assign(window, { Explore, QRScan, Library, MyPage });
})();
