// LoginScreen — KARE Partner App PA-001
// AuthLayout, mobile 375px

const KARE = {
  primary: '#0D7A6E',
  primaryBgHover: '#E6F4F2',
  primaryPressed: '#085C53',
  gold: '#C9A84C',
  n900: '#111827', n700: '#374151', n500: '#6B7280',
  n300: '#D1D5DB', n100: '#F3F4F6', n000: '#FFFFFF',
  error: '#DC2626', errorBg: '#FEF2F2',
  warning: '#D97706', warningBg: '#FFFBEB',
  success: '#059669', successBg: '#ECFDF5',
};

const KO = {
  partner: 'Partner',
  title: '파트너 로그인',
  subtitle: 'Sign in to manage your services',
  email: '이메일',
  emailPh: 'name@partner.com',
  password: '비밀번호',
  pwPh: '비밀번호 입력',
  show: '표시',
  hide: '숨김',
  signIn: '로그인',
  forgot: '비밀번호 찾기',
  invalid: '이메일 또는 비밀번호가 올바르지 않습니다',
  accountSuspended: '계정이 정지되었습니다. KARE 지원팀에 문의하세요',
  partnerSuspended: '파트너사가 정지 상태입니다. 조회 전용 모드로 진입합니다',
  copyright: '© KARE 2026 · Partner App',
};
const EN = {
  partner: 'Partner',
  title: 'Partner Sign In',
  subtitle: 'Sign in to manage your services',
  email: 'Email',
  emailPh: 'name@partner.com',
  password: 'Password',
  pwPh: 'Enter password',
  show: 'Show',
  hide: 'Hide',
  signIn: 'Sign in',
  forgot: 'Forgot password',
  invalid: 'Incorrect email or password',
  accountSuspended: 'Your account is suspended. Please contact KARE support.',
  partnerSuspended: 'Partner is suspended. Entering view-only mode.',
  copyright: '© KARE 2026 · Partner App',
};
const COPY = { ko: KO, en: EN };

// ─────────────────────────────────────────────────────────────
// KARE logo — wordmark + accent square (no complex SVG)
// ─────────────────────────────────────────────────────────────
function KareLogo({ size = 80 }) {
  // size = total square footprint; render wordmark + small accent
  const fs = Math.round(size * 0.36);
  return (
    <div style={{
      width: size, height: size,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      gap: 6,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        <div style={{
          width: fs * 0.55, height: fs * 0.55,
          background: KARE.primary, borderRadius: 4,
        }} />
        <div style={{
          fontFamily: 'Inter, system-ui, sans-serif',
          fontSize: fs, fontWeight: 800, letterSpacing: -1.2,
          color: KARE.primary, lineHeight: 1,
        }}>KARE</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Lang toggle (top-right)
// ─────────────────────────────────────────────────────────────
function LangToggle({ lang, onChange }) {
  const opt = (v, label) => (
    <button
      onClick={() => onChange(v)}
      style={{
        border: 'none', background: 'transparent', cursor: 'pointer',
        padding: '4px 8px', borderRadius: 4,
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: 12, fontWeight: lang === v ? 600 : 400,
        color: lang === v ? KARE.n900 : KARE.n500,
      }}
    >{label}</button>
  );
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      background: KARE.n000, border: `1px solid ${KARE.n300}`,
      borderRadius: 9999, padding: 2, height: 28,
    }}>
      {opt('ko', 'KO')}
      <div style={{ width: 1, height: 14, background: KARE.n300 }} />
      {opt('en', 'EN')}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Text input
// ─────────────────────────────────────────────────────────────
function TextField({
  label, value, onChange, placeholder, type = 'text',
  error = false, trailing, autoComplete, onFocus, onBlur, focused,
}) {
  const border = error ? KARE.error : (focused ? KARE.primary : KARE.n300);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label style={{
        fontSize: 12, fontWeight: 600, color: KARE.n700,
        fontFamily: 'inherit',
      }}>{label}</label>
      <div style={{
        display: 'flex', alignItems: 'center',
        height: 52, padding: '0 14px',
        background: KARE.n000,
        border: `1.5px solid ${border}`,
        borderRadius: 8,
        transition: 'border-color 120ms',
      }}>
        <input
          dir="ltr"
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={onFocus} onBlur={onBlur}
          placeholder={placeholder}
          autoComplete={autoComplete}
          style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent',
            fontFamily: 'inherit', fontSize: 16, color: KARE.n900,
            minWidth: 0,
          }}
        />
        {trailing}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Primary button — 56px glove-friendly
// ─────────────────────────────────────────────────────────────
function PrimaryBtn({ children, disabled, loading, onClick }) {
  const bg = disabled ? KARE.n300 : KARE.primary;
  return (
    <button
      onClick={loading || disabled ? undefined : onClick}
      disabled={disabled}
      style={{
        height: 56, width: '100%',
        border: 'none', borderRadius: 8,
        background: bg, color: KARE.n000,
        fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
        cursor: disabled || loading ? 'default' : 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        transition: 'background 120ms',
        WebkitTapHighlightColor: 'transparent',
      }}
    >
      {loading ? <Spinner /> : children}
    </button>
  );
}

function Spinner() {
  return (
    <div style={{
      width: 20, height: 20, borderRadius: '50%',
      border: '2.5px solid rgba(255,255,255,0.35)',
      borderTopColor: '#fff',
      animation: 'kareSpin 0.8s linear infinite',
    }} />
  );
}

// ─────────────────────────────────────────────────────────────
// Toast — top-anchored, error or warning
// ─────────────────────────────────────────────────────────────
function Toast({ kind = 'error', children, top = 56 }) {
  const palette = kind === 'warning'
    ? { fg: KARE.warning, bg: KARE.warningBg, border: '#FBE5BE', icon: '!' }
    : { fg: KARE.error,   bg: KARE.errorBg,   border: '#FBD5D5', icon: '!' };
  return (
    <div style={{
      position: 'absolute', top, left: 16, right: 16, zIndex: 30,
      display: 'flex', alignItems: 'flex-start', gap: 10,
      background: palette.bg, border: `1px solid ${palette.border}`,
      borderRadius: 8, padding: '12px 14px',
      boxShadow: '0 6px 20px rgba(17,24,39,0.10)',
    }}>
      <div style={{
        flexShrink: 0,
        width: 20, height: 20, borderRadius: '50%',
        background: palette.fg, color: '#fff',
        fontSize: 13, fontWeight: 700, lineHeight: '20px',
        textAlign: 'center', fontFamily: 'Inter, system-ui, sans-serif',
      }}>{palette.icon}</div>
      <div style={{
        flex: 1, fontSize: 13, lineHeight: 1.45,
        color: palette.fg, fontWeight: 500,
      }}>{children}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Inline error
// ─────────────────────────────────────────────────────────────
function InlineError({ children }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      fontSize: 13, color: KARE.error, fontWeight: 500,
      marginTop: -4,
    }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="10" stroke={KARE.error} strokeWidth="2"/>
        <path d="M12 7v6" stroke={KARE.error} strokeWidth="2" strokeLinecap="round"/>
        <circle cx="12" cy="16.5" r="1.1" fill={KARE.error}/>
      </svg>
      <span>{children}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Eye icon (show/hide password)
// ─────────────────────────────────────────────────────────────
function EyeBtn({ shown, onToggle }) {
  return (
    <button
      onClick={onToggle}
      type="button"
      aria-label={shown ? 'Hide password' : 'Show password'}
      style={{
        marginLeft: 8, border: 'none', background: 'transparent',
        padding: 6, cursor: 'pointer', display: 'flex',
        WebkitTapHighlightColor: 'transparent',
      }}
    >
      {shown ? (
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
          <path d="M3 3l18 18" stroke={KARE.n500} strokeWidth="1.8" strokeLinecap="round"/>
          <path d="M10.6 6.2A10.4 10.4 0 0112 6c5 0 9 4.5 10 6-0.5 0.8-1.7 2.3-3.4 3.6M6.6 7.6C4.5 9 3.4 10.7 2 12c1 1.5 5 6 10 6 1.4 0 2.7-0.3 3.9-0.8" stroke={KARE.n500} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          <path d="M9.9 9.9a3 3 0 004.2 4.2" stroke={KARE.n500} strokeWidth="1.8" strokeLinecap="round"/>
        </svg>
      ) : (
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
          <path d="M2 12s4-6 10-6 10 6 10 6-4 6-10 6-10-6-10-6z" stroke={KARE.n500} strokeWidth="1.8" strokeLinejoin="round"/>
          <circle cx="12" cy="12" r="3" stroke={KARE.n500} strokeWidth="1.8"/>
        </svg>
      )}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// LoginScreen — full screen, designed for 375 viewport
// ─────────────────────────────────────────────────────────────
//   state: 'default' | 'filled' | 'loading' | 'invalid'
//          | 'accountSuspended' | 'partnerSuspended'
//   interactive: if true, manages its own state from a 'default' baseline
// ─────────────────────────────────────────────────────────────
function LoginScreen({ state: stateProp = 'default', interactive = false, initialLang = 'ko' }) {
  const [lang, setLang] = React.useState(initialLang);
  const t = COPY[lang];

  // Interactive state
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [focused, setFocused] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [invalid, setInvalid] = React.useState(false);
  const [toast, setToast] = React.useState(null); // 'accountSuspended' | 'partnerSuspended' | null

  // Static state overrides (for static showcase artboards)
  let _email = email, _pw = pw, _showPw = showPw, _loading = loading,
      _invalid = invalid, _toast = toast;

  if (!interactive) {
    if (stateProp === 'default') {
      _email = ''; _pw = '';
    } else if (stateProp === 'filled') {
      _email = 'jiwon.kim@seoulmed.kr'; _pw = '••••••••••';
    } else if (stateProp === 'loading') {
      _email = 'jiwon.kim@seoulmed.kr'; _pw = '••••••••••'; _loading = true;
    } else if (stateProp === 'invalid') {
      _email = 'jiwon.kim@seoulmed.kr'; _pw = '••••••••••'; _invalid = true;
    } else if (stateProp === 'accountSuspended') {
      _email = 'jiwon.kim@seoulmed.kr'; _pw = '••••••••••';
      _toast = 'accountSuspended';
    } else if (stateProp === 'partnerSuspended') {
      _email = 'jiwon.kim@seoulmed.kr'; _pw = '••••••••••';
      _toast = 'partnerSuspended';
    }
  }

  const canSubmit = _email.trim().length > 0 && _pw.length > 0 && !_loading;

  const handleSubmit = () => {
    if (!interactive || !canSubmit) return;
    setInvalid(false); setToast(null); setLoading(true);
    // Demo behavior: short timeout → invalid (unless special pwd)
    setTimeout(() => {
      setLoading(false);
      if (pw === 'kare2026') {
        setToast('partnerSuspended'); // success-but-suspended demo
      } else if (pw === 'suspended') {
        setToast('accountSuspended');
      } else {
        setInvalid(true);
      }
    }, 1200);
  };

  return (
    <div style={{
      width: '100%', height: '100%',
      background: KARE.n100,
      position: 'relative', overflow: 'hidden',
      fontFamily: lang === 'ko'
        ? "'Pretendard', 'Noto Sans KR', system-ui, sans-serif"
        : "'Inter', 'Noto Sans', system-ui, sans-serif",
      color: KARE.n900,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Lang toggle, top-right, below status bar */}
      <div style={{
        position: 'absolute', top: 56, right: 16, zIndex: 20,
      }}>
        <LangToggle lang={lang} onChange={interactive ? setLang : () => {}} />
      </div>

      {/* Toast layer */}
      {_toast === 'accountSuspended' && (
        <Toast kind="error">{t.accountSuspended}</Toast>
      )}
      {_toast === 'partnerSuspended' && (
        <Toast kind="warning">{t.partnerSuspended}</Toast>
      )}

      {/* Main content — centered */}
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        padding: '90px 20px 24px',
        gap: 24,
      }}>
        {/* Logo + Partner caption */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
          <KareLogo size={80} />
          <div style={{
            fontSize: 12, fontWeight: 400, color: KARE.n500,
            letterSpacing: 0.3, textTransform: 'uppercase',
          }}>{t.partner}</div>
        </div>

        {/* Card */}
        <div style={{
          width: '100%', maxWidth: '100%',
          background: KARE.n000,
          borderRadius: 12,
          padding: 24,
          boxShadow: '0 4px 12px rgba(17,24,39,0.06), 0 1px 2px rgba(17,24,39,0.04)',
          display: 'flex', flexDirection: 'column', gap: 18,
        }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <h1 style={{
              margin: 0, fontSize: 22, fontWeight: 700, lineHeight: 1.3,
              color: KARE.n900, letterSpacing: -0.3,
            }}>{t.title}</h1>
            <p style={{
              margin: 0, fontSize: 12, fontWeight: 400, color: KARE.n500,
              fontFamily: "'Inter', system-ui, sans-serif",
            }}>{t.subtitle}</p>
          </div>

          <TextField
            label={t.email}
            value={_email}
            onChange={interactive ? setEmail : () => {}}
            placeholder={t.emailPh}
            type="email"
            autoComplete="email"
            error={_invalid}
            focused={focused === 'email'}
            onFocus={() => setFocused('email')}
            onBlur={() => setFocused(null)}
          />

          <TextField
            label={t.password}
            value={_pw}
            onChange={interactive ? setPw : () => {}}
            placeholder={t.pwPh}
            type={_showPw ? 'text' : 'password'}
            autoComplete="current-password"
            error={_invalid}
            focused={focused === 'password'}
            onFocus={() => setFocused('password')}
            onBlur={() => setFocused(null)}
            trailing={
              <EyeBtn
                shown={_showPw}
                onToggle={interactive ? () => setShowPw(!showPw) : () => {}}
              />
            }
          />

          {_invalid && <InlineError>{t.invalid}</InlineError>}

          <PrimaryBtn
            disabled={!canSubmit}
            loading={_loading}
            onClick={handleSubmit}
          >{t.signIn}</PrimaryBtn>

          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: -4 }}>
            <button style={{
              border: 'none', background: 'transparent', cursor: 'pointer',
              padding: '4px 0', fontFamily: 'inherit',
              fontSize: 13, fontWeight: 500, color: KARE.primary,
              WebkitTapHighlightColor: 'transparent',
            }}>{t.forgot}</button>
          </div>
        </div>
      </div>

      {/* Footer copyright */}
      <div style={{
        padding: '0 20px 28px',
        textAlign: 'center',
        fontSize: 12, fontWeight: 400, color: KARE.n500,
        fontFamily: "'Inter', system-ui, sans-serif",
      }}>{t.copyright}</div>
    </div>
  );
}

Object.assign(window, {
  LoginScreen, KARE, KareLogo, LangToggle,
  TextField, PrimaryBtn, Spinner, Toast, InlineError, EyeBtn, COPY,
});
