/* screen-auth.jsx — Email/password auth + Google as the only social option + inline language switcher */
/* global React, Counter, Sparkline, Icon, useT, LOCALES */

function ScreenAuth({ mode: initialMode = 'login', onDone, onForgot }) {
  const [mode, setMode] = React.useState(initialMode);
  const [role, setRole] = React.useState('brand');
  const [showPw, setShowPw] = React.useState(false);
  const { t, locale } = useT();

  return (
    <div className="screen" style={{ position: 'relative', minHeight: '100vh', overflow: 'hidden', display: 'grid', gridTemplateColumns: '1fr 1fr', background: 'white' }}>

      {/* LEFT: data-poetic decorative panel */}
      <AuthVisualPanel />

      {/* RIGHT: form */}
      <div style={{ display: 'grid', placeItems: 'center', padding: '40px 32px', position: 'relative' }}>

        {/* Inline language switcher — top-right of the auth pane */}
        <div style={{ position: 'absolute', top: 24, right: 24, zIndex: 5 }}>
          <AuthLangSwitcher />
        </div>

        <div style={{ width: '100%', maxWidth: 400 }}>
          <div className="row items-center gap-8 mb-6">
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: 'linear-gradient(135deg, #009CFF, #1C1CC9)',
              color: 'white', fontWeight: 800, display: 'grid', placeItems: 'center',
              fontFamily: 'Space Grotesk', fontSize: 18,
              boxShadow: '0 6px 16px rgba(28,28,201,0.4)'
            }}>P</div>
            <div>
              <div className="font-display bold" style={{ fontSize: 17, lineHeight: 1 }}>Prime Influencer</div>
              <div className="muted" style={{ fontSize: 11 }}>{t('auth.poweredBy')}</div>
            </div>
          </div>

          <h1 key={locale + mode} className="font-display" style={{ fontSize: 34, fontWeight: 700, letterSpacing: '-0.025em', lineHeight: 1.08, margin: '12px 0 6px', animation: 'authFade .35s ease-out' }}>
            {mode === 'login' ? t('auth.welcomeBack') : t('auth.firstMatch')}
          </h1>
          <p className="muted" style={{ fontSize: 13.5, margin: 0, lineHeight: 1.5 }}>
            {mode === 'login' ? t('auth.subLogin') : t('auth.subSignup')}
          </p>

          {/* role picker — only on signup */}
          {mode === 'signup' && (
            <>
              <div className="label" style={{ marginTop: 22, marginBottom: 8 }}>{t('auth.iAmA')}</div>
              <div className="row gap-8" role="radiogroup" aria-label={t('auth.iAmA')}>
                {['brand', 'creator'].map(r => (
                  <button
                    key={r}
                    className="row items-center gap-8"
                    onClick={() => setRole(r)}
                    style={{
                      flex: 1,
                      padding: 12,
                      border: '2px solid ' + (role === r ? 'var(--ink)' : 'var(--line)'),
                      background: role === r ? 'var(--ink)' : 'white',
                      color: role === r ? 'white' : 'var(--ink)',
                      borderRadius: 14,
                      fontFamily: 'inherit', textAlign: 'left',
                      cursor: 'pointer',
                      transition: 'all .2s'
                    }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: 8,
                      background: r === 'brand' ? 'var(--cyan)' : 'var(--mint)',
                      color: r === 'brand' ? 'white' : 'var(--ink)',
                      display: 'grid', placeItems: 'center'
                    }}>
                      {r === 'brand' ? Icon.bag : Icon.trophy}
                    </div>
                    <div>
                      <div className="bold" style={{ fontSize: 13 }}>{r === 'brand' ? t('auth.brand') : t('auth.creator')}</div>
                      <div style={{ fontSize: 11, opacity: 0.7 }}>{r === 'brand' ? t('auth.brandDesc') : t('auth.creatorDesc')}</div>
                    </div>
                  </button>
                ))}
              </div>
            </>
          )}

          {/* Username/password form */}
          <form
            onSubmit={(e) => { e.preventDefault(); onDone?.(role); }}
            style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>

            {mode === 'signup' && (
              <div>
                <label className="label">{t('auth.fullname')}</label>
                <input className="input" placeholder="Linh Châu" defaultValue="" />
              </div>
            )}

            <div>
              <label className="label">{t('auth.email')}</label>
              <input
                className="input"
                type="email"
                placeholder="you@brand.com"
                defaultValue="admin@example.com"
                autoComplete="email" />
            </div>

            <div>
              <label className="label" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>{t('auth.password')}</span>
                {mode === 'login' && (
                  <button
                    type="button"
                    onClick={() => onForgot?.()}
                    style={{
                      background: 'transparent', border: 0, padding: 0,
                      color: 'var(--cyan-dark)', fontWeight: 700, fontSize: 11,
                      cursor: 'pointer', fontFamily: 'inherit',
                      textTransform: 'none', letterSpacing: 0
                    }}>
                    {t('auth.forgot')}
                  </button>
                )}
              </label>
              <div style={{ position: 'relative' }}>
                <input
                  className="input"
                  type={showPw ? 'text' : 'password'}
                  placeholder="••••••••"
                  defaultValue="password123"
                  autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
                  style={{ paddingRight: 44 }} />
                <button
                  type="button"
                  onClick={() => setShowPw(s => !s)}
                  aria-label={showPw ? 'Hide password' : 'Show password'}
                  style={{
                    position: 'absolute', top: '50%', right: 10, transform: 'translateY(-50%)',
                    background: 'transparent', border: 0, padding: 6,
                    color: 'var(--ink-soft)', cursor: 'pointer',
                    display: 'grid', placeItems: 'center'
                  }}>
                  {showPw ? (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94" /><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19" /><path d="m1 1 22 22" /><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24" /></svg>
                  ) : (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg>
                  )}
                </button>
              </div>
            </div>

            {mode === 'signup' && (
              <label className="row items-center gap-8" style={{ fontSize: 12, color: 'var(--ink-soft)', cursor: 'pointer' }}>
                <input type="checkbox" defaultChecked style={{ width: 16, height: 16, accentColor: 'var(--cyan)' }} />
                <span>
                  {t('auth.termsLine')}{' '}
                  <a style={{ color: 'var(--cyan-dark)', fontWeight: 700 }}>{t('auth.terms')}</a>
                  {' '}{t('auth.and')}{' '}
                  <a style={{ color: 'var(--cyan-dark)', fontWeight: 700 }}>{t('auth.privacy')}</a>
                </span>
              </label>
            )}

            <button type="submit" className="btn btn-primary" style={{ marginTop: 4, width: '100%' }}>
              {mode === 'login' ? t('auth.signin') : t('auth.signup')} {Icon.arrow}
            </button>
          </form>

          {/* Divider */}
          <div className="row items-center gap-12 mt-6" style={{ color: 'var(--ink-soft)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em' }}>
            <div style={{ height: 1, background: 'var(--line)', flex: 1 }} />
            {t('auth.orContinue') /* falls back to key */}
            <div style={{ height: 1, background: 'var(--line)', flex: 1 }} />
          </div>

          {/* Social — Google only for now (Microsoft & SSO removed per request) */}
          <button
            onClick={() => onDone?.(role)}
            className="google-btn"
            style={{
              marginTop: 14,
              width: '100%',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              gap: 10,
              padding: '14px 18px',
              background: 'white',
              color: 'var(--ink)',
              border: '1.5px solid var(--line)',
              borderRadius: 12,
              fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
              cursor: 'pointer',
              transition: 'transform .15s ease, box-shadow .15s ease, border-color .15s ease'
            }}>
            <GoogleGlyph />
            {t('auth.continueGoogle')}
          </button>

          <p className="muted" style={{ fontSize: 11, marginTop: 8, lineHeight: 1.5, textAlign: 'center' }}>
            {t('auth.moreSoonHint')}
          </p>

          {/* Bottom mode-switch banner */}
          <div style={{
            marginTop: 22,
            padding: '12px 14px',
            background: 'var(--bg-soft, #F5F7FA)',
            borderRadius: 12,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            gap: 12,
            fontSize: 13
          }}>
            <span className="muted">
              {mode === 'login' ? t('auth.newHere') : t('auth.alreadyOn')}
            </span>
            <button
              onClick={() => setMode(mode === 'login' ? 'signup' : 'login')}
              style={{
                background: 'transparent', border: 0, padding: 0,
                color: 'var(--cyan-dark)', fontWeight: 700, fontSize: 13,
                cursor: 'pointer', fontFamily: 'inherit'
              }}>
              {mode === 'login' ? t('auth.signup') : t('auth.signin')} →
            </button>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes authFade { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
        .google-btn:hover { border-color: var(--ink) !important; box-shadow: 0 8px 18px rgba(0,43,80,0.08); transform: translateY(-1px); }
        .google-btn:active { transform: translateY(0); }
      `}</style>
    </div>
  );
}

/* Generic 4-color "G" mark — placeholder, not Google's official brand asset */
function GoogleGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true" style={{ flexShrink: 0 }}>
      <path d="M12 4 A 8 8 0 1 1 4 12" fill="none" stroke="#1C1CC9" strokeWidth="2.8" strokeLinecap="round" />
      <path d="M4 12 A 8 8 0 0 1 12 4" fill="none" stroke="#FF6FA3" strokeWidth="2.8" strokeLinecap="round" />
      <path d="M20 12 A 8 8 0 0 1 12 20" fill="none" stroke="#FEE960" strokeWidth="2.8" strokeLinecap="round" />
      <path d="M12 12 L 20 12" fill="none" stroke="#1FD6B4" strokeWidth="2.8" strokeLinecap="round" />
      <circle cx="12" cy="12" r="1.4" fill="#1C1CC9" />
    </svg>
  );
}

/* ── Inline language switcher built specifically for the auth screen ── */
function AuthLangSwitcher() {
  const { locale } = useT();
  const [open, setOpen] = React.useState(false);
  const cur = LOCALES.find(l => l.code === locale) || LOCALES[0];
  const setLocale = (code) => {
    if (window.__setLocale) window.__setLocale(code);
    setOpen(false);
  };
  return (
    <div style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          background: 'white', border: '1px solid var(--line)',
          borderRadius: 999, padding: '8px 12px 8px 10px',
          display: 'inline-flex', alignItems: 'center', gap: 8,
          fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
          cursor: 'pointer', color: 'var(--ink)',
          boxShadow: '0 2px 8px rgba(0,43,80,0.06)'
        }}>
        <span aria-hidden="true" style={{ fontSize: 14, lineHeight: 1 }}>{cur.flag}</span>
        <span style={{ letterSpacing: '0.04em' }}>{cur.code.toUpperCase()}</span>
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}><path d="m6 9 6 6 6-6" /></svg>
      </button>
      {open && (
        <>
          <div style={{ position: 'fixed', inset: 0, zIndex: 50 }} onClick={() => setOpen(false)} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 8px)', right: 0,
            background: 'white', borderRadius: 14,
            boxShadow: '0 18px 40px rgba(0,43,80,0.18)',
            border: '1px solid var(--line)',
            minWidth: 220, padding: 6, zIndex: 51,
            animation: 'authFade .18s ease-out'
          }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'var(--ink-soft)', padding: '6px 10px 4px', textTransform: 'uppercase' }}>
              Language / Ngôn ngữ / Bahasa
            </div>
            {LOCALES.map(l => (
              <button key={l.code} onClick={() => setLocale(l.code)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  width: '100%', padding: '10px 10px',
                  border: 0, background: l.code === locale ? 'var(--bg-soft, #F5F7FA)' : 'transparent',
                  borderRadius: 10, fontSize: 13, fontWeight: 600,
                  cursor: 'pointer', textAlign: 'left', color: 'var(--ink)',
                  fontFamily: 'inherit'
                }}>
                <span aria-hidden="true" style={{ fontSize: 18 }}>{l.flag}</span>
                <span style={{ flex: 1 }}>{l.label}</span>
                <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-soft)', letterSpacing: '0.06em' }}>{l.code.toUpperCase()}</span>
                {l.code === locale && (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--cyan-dark)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg>
                )}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function AuthVisualPanel() {
  const { t } = useT();
  return (
    <div style={{
      background: 'linear-gradient(135deg, #002B50 0%, #1C1CC9 100%)',
      color: 'white',
      position: 'relative',
      overflow: 'hidden',
      padding: '60px 56px',
      display: 'flex', flexDirection: 'column'
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(rgba(255,255,255,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.04) 1px, transparent 1px)',
        backgroundSize: '40px 40px',
        animation: 'gridShift 20s linear infinite'
      }} />
      <div style={{
        position: 'absolute', top: -100, right: -100,
        width: 400, height: 400, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,111,163,0.6), transparent 60%)',
        filter: 'blur(40px)',
        animation: 'authBlob1 12s ease-in-out infinite'
      }} />
      <div style={{
        position: 'absolute', bottom: -150, left: -50,
        width: 500, height: 500, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(121,254,231,0.45), transparent 60%)',
        filter: 'blur(40px)',
        animation: 'authBlob2 14s ease-in-out infinite'
      }} />

      <div style={{ position: 'relative', zIndex: 1 }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '6px 12px', borderRadius: 999,
          background: 'rgba(255,255,255,0.08)',
          border: '1px solid rgba(255,255,255,0.16)',
          fontSize: 11, fontWeight: 700, letterSpacing: '0.04em'
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--mint)', display: 'inline-block', boxShadow: '0 0 12px var(--mint)' }} />
          {t('auth.heroBadge')}
        </div>
        <h2 className="font-display" style={{ fontSize: 44, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.05, marginTop: 16, marginBottom: 0 }}>
          {t('auth.heroH1')}<br />
          <span style={{
            background: 'linear-gradient(90deg, #79FEE7, #FEE960)',
            WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent'
          }}>{t('auth.heroH2')}</span>
        </h2>
        <p style={{ marginTop: 14, color: 'rgba(255,255,255,0.7)', fontSize: 15, lineHeight: 1.55, maxWidth: 380 }}>
          {t('auth.heroBody')}
        </p>
      </div>

      <div style={{ position: 'relative', zIndex: 1, marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <AuthStatCard label={t('auth.stat1')} value={6.4} suffix="s" decimals={1} color="#FEE960" />
        <AuthStatCard label={t('auth.stat2')} value={284} color="#FF6FA3" />
        <AuthStatCard label={t('auth.stat3')} value={184} suffix="M / week" color="#79FEE7"
          spark={[80, 100, 110, 130, 140, 160, 170, 180, 184]} />
      </div>

      <style>{`
        @keyframes gridShift { from { transform: translateY(0); } to { transform: translateY(40px); } }
        @keyframes authBlob1 { 0%,100% { transform: translate(0,0); } 50% { transform: translate(-60px, 60px); } }
        @keyframes authBlob2 { 0%,100% { transform: translate(0,0); } 50% { transform: translate(60px, -40px); } }
      `}</style>
    </div>
  );
}

function AuthStatCard({ label, value, prefix = '', suffix = '', decimals = 0, color, spark }) {
  return (
    <div style={{
      background: 'rgba(255,255,255,0.07)',
      backdropFilter: 'blur(10px)',
      WebkitBackdropFilter: 'blur(10px)',
      border: '1px solid rgba(255,255,255,0.12)',
      borderRadius: 16,
      padding: 16,
      display: 'flex', alignItems: 'center', gap: 14
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: color, opacity: 0.25,
        position: 'relative'
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          border: '2px solid ' + color, borderRadius: 12,
          animation: 'statPulse 2.4s ease-out infinite'
        }} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', fontWeight: 600, letterSpacing: '0.04em' }}>{label}</div>
        <div className="font-display tabular" style={{ fontSize: 26, fontWeight: 700, color: color, letterSpacing: '-0.02em' }}>
          <Counter to={value} prefix={prefix} suffix={suffix} decimals={decimals} duration={1800} />
        </div>
      </div>
      {spark && (
        <div style={{ width: 80 }}>
          <Sparkline data={spark} color={color} fillId={`authSpark-${label}`} height={36} />
        </div>
      )}
      <style>{`@keyframes statPulse { 0% { transform: scale(1); opacity: 1; } 100% { transform: scale(1.4); opacity: 0; } }`}</style>
    </div>
  );
}

Object.assign(window, { ScreenAuth });
