const { useState: useLgSt, useContext: useLgCtx } = React;

/* Autenticação via Supabase — sem senha hardcoded */

/* ── Icons ───────────────────────────────────────────────────────── */
const IconMail = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
    <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
    <polyline points="22,6 12,13 2,6"/>
  </svg>
);
const IconLock = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
    <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
  </svg>
);
const IconEye = ({ size = 14, off = false }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
    {off
      ? <>
          <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.94M9.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.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>
          <line x1="1" y1="1" x2="23" y2="23"/>
        </>
      : <>
          <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>
);

/* ── LoginScreen ─────────────────────────────────────────────────── */
const LoginScreen = ({ onLogin }) => {
  const { theme, toggleTheme } = useLgCtx(ThemeCtx);
  const [email, setEmail]       = useLgSt('');
  const [password, setPassword] = useLgSt('');
  const [showPwd, setShowPwd]   = useLgSt(false);
  const [error, setError]       = useLgSt('');
  const [loading, setLoading]   = useLgSt(false);

  const submit = async (e) => {
    e.preventDefault();
    setError('');

    if (!email.trim() || !password.trim()) {
      setError('Preencha e-mail e senha para continuar.');
      return;
    }

    setLoading(true);
    const { data, error: authError } = await _supabase.auth.signInWithPassword({
      email: email.trim().toLowerCase(),
      password,
    });
    setLoading(false);

    if (authError) {
      setError('E-mail ou senha incorretos. Verifique e tente de novo.');
      return;
    }

    /* Normaliza o usuário Supabase para o formato que a app usa */
    const sbUser = data.user;
    onLogin({
      email: sbUser.email,
      name:  sbUser.user_metadata?.name || sbUser.email.split('@')[0],
    });
  };

  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      display: 'flex', background: 'var(--bg)',
      position: 'relative', overflow: 'hidden',
    }}>

      {/* ── Theme toggle (top right) ── */}
      <button
        onClick={toggleTheme}
        title={theme === 'dark' ? 'Tema claro' : 'Tema escuro'}
        style={{
          position: 'absolute', top: 22, right: 22, zIndex: 10,
          width: 36, height: 36, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: 'var(--gold-bg)', border: '1px solid var(--border)',
          color: 'var(--gold)', backdropFilter: 'blur(8px)',
        }}
      >
        {theme === 'dark' ? <IconSun size={16}/> : <IconMoon size={16}/>}
      </button>

      {/* ── BRAND PANEL (left, hidden on narrow) ── */}
      <div style={{
        flex: '1 1 50%', minWidth: 0,
        background: 'var(--bg2)',
        borderRight: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column',
        position: 'relative', overflow: 'hidden',
        padding: '56px 64px',
      }} className="login-brand">

        {/* Decorative SVG pattern */}
        <svg
          viewBox="0 0 600 800" preserveAspectRatio="xMidYMid slice"
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.5 }}
          aria-hidden="true"
        >
          <defs>
            <radialGradient id="lgrad" cx="40%" cy="40%" r="55%">
              <stop offset="0%"   stopColor="var(--gold)" stopOpacity="0.18"/>
              <stop offset="100%" stopColor="var(--bg2)"  stopOpacity="0"/>
            </radialGradient>
          </defs>
          <rect width="600" height="800" fill="url(#lgrad)"/>
          {/* concentric circles */}
          {[80, 140, 210, 290, 380].map(r => (
            <circle key={r} cx="300" cy="340" r={r} fill="none"
              stroke="var(--gold)" strokeOpacity={0.06 + (5 - [80,140,210,290,380].indexOf(r))*0.025}
              strokeWidth="0.7"/>
          ))}
          {/* fine grid */}
          {[100, 200, 300, 400, 500].map(x => (
            <line key={`v${x}`} x1={x} y1="0" x2={x} y2="800"
              stroke="var(--gold)" strokeOpacity="0.04" strokeWidth="0.5"/>
          ))}
          {[120, 240, 360, 480, 600, 720].map(y => (
            <line key={`h${y}`} x1="0" y1={y} x2="600" y2={y}
              stroke="var(--gold)" strokeOpacity="0.04" strokeWidth="0.5"/>
          ))}
          {/* central diamond */}
          <polygon points="300,200 380,340 300,480 220,340"
            fill="none" stroke="var(--gold)" strokeOpacity="0.32" strokeWidth="1"/>
          <polygon points="300,240 350,340 300,440 250,340"
            fill="none" stroke="var(--gold)" strokeOpacity="0.18" strokeWidth="0.8"/>
        </svg>

        {/* Brand content */}
        <div style={{ position: 'relative', zIndex: 1, marginTop: 'auto' }}>
          <p style={{
            fontSize: 11, fontWeight: 700, color: 'var(--gold)',
            letterSpacing: '0.2em', textTransform: 'uppercase', marginBottom: 14,
          }}>
            Área de Membros
          </p>
          <h1 style={{
            fontSize: 44, fontWeight: 600, color: 'var(--text)',
            lineHeight: 1.05, letterSpacing: '-0.02em', marginBottom: 18,
            maxWidth: 440,
          }}>
            {COURSE.title}
          </h1>
          <p style={{
            fontSize: 15, color: 'var(--text2)', lineHeight: 1.6, maxWidth: 420,
          }}>
            Acesse seu curso, retome de onde parou e construa uma clínica ética,
            sustentável e cheia de propósito.
          </p>

          {/* Decorative divider */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 36, maxWidth: 200 }}>
            <div style={{ flex: 1, height: 1, background: 'var(--border-h)' }}/>
            <span style={{ fontSize: 10, color: 'var(--gold)', letterSpacing: '0.18em' }}>
              {COURSE.totalLessons} AULAS
            </span>
            <div style={{ flex: 1, height: 1, background: 'var(--border-h)' }}/>
          </div>
        </div>
      </div>

      {/* ── FORM PANEL (right) ── */}
      <div style={{
        flex: '1 1 50%', minWidth: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '40px 24px',
      }}>
        <form
          onSubmit={submit}
          style={{
            width: '100%', maxWidth: 380,
            display: 'flex', flexDirection: 'column', gap: 22,
          }}
        >
          <div>
            <p style={{
              fontSize: 11, fontWeight: 700, color: 'var(--gold)',
              letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 10,
            }}>
              Bem-vinda de volta
            </p>
            <h2 style={{
              fontSize: 26, fontWeight: 600, color: 'var(--text)',
              lineHeight: 1.2, marginBottom: 6,
            }}>
              Entre na sua conta
            </h2>
            <p style={{ fontSize: 13, color: 'var(--text2)' }}>
              Use o e-mail e senha que você recebeu por e-mail.
            </p>
          </div>

          {/* E-MAIL */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <label style={{
              fontSize: 11, fontWeight: 600, color: 'var(--text2)',
              letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>
              E-mail
            </label>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              background: 'var(--card)', border: '1px solid var(--border)',
              borderRadius: 9, padding: '12px 14px',
              transition: 'border-color 0.15s',
            }} className="lg-input">
              <span style={{ color: 'var(--text3)' }}><IconMail size={15}/></span>
              <input
                type="email"
                autoComplete="email"
                placeholder="seu@email.com"
                value={email}
                onChange={e => setEmail(e.target.value)}
                style={{
                  flex: 1, background: 'none', border: 'none', outline: 'none',
                  fontSize: 14, color: 'var(--text)', fontFamily: 'inherit',
                }}
              />
            </div>
          </div>

          {/* SENHA */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <label style={{
              fontSize: 11, fontWeight: 600, color: 'var(--text2)',
              letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>
              Senha
            </label>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              background: 'var(--card)', border: '1px solid var(--border)',
              borderRadius: 9, padding: '12px 14px',
            }} className="lg-input">
              <span style={{ color: 'var(--text3)' }}><IconLock size={15}/></span>
              <input
                type={showPwd ? 'text' : 'password'}
                autoComplete="current-password"
                placeholder="••••••••"
                value={password}
                onChange={e => setPassword(e.target.value)}
                style={{
                  flex: 1, background: 'none', border: 'none', outline: 'none',
                  fontSize: 14, color: 'var(--text)', fontFamily: 'inherit',
                }}
              />
              <button
                type="button"
                onClick={() => setShowPwd(v => !v)}
                title={showPwd ? 'Ocultar senha' : 'Mostrar senha'}
                style={{
                  background: 'none', color: 'var(--text3)', padding: 2,
                  display: 'flex', alignItems: 'center',
                }}
              >
                <IconEye size={15} off={showPwd}/>
              </button>
            </div>
          </div>

          {/* ERROR */}
          {error && (
            <div style={{
              background: 'rgba(220, 80, 80, 0.08)',
              border: '1px solid rgba(220, 80, 80, 0.3)',
              borderRadius: 8, padding: '10px 14px',
              fontSize: 12.5, color: '#E07070', lineHeight: 1.5,
            }}>
              {error}
            </div>
          )}

          {/* SUBMIT */}
          <button
            type="submit"
            disabled={loading}
            style={{
              width: '100%', background: 'var(--gold)', borderRadius: 9,
              padding: '13px 22px', fontSize: 14, fontWeight: 600, color: '#0A0A0A',
              opacity: loading ? 0.65 : 1, cursor: loading ? 'wait' : 'pointer',
              transition: 'opacity 0.2s, transform 0.1s',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}
          >
            {loading ? (
              <>
                <span style={{
                  width: 14, height: 14, borderRadius: '50%',
                  border: '2px solid rgba(10,10,10,0.25)',
                  borderTopColor: '#0A0A0A',
                  animation: 'lg-spin 0.7s linear infinite',
                }}/>
                Entrando…
              </>
            ) : 'Entrar'}
          </button>

          {/* Forgot password (placeholder) */}
          <div style={{ textAlign: 'center' }}>
            <button
              type="button"
              onClick={() => alert('Entre em contato com o suporte: contato@andrezabarros.com')}
              style={{
                background: 'none', color: 'var(--text2)', fontSize: 12.5,
                padding: 4, textDecoration: 'underline', textUnderlineOffset: 3,
              }}
            >
              Esqueceu sua senha?
            </button>
          </div>

          <p style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--text3)', marginTop: 4 }}>
            Seu acesso é enviado por e-mail após a compra.
          </p>
        </form>
      </div>

      {/* Styles */}
      <style>{`
        @keyframes lg-spin { to { transform: rotate(360deg); } }
        .lg-input:focus-within { border-color: var(--gold) !important; }
        @media (max-width: 860px) {
          .login-brand { display: none; }
        }
      `}</style>
    </div>
  );
};

window.LoginScreen = LoginScreen;
