function PermissionModal({ kind, on, onCancel, onConfirm }) {
  const copy = {
    push: {
      on: { icon: 'bell-ringing', title: '푸시 알림을 켜드릴까요?', body: '이웃이 내 사진에 장소를 제안하거나 배지를 받으면 바로 알려드리고, 다음 화면에서 기기 알림 허용을 물어봐요.', list: ['위치 제안 · 장소 확정 알림', '배지 획득과 챌린지 마감 알림', '내 게시물의 좋아요 · 댓글'], cta: '켜기' },
      off: { icon: 'bell-off', title: '푸시 알림을 끔긌요?', body: '지금 끔으면 이웃의 위치 제안이나 심사 결과를 놓칠 수 있어요. 약속한 챌린지 마감도 알려드리지 않아요.', warn: '미션 심사 결과 알림도 함께 꺼집니다', cta: '끄기' }
    },
    marketing: {
      on: { icon: 'speakerphone', title: '마케팅 알림 수신 동의', body: '동네 신규 가게 오픈 소식, 미션 보상 이벤트, 제휴 혜택을 보내드릴까요? 하루 한 번을 넘지 않아요.', list: ['내 동네 신규 오픈 · 팝업 소식', '미션 보상 · 이벤트 응모', '제휴 할인 코드'], note: '수신 동의 일자가 기록되며 언제든 해제할 수 있습니다', cta: '동의하기' },
      off: { icon: 'speakerphone', title: '마케팅 알림을 해제할까요?', body: '이벤트와 할인 소식을 받지 않게 됩니다. 미션 진행처럼 내 활동에 관한 알림은 그대로 와요.', cta: '해제하기' }
    },
    locate: {
      on: { icon: 'map-pin', title: '위치 정보를 사용할까요?', body: 'Spoture는 사진을 지도에 연결하는 서별이에요. 위치를 허용하면 사진의 가게를 자동으로 추정해드립니다.', list: ['사진 장소 자동 추정', '가까운 맛집 · 핫플레이스 추천', '동네 미션 자동 인증'], note: '집 주소는 이웃에게 공개되지 않아요', cta: '허용하기' },
      off: { icon: 'map-pin-off', title: '위치 사용을 끄면 이러해지려요', body: '사진을 올릴 때 장소를 직접 검색해 골라야 하고, 동네 미션과 거리순 추천은 사용할 수 없어요.', warn: '진행 중인 동네 미션 2건이 자동 인증되지 않아요', cta: '그래도 끄기' }
    }
  }[kind][on ? 'on' : 'off'];
  const danger = !on;
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(20,20,20,.42)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 28, zIndex: 70 }}>
      <div style={{ background: 'var(--surface-1)', borderRadius: 'var(--radius-card)', padding: 24, textAlign: 'center', boxShadow: 'var(--shadow-float)', maxWidth: 306, width: '100%' }}>
        <div style={{ width: 58, height: 58, borderRadius: '50%', background: danger ? 'var(--bg-danger)' : 'var(--bg-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 15px' }}><i className={'ti ti-' + copy.icon} style={{ fontSize: 25, color: danger ? 'var(--text-danger)' : 'var(--text-accent)' }}></i></div>
        <span style={{ font: 'var(--text-heading)', display: 'block', marginBottom: 8 }}>{copy.title}</span>
        <p style={{ font: 'var(--text-caption)', color: 'var(--text-secondary)', margin: '0 0 16px', lineHeight: 1.65, textWrap: 'pretty' }}>{copy.body}</p>
        {copy.list && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9, background: 'var(--surface-2)', borderRadius: 'var(--radius-tile)', padding: '14px 15px', marginBottom: 14, textAlign: 'left' }}>
            {copy.list.map(l => (
              <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                <i className="ti ti-check" style={{ fontSize: 15, color: 'var(--text-accent)', flexShrink: 0 }}></i>
                <span style={{ font: 'var(--text-small)', color: 'var(--text-secondary)' }}>{l}</span>
              </div>
            ))}
          </div>
        )}
        {copy.warn && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--bg-danger)', borderRadius: 'var(--radius-tile)', padding: '13px 14px', marginBottom: 14, textAlign: 'left' }}>
            <i className="ti ti-alert-triangle" style={{ fontSize: 16, color: 'var(--text-danger)', flexShrink: 0 }}></i>
            <span style={{ font: 'var(--text-small)', color: 'var(--text-danger)', lineHeight: 1.5 }}>{copy.warn}</span>
          </div>
        )}
        {copy.note && <span style={{ font: 'var(--text-micro)', color: 'var(--text-muted)', display: 'block', marginBottom: 16, lineHeight: 1.5 }}>{copy.note}</span>}
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={onCancel} style={{ flex: 1, padding: '14px 0', font: '600 14px/1 var(--font-family)', border: '1px solid var(--border-strong)', background: 'var(--surface-1)', color: 'var(--text-secondary)', borderRadius: 999, cursor: 'pointer' }}>{on ? '다음에' : '유지하기'}</button>
          <button onClick={onConfirm} style={{ flex: 1, padding: '14px 0', font: '600 14px/1 var(--font-family)', border: 'none', background: danger ? 'var(--surface-2)' : 'var(--text-accent)', color: danger ? 'var(--text-danger)' : '#fff', borderRadius: 999, cursor: 'pointer' }}>{copy.cta}</button>
        </div>
      </div>
    </div>
  );
}
window.PermissionModal = PermissionModal;

function PostVisibilitySheet({ current, onPick, onClose }) {
  const { BottomSheet, Button } = window.SpotureDesignSystem_f7ad96;
  const [sel, setSel] = React.useState(current);
  const options = [
    { key: '전체 공개', icon: 'world', label: '전체 공개', sub: '누구나 내 사진을 보고 지도에서 찾을 수 있어요', note: '미션 · 핫플레이스 집계에 포함되어요' },
    { key: '팔로워에게만', icon: 'users', label: '팔로워에게만', sub: '나를 팔로우하는 이웃만 볼 수 있어요', note: '장소 제안도 팔로우 이웃만 보낼 수 있어요' },
    { key: '나만 보기', icon: 'lock', label: '나만 보기', sub: '기록으로만 사용해요. 피드와 지도에 노출되지 않아요', note: '배지 · 챌린지 집계에는 그대로 반영되요' }
  ];
  return (
    <BottomSheet title="게시물 공개 범위" footer={<Button variant="primary" onClick={() => onPick(sel)}>이 범위로 설정</Button>} onClose={onClose}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <span style={{ font: 'var(--text-caption)', color: 'var(--text-secondary)', lineHeight: 1.6 }}>새로 올리는 사진에 기본으로 적용되고, 게시물마다 개별로 바꿀 수도 있어요.</span>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {options.map(o => {
            const on = sel === o.key;
            return (
              <div key={o.key} onClick={() => setSel(o.key)} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '15px 16px', background: on ? 'var(--bg-accent)' : 'var(--surface-2)', border: '1.5px solid ' + (on ? 'var(--text-accent)' : 'transparent'), borderRadius: 'var(--radius-tile)', cursor: 'pointer' }}>
                <i className={'ti ti-' + o.icon} style={{ fontSize: 19, color: on ? 'var(--text-accent)' : 'var(--text-secondary)', flexShrink: 0, marginTop: 1 }}></i>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ font: 'var(--text-body-strong)', color: on ? 'var(--text-accent)' : 'var(--text-primary)', marginBottom: 4 }}>{o.label}</div>
                  <div style={{ font: 'var(--text-small)', color: 'var(--text-secondary)', lineHeight: 1.5, marginBottom: on ? 6 : 0 }}>{o.sub}</div>
                  {on && <div style={{ font: 'var(--text-micro)', color: 'var(--text-muted)' }}>{o.note}</div>}
                </div>
                <span style={{ width: 18, height: 18, borderRadius: '50%', border: '2px solid ' + (on ? 'var(--text-accent)' : 'var(--border-strong)'), background: on ? 'var(--text-accent)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{on && <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#fff' }}></span>}</span>
              </div>
            );
          })}
        </div>
      </div>
    </BottomSheet>
  );
}
window.PostVisibilitySheet = PostVisibilitySheet;

function Settings({ nav }) {
  const { ListRow, Toggle } = window.SpotureDesignSystem_f7ad96;
  const [push, setPush] = React.useState(true);
  const [marketing, setMarketing] = React.useState(false);
  const [locate, setLocate] = React.useState(true);
  const [ask, setAsk] = React.useState(null);
  const [visSheet, setVisSheet] = React.useState(new URLSearchParams(location.search).get('visopen') === '1');
  const [logout, setLogout] = React.useState(false);
  const [vis, setVis] = React.useState(accountVis());
  const setters = { push: setPush, marketing: setMarketing, locate: setLocate };
  const Group = ({ title, children }) => (
    <div style={{ padding: '0 20px 18px' }}>
      <span style={{ font: 'var(--text-small)', color: 'var(--text-muted)', display: 'block', marginBottom: 8, paddingLeft: 4 }}>{title}</span>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, background: 'var(--surface-1)', borderRadius: 'var(--radius-tile)', overflow: 'hidden' }}>{children}</div>
    </div>
  );
  const ToggleRow = ({ label, on, onChange, icon }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px' }}>
      <i className={'ti ti-' + icon} style={{ fontSize: 18, color: 'var(--text-secondary)' }}></i>
      <span style={{ font: 'var(--text-body)', flex: 1 }}>{label}</span>
      <Toggle on={on} onChange={onChange} />
    </div>
  );
  return (
    <div style={{ flex: '1 1 0%', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      <StatusBar />
      <ScreenHeader title="설정" onBack={() => nav('profile')} />
      <div style={{ flex: '1 1 0%', minHeight: 0, overflowY: 'auto', paddingBottom: 104 }}>
        <Group title="계정">
          <ListRow icon="user" label="프로필 편집" onClick={() => nav('editProfile')} />
          <ListRow icon="link" label="연동된 소셜 계정" value="카카오" onClick={() => nav('socialAccounts')} />
          <ListRow icon="user-off" label="차단한 사용자" value="2명" onClick={() => nav('blockedUsers')} />
        </Group>
        <Group title="알림">
          <ToggleRow icon="bell" label="푸시 알림" on={push} onChange={() => setAsk({ kind: 'push', on: !push })} />
          <ToggleRow icon="speakerphone" label="마케팅 알림" on={marketing} onChange={() => setAsk({ kind: 'marketing', on: !marketing })} />
        </Group>
        <Group title="개인정보">
          <ToggleRow icon="map-pin" label="위치 정보 사용" on={locate} onChange={() => setAsk({ kind: 'locate', on: !locate })} />
          <ListRow icon="eye" label="계정 공개 범위" value={visMeta(vis).label} onClick={() => setVisSheet(true)} />
        </Group>
        {vis !== 'public' && (
          <div style={{ padding: '0 20px 18px', marginTop: -12 }}>
            <div style={{ display: 'flex', gap: 10, background: 'var(--bg-warning)', border: '1px solid var(--border)', borderRadius: 'var(--radius-tile)', padding: '13px 14px' }}>
              <i className="ti ti-alert-triangle" style={{ fontSize: 15, color: 'var(--text-warning)', flexShrink: 0, marginTop: 1 }}></i>
              <span style={{ font: 'var(--text-small)', color: 'var(--text-secondary)', lineHeight: 1.6 }}>{vis === 'private' ? '지금은 모든 게시물과 컬렉션이 비공개예요. 개별 설정은 그대로 보관돼요.' : '전체 공개로 둔 게시물·컬렉션도 지금은 팔로워에게만 보여요.'}</span>
            </div>
          </div>
        )}
        <Group title="정보">
          <ListRow icon="speakerphone" label="공지사항" value="새 소식 2" onClick={() => nav('notices')} />
          <ListRow icon="headset" label="문의하기" onClick={() => nav('support')} />
          <ListRow icon="file-text" label="이용약관" onClick={() => nav('terms')} />
          <ListRow icon="shield-lock" label="개인정보처리방침" onClick={() => nav('privacy')} />
          <ListRow icon="info-circle" label="앱 버전" value="1.4.2" />
        </Group>
        <Group title="">
          <ListRow icon="logout" label="로그아웃" danger onClick={() => setLogout(true)} />
          <ListRow icon="trash" label="회원 탈퇴" danger onClick={() => nav('deleteAccount')} />
        </Group>
      </div>
      {ask && <PermissionModal kind={ask.kind} on={ask.on} onCancel={() => setAsk(null)} onConfirm={() => { setters[ask.kind](ask.on); setAsk(null); }} />}
      {visSheet && <AccountVisibilitySheet current={vis} onPick={v => { setVis(v); setAccountVis(v); setVisSheet(false); }} onClose={() => setVisSheet(false)} />}
      {logout && <LogoutModal onCancel={() => setLogout(false)} onConfirm={() => { setLogout(false); location.search = '?login=1'; }} />}
    </div>
  );
}
window.Settings = Settings;
