// p13-settings.jsx — Settings + P13a delete-account confirm + logout popup

function ScreenSettings({ state, onNavigate, onSetTheme, theme, onLogout, onDeleteAccount }) {
  const T = window.T;
  const offline = state === 'offline';
  const [speed, setSpeed] = React.useState('normal');
  const [voice, setVoice] = React.useState('female');
  const [themeMode, setThemeMode] = React.useState(theme || 'system');
  const [showLogoutAlert, setShowLogoutAlert] = React.useState(false);
  const [showDeleteSheet, setShowDeleteSheet] = React.useState(false);

  const handleTheme = (v) => {
    setThemeMode(v);
    onSetTheme && onSetTheme(v);
  };

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg,
                  display: 'flex', flexDirection: 'column' }}>
      <TopBar
        title="설정"
        offline={offline}
        leading={<IconButton icon={<Icons.Back size={22} color={T.ink}/>}
                             onClick={() => onNavigate('back')}/>}
      />

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 16px 32px' }}>
        <Group title="소리">
          <ListRow
            label="발음 속도"
            trailing={<Segment options={[
              { value: 'slow',   label: '느리게' },
              { value: 'normal', label: '보통' },
              { value: 'fast',   label: '빠르게' },
            ]} value={speed} onChange={setSpeed} size="sm"/>}
          />
          <ListRow
            label="목소리"
            trailing={<Segment options={[
              { value: 'female', label: '여성' },
              { value: 'male',   label: '남성' },
            ]} value={voice} onChange={setVoice} size="sm"/>}
            last
          />
        </Group>

        <Group title="콘텐츠">
          <ListRow
            label="카테고리 관리"
            sub="씨앗 분류를 만들고 정리해요"
            trailing={<Icons.ChevronR size={18} color={T.ink3}/>}
            onClick={() => onNavigate('P13b')}
            last
          />
        </Group>

        <Group title="모양">
          <ListRow
            label="테마"
            trailing={<Segment options={[
              { value: 'light',  label: '라이트' },
              { value: 'dark',   label: '다크' },
              { value: 'system', label: '시스템' },
            ]} value={themeMode} onChange={handleTheme} size="sm"/>}
            last
          />
        </Group>

        <Group title="계정">
          <ListRow
            label="로그아웃"
            trailing={<Icons.ChevronR size={18} color={T.ink3}/>}
            onClick={() => setShowLogoutAlert(true)}
            disabled={offline}
          />
          <ListRow
            label="계정 탈퇴" danger
            trailing={<Icons.ChevronR size={18} color={T.danger}/>}
            onClick={() => setShowDeleteSheet(true)}
            disabled={offline}
            last
          />
        </Group>

        <Group title="도움말">
          <ListRow
            label="도움말 · FAQ"
            trailing={<Icons.ChevronR size={18} color={T.ink3}/>}
            onClick={() => onNavigate('P14')}
            last
          />
        </Group>

        <Group title="앱 정보">
          <ListRow label="버전" trailing={<span style={{ fontSize: 13, color: T.ink3 }}>1.0.0</span>}/>
          <ListRow label="이용약관" trailing={<Icons.ChevronR size={18} color={T.ink3}/>}
                   onClick={() => onNavigate('terms', { from: 'P13' })}/>
          <ListRow label="개인정보 처리방침" trailing={<Icons.ChevronR size={18} color={T.ink3}/>}
                   onClick={() => onNavigate('privacy', { from: 'P13' })}
                   last/>
        </Group>
      </div>

      <AlertModal
        open={showLogoutAlert}
        title="로그아웃할까요?"
        message="다시 로그인하면 데이터는 그대로 있어요"
        confirmLabel="로그아웃"
        cancelLabel="취소"
        danger
        onConfirm={() => { setShowLogoutAlert(false); onLogout && onLogout(); }}
        onCancel={() => setShowLogoutAlert(false)}
      />

      <BottomSheet open={showDeleteSheet} onClose={() => setShowDeleteSheet(false)}>
        <DeleteAccountSheet
          onCancel={() => setShowDeleteSheet(false)}
          onConfirm={() => { setShowDeleteSheet(false); onDeleteAccount && onDeleteAccount(); }}
          user={window.MOCK_USER}
          pouchCount={window.MOCK_POUCHES.length}
        />
      </BottomSheet>
    </div>
  );
}

function DeleteAccountSheet({ onCancel, onConfirm, user, pouchCount }) {
  const T = window.T;
  return (
    <div style={{ padding: '14px 20px 28px' }}>
      <div style={{ textAlign: 'center', padding: '8px 0 18px' }}>
        <div style={{
          width: 56, height: 56, borderRadius: '50%',
          background: T.dangerSoft,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 14,
        }}>
          <Icons.Warning size={28} color={T.danger}/>
        </div>
        <div style={{ fontSize: 19, fontWeight: 700, color: T.ink,
                      letterSpacing: '-0.02em', marginBottom: 8 }}>
          정말 탈퇴할까요?
        </div>
        <div style={{ fontSize: 14, color: T.ink2, lineHeight: 1.5, padding: '0 12px' }}>
          모든 데이터가 즉시 삭제되며<br/>복구할 수 없습니다
        </div>
      </div>

      <div style={{
        background: T.surface, borderRadius: 14,
        border: `0.5px solid ${T.hairline}`,
        padding: 14, marginBottom: 18,
      }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: T.ink3,
                      letterSpacing: '0.08em', textTransform: 'uppercase',
                      marginBottom: 10 }}>삭제될 데이터</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <DelRow label="씨앗" count={user?.totalSeeds ?? 47} icon="🌱"/>
          <DelRow label="주머니" count={pouchCount} icon="👜"/>
          <DelRow label="프로필 · 설정" count="—" icon="👤"/>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Button kind="primary" danger fullWidth onClick={onConfirm} style={{ height: 52 }}>
          탈퇴하기
        </Button>
        <Button kind="ghost" fullWidth onClick={onCancel} style={{ height: 48 }}>
          취소
        </Button>
      </div>
    </div>
  );
}

function DelRow({ label, count, icon }) {
  const T = window.T;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{ width: 24, fontSize: 16 }}>{icon}</div>
      <div style={{ flex: 1, fontSize: 13.5, color: T.ink }}>{label}</div>
      <div style={{ fontSize: 13.5, color: T.ink2, fontWeight: 600 }}>{count}{typeof count === 'number' ? '개' : ''}</div>
    </div>
  );
}

function ContactSheet({ onClose }) {
  const T = window.T;
  const email = 'hello@cheekpouch.app';
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(email);
    } catch (e) {
      const ta = document.createElement('textarea');
      ta.value = email; document.body.appendChild(ta);
      ta.select(); document.execCommand('copy'); ta.remove();
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  const openMail = () => {
    window.location.href = `mailto:${email}?subject=${encodeURIComponent('CheekPouch 문의')}`;
    setTimeout(onClose, 100);
  };
  return (
    <div style={{ padding: '14px 20px 28px' }}>
      <div style={{ textAlign: 'center', padding: '4px 0 18px' }}>
        <div style={{ fontSize: 19, fontWeight: 700, color: T.ink,
                      letterSpacing: '-0.02em', marginBottom: 6 }}>
          문의하기
        </div>
        <div style={{ fontSize: 13.5, color: T.ink2, lineHeight: 1.5 }}>
          궁금한 점이나 의견을 보내주세요.<br/>보통 1–2일 안에 답변드려요.
        </div>
      </div>

      <div style={{
        background: T.surface, borderRadius: 14,
        border: `0.5px solid ${T.hairline}`,
        padding: '14px 16px', marginBottom: 16,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: T.ink3,
                        letterSpacing: '0.08em', textTransform: 'uppercase',
                        marginBottom: 4 }}>이메일</div>
          <div style={{ fontSize: 15, color: T.ink, fontWeight: 600,
                        letterSpacing: '-0.01em',
                        overflow: 'hidden', textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap' }}>{email}</div>
        </div>
        <button onClick={copy} style={{
          height: 34, padding: '0 12px',
          background: copied ? T.ink : T.bg,
          color: copied ? T.onInk : T.ink,
          border: `1px solid ${T.hairline}`,
          borderRadius: 10, fontSize: 12.5, fontWeight: 600,
          fontFamily: 'inherit', cursor: 'pointer',
          letterSpacing: '-0.01em',
        }}>{copied ? '복사됨' : '복사'}</button>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Button kind="primary" fullWidth onClick={openMail} style={{ height: 52 }}>
          메일 앱 열기
        </Button>
        <Button kind="ghost" fullWidth onClick={onClose} style={{ height: 48 }}>
          닫기
        </Button>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenSettings, ContactSheet });
