// Admin emails allowed into the dashboard
const ADMIN_EMAILS = ["adi@talio.fun", "adigold1@gmail.com", "info@adigoldstein.com"];

function authErrMsg(code) {
  if (code === "auth/invalid-credential" || code === "auth/wrong-password" || code === "auth/user-not-found")
    return "Incorrect email or password.";
  if (code === "auth/too-many-requests")
    return "Too many attempts. Try again later.";
  if (code === "auth/invalid-email")
    return "Invalid email address.";
  return "Sign-in failed. Please try again.";
}

function Login({ onLogin }) {
  const [email, setEmail]       = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState("");

  async function submit(e) {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const cred = await window.__signInEmail(email.trim(), password);
      const user = cred.user;
      if (!ADMIN_EMAILS.includes(user.email)) {
        await window.__signOut();
        setError("This account is not authorised as an admin.");
        return;
      }
      onLogin(user);
    } catch (err) {
      setError(authErrMsg(err.code));
    } finally {
      setLoading(false);
    }
  }

  async function googleSignIn() {
    setError("");
    setLoading(true);
    try {
      const cred = await window.__signInGoogle();
      const user = cred.user;
      if (!ADMIN_EMAILS.includes(user.email)) {
        await window.__signOut();
        setError("This Google account is not authorised as an admin.");
        return;
      }
      onLogin(user);
    } catch (err) {
      if (err.code !== "auth/popup-closed-by-user") setError(authErrMsg(err.code));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="login-wrap">
      <div className="login-left">
        <div className="login-brand">
          <div className="mark">T</div>
          <div className="name">Talio</div>
          <div className="tag">admin · talio.fun</div>
        </div>

        <form className="login-card" onSubmit={submit}>
          <h1>Welcome back.</h1>
          <p className="sub">Sign in to the Talio admin console.</p>

          <div className="field">
            <label>Work email</label>
            <input type="email" value={email} onChange={e=>setEmail(e.target.value)} autoFocus placeholder="you@talio.fun"/>
          </div>

          <div className="field">
            <label>Password</label>
            <input type="password" value={password} onChange={e=>{setPassword(e.target.value); setError("");}} placeholder="Enter password"/>
          </div>

          {error && (
            <p style={{fontSize:12, color:"var(--red)", marginTop:-4, marginBottom:4}}>
              {error}
            </p>
          )}

          <button className="btn primary" type="submit" disabled={loading || !email || !password}>
            {loading ? "Signing in…" : "Sign in"} {!loading && <Icon.chevRight size={14}/>}
          </button>

          <div style={{marginTop:16, display:"flex", alignItems:"center", gap:8, justifyContent:"center"}}>
            <div style={{flex:1, height:1, background:"var(--border)"}}/>
            <span style={{fontSize:11, color:"var(--ink-3)"}}>or</span>
            <div style={{flex:1, height:1, background:"var(--border)"}}/>
          </div>

          <button type="button" className="btn" onClick={googleSignIn} disabled={loading}
            style={{marginTop:14, width:"100%", height:38, justifyContent:"center"}}>
            <svg width="14" height="14" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.5l6.7-6.7C35.5 2.4 30 0 24 0 14.7 0 6.7 5.4 2.8 13.3l7.8 6C12.5 13.3 17.8 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.5-.2-3-.4-4.5H24v9h12.6c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4 6.9-10 6.9-17.5z"/><path fill="#FBBC05" d="M10.6 28.7c-.6-1.7-1-3.5-1-5.5s.4-3.8 1-5.5l-7.8-6C1 15.5 0 19.6 0 24s1 8.5 2.8 12.3l7.8-6z"/><path fill="#34A853" d="M24 48c6 0 11.5-2 15.5-5.5l-7.5-5.8c-2 1.4-4.7 2.3-8 2.3-6.2 0-11.5-3.8-13.4-9.7l-7.8 6C6.7 42.6 14.7 48 24 48z"/></svg>
            Continue with Google
          </button>

          <p style={{fontSize:11, color:"var(--ink-3)", marginTop:20, textAlign:"center"}}>
            <Icon.lock size={10}/> Admin-only access · Firebase Auth
          </p>
        </form>

        <div className="login-foot">
          <span>© 2026 Talio.fun</span>
          <span>Admin console</span>
        </div>
      </div>

      <div className="login-right">
        <div className="cloud" style={{width:120, height:40, top:"12%", left:"8%", filter:"blur(1px)"}}/>
        <div className="cloud" style={{width:90, height:34, top:"28%", right:"12%", opacity:.5, filter:"blur(1px)"}}/>
        <div className="cloud" style={{width:160, height:50, bottom:"18%", left:"18%", opacity:.6, filter:"blur(1.5px)"}}/>
        <div className="cloud" style={{width:70, height:28, bottom:"35%", right:"22%", opacity:.5, filter:"blur(1px)"}}/>

        <div className="stage">
          <div style={{display:"flex", alignItems:"center", gap:14, marginBottom:28, justifyContent:"center"}}>
            <div className="owl-badge">
              <svg width="34" height="34" viewBox="0 0 48 48" fill="none">
                <ellipse cx="24" cy="28" rx="14" ry="16" fill="oklch(0.55 0.14 240)"/>
                <ellipse cx="24" cy="32" rx="10" ry="11" fill="oklch(0.90 0.05 60)"/>
                <circle cx="18" cy="22" r="5" fill="white"/><circle cx="30" cy="22" r="5" fill="white"/>
                <circle cx="18" cy="22" r="2.5" fill="#3b2112"/><circle cx="30" cy="22" r="2.5" fill="#3b2112"/>
                <path d="M21 25 L24 28 L27 25Z" fill="oklch(0.72 0.18 55)"/>
                <path d="M10 10 Q14 8 16 12M38 10 Q34 8 32 12" stroke="oklch(0.55 0.14 240)" strokeWidth="3" fill="none" strokeLinecap="round"/>
              </svg>
            </div>
            <div>
              <div style={{fontFamily:"var(--fraunces)", fontSize:32, fontWeight:700, color:"oklch(0.32 0.13 330)", lineHeight:1}}>Talio</div>
              <div style={{fontSize:11, color:"var(--ink-3)", fontFamily:"var(--mono)", marginTop:4, letterSpacing:".08em"}}>STORIES · FOR · LITTLE · ONES</div>
            </div>
          </div>

          <div className="stat-card" style={{top:0, left:0, width:200}}>
            <div style={{fontSize:10, color:"var(--ink-3)", textTransform:"uppercase", letterSpacing:".06em", fontWeight:600}}>MRR</div>
            <div style={{fontFamily:"var(--display)", fontSize:24, fontWeight:600, marginTop:2}}>$31,420</div>
            <div style={{fontSize:11, color:"var(--green)", fontFamily:"var(--mono)", marginTop:2}}>▲ 8.4% mo/mo</div>
          </div>

          <div className="stat-card" style={{top:30, right:0, width:190}}>
            <div style={{fontSize:10, color:"var(--ink-3)", textTransform:"uppercase", letterSpacing:".06em", fontWeight:600}}>Stories today</div>
            <div style={{fontFamily:"var(--display)", fontSize:24, fontWeight:600, marginTop:2}}>1,420</div>
            <div style={{fontSize:11, color:"var(--green)", fontFamily:"var(--mono)", marginTop:2}}>▲ 14.2%</div>
          </div>

          <div className="stat-card" style={{top:200, left:40, width:230}}>
            <div style={{fontSize:10, color:"var(--ink-3)", textTransform:"uppercase", letterSpacing:".06em", fontWeight:600, marginBottom:10}}>Active users · live</div>
            <div style={{display:"flex", alignItems:"center", gap:10}}>
              <span className="pulse"/>
              <div style={{fontFamily:"var(--display)", fontSize:22, fontWeight:600}}>847</div>
              <div style={{fontSize:11, color:"var(--ink-3)", marginLeft:"auto"}}>creating stories now</div>
            </div>
          </div>

          <div className="stat-card" style={{top:170, right:30, width:160}}>
            <div style={{fontSize:10, color:"var(--ink-3)", textTransform:"uppercase", letterSpacing:".06em", fontWeight:600}}>Moderation</div>
            <div style={{display:"flex", alignItems:"baseline", gap:4, marginTop:4}}>
              <div style={{fontFamily:"var(--display)", fontSize:22, fontWeight:600}}>3</div>
              <div style={{fontSize:11, color:"var(--ink-3)"}}>pending review</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Login = Login;
