/* Auth: Login + Signup + Forgot/Reset */
const AuthShell = ({ children }) => (
  <div className="auth-shell">
    <div className="auth-form-wrap">
      <div className="auth-form">{children}</div>
    </div>
    <div className="auth-visual">
      <div style={{ position: "relative", zIndex: 1 }}>
        <div className="row gap-2" style={{ marginBottom: 40 }}>
          <MikakaMark size={32}/>
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 20 }}>
            mikaka<span style={{ color: "var(--mk-orange)" }}>voice</span>
          </span>
        </div>
        <h2 className="display" style={{ fontSize: 44, fontWeight: 600, letterSpacing: "-0.03em", lineHeight: 1.05, margin: "0 0 20px" }}>
          Your receptionist, now on every line.
        </h2>
        <p style={{ color: "rgba(255,255,255,.7)", fontSize: 16, lineHeight: 1.6, maxWidth: 440 }}>
          Mikaka answers calls for 4,200+ businesses across Africa. Join them —
          your first number rings in under 15 minutes.
        </p>
      </div>
      <div style={{ position: "relative", zIndex: 1, display: "flex", gap: 12, alignItems: "center", color: "rgba(255,255,255,.6)", fontSize: 13 }}>
        <div className="live-dot"/>
        <span className="mono">1,284 calls handled in the last hour</span>
      </div>
    </div>
  </div>
);

const Login = ({ onGo }) => {
  const [email, setEmail] = useState("ayo@acme.ke");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const submit = async (e) => {
    e && e.preventDefault();
    setError("");
    if (!email || !password) {
      setError("Email and password are required.");
      return;
    }
    setLoading(true);
    try {
      await api.auth.login(email, password);
      const user = api.getStore().currentUser || {};
      const isAdmin = Boolean(user.is_super_admin) || user.role === "super_admin";
      onGo(isAdmin ? "dashboard" : "tenant-dashboard");
    } catch (err) {
      setError(err?.message || "Sign-in failed. Check your credentials.");
    } finally {
      setLoading(false);
    }
  };
  return (
    <AuthShell>
      <Chip>Welcome back</Chip>
      <h1 className="display" style={{ fontSize: 36, fontWeight: 600, letterSpacing: "-0.03em", margin: "16px 0 8px" }}>Sign in</h1>
      <p style={{ color: "var(--fg-muted)", marginBottom: 32, fontSize: 14.5 }}>Enter your email and we'll send a magic link — or use a password.</p>
      <form onSubmit={submit} className="stack gap-4">
        <div className="field"><label>Work email</label><input className="input" value={email} onChange={e => setEmail(e.target.value)} /></div>
        <div className="field">
          <div className="row between"><label>Password</label><a className="link-u" style={{ fontSize: 12.5, color: "var(--fg-muted)" }} onClick={() => onGo("forgot")}>Forgot?</a></div>
          <input className="input" type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Your password"/>
        </div>
        {error ? <div style={{ fontSize: 12.5, color: "var(--mk-danger)" }}>{error}</div> : null}
        <button type="submit" className="btn btn-accent btn-lg" style={{ justifyContent: "center" }} disabled={loading}>
          {loading ? "Signing in…" : "Continue"} <Icon name="arrow-right"/>
        </button>
        <div className="row gap-3" style={{ marginTop: 8 }}>
          <div className="hr" style={{ flex: 1 }}/>
          <span style={{ fontSize: 12, color: "var(--fg-faint)" }}>or</span>
          <div className="hr" style={{ flex: 1 }}/>
        </div>
        <button type="button" className="btn btn-outline btn-lg" style={{ justifyContent: "center" }} onClick={() => window.open(`https://wwdfapempllqkapctcgh.supabase.co/auth/v1/authorize?provider=google&redirect_to=${encodeURIComponent(window.location.origin + "/login")}`, "_self")}>
          <Icon name="globe"/> Continue with Google
        </button>
        <div style={{ fontSize: 13.5, color: "var(--fg-muted)", marginTop: 12 }}>
          Don't have an account? <a className="dot-link" onClick={() => onGo("signup")}>Start a free trial</a>
        </div>
        <div style={{ fontSize: 12, color: "var(--fg-faint)", marginTop: 4 }}>
          Admin? <a className="dot-link" onClick={() => onGo("dashboard")}>Sign in as operator</a>
        </div>
      </form>
    </AuthShell>
  );
};

const Signup = ({ onGo }) => {
  const [form, setForm] = useState({ name: "Ayo Mwangi", business: "Acme Nairobi", email: "ayo@acme.ke", password: "" });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const submit = async (e) => {
    e && e.preventDefault();
    setError("");
    if (!form.name || !form.business || !form.email || !form.password) {
      setError("All fields are required.");
      return;
    }
    if (form.password.length < 10) {
      setError("Password must be at least 10 characters.");
      return;
    }
    setLoading(true);
    try {
      await api.auth.signup(form);
      onGo("tenant-onboarding");
    } catch (err) {
      setError(err?.message || "Signup failed.");
    } finally {
      setLoading(false);
    }
  };
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  return (
    <AuthShell>
      <Chip kind="accent">14-day free trial</Chip>
      <h1 className="display" style={{ fontSize: 36, fontWeight: 600, letterSpacing: "-0.03em", margin: "16px 0 8px" }}>Create your workspace</h1>
      <p style={{ color: "var(--fg-muted)", marginBottom: 28, fontSize: 14.5 }}>No credit card. Your first number is waiting.</p>
      <form onSubmit={submit} className="stack gap-4">
        <div className="grid grid-2">
          <div className="field"><label>Your name</label><input className="input" value={form.name} onChange={set("name")}/></div>
          <div className="field"><label>Business</label><input className="input" value={form.business} onChange={set("business")}/></div>
        </div>
        <div className="field"><label>Work email</label><input className="input" value={form.email} onChange={set("email")}/></div>
        <div className="field"><label>Password</label><input className="input" type="password" placeholder="At least 10 characters" value={form.password} onChange={set("password")}/></div>
        {error ? <div style={{ fontSize: 12.5, color: "var(--mk-danger)" }}>{error}</div> : null}
        <button type="submit" className="btn btn-accent btn-lg" style={{ justifyContent: "center" }} disabled={loading}>
          {loading ? "Creating…" : "Create workspace"} <Icon name="arrow-right"/>
        </button>
        <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 4 }}>
          By signing up you agree to the <a className="dot-link">Terms</a> and <a className="dot-link">Privacy Policy</a>.
        </div>
        <div style={{ fontSize: 13.5, color: "var(--fg-muted)", marginTop: 12 }}>
          Have an account? <a className="dot-link" onClick={() => onGo("login")}>Sign in</a>
        </div>
      </form>
    </AuthShell>
  );
};

const Forgot = ({ onGo }) => {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  const [error, setError] = useState("");
  const submit = async (e) => {
    e.preventDefault();
    setError("");
    try {
      await api.auth.forgot(email);
      setSent(true);
    } catch (err) {
      setError(err?.message || "Could not send reset link.");
    }
  };
  return (
    <AuthShell>
      <a className="dot-link" style={{ fontSize: 13 }} onClick={() => onGo("login")}>← Back to sign in</a>
      <h1 className="display" style={{ fontSize: 36, fontWeight: 600, letterSpacing: "-0.03em", margin: "16px 0 8px" }}>Reset your password</h1>
      {!sent ? (
        <>
          <p style={{ color: "var(--fg-muted)", marginBottom: 28, fontSize: 14.5 }}>Enter your work email. We'll send a link to set a new password.</p>
          <form onSubmit={submit} className="stack gap-4">
            <div className="field"><label>Work email</label><input className="input" type="email" autoFocus required value={email} onChange={e => setEmail(e.target.value)} placeholder="you@business.co"/></div>
            {error ? <div style={{ fontSize: 12.5, color: "var(--mk-danger)" }}>{error}</div> : null}
            <button type="submit" className="btn btn-accent btn-lg" style={{ justifyContent: "center" }}>Send reset link <Icon name="arrow-right"/></button>
          </form>
        </>
      ) : (
        <>
          <div style={{ padding: 16, background: "var(--accent-soft)", borderRadius: 10, marginBottom: 16, display: "flex", alignItems: "flex-start", gap: 12 }}>
            <Icon name="mail" size={18} style={{ color: "var(--mk-orange-600)", marginTop: 2 }}/>
            <div><div style={{ fontWeight: 500, marginBottom: 4 }}>Check your inbox</div><div style={{ fontSize: 13.5, color: "var(--fg-muted)" }}>We sent reset instructions to <b style={{ color: "var(--fg)" }}>{email}</b>. The link expires in 30 minutes.</div></div>
          </div>
          <button className="btn btn-outline btn-lg" style={{ width: "100%", justifyContent: "center" }} onClick={() => onGo("reset")}>Open reset page</button>
          <div style={{ fontSize: 13, color: "var(--fg-muted)", marginTop: 16 }}>Didn't get it? <a className="dot-link" onClick={() => setSent(false)}>Try another address</a></div>
        </>
      )}
    </AuthShell>
  );
};

const ResetPassword = ({ onGo }) => {
  const [pw, setPw] = useState("");
  const [confirm, setConfirm] = useState("");
  const [done, setDone] = useState(false);
  const [error, setError] = useState("");
  const match = pw && pw === confirm && pw.length >= 10;
  const submit = async (e) => {
    e.preventDefault();
    if (!match) return;
    setError("");
    try {
      await api.auth.reset(null, pw);
      setDone(true);
      setTimeout(() => onGo("login"), 1400);
    } catch (err) {
      setError(err?.message || "Reset failed. Use the latest link from your email.");
    }
  };
  return (
    <AuthShell>
      <Chip kind="accent">Almost there</Chip>
      <h1 className="display" style={{ fontSize: 36, fontWeight: 600, letterSpacing: "-0.03em", margin: "16px 0 8px" }}>Set a new password</h1>
      {done ? (
        <div style={{ padding: 16, background: "var(--accent-soft)", borderRadius: 10 }}>
          <div className="row gap-2" style={{ marginBottom: 4 }}><Icon name="check" size={16} style={{ color: "var(--mk-success)" }}/><b>Password updated</b></div>
          <div style={{ fontSize: 13.5, color: "var(--fg-muted)" }}>Redirecting you to sign in…</div>
        </div>
      ) : (
        <>
          <p style={{ color: "var(--fg-muted)", marginBottom: 28, fontSize: 14.5 }}>Use at least 10 characters. Mix cases and numbers.</p>
          <form onSubmit={submit} className="stack gap-4">
            <div className="field"><label>New password</label><input className="input" type="password" autoFocus value={pw} onChange={e => setPw(e.target.value)}/></div>
            <div className="field"><label>Confirm password</label><input className="input" type="password" value={confirm} onChange={e => setConfirm(e.target.value)}/></div>
            <div style={{ fontSize: 12, color: match ? "var(--mk-success)" : "var(--fg-faint)" }}>
              {pw.length >= 10 ? "✓ 10+ chars" : "• 10+ chars"} {" "}
              {pw && confirm && pw === confirm ? "✓ passwords match" : "• passwords match"}
            </div>
            {error ? <div style={{ fontSize: 12.5, color: "var(--mk-danger)" }}>{error}</div> : null}
            <button type="submit" className="btn btn-accent btn-lg" style={{ justifyContent: "center" }} disabled={!match}>Update password <Icon name="arrow-right"/></button>
          </form>
        </>
      )}
    </AuthShell>
  );
};

Object.assign(window, { Login, Signup, Forgot, ForgotPassword: Forgot, ResetPassword });
