const { useState, useEffect } = React;

const MODE = window.__AUTH_MODE__ || "signup";

function SSOButton({ icon, label, onClick }) {
  return (
    <button className="auth-sso-btn" onClick={onClick} type="button">
      {icon}
      <span>{label}</span>
    </button>
  );
}

function AuthForm() {
  const isSignup = MODE === "signup";
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [emailTouched, setEmailTouched] = useState(false);
  const [pwTouched, setPwTouched] = useState(false);

  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const pwValid = password.length >= 8;
  const valid = emailValid && pwValid && (!isSignup || name.trim().length > 1);

  const onSubmit = (e) => {
    e.preventDefault();
    if (!valid) return;
    setSubmitting(true);
    setTimeout(() => {
      alert(isSignup ? `Account created for ${email}.\n(This is a prototype — no real account is made.)` : `Signed in as ${email}.\n(Prototype.)`);
      setSubmitting(false);
    }, 900);
  };

  return (
    <form className="auth-form" onSubmit={onSubmit}>
      <h1>{isSignup ? "Start calling in minutes." : "Welcome back."}</h1>
      <p className="sub">
        {isSignup
          ? "5 free minutes to try. No credit card required."
          : "Sign in to your Ringlist workspace."}
      </p>

      <div className="auth-sso">
        <SSOButton
          onClick={() => alert("Google SSO (prototype)")}
          icon={
            <svg width="16" height="16" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
          }
          label="Continue with Google"
        />
        <SSOButton
          onClick={() => alert("Microsoft SSO (prototype)")}
          icon={
            <svg width="16" height="16" viewBox="0 0 24 24"><rect x="1" y="1" width="10" height="10" fill="#F25022"/><rect x="13" y="1" width="10" height="10" fill="#7FBA00"/><rect x="1" y="13" width="10" height="10" fill="#00A4EF"/><rect x="13" y="13" width="10" height="10" fill="#FFB900"/></svg>
          }
          label="Continue with Microsoft"
        />
      </div>

      <div className="auth-divider">Or with email</div>

      {isSignup && (
        <div className="auth-field">
          <label htmlFor="name">Full name</label>
          <input id="name" type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Jane Doe" autoComplete="name" />
        </div>
      )}

      <div className={`auth-field ${emailTouched && email && !emailValid ? "error" : ""}`}>
        <label htmlFor="email">Work email</label>
        <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} onBlur={() => setEmailTouched(true)} placeholder="jane@company.com" autoComplete="email" />
        {emailTouched && email && !emailValid && <span className="helper">Please enter a valid email.</span>}
      </div>

      <div className={`auth-field ${pwTouched && password && !pwValid ? "error" : pwValid ? "valid" : ""}`}>
        <label htmlFor="password" style={{ display: "flex", justifyContent: "space-between" }}>
          <span>Password</span>
          {!isSignup && <a href="#" style={{ fontSize: 12, color: "var(--text-muted)" }}>Forgot?</a>}
        </label>
        <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} onBlur={() => setPwTouched(true)} placeholder={isSignup ? "Min 8 characters" : "Your password"} autoComplete={isSignup ? "new-password" : "current-password"} />
        {isSignup && password && (
          <span className="helper">{pwValid ? "Strong enough." : `Needs ${8 - password.length} more characters.`}</span>
        )}
      </div>

      {isSignup && (
        <div style={{ fontSize: 12, color: "var(--text-muted)", margin: "10px 0 14px", lineHeight: 1.5 }}>
          By signing up, you agree to our <a href="#" style={{ color: "var(--text)", textDecoration: "underline" }}>Terms</a> and <a href="#" style={{ color: "var(--text)", textDecoration: "underline" }}>Privacy</a>. GDPR DPA available.
        </div>
      )}

      <button type="submit" className="btn btn-primary btn-lg auth-submit" disabled={!valid || submitting}>
        {submitting ? (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ animation: "spin 0.8s linear infinite" }}><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
            {isSignup ? "Creating account…" : "Signing in…"}
          </span>
        ) : (
          <>
            {isSignup ? "Create account" : "Sign in"}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </>
        )}
      </button>

      <div className="auth-footer">
        {isSignup ? (
          <>Already have an account? <a href="signin.html">Sign in</a></>
        ) : (
          <>New to Ringlist? <a href="signup.html">Create an account</a></>
        )}
      </div>
    </form>
  );
}

function Visual() {
  const isSignup = MODE === "signup";
  return (
    <aside className="auth-visual">
      <div className="auth-logo-row">
        <div className="logo">
          <svg className="logo-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3.5" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="7" opacity="0.55"/><circle cx="12" cy="12" r="10.5" opacity="0.25"/></svg>
          <span>Ringlist</span>
        </div>
        <a href="index.html" style={{ fontSize: 13, color: "var(--text-muted)" }}>← Back to home</a>
      </div>

      <div className="auth-quote">
        <div style={{ fontSize: 13, color: "var(--accent-text)", fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 20, fontWeight: 500 }}>
          {isSignup ? "What you get, free" : "Trusted by outbound teams"}
        </div>
        <div className="auth-quote-text">
          {isSignup
            ? "5 minutes of calls to test the voice. No credit card. Upload a spreadsheet and watch it work."
            : "We replaced three SDRs and a dialer subscription with Ringlist. Booked demos went up."}
        </div>
        {!isSignup && (
          <div className="auth-quote-attr">
            <div className="auth-quote-avatar">LC</div>
            <div>
              <div style={{ color: "var(--text)", fontWeight: 500 }}>Lena Chen</div>
              <div>Head of Growth, Northwind Labs</div>
            </div>
          </div>
        )}
      </div>

      <div className="auth-stats">
        <div>
          <div className="auth-stat-num mono">2.1M</div>
          <div className="auth-stat-label">calls placed</div>
        </div>
        <div>
          <div className="auth-stat-num mono">38%</div>
          <div className="auth-stat-label">avg contact rate</div>
        </div>
        <div>
          <div className="auth-stat-num mono">€0.15</div>
          <div className="auth-stat-label">per minute</div>
        </div>
      </div>
    </aside>
  );
}

function App() {
  return (
    <div className="auth">
      <div className="auth-panel">
        <div className="auth-head">
          <a href="index.html" className="logo">
            <svg className="logo-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3.5" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="7" opacity="0.55"/><circle cx="12" cy="12" r="10.5" opacity="0.25"/></svg>
            <span>Ringlist</span>
          </a>
          <a href={MODE === "signup" ? "signin.html" : "signup.html"} style={{ fontSize: 13, color: "var(--text-muted)" }}>
            {MODE === "signup" ? "Sign in" : "Create account"}
          </a>
        </div>
        <div className="auth-form-wrap">
          <AuthForm />
        </div>
      </div>
      <Visual />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);

// Add spin keyframes
const style = document.createElement('style');
style.textContent = `@keyframes spin { to { transform: rotate(360deg); } }`;
document.head.appendChild(style);
