// p01-login.jsx — Login screen with Apple/Google/Kakao providers
// States: default / loading / failed / offline + terms/privacy modals

function ScreenLogin({ state = 'default', onSignIn, onShowTerms, onShowPrivacy, busyProvider, errorMsg }) {
  const T = window.T;
  const offline = state === 'offline';
  const busy = busyProvider; // 'apple' | 'google' | 'kakao' | null
  const isLoading = !!busy;

  const hasBanner = (state === 'failed' || offline);
  // Reserve fixed space at the bottom for banner+buttons so hero stays centered
  const BOTTOM_H = 320; // covers banner area + 3 buttons + email + terms

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: T.bg,
      overflow: 'hidden',
    }}>
      {/* Decorative gradient blobs */}
      <div style={{
        position: 'absolute', top: -120, right: -100,
        width: 320, height: 320, borderRadius: 320,
        background: `radial-gradient(circle at 35% 35%, ${T.accent}24 0%, ${T.accent}10 50%, transparent 75%)`,
        pointerEvents: 'none',
      }}/>
      <div style={{
        position: 'absolute', bottom: -160, left: -120,
        width: 320, height: 320, borderRadius: 320,
        background: `radial-gradient(circle at 60% 50%, ${T.accent}18 0%, ${T.accent}08 55%, transparent 80%)`,
        pointerEvents: 'none',
      }}/>

      {/* Hero — absolutely positioned so banner doesn't push it */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, bottom: BOTTOM_H,
        padding: '0 32px',
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        zIndex: 1,
      }}>
        {/* Mascot — cream "stage" baked into the container background so the hamster body keeps its true color in dark mode */}
        <div style={{
          marginBottom: 20,
          width: 200, height: 200,
          background: 'radial-gradient(circle at 50% 50%, #F2EBE0 0%, #F2EBE0 36%, rgba(242,235,224,0.55) 55%, rgba(242,235,224,0) 78%)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Hamster count={5} max={10} size={150}/>
        </div>
        <div style={{
          fontSize: 36, fontWeight: 800, color: T.ink,
          letterSpacing: '-0.04em', lineHeight: 1, marginBottom: 14,
        }}>CheekPouch</div>
        <div style={{
          fontSize: 16, color: T.ink2, lineHeight: 1.45,
          textAlign: 'center', maxWidth: 280, letterSpacing: '-0.01em',
        }}>
          한 입씩, 한 문장씩.<br/>
          볼주머니에 담아두면 잊지 않아요.
        </div>
      </div>

      {/* Bottom container — fixed height; holds banner + buttons */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: BOTTOM_H,
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
        zIndex: 1,
      }}>

      {/* Error banner (above buttons) */}
      {hasBanner && (
        <div style={{
          position: 'relative', zIndex: 1,
          margin: '0 20px 12px',
          animation: 'cp-toast-in 0.22s ease',
          background: T.surface,
          border: `0.5px solid ${T.hairlineStrong}`,
          borderRadius: 14, padding: '12px 14px',
          display: 'flex', alignItems: 'flex-start', gap: 10,
          boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
        }}>
          <div style={{
            width: 22, height: 22, borderRadius: 11,
            background: T.dangerSoft,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: T.danger, fontSize: 13, fontWeight: 700,
            flexShrink: 0, marginTop: 1,
          }}>!</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: T.ink,
                          letterSpacing: '-0.01em', marginBottom: 2 }}>
              {offline ? '인터넷 연결을 확인해주세요' : (errorMsg || '로그인이 잠시 막혔어요')}
            </div>
            <div style={{ fontSize: 12, color: T.ink2, lineHeight: 1.4 }}>
              {offline
                ? '재방문 사용자는 자동으로 홈에 들어가요. Wi-Fi · 데이터 켜고 다시 시도해주세요'
                : '다시 시도해볼까요?'}
            </div>
          </div>
          {!offline && (
            <button style={{
              alignSelf: 'center',
              background: T.ink, color: T.bg,
              border: 'none', borderRadius: 14,
              padding: '6px 12px', fontSize: 12, fontWeight: 600,
              fontFamily: 'inherit', cursor: 'pointer',
            }}>다시 시도</button>
          )}
        </div>
      )}

      {/* Provider buttons */}
      <div style={{
        padding: '0 20px 16px',
        display: 'flex', flexDirection: 'column', gap: 10,
        position: 'relative', zIndex: 1,
      }}>
        <ProviderBtn provider="apple"
          label="Apple로 계속하기"
          background="#000" color="#FFF"
          icon={<AppleGlyph/>}
          busy={busy === 'apple'} disabled={(!!busy && busy !== 'apple') || offline}
          onClick={() => onSignIn && onSignIn('apple')}/>
        <ProviderBtn provider="google"
          label="Google로 계속하기"
          background="#FFF" color="#1F1812"
          border={`0.5px solid ${T.hairlineStrong}`}
          icon={<GoogleGlyph/>}
          busy={busy === 'google'} disabled={(!!busy && busy !== 'google') || offline}
          onClick={() => onSignIn && onSignIn('google')}/>
        <ProviderBtn provider="kakao"
          label="카카오로 계속하기"
          background="#FEE500" color="#191919"
          icon={<KakaoGlyph/>}
          busy={busy === 'kakao'} disabled={(!!busy && busy !== 'kakao') || offline}
          onClick={() => onSignIn && onSignIn('kakao')}/>

        <button onClick={() => onSignIn && onSignIn('email')} disabled={offline} style={{
          background: 'transparent', border: 'none',
          color: T.ink2, fontSize: 14, fontWeight: 600,
          padding: '10px 0 6px', cursor: offline ? 'default' : 'pointer',
          fontFamily: 'inherit', opacity: offline ? 0.5 : 1,
        }}>이메일로 시작하기</button>

        <div style={{
          fontSize: 11.5, color: T.ink3, textAlign: 'center',
          lineHeight: 1.6, letterSpacing: '-0.01em',
        }}>
          계속하면{' '}
          <span onClick={onShowTerms} style={{ color: T.ink2, textDecoration: 'underline', cursor: 'pointer' }}>이용약관</span>
          {' '}및{' '}
          <span onClick={onShowPrivacy} style={{ color: T.ink2, textDecoration: 'underline', cursor: 'pointer' }}>개인정보 처리방침</span>에<br/>
          동의하는 것으로 간주합니다
        </div>
      </div>
      </div>
    </div>
  );
}

function ProviderBtn({ label, icon, background, color, border, busy, disabled, onClick }) {
  return (
    <button onClick={onClick} disabled={disabled || busy} style={{
      width: '100%', height: 52, borderRadius: 14,
      background, color, border: border || 'none',
      padding: '0 18px',
      display: 'flex', alignItems: 'center', gap: 10,
      fontFamily: 'inherit', fontSize: 15.5, fontWeight: 600,
      letterSpacing: '-0.01em',
      cursor: (busy || disabled) ? 'default' : 'pointer',
      opacity: disabled ? 0.4 : 1,
      transition: 'opacity .18s, transform .12s',
      WebkitTapHighlightColor: 'transparent',
    }}>
      <span style={{
        width: 22, height: 22,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{busy ? <Spinner color={color} size={18}/> : icon}</span>
      <span style={{ flex: 1, textAlign: 'center', paddingRight: 22 }}>
        {busy ? '계속 진행 중…' : label}
      </span>
    </button>
  );
}

function AppleGlyph() {
  return (
    <svg width="18" height="20" viewBox="0 0 18 20" fill="none">
      <path d="M14.5 10.5c0-2.4 2-3.5 2-3.5-1.1-1.6-2.8-1.8-3.4-1.8-1.5-.1-2.8.8-3.6.8-.8 0-1.9-.8-3.2-.8-1.6 0-3.2.9-4 2.4-1.7 3-.4 7.4 1.2 9.8.8 1.2 1.8 2.5 3 2.5 1.2 0 1.7-.8 3.1-.8s1.9.8 3.2.8c1.3 0 2.2-1.2 3-2.4.9-1.4 1.3-2.8 1.3-2.9-.1 0-2.6-1-2.6-4z" fill="currentColor"/>
      <path d="M12.4 3.6c.7-.8 1.1-2 1-3.2-1 0-2.3.7-3 1.6-.6.7-1.2 1.9-1 3 1.1.1 2.3-.5 3-1.4z" fill="currentColor"/>
    </svg>
  );
}
function GoogleGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <path d="M17.6 9.2c0-.6 0-1.1-.1-1.7H9v3.2h4.8c-.2 1.1-.8 2-1.8 2.7v2.2h2.9c1.7-1.5 2.7-3.8 2.7-6.4z" fill="#4285F4"/>
      <path d="M9 18c2.4 0 4.5-.8 6-2.2l-2.9-2.2c-.8.5-1.8.9-3.1.9-2.4 0-4.4-1.6-5.1-3.7H.9v2.3C2.4 16.1 5.5 18 9 18z" fill="#34A853"/>
      <path d="M3.9 10.8c-.2-.5-.3-1.1-.3-1.8s.1-1.2.3-1.8V4.9H.9C.3 6.1 0 7.5 0 9s.3 2.9.9 4.1l3-2.3z" fill="#FBBC05"/>
      <path d="M9 3.6c1.3 0 2.5.5 3.5 1.4l2.6-2.6C13.5.9 11.4 0 9 0 5.5 0 2.4 1.9.9 4.9l3 2.3C4.6 5.2 6.6 3.6 9 3.6z" fill="#EA4335"/>
    </svg>
  );
}
function KakaoGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <path d="M9 2C4.6 2 1 4.7 1 8c0 2.1 1.4 4 3.6 5.1l-.7 2.7c-.1.3.3.6.6.4l3.2-2.1c.4 0 .8.1 1.3.1 4.4 0 8-2.7 8-6.2S13.4 2 9 2z" fill="#191919"/>
    </svg>
  );
}

// Legal modal (terms / privacy)
function ScreenLegal({ kind, onClose }) {
  const T = window.T;
  const isTerms = kind === 'terms';
  const title = isTerms ? '이용약관' : '개인정보 처리방침';
  const bodyParas = isTerms ? [
    '제1조 (목적) 본 약관은 CheekPouch(이하 "서비스")의 이용과 관련하여 회사와 회원 간의 권리·의무 및 책임사항, 기타 필요한 사항을 규정함을 목적으로 합니다.',
    '제2조 (정의) "회원"이란 서비스에 접속하여 본 약관에 동의하고 회원가입을 한 자로서, 서비스가 제공하는 정보 및 기능을 이용하는 자를 말합니다.',
    '제3조 (약관의 게시 및 개정) 회사는 본 약관의 내용을 회원이 쉽게 알 수 있도록 서비스 초기 화면 또는 연결 화면에 게시합니다.',
    '제4조 (회원가입) 회원가입은 이용자가 본 약관에 동의한 후, 서비스에서 제공하는 양식에 따라 회원정보를 기입하고 회원가입을 신청함으로써 체결됩니다.',
    '제5조 (개인정보보호) 회사는 회원의 개인정보를 본인의 승낙없이 제3자에게 누설·배포하지 않으며, 관련 법령에 따라 보호합니다.',
    '제6조 (회원의 의무) 회원은 관계 법령, 약관의 규정, 이용안내 및 서비스 상에 공지한 주의사항을 준수하여야 합니다.',
    '제7조 (서비스의 변경) 회사는 상당한 이유가 있는 경우에 운영상, 기술상의 필요에 따라 제공하고 있는 전부 또는 일부 서비스를 변경할 수 있습니다.',
  ] : [
    '1. 수집하는 개인정보 항목 — 서비스는 회원가입, 원활한 고객상담, 각종 서비스 제공을 위해 OAuth 인증 정보(이메일, 표시 이름), 기기 식별자를 수집합니다.',
    '2. 개인정보의 수집 및 이용목적 — 서비스 제공, 본인 식별 및 인증, 부정 이용 방지, 신규 서비스 개발 및 마케팅에 활용됩니다.',
    '3. 개인정보의 보유 및 이용기간 — 회원 탈퇴 시 모든 개인정보는 즉시 파기되며, 관련 법령에 따라 보존이 필요한 경우 해당 기간 동안 보관됩니다.',
    '4. 개인정보의 파기절차 및 방법 — 회원이 회원가입 등을 위해 입력하신 정보는 목적이 달성된 후 즉시 파기됩니다.',
    '5. 개인정보의 제3자 제공 — 회사는 이용자의 개인정보를 원칙적으로 외부에 제공하지 않습니다. 다만, 법령의 규정에 의거하거나, 수사 목적으로 법령에 정해진 절차와 방법에 따라 수사기관의 요구가 있는 경우는 예외로 합니다.',
    '6. 이용자의 권리 — 이용자는 언제든지 자신의 개인정보를 조회, 수정, 삭제할 수 있으며, 처리정지를 요청할 수 있습니다.',
    '7. 개인정보 보호책임자 — 개인정보 보호 책임자: 한지원 / 연락처: privacy@cheekpouch.app',
  ];

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: T.bg,
      display: 'flex', flexDirection: 'column',
      animation: 'cp-sheet-up 0.28s cubic-bezier(0.32, 0.72, 0, 1)',
    }}>
      <TopBar
        title={title}
        leading={<IconButton icon={<Icons.Close size={22} color={T.ink}/>} onClick={onClose}/>}
      />
      <div style={{
        flex: 1, overflowY: 'auto', padding: '8px 20px 32px',
      }}>
        <div style={{
          fontSize: 12, color: T.ink3,
          padding: '0 0 16px', borderBottom: `0.5px solid ${T.hairline}`,
          marginBottom: 16,
        }}>최종 갱신: 2026-05-15</div>
        {bodyParas.map((p, i) => (
          <p key={i} style={{
            fontSize: 14, color: T.ink2,
            lineHeight: 1.7, letterSpacing: '-0.005em',
            margin: '0 0 14px',
          }}>{p}</p>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenLogin, ScreenLegal });
