// onboarding.jsx — Muna onboarding: splash, intro slides, permissions, interests.
(function () {
  const T = window.T, { Btn, Chip, Eyebrow, ImgSlot } = window;
  const { useState } = React;

  // ── Brand mark ──────────────────────────────────────────────
  function Logo({ size = 40, light }) {
    const ink = light ? T.onDark : T.ink;
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: size, height: size, borderRadius: '32%', background: T.teal,
          display: 'grid', placeItems: 'center', position: 'relative',
          boxShadow: 'inset 0 0 0 2px ' + T.gold }}>
          <Icon name="location" size={size * 0.5} color={T.gold} stroke={2} />
        </div>
        <span style={{ fontFamily: T.display, fontSize: size * 0.72, color: ink,
          letterSpacing: -.5, lineHeight: 1 }}>Muna</span>
      </div>
    );
  }
  window.Logo = Logo;

  // ── 1. Splash ───────────────────────────────────────────────
  function Splash({ go }) {
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.canvas,
        padding: '0 26px 34px', overflow: 'hidden' }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 26 }}>
          <Logo size={46} />
          <div>
            <h1 style={{ fontFamily: T.display, fontSize: 40, lineHeight: 1.18, letterSpacing: -1,
              color: T.ink, margin: '0 0 14px' }}>발걸음마다,<br/>당신만의 이야기</h1>
            <p style={{ fontFamily: T.sans, fontSize: 16, lineHeight: 1.6, color: T.body, margin: 0,
              maxWidth: 300 }}>지금 선 자리의 문화유산을, 당신이 좋아하는 결의 이야기로 들려드려요.</p>
          </div>
          <ImgSlot label="히어로 · 클레이메이션 일러스트" h={250} r={T.r.xl} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Btn full kind="primary" onClick={() => go('intro')}>시작하기</Btn>
          <button onClick={() => go('home')} style={{ background: 'none', border: 'none', cursor: 'pointer',
            fontFamily: T.sans, fontSize: 14.5, fontWeight: 600, color: T.muted, padding: 6 }}>
            먼저 둘러볼게요
          </button>
        </div>
      </div>
    );
  }

  // ── 2. Intro slides ─────────────────────────────────────────
  const SLIDES = [
    { e: '관점이 다르면', t: '같은 유적,\n다른 이야기', d: '건축이 궁금한 사람과 사람 이야기에 끌리는 사람에게, 해설의 관점과 서사가 달라집니다.', label: '관심사별 스토리 분기', tone: 'cream' },
    { e: '어울리는 목소리', t: '이야기에 맞춰\n목소리를 골라요', d: '관심사에 어울리는 화자를 AI가 자동으로 배정해요. 고를 필요 없이, 어울리는 목소리가 들려옵니다.', label: '보이스 자동 배정', tone: 'dark' },
    { e: '지금, 그 자리에서', t: '걷다 보면\n이야기가 닿아요', d: '주변 유산을 자동으로 찾아 알려주고, QR을 비추면 그 자리에서 바로 청취가 시작됩니다.', label: '위치 · QR 진입', tone: 'cream' },
  ];
  function Intro({ go }) {
    const [i, setI] = useState(0);
    const s = SLIDES[i];
    const last = i === SLIDES.length - 1;
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.canvas,
        padding: '12px 26px 34px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <div style={{ display: 'flex', gap: 6 }}>
            {SLIDES.map((_, k) => <div key={k} style={{ width: k === i ? 22 : 7, height: 7, borderRadius: 9,
              background: k === i ? T.ink : T.hairline, transition: 'all .25s' }} />)}
          </div>
          <button onClick={() => go('permission')} style={{ background: 'none', border: 'none', cursor: 'pointer',
            fontFamily: T.sans, fontSize: 14, fontWeight: 600, color: T.muted }}>건너뛰기</button>
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 26 }}>
          <ImgSlot label={s.label} h={232} r={T.r.xl} tone={s.tone} />
          <div>
            <Eyebrow color={T.gold}>{s.e}</Eyebrow>
            <h2 style={{ fontFamily: T.display, fontSize: 34, lineHeight: 1.22, letterSpacing: -.8,
              color: T.ink, margin: '12px 0 14px', whiteSpace: 'pre-line' }}>{s.t}</h2>
            <p style={{ fontFamily: T.sans, fontSize: 15.5, lineHeight: 1.62, color: T.body, margin: 0 }}>{s.d}</p>
          </div>
        </div>
        <Btn full kind="primary" icon={last ? undefined : undefined}
          onClick={() => last ? go('permission') : setI(i + 1)}>
          {last ? '다음' : '계속'}
        </Btn>
      </div>
    );
  }

  // ── 3. Permissions ──────────────────────────────────────────
  function Permission({ go, app, set }) {
    const lang = (window.LANGS.find(l => l.code === app.lang) || window.LANGS[0]);
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.canvas,
        padding: '24px 26px 34px' }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <div style={{ width: 70, height: 70, borderRadius: 24, background: T.teal, display: 'grid',
            placeItems: 'center', marginBottom: 24, boxShadow: 'inset 0 0 0 2px ' + T.gold }}>
            <Icon name="location" size={34} color={T.gold} stroke={1.9} />
          </div>
          <Eyebrow color={T.gold}>거의 다 왔어요</Eyebrow>
          <h2 style={{ fontFamily: T.display, fontSize: 30, lineHeight: 1.22, letterSpacing: -.7,
            color: T.ink, margin: '12px 0 12px' }}>위치를 알려주시면,<br/>곁의 이야기를 찾아드려요</h2>
          <p style={{ fontFamily: T.sans, fontSize: 15, lineHeight: 1.6, color: T.body, margin: '0 0 24px' }}>
            현재 위치를 기준으로 주변 문화유산을 지도에 표시하고, 가까워지면 알려드립니다. 위치 정보는 청취 안내에만 쓰여요.</p>

          {/* permission rows */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Row icon="location" title="위치 접근" sub="주변 유산 탐지 · 근접 알림" badge="필수" />
            <button onClick={() => go('langPick')} style={{ all: 'unset', cursor: 'pointer' }}>
              <Row icon="globe" title="청취 언어" sub={lang.native + ' 로 안내'} chevron />
            </button>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 20 }}>
          <Btn full kind="primary" onClick={() => go('interest')}>위치 허용하고 계속</Btn>
          <button onClick={() => go('interest')} style={{ background: 'none', border: 'none', cursor: 'pointer',
            fontFamily: T.sans, fontSize: 14.5, fontWeight: 600, color: T.muted, padding: 6 }}>
            나중에 할게요
          </button>
        </div>
      </div>
    );
  }
  function Row({ icon, title, sub, badge, chevron }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 16px',
        background: T.soft, borderRadius: T.r.lg, border: '1px solid ' + T.hairlineSoft }}>
        <div style={{ width: 42, height: 42, borderRadius: 13, background: T.canvas, display: 'grid',
          placeItems: 'center', flexShrink: 0, border: '1px solid ' + T.hairline }}>
          <Icon name={icon} size={21} color={T.teal} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: T.sans, fontSize: 15.5, fontWeight: 600, color: T.ink }}>{title}</div>
          <div style={{ fontFamily: T.sans, fontSize: 13, color: T.muted, marginTop: 1 }}>{sub}</div>
        </div>
        {badge && <span style={{ fontFamily: T.sans, fontSize: 11.5, fontWeight: 700, color: T.gold,
          background: '#f3e6c4', padding: '3px 9px', borderRadius: 99 }}>{badge}</span>}
        {chevron && <Icon name="chevronR" size={18} color={T.mutedSoft} />}
      </div>
    );
  }

  // ── 4. Interests ────────────────────────────────────────────
  function Interest({ go, app, set }) {
    const sel = app.interests;
    const toggle = (id) => {
      const next = sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id];
      set({ interests: next });
    };
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.canvas }}>
        <div style={{ padding: '20px 26px 4px' }}>
          <Eyebrow color={T.gold}>관심사 선택</Eyebrow>
          <h2 style={{ fontFamily: T.display, fontSize: 29, lineHeight: 1.22, letterSpacing: -.7,
            color: T.ink, margin: '10px 0 8px' }}>어떤 이야기에<br/>끌리시나요?</h2>
          <p style={{ fontFamily: T.sans, fontSize: 14.5, lineHeight: 1.55, color: T.body, margin: 0 }}>
            고른 관심사로 해설의 결과 어울리는 목소리가 정해져요. 여러 개를 골라도 좋아요.</p>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: '18px 22px 12px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 11 }}>
            {window.INTERESTS.map(it => {
              const on = sel.includes(it.id);
              const col = window.TAG_COLORS[it.c];
              return (
                <button key={it.id} onClick={() => toggle(it.id)} style={{
                  textAlign: 'left', cursor: 'pointer', padding: '15px 15px 14px', borderRadius: T.r.lg,
                  background: on ? col.bg : T.soft, border: '1.5px solid ' + (on ? col.bg : T.hairlineSoft),
                  transition: 'all .16s', position: 'relative', minHeight: 92,
                  display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: 3 }}>
                  <div style={{ position: 'absolute', top: 13, right: 13, width: 22, height: 22,
                    borderRadius: 99, border: '1.5px solid ' + (on ? 'transparent' : T.hairline),
                    background: on ? col.fg : 'transparent', display: 'grid', placeItems: 'center' }}>
                    {on && <Icon name="check" size={14} color={col.bg} stroke={2.6} />}
                  </div>
                  <span style={{ fontFamily: T.display, fontSize: 19, letterSpacing: -.4,
                    color: on ? col.fg : T.ink }}>{it.label}</span>
                  <span style={{ fontFamily: T.sans, fontSize: 12.5, fontWeight: 500,
                    color: on ? col.fg : T.muted, opacity: on ? .8 : 1 }}>{it.sub}</span>
                </button>
              );
            })}
          </div>
        </div>
        <div style={{ padding: '12px 26px 30px', borderTop: '1px solid ' + T.hairlineSoft,
          background: T.canvas, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ fontFamily: T.sans, fontSize: 13.5, color: T.muted, flexShrink: 0 }}>
            <b style={{ color: T.ink, fontWeight: 700 }}>{sel.length}</b>개 선택</div>
          <Btn full kind="primary" disabled={sel.length === 0} onClick={() => go('home')}>
            {sel.length === 0 ? '하나 이상 골라주세요' : '이야기 만나러 가기'}
          </Btn>
        </div>
      </div>
    );
  }

  Object.assign(window, { Splash, Intro, Permission, Interest });
})();
