// settings.jsx — Settings screen + About screen
// Entry from HomeV2's avatar icon. Wires accent/mode through useTweaks.

const ST = window.__cpMakeTheme();

const SETTINGS_ACCENTS = {
  walnut:    '#8B6F47',
  terracotta:'#C97B5C',
  forest:    '#4A6B4F',
  plum:      '#8B5C7A',
};

// ─────────────────────────────────────────────────────────────
// Atoms
// ─────────────────────────────────────────────────────────────
function Section({ label, children, footer }) {
  return (
    <div style={{ padding: '0 22px' }}>
      <div style={{
        padding: '24px 6px 8px',
        fontSize: 11, fontWeight: 600, color: ST.ink3,
        letterSpacing: '0.08em', textTransform: 'uppercase',
      }}>{label}</div>
      <div style={{
        background: ST.surface,
        border: `0.5px solid ${ST.hairline}`,
        borderRadius: 14,
        overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>{children}</div>
      {footer && (
        <div style={{
          padding: '8px 6px 0',
          fontSize: 12, color: ST.ink3, letterSpacing: '-0.01em', lineHeight: 1.45,
        }}>{footer}</div>
      )}
    </div>
  );
}

function Row({ label, sub, value, onClick, chevron, end, danger, first }) {
  const Tag = onClick ? 'button' : 'div';
  return (
    <Tag onClick={onClick} style={{
      width: '100%',
      display: 'flex', alignItems: 'center', gap: 12,
      minHeight: 48,
      padding: '11px 14px',
      borderTop: first ? 'none' : `0.5px solid ${ST.hairline}`,
      background: 'transparent',
      border: 'none',
      borderTopLeftRadius: 0, borderTopRightRadius: 0,
      borderBottomLeftRadius: 0, borderBottomRightRadius: 0,
      fontFamily: 'inherit',
      cursor: onClick ? 'pointer' : 'default',
      textAlign: 'left',
      WebkitTapHighlightColor: 'transparent',
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 14.5, color: danger ? ST.danger : ST.ink,
          letterSpacing: '-0.01em',
          fontWeight: danger ? 500 : 400,
        }}>{label}</div>
        {sub && (
          <div style={{
            marginTop: 2,
            fontSize: 12, color: ST.ink3,
            letterSpacing: '-0.01em', lineHeight: 1.35,
          }}>{sub}</div>
        )}
      </div>
      {end}
      {value && (
        <div style={{
          fontSize: 14, color: ST.ink2,
          letterSpacing: '-0.01em', whiteSpace: 'nowrap',
        }}>{value}</div>
      )}
      {chevron && (
        <svg width="7" height="12" viewBox="0 0 8 14" fill="none" style={{ flexShrink: 0, marginLeft: 2 }}>
          <path d="M1.5 1.5L6.5 7L1.5 12.5" stroke={ST.ink3} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      )}
    </Tag>
  );
}

function Toggle({ on, onChange, accent }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 46, height: 28, borderRadius: 999,
      background: on ? (accent || '#4A6B4F') : 'rgba(60,42,20,0.18)',
      border: 'none',
      padding: 0,
      position: 'relative',
      cursor: 'pointer', flexShrink: 0,
      transition: 'background 0.2s ease',
      WebkitTapHighlightColor: 'transparent',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 20 : 2,
        width: 24, height: 24, borderRadius: 24,
        background: '#FFF',
        boxShadow: '0 1.5px 3px rgba(0,0,0,0.18)',
        transition: 'left 0.2s ease',
      }} />
    </button>
  );
}

function Segmented({ options, value, onChange }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      padding: 3, borderRadius: 9,
      background: 'rgba(60,42,20,0.06)',
      flexShrink: 0,
    }}>
      {options.map(o => {
        const isOn = value === o.value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            height: 28, padding: '0 12px',
            border: 'none',
            borderRadius: 7,
            background: isOn ? ST.surface2 : 'transparent',
            boxShadow: isOn ? '0 1px 2px rgba(31,24,18,0.08)' : 'none',
            fontFamily: 'inherit', fontSize: 12, fontWeight: 500,
            color: isOn ? ST.ink : ST.ink2,
            cursor: 'pointer', letterSpacing: '-0.01em',
            WebkitTapHighlightColor: 'transparent',
            display: 'inline-flex', alignItems: 'center', gap: 5,
          }}>{o.icon}{o.label}</button>
        );
      })}
    </div>
  );
}

function ColorSwatches({ value, options, onChange }) {
  return (
    <div style={{ display: 'inline-flex', gap: 8, flexShrink: 0 }}>
      {options.map(c => {
        const isOn = value === c;
        return (
          <button key={c} onClick={() => onChange(c)} style={{
            width: 28, height: 28, borderRadius: 28, padding: 0,
            background: c,
            border: isOn ? `2.5px solid ${ST.surface}` : `0.5px solid ${ST.hairlineStrong}`,
            outline: isOn ? `2px solid ${c}` : 'none',
            cursor: 'pointer',
            WebkitTapHighlightColor: 'transparent',
          }} />
        );
      })}
    </div>
  );
}

function Avatar({ name, size = 56, accent }) {
  const initial = (name || '?').slice(0, 1);
  return (
    <div style={{
      width: size, height: size, borderRadius: size,
      background: `linear-gradient(135deg, ${accent} 0%, ${shade(accent, -18)} 100%)`,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      color: '#FFF', fontWeight: 700, fontSize: size * 0.42,
      letterSpacing: '-0.02em',
      flexShrink: 0,
      boxShadow: `0 1px 0 rgba(255,255,255,0.4) inset`,
    }}>{initial}</div>
  );
}

function HamsterAvatar({ size = 56, accent, count = 3, face = 'basic', ring }) {
  return (
    <div style={{
      position: 'relative',
      width: size, height: size, borderRadius: size,
      background: `radial-gradient(circle at 50% 38%, ${accent}26 0%, ${accent}10 60%, ${accent}05 100%)`,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
      overflow: 'hidden',
      border: ring ? `1.5px solid ${accent}40` : 'none',
    }}>
      <CheekPouch count={count} max={10} accent={accent}
                  face={face}
                  headOnly={true}
                  size={size} animateOnChange={false} />
    </div>
  );
}

function shade(hex, percent) {
  // Quick darken (positive = lighten, negative = darken)
  const h = hex.replace('#', '');
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  const adj = (n) => Math.max(0, Math.min(255, Math.round(n + (percent / 100) * 255)));
  return '#' + [adj(r), adj(g), adj(b)].map(n => n.toString(16).padStart(2, '0')).join('');
}

// ─────────────────────────────────────────────────────────────
// Settings main
// ─────────────────────────────────────────────────────────────
function SettingsScreen({ accent, mode, fontSize, onBack, onOpenAbout, onOpenHowTo, onOpenContact, onOpenTerms, onOpenPrivacy, setTweak, profile, setProfile, focusSection }) {
  const name = profile?.name || '윤재';
  const face = profile?.face || 'basic';
  const [showProfileEdit, setShowProfileEdit] = React.useState(false);
  const notifSectionRef = React.useRef(null);

  React.useEffect(() => {
    if (focusSection === 'notifications' && notifSectionRef.current) {
      // scroll the section into view inside the scroll pane
      const pane = notifSectionRef.current.closest('[data-pane]');
      if (pane) {
        const r = notifSectionRef.current.getBoundingClientRect();
        const pr = pane.getBoundingClientRect();
        pane.scrollTo({ top: pane.scrollTop + r.top - pr.top - 16, behavior: 'smooth' });
      }
    }
  }, [focusSection]);
  const [primaryLang, setPrimaryLang] = React.useState('한국어');
  const [frequentLangs] = React.useState(['일본어', '영어', '스페인어']);
  const [defaultTone] = React.useState('자동');
  const [autoCategorize, setAutoCategorize] = React.useState(true);

  const [autoPlay, setAutoPlay] = React.useState(false);
  const [speechRate, setSpeechRate] = React.useState('보통');
  const [voice, setVoice] = React.useState('여성');

  const [reviewNotif, setReviewNotif] = React.useState(true);
  const [travelMode, setTravelMode] = React.useState(true);

  const [iCloudSync, setICloudSync] = React.useState(true);

  const [sheet, setSheet] = React.useState(null); // 'primaryLang' | 'frequentLangs' | 'tone'

  const totalCards = (window.EXPANDED_CARDS || []).length || 0;

  return (
    <div style={{ paddingBottom: 60 }}>
      {/* Top bar — sticky */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 30,
        background: ST.bg,
        padding: '54px 14px 8px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 38,
          background: 'transparent', border: 'none', padding: 0,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
          WebkitTapHighlightColor: 'transparent',
        }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M14 4L7 11l7 7" stroke={ST.ink} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{
          fontSize: 16, fontWeight: 600, color: ST.ink,
          letterSpacing: '-0.01em', whiteSpace: 'nowrap',
        }}>설정</div>
        <div style={{ width: 38 }} />
      </div>

      {/* Profile hero */}
      <div style={{
        margin: '14px 22px 0',
        padding: '20px 18px',
        background: ST.surface,
        border: `0.5px solid ${ST.hairline}`,
        borderRadius: 18,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <HamsterAvatar size={64} accent={accent} count={3} face={face} ring />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 18, fontWeight: 700, color: ST.ink,
            letterSpacing: '-0.02em', lineHeight: 1.2,
          }}>{name}</div>
          <div style={{
            marginTop: 4,
            fontSize: 13, color: ST.ink2, letterSpacing: '-0.01em',
          }}>{totalCards}개 · CheekPouch와 <span style={{ color: ST.ink, fontWeight: 600 }}>124일</span> 째</div>
        </div>
        <button onClick={() => setShowProfileEdit(true)} style={{
          height: 32, padding: '0 14px', borderRadius: 999,
          background: 'transparent',
          border: `0.5px solid ${ST.hairlineStrong}`,
          color: ST.ink,
          fontFamily: 'inherit', fontSize: 12.5, fontWeight: 500,
          letterSpacing: '-0.01em', cursor: 'pointer',
          WebkitTapHighlightColor: 'transparent',
        }}>편집</button>
      </div>

      {/* Learning */}
      <Section label="학습">
        <Row first label="주 언어" sub="번역 결과는 이 언어로 표시돼요"
             value={primaryLang} chevron onClick={() => setSheet('primaryLang')} />
        <Row label="자주 담는 언어" sub="입력 화면에서 빠르게 선택할 수 있어요"
             value={`${frequentLangs.length}개`} chevron onClick={() => setSheet('frequentLangs')} />
        <Row label="기본 톤" value={defaultTone} chevron onClick={() => setSheet('tone')} />
        <Row label="자동 카테고리 분류"
             sub="새 씨앗을 AI가 알아서 분류해요"
             end={<Toggle on={autoCategorize} onChange={setAutoCategorize} accent={accent} />} />
      </Section>

      {/* Sound */}
      <Section label="소리">
        <Row first label="자동 재생"
             sub="씨앗을 열면 바로 발음을 들려줘요"
             end={<Toggle on={autoPlay} onChange={setAutoPlay} accent={accent} />} />
        <Row label="발음 속도"
             end={<Segmented value={speechRate} onChange={setSpeechRate}
                             options={[
                               { value: '느리게', label: '느리게' },
                               { value: '보통', label: '보통' },
                               { value: '빠르게', label: '빠르게' },
                             ]} />} />
        <Row label="목소리"
             end={<Segmented value={voice} onChange={setVoice}
                             options={[
                               { value: '여성', label: '여성' },
                               { value: '남성', label: '남성' },
                             ]} />} />
      </Section>

      {/* Appearance */}
      <Section label="모양">
        <Row first label="모드"
             end={<Segmented value={mode}
                             onChange={(v) => setTweak('mode', v)}
                             options={[
                               { value: 'light', label: '라이트' },
                               { value: 'dark', label: '다크' },
                               { value: 'system', label: '시스템' },
                             ]} />} />
        <Row label="글자 크기"
             sub={fontSize === 'S' ? '조금 작게' : fontSize === 'L' ? '크게' : '보통 크기'}
             end={<Segmented value={fontSize}
                             onChange={(v) => setTweak('fontSize', v)}
                             options={[
                               { value: 'S', label: '작게' },
                               { value: 'M', label: '보통' },
                               { value: 'L', label: '크게' },
                             ]} />} />
      </Section>

      {/* Notifications */}
      <div ref={notifSectionRef}>
        <Section label="알림">
        <Row first label="복습 알림"
             sub="아침 9시에 복습할 씨앗 알려줘요"
             end={<Toggle on={reviewNotif} onChange={setReviewNotif} accent={accent} />} />
        <Row label="여행 모드"
             sub="해외에서 자동으로 관련 주머니를 띄워요"
             end={<Toggle on={travelMode} onChange={setTravelMode} accent={accent} />} />
      </Section>
      </div>

      {/* Data */}
      <Section label="데이터" footer={`마지막 동기화 · 방금 전`}>
        <Row first label="iCloud 동기화"
             end={<Toggle on={iCloudSync} onChange={setICloudSync} accent={accent} />} />
        <Row label="내보내기" sub="CSV, PDF로 저장하기" chevron onClick={() => {}} />
        <Row label="가져오기" sub="다른 앱에서 단어 가져오기" chevron onClick={() => {}} />
      </Section>

      {/* Help & info */}
      <Section label="도움말 & 정보">
        <Row first label="사용법 안내" chevron onClick={onOpenHowTo} />
        <Row label="문의하기" chevron onClick={onOpenContact} />
        <Row label="CheekPouch에 대하여" chevron onClick={onOpenAbout} />
        <Row label="버전" value="1.0.0 (12)" />
      </Section>

      {/* Danger zone */}
      <div style={{ padding: '24px 22px 0' }}>
        <button style={{
          width: '100%', padding: '14px',
          background: ST.surface,
          border: `0.5px solid ${ST.hairline}`,
          borderRadius: 14,
          color: ST.danger, fontFamily: 'inherit',
          fontSize: 14.5, fontWeight: 500, letterSpacing: '-0.01em',
          cursor: 'pointer',
          WebkitTapHighlightColor: 'transparent',
        }}>로그아웃</button>
      </div>

      {/* Sheets */}
      {sheet === 'primaryLang' && (
        <SettingPickerSheet
          title="주 언어"
          options={[
            { value: '한국어', desc: '기본' },
            { value: 'English', desc: 'English' },
            { value: '日本語', desc: 'Japanese' },
          ]}
          current={primaryLang}
          accent={accent}
          onSelect={(v) => { setPrimaryLang(v); setSheet(null); }}
          onClose={() => setSheet(null)}
        />
      )}
      {sheet === 'frequentLangs' && (
        <FrequentLangsSheet
          current={frequentLangs}
          accent={accent}
          onClose={() => setSheet(null)}
        />
      )}
      {sheet === 'tone' && (
        <SettingPickerSheet
          title="기본 톤"
          options={[
            { value: '자동', desc: 'AI가 맥락에 맞게' },
            { value: '정중하게', desc: '존중하는 느낌으로' },
            { value: '친근하게', desc: '편한 사이처럼' },
          ]}
          current={defaultTone}
          accent={accent}
          onSelect={() => { setSheet(null); }}
          onClose={() => setSheet(null)}
        />
      )}
      {showProfileEdit && (
        <ProfileEditSheet
          accent={accent}
          name={name} face={face}
          onClose={() => setShowProfileEdit(false)}
          onSave={({ name: n, face: f }) => {
            setProfile && setProfile({ name: n, face: f });
            setShowProfileEdit(false);
          }}
        />
      )}
    </div>
  );
}

const ssStep = {
  width: 32, height: 28, borderRadius: 7,
  background: 'rgba(60,42,20,0.06)',
  border: 'none',
  fontFamily: 'inherit', fontSize: 16, fontWeight: 500, color: ST.ink,
  cursor: 'pointer',
  WebkitTapHighlightColor: 'transparent',
};

// ─────────────────────────────────────────────────────────────
// Sheets
// ─────────────────────────────────────────────────────────────
function SettingPickerSheet({ title, options, current, accent, onSelect, onClose }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 200,
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
    }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(31, 24, 18, 0.32)',
        animation: 'cp-fade-bg 0.25s ease',
      }} />
      <div style={{
        position: 'relative',
        background: ST.surface,
        borderTopLeftRadius: 26, borderTopRightRadius: 26,
        paddingBottom: 30,
        maxHeight: '78%',
        boxShadow: '0 -8px 32px rgba(31,24,18,0.12)',
        animation: 'cp-sheet-up 0.32s cubic-bezier(0.22, 1, 0.36, 1)',
      }}>
        <div style={{
          width: 38, height: 4.5, borderRadius: 4,
          background: 'rgba(31,24,18,0.18)',
          margin: '8px auto 14px',
        }} />
        <div style={{
          padding: '0 24px 16px',
          fontSize: 17, fontWeight: 600, color: ST.ink,
          letterSpacing: '-0.02em', textAlign: 'center',
        }}>{title}</div>
        <div style={{ padding: '0 12px' }}>
          {options.map(o => (
            <button key={o.value} onClick={() => onSelect(o.value)} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12,
              padding: '14px 16px',
              borderRadius: 12,
              border: 'none', background: 'transparent',
              cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
              WebkitTapHighlightColor: 'transparent',
            }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontSize: 16, fontWeight: 500, color: ST.ink,
                  letterSpacing: '-0.01em',
                }}>{o.value}</div>
                {o.desc && (
                  <div style={{ fontSize: 12, color: ST.ink3, marginTop: 2 }}>{o.desc}</div>
                )}
              </div>
              {current === o.value && (
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style={{ flexShrink: 0 }}>
                  <path d="M4 9.5l3.5 3.5L14 5.5" stroke={accent} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function FrequentLangsSheet({ current, accent, onClose }) {
  const all = ['일본어', '영어', '스페인어', '프랑스어', '중국어', '베트남어', '태국어', '독일어', '이탈리아어', '포르투갈어'];
  const [picked, setPicked] = React.useState(new Set(current));
  const toggle = (v) => {
    const next = new Set(picked);
    if (next.has(v)) next.delete(v); else next.add(v);
    setPicked(next);
  };
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 200,
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
    }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(31, 24, 18, 0.32)',
        animation: 'cp-fade-bg 0.25s ease',
      }} />
      <div style={{
        position: 'relative',
        background: ST.surface,
        borderTopLeftRadius: 26, borderTopRightRadius: 26,
        paddingBottom: 30,
        maxHeight: '82%',
        boxShadow: '0 -8px 32px rgba(31,24,18,0.12)',
        animation: 'cp-sheet-up 0.32s cubic-bezier(0.22, 1, 0.36, 1)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{
          width: 38, height: 4.5, borderRadius: 4,
          background: 'rgba(31,24,18,0.18)',
          margin: '8px auto 14px',
        }} />
        <div style={{
          padding: '0 24px 6px',
          fontSize: 17, fontWeight: 600, color: ST.ink,
          letterSpacing: '-0.02em', textAlign: 'center',
        }}>자주 담는 언어</div>
        <div style={{
          padding: '0 24px 16px',
          fontSize: 13, color: ST.ink2, letterSpacing: '-0.01em',
          textAlign: 'center', lineHeight: 1.45,
        }}>입력 화면 언어 선택에서 위쪽에 떠요</div>

        <div style={{ overflowY: 'auto', padding: '4px 12px 12px' }}>
          {all.map(v => {
            const on = picked.has(v);
            return (
              <button key={v} onClick={() => toggle(v)} style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 16px',
                borderRadius: 12,
                border: 'none',
                background: 'transparent',
                cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
                WebkitTapHighlightColor: 'transparent',
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 6,
                  background: on ? accent : 'transparent',
                  border: on ? 'none' : `1.5px solid ${ST.hairlineStrong}`,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                  transition: 'background 0.15s ease',
                }}>
                  {on && (
                    <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
                      <path d="M3 7.2l2.8 2.8L11 5" stroke="#FFF" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  )}
                </div>
                <span style={{
                  flex: 1, fontSize: 15.5, color: ST.ink,
                  letterSpacing: '-0.01em',
                  fontWeight: on ? 500 : 400,
                }}>{v}</span>
              </button>
            );
          })}
        </div>

        <div style={{ padding: '8px 22px 0' }}>
          <button onClick={onClose} style={{
            width: '100%', height: 48, borderRadius: 14,
            background: accent, color: '#FFF',
            border: 'none', fontFamily: 'inherit',
            fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em',
            cursor: 'pointer',
            WebkitTapHighlightColor: 'transparent',
          }}>{picked.size}개 선택 · 저장</button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// About screen
// ─────────────────────────────────────────────────────────────
function AboutScreen({ accent, onBack, onOpenTerms, onOpenPrivacy, onOpenLicenses, onOpenContact, onOpenRating, onOpenSocial }) {
  return (
    <div style={{ paddingBottom: 60 }}>
      {/* Top bar — sticky */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 30,
        background: ST.bg,
        padding: '54px 14px 8px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 38,
          background: 'transparent', border: 'none', padding: 0,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
          WebkitTapHighlightColor: 'transparent',
        }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M14 4L7 11l7 7" stroke={ST.ink} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{ width: 38 }} />
      </div>

      {/* Hero */}
      <div style={{
        padding: '20px 22px 0',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
      }}>
        <CheekPouch count={6} accent={accent} size={140} animateOnChange={false} />
        <div style={{
          marginTop: 18,
          fontSize: 32, fontWeight: 700, color: ST.ink,
          letterSpacing: '-0.03em', lineHeight: 1,
        }}>CheekPouch</div>
        <div style={{
          marginTop: 10,
          padding: '4px 10px',
          fontSize: 11, fontWeight: 600, color: ST.ink2,
          letterSpacing: '0.04em',
          background: 'rgba(60,42,20,0.06)',
          borderRadius: 999,
        }}>VERSION 1.0.0</div>
      </div>

      {/* Tagline */}
      <div style={{
        margin: '28px 26px 0',
        padding: '20px 18px',
        background: ST.surface,
        border: `0.5px solid ${ST.hairline}`,
        borderRadius: 18,
      }}>
        <div style={{
          fontSize: 19, fontWeight: 600, color: ST.ink,
          letterSpacing: '-0.02em', lineHeight: 1.35,
          textWrap: 'balance',
        }}>한 입씩, 한 문장씩.<br/>볼주머니에 담아두면 잊지 않아요.</div>
        <div style={{
          marginTop: 14,
          fontSize: 14, color: ST.ink2,
          letterSpacing: '-0.01em', lineHeight: 1.6,
        }}>
          여행 중 마주친 표현, 메뉴판의 단어, 길에서 들은 한마디.
          어디든 적어두지만 다시 찾기 어려운 그 조각들을, 햄스터처럼 볼주머니에
          잠깐 담아두는 앱이에요.
        </div>
      </div>

      {/* Credits */}
      <Section label="만든 사람">
        <Row first label="기획 · 디자인" value="윤재" />
        <Row label="개발" value="윤재 + Claude" />
        <Row label="피드백" value="베타 테스터 12명" />
      </Section>

      {/* Resources */}
      <Section label="더 알아보기">
        <Row first label="소셜에서 보기" sub="새 기능, 업데이트 소식" chevron onClick={onOpenSocial} />
        <Row label="문의하기" chevron onClick={onOpenContact} />
        <Row label="앱스토어에 별점 남기기" chevron onClick={onOpenRating} />
      </Section>

      {/* Bottom footer */}
      <div style={{
        margin: '24px 22px 0',
        textAlign: 'center',
        fontSize: 12, color: ST.ink3, lineHeight: 1.5,
        letterSpacing: '-0.01em',
      }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 14,
          padding: '2px 0',
        }}>
          <button onClick={onOpenTerms} style={legalLinkStyle}>이용약관</button>
          <span style={{ width: 1, height: 10, background: ST.hairlineStrong }} />
          <button onClick={onOpenPrivacy} style={legalLinkStyle}>개인정보 처리방침</button>
          <span style={{ width: 1, height: 10, background: ST.hairlineStrong }} />
          <button onClick={onOpenLicenses} style={legalLinkStyle}>오픈소스</button>
        </div>
        <div style={{ marginTop: 14 }}>© 2026 CheekPouch</div>
        <div style={{ marginTop: 4 }}>서울에서 만들어졌어요</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Profile edit sheet
// ─────────────────────────────────────────────────────────────
function ProfileEditSheet({ accent, name, face, onClose, onSave }) {
  const [n, setN] = React.useState(name);
  const [f] = React.useState(face || 'basic'); // single character — picker arrives next update
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 280);
    return () => clearTimeout(t);
  }, []);

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 200,
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
    }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(31, 24, 18, 0.40)',
        animation: 'cp-fade-bg 0.25s ease',
      }} />
      <div style={{
        position: 'relative',
        background: ST.surface,
        borderTopLeftRadius: 26, borderTopRightRadius: 26,
        paddingBottom: 28,
        boxShadow: '0 -8px 32px rgba(31,24,18,0.16)',
        animation: 'cp-sheet-up 0.32s cubic-bezier(0.22, 1, 0.36, 1)',
        display: 'flex', flexDirection: 'column',
        maxHeight: '90%',
      }}>
        <div style={{
          width: 38, height: 4.5, borderRadius: 4,
          background: 'rgba(31,24,18,0.18)',
          margin: '8px auto 14px',
          flexShrink: 0,
        }} />

        <div style={{ padding: '0 24px 4px' }}>
          <div style={{
            fontSize: 19, fontWeight: 700, color: ST.ink,
            letterSpacing: '-0.02em',
          }}>프로필 편집</div>
        </div>

        <div style={{ overflowY: 'auto' }}>
          {/* Mascot preview */}
          <div style={{
            margin: '18px 22px 0',
            padding: '24px 0',
            background: ST.surface2,
            borderRadius: 18,
            border: `0.5px solid ${ST.hairline}`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
          }}>
            <HamsterAvatar size={108} accent={accent} count={3} face={f} ring />
            <div style={{
              fontSize: 14, fontWeight: 600, color: ST.ink,
              letterSpacing: '-0.01em',
            }}>{n || '이름 없음'}</div>
          </div>

          {/* Name */}
          <div style={{ padding: '24px 24px 0' }}>
            <div style={{
              fontSize: 11, fontWeight: 600, color: ST.ink3,
              letterSpacing: '0.08em', textTransform: 'uppercase',
              marginBottom: 8,
            }}>이름</div>
            <input
              ref={inputRef}
              value={n}
              onChange={(e) => setN(e.target.value)}
              maxLength={20}
              placeholder="앱에서 부를 이름"
              style={{
                width: '100%', height: 46, borderRadius: 12,
                background: ST.surface2,
                border: `1px solid ${ST.hairlineStrong}`,
                padding: '0 14px',
                fontFamily: 'inherit', fontSize: 16, color: ST.ink,
                outline: 'none', letterSpacing: '-0.01em',
                boxSizing: 'border-box',
              }}
            />
          </div>

          {/* Mascot — picker arrives in the next update */}
          <div style={{ padding: '20px 24px 0' }}>
            <div style={{
              fontSize: 11, fontWeight: 600, color: ST.ink3,
              letterSpacing: '0.08em', textTransform: 'uppercase',
              marginBottom: 10,
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              마스코트
              <span style={{
                fontSize: 9.5, fontWeight: 700,
                padding: '2px 6px', borderRadius: 4,
                background: `${accent}1F`, color: accent,
                letterSpacing: '0.04em',
              }}>SOON</span>
            </div>
            <div style={{
              padding: '14px 14px',
              borderRadius: 14,
              background: ST.surface2,
              border: `0.5px dashed ${ST.hairlineStrong}`,
              display: 'flex', alignItems: 'center', gap: 14,
            }}>
              <div style={{ flexShrink: 0 }}>
                <HamsterAvatar size={52} accent={accent} count={4} face={f} />
              </div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{
                  fontSize: 13.5, fontWeight: 600, color: ST.ink,
                  letterSpacing: '-0.01em', marginBottom: 2,
                }}>지금은 이 친구 하나예요</div>
                <div style={{
                  fontSize: 12, color: ST.ink2, lineHeight: 1.45,
                  letterSpacing: '-0.01em',
                }}>다른 마스코트는 다음 업데이트에서 골라볼 수 있어요.</div>
              </div>
            </div>
          </div>

          <div style={{
            padding: '14px 26px 0',
            fontSize: 12, color: ST.ink3, lineHeight: 1.5,
            letterSpacing: '-0.01em',
          }}>
            마스코트는 볼주머니가 채워질수록 점점 부풀어요.
          </div>
        </div>

        {/* Action bar */}
        <div style={{
          padding: '20px 22px 0',
          display: 'flex', gap: 10, flexShrink: 0,
        }}>
          <button onClick={onClose} style={{
            flex: 1, height: 48, borderRadius: 14,
            background: 'transparent', color: ST.ink2,
            border: `1px solid ${ST.hairlineStrong}`,
            fontFamily: 'inherit', fontSize: 15, fontWeight: 500,
            cursor: 'pointer',
            WebkitTapHighlightColor: 'transparent',
          }}>취소</button>
          <button onClick={() => onSave({ name: n.trim() || '이름 없음', face: f })} style={{
            flex: 2, height: 48, borderRadius: 14,
            background: accent, color: '#FFF',
            border: 'none',
            fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
            letterSpacing: '-0.01em', cursor: 'pointer',
            WebkitTapHighlightColor: 'transparent',
          }}>저장</button>
        </div>
      </div>
    </div>
  );
}

const legalLinkStyle = {
  background: 'transparent', border: 'none', padding: 0,
  fontFamily: 'inherit', fontSize: 12,
  color: ST.ink2, cursor: 'pointer',
  textDecoration: 'underline', textDecorationColor: 'rgba(60,42,20,0.2)',
  textUnderlineOffset: 3,
  letterSpacing: '-0.01em',
};

// ─────────────────────────────────────────────────────────────
// Expose
// ─────────────────────────────────────────────────────────────
Object.assign(window, {
  SettingsScreen,
  AboutScreen,
  HamsterAvatar,
  ProfileEditSheet,
});
