/* global React, Icon */
const { useState, useEffect, useCallback } = React;

const API = () => window.PULSE_CONFIG?.apiBase || "http://localhost:8000";

// ── Common timezone list ───────────────────────────────────────────────────
const TIMEZONES = [
  { value: "Europe/London", label: "London (GMT/BST)" },
  { value: "Europe/Dublin", label: "Dublin (GMT/IST)" },
  { value: "Europe/Paris", label: "Paris (CET/CEST)" },
  { value: "Europe/Berlin", label: "Berlin (CET/CEST)" },
  { value: "Europe/Bucharest", label: "Bucharest (EET/EEST)" },
  { value: "Asia/Kolkata", label: "Mumbai (IST)" },
  { value: "Asia/Singapore", label: "Singapore (SGT)" },
  { value: "America/New_York", label: "New York (EST/EDT)" },
  { value: "America/Chicago", label: "Chicago (CST/CDT)" },
  { value: "America/Denver", label: "Denver (MST/MDT)" },
  { value: "America/Los_Angeles", label: "Los Angeles (PST/PDT)" },
  { value: "Australia/Sydney", label: "Sydney (AEST/AEDT)" },
];

// ── Onboarding Wizard (post-registration) ─────────────────────────────────
const ONB_STEPS = ["Welcome", "Your role", "Your squads", "Rhythm"];

function OnboardingWizard({ user, token, orgs, setOrgs, onComplete }) {
  const [step, setStep] = useState(0);
  const [name, setName] = useState(user.name || "");
  const [role, setRole] = useState(user.role || "");
  const [roleTag, setRoleTag] = useState(user.role_tag || "");
  const [tz, setTz] = useState(
    user.timezone ||
      Intl.DateTimeFormat().resolvedOptions().timeZone ||
      "Europe/London",
  );
  const [selectedSquads, setSelectedSquads] = useState(() => {
    if (user.squad_ids?.length && orgs.length) {
      return user.squad_ids
        .map((sid) => orgs.find((o) => o.id === sid))
        .filter(Boolean);
    }
    return [];
  });
  const [rhythm, setRhythm] = useState(user.rhythm || "daily");

  // Pre-fill squads once orgs load (for admin-provisioned users)
  useEffect(() => {
    if (user.squad_ids?.length && orgs.length && selectedSquads.length === 0) {
      const mapped = user.squad_ids
        .map((sid) => orgs.find((o) => o.id === sid))
        .filter(Boolean);
      if (mapped.length) setSelectedSquads(mapped);
    }
  }, [orgs]);

  // Org tree helpers for adding squads (multi-select at each level)
  const businesses = orgs.filter((o) => o.type === "business");
  const [bizIds, setBizIds] = useState([]);
  const [fnIds, setFnIds] = useState([]);
  const [grpIds, setGrpIds] = useState([]);
  const [teamIds, setTeamIds] = useState([]);

  const functions_ = orgs.filter(
    (o) => o.type === "function" && bizIds.includes(o.parent_id),
  );
  const groups = orgs.filter(
    (o) => o.type === "group" && fnIds.includes(o.parent_id),
  );
  const teams = orgs.filter(
    (o) => o.type === "team" && grpIds.includes(o.parent_id),
  );
  const squads = orgs.filter(
    (o) => o.type === "squad" && teamIds.includes(o.parent_id),
  );

  const addSquad = (squad) => {
    if (!selectedSquads.find((s) => s.id === squad.id)) {
      setSelectedSquads((prev) => [...prev, squad]);
    }
  };

  const removeSquad = (id) => {
    setSelectedSquads((prev) => prev.filter((s) => s.id !== id));
  };

  const next = () => setStep((s) => Math.min(s + 1, ONB_STEPS.length - 1));
  const prev = () => setStep((s) => Math.max(s - 1, 0));

  const finish = async () => {
    if (!selectedSquads.length) return;
    const primarySquad = selectedSquads[0].id;
    try {
      await fetch(`${API()}/me/profile`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          name,
          role,
          role_tag: roleTag || null,
          timezone: tz,
          rhythm,
          squad_id: primarySquad,
          squad_ids: selectedSquads.map((s) => s.id),
        }),
      });
    } catch (e) {
      /* proceed anyway */
    }
    onComplete({
      ...user,
      name,
      role,
      squad_id: primarySquad,
      timezone: tz,
      rhythm,
    });
  };

  const canNext = () => {
    if (step === 1) return name.trim() && role.trim();
    if (step === 2) return selectedSquads.length > 0;
    return true;
  };

  const renderStep = () => {
    switch (step) {
      case 0: // Welcome
        return (
          <>
            <span className="onb-eyebrow">WELCOME</span>
            <h2 className="auth-h2">Let's get you set up</h2>
            <p className="auth-sub">
              We'll walk you through a few quick steps so Pulse can surface the
              right insights for your squad.
            </p>
            <ul className="onb-checklist">
              <li>
                <span className="onb-check">✓</span> Confirm your role &amp;
                timezone
              </li>
              <li>
                <span className="onb-check">✓</span> Choose your squads
              </li>
              <li>
                <span className="onb-check">✓</span> Set your check-in rhythm
              </li>
            </ul>
          </>
        );

      case 1: // Role + timezone
        return (
          <>
            <span className="onb-eyebrow">STEP 1 OF 3</span>
            <h2 className="auth-h2">About you</h2>
            <p className="auth-sub">
              Confirm your details — this helps your squad identify you and
              shows times in your zone.
            </p>
            <div className="onb-field">
              <label>Full name</label>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Jane Smith"
                autoFocus
              />
            </div>
            <div className="onb-field">
              <label>Job title</label>
              <input
                type="text"
                value={role}
                onChange={(e) => setRole(e.target.value)}
                placeholder="e.g. Product Lead"
              />
            </div>
            <div className="onb-field">
              <label>Role</label>
              <select
                value={roleTag}
                onChange={(e) => setRoleTag(e.target.value)}
              >
                <option value="">Select your role…</option>
                <option value="Developer">Developer</option>
                <option value="Designer">Designer</option>
                <option value="Project Management">Project Management</option>
              </select>
            </div>
            <div className="onb-field">
              <label>Timezone</label>
              <select value={tz} onChange={(e) => setTz(e.target.value)}>
                {TIMEZONES.map((t) => (
                  <option key={t.value} value={t.value}>
                    {t.label}
                  </option>
                ))}
              </select>
            </div>
          </>
        );

      case 2: // Squads (multi-select + create)
        return (
          <>
            <span className="onb-eyebrow">STEP 2 OF 3</span>
            <h2 className="auth-h2">Your squads</h2>
            <p className="auth-sub">
              Select one or more squads you belong to. The first will be your
              primary scope.
            </p>

            {/* Org tree pickers — multi-select chips at each level */}
            <div className="onb-field">
              <label>Business</label>
              <div className="onb-chips">
                {businesses.map((b) => (
                  <button
                    key={b.id}
                    type="button"
                    className={
                      "onb-chip" + (bizIds.includes(b.id) ? " active" : "")
                    }
                    onClick={() => {
                      const next = bizIds.includes(b.id)
                        ? bizIds.filter((x) => x !== b.id)
                        : [...bizIds, b.id];
                      setBizIds(next);
                      setFnIds((prev) =>
                        prev.filter((id) =>
                          orgs.find(
                            (o) => o.id === id && next.includes(o.parent_id),
                          ),
                        ),
                      );
                      setGrpIds([]);
                      setTeamIds([]);
                    }}
                  >
                    {b.name}
                  </button>
                ))}
              </div>
            </div>
            {functions_.length > 0 && (
              <div className="onb-field">
                <label>Function</label>
                <div className="onb-chips">
                  {functions_.map((f) => (
                    <button
                      key={f.id}
                      type="button"
                      className={
                        "onb-chip" + (fnIds.includes(f.id) ? " active" : "")
                      }
                      onClick={() => {
                        const next = fnIds.includes(f.id)
                          ? fnIds.filter((x) => x !== f.id)
                          : [...fnIds, f.id];
                        setFnIds(next);
                        setGrpIds((prev) =>
                          prev.filter((id) =>
                            orgs.find(
                              (o) => o.id === id && next.includes(o.parent_id),
                            ),
                          ),
                        );
                        setTeamIds([]);
                      }}
                    >
                      {f.name}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {groups.length > 0 && (
              <div className="onb-field">
                <label>Group</label>
                <div className="onb-chips">
                  {groups.map((g) => (
                    <button
                      key={g.id}
                      type="button"
                      className={
                        "onb-chip" + (grpIds.includes(g.id) ? " active" : "")
                      }
                      onClick={() => {
                        const next = grpIds.includes(g.id)
                          ? grpIds.filter((x) => x !== g.id)
                          : [...grpIds, g.id];
                        setGrpIds(next);
                        setTeamIds((prev) =>
                          prev.filter((id) =>
                            orgs.find(
                              (o) => o.id === id && next.includes(o.parent_id),
                            ),
                          ),
                        );
                      }}
                    >
                      {g.name}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {teams.length > 0 && (
              <div className="onb-field">
                <label>Team</label>
                <div className="onb-chips">
                  {teams.map((t) => (
                    <button
                      key={t.id}
                      type="button"
                      className={
                        "onb-chip" + (teamIds.includes(t.id) ? " active" : "")
                      }
                      onClick={() => {
                        const next = teamIds.includes(t.id)
                          ? teamIds.filter((x) => x !== t.id)
                          : [...teamIds, t.id];
                        setTeamIds(next);
                      }}
                    >
                      {t.name}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {squads.length > 0 && (
              <div className="onb-field">
                <label>Squad</label>
                <div className="onb-chips">
                  {squads
                    .filter(
                      (s) => !selectedSquads.find((sel) => sel.id === s.id),
                    )
                    .map((s) => (
                      <button
                        key={s.id}
                        type="button"
                        className="onb-chip"
                        onClick={() => addSquad(s)}
                      >
                        {s.name}
                      </button>
                    ))}
                </div>
              </div>
            )}

            {/* Selected squads */}
            {selectedSquads.length > 0 && (
              <div
                style={{
                  display: "flex",
                  flexWrap: "wrap",
                  gap: 8,
                  marginTop: 16,
                }}
              >
                {selectedSquads.map((s, i) => (
                  <span
                    key={s.id}
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 6,
                      padding: "6px 12px",
                      background: "var(--accent-soft)",
                      border: "1px solid var(--accent)",
                      borderRadius: 99,
                      fontSize: 13,
                      fontWeight: 500,
                      color: "var(--accent)",
                    }}
                  >
                    {s.name}
                    {i === 0 && (
                      <span style={{ fontSize: 10, opacity: 0.7 }}>
                        primary
                      </span>
                    )}
                    <button
                      type="button"
                      onClick={() => removeSquad(s.id)}
                      style={{
                        border: 0,
                        background: "transparent",
                        cursor: "pointer",
                        color: "inherit",
                        fontSize: 14,
                        lineHeight: 1,
                        padding: 0,
                        marginLeft: 2,
                      }}
                    >
                      ×
                    </button>
                  </span>
                ))}
              </div>
            )}
          </>
        );

      case 3: // Rhythm
        return (
          <>
            <span className="onb-eyebrow">STEP 3 OF 3</span>
            <h2 className="auth-h2">Check-in rhythm</h2>
            <p className="auth-sub">
              How often would you like to check in? Your check-in button resets
              based on this cadence.
            </p>
            <div className="onb-options">
              {[
                {
                  id: "daily",
                  name: "Daily",
                  sub: "Quick pulse every workday",
                },
                { id: "3x", name: "3× per week", sub: "Mon, Wed, Fri" },
                {
                  id: "weekly",
                  name: "Weekly",
                  sub: "Once per week (recommended for leads)",
                  suggested: true,
                },
              ].map((opt) => (
                <button
                  key={opt.id}
                  type="button"
                  className="onb-option"
                  aria-current={rhythm === opt.id}
                  onClick={() => setRhythm(opt.id)}
                >
                  <div className="onb-option-radio">
                    {rhythm === opt.id && (
                      <div className="onb-option-radio-inner" />
                    )}
                  </div>
                  <div>
                    <div className="onb-option-name">
                      {opt.name}
                      {opt.suggested && (
                        <span className="onb-suggested">suggested</span>
                      )}
                    </div>
                    <div className="onb-option-sub">{opt.sub}</div>
                  </div>
                </button>
              ))}
            </div>
          </>
        );
    }
  };

  return (
    <div className="auth-shell variant-a">
      <div className="auth-bg-soft" />
      <div className="onb-shell">
        {/* Progress */}
        <div className="onb-progress">
          {ONB_STEPS.map((label, i) => (
            <div
              key={i}
              className={`onb-step ${i < step ? "done" : ""} ${i === step ? "curr" : ""}`}
            >
              <div className="onb-dot">{i < step ? "✓" : i + 1}</div>
              <span className="onb-step-label">{label}</span>
            </div>
          ))}
        </div>

        {/* Card */}
        <div className="onb-card">
          {renderStep()}

          <div className="onb-card-foot">
            {step > 0 && (
              <button type="button" className="onb-btn-ghost" onClick={prev}>
                Back
              </button>
            )}
            <div style={{ flex: 1 }} />
            {step < ONB_STEPS.length - 1 ? (
              <button
                type="button"
                className="onb-btn-primary"
                onClick={next}
                disabled={!canNext()}
              >
                Continue
              </button>
            ) : (
              <button
                type="button"
                className="onb-btn-primary"
                onClick={finish}
              >
                Get started
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── PKCE helpers ─────────────────────────────────────────────────────────────

function generateCodeVerifier() {
  const arr = new Uint8Array(32);
  crypto.getRandomValues(arr);
  return btoa(String.fromCharCode(...arr))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

async function generateCodeChallenge(verifier) {
  const data = new TextEncoder().encode(verifier);
  const hash = await crypto.subtle.digest("SHA-256", data);
  return btoa(String.fromCharCode(...new Uint8Array(hash)))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

async function startSSOLogin() {
  const cfg = window.PULSE_CONFIG?.cognito;
  if (!cfg?.clientId) {
    alert("SSO not configured yet — client ID is missing from config.");
    return;
  }
  const verifier = generateCodeVerifier();
  sessionStorage.setItem("pkce_verifier", verifier);
  const challenge = await generateCodeChallenge(verifier);
  const params = new URLSearchParams({
    response_type: "code",
    client_id: cfg.clientId,
    redirect_uri: cfg.redirectUri,
    scope: cfg.scopes,
    code_challenge_method: "S256",
    code_challenge: challenge,
    identity_provider: "EntraID",
  });
  window.location.href = `https://${cfg.domain}/oauth2/authorize?${params}`;
}

async function handleSSOCallback(
  code,
  onAuth,
  setError,
  setLoading,
  setMode,
  setPendingToken,
  setPendingUser,
  orgs,
  setOrgs,
) {
  const cfg = window.PULSE_CONFIG?.cognito;
  const verifier = sessionStorage.getItem("pkce_verifier");
  sessionStorage.removeItem("pkce_verifier");

  if (!verifier || !cfg?.clientId) {
    setError("SSO session expired. Please try again.");
    return;
  }

  setLoading(true);
  try {
    // Exchange auth code for tokens at Cognito token endpoint
    const tokenRes = await fetch(`https://${cfg.domain}/oauth2/token`, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        grant_type: "authorization_code",
        client_id: cfg.clientId,
        code,
        redirect_uri: cfg.redirectUri,
        code_verifier: verifier,
      }),
    });
    const tokens = await tokenRes.json();
    if (!tokenRes.ok || !tokens.id_token) {
      throw new Error(
        tokens.error_description || tokens.error || "Token exchange failed",
      );
    }

    // Send id_token to our backend to get a Pulse JWT
    const authRes = await fetch(`${API()}/auth/cognito`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id_token: tokens.id_token }),
    });
    const data = await authRes.json();
    if (!authRes.ok)
      throw new Error(data.detail || "SSO authentication failed");

    if (data.new_user) {
      // New user — go through onboarding
      setPendingToken(data.token);
      setPendingUser(data.user);
      // Load orgs for onboarding
      if (!orgs.length) {
        fetch(`${API()}/orgs`)
          .then((r) => r.json())
          .then(setOrgs)
          .catch(() => {});
      }
      setMode("onboarding");
    } else if (!data.user.squad_id && !data.user.squad_ids?.length) {
      setPendingToken(data.token);
      setPendingUser(data.user);
      if (!orgs.length) {
        fetch(`${API()}/orgs`)
          .then((r) => r.json())
          .then(setOrgs)
          .catch(() => {});
      }
      setMode("onboarding");
    } else {
      localStorage.setItem("pulse_token", data.token);
      localStorage.setItem("pulse_user", JSON.stringify(data.user));
      onAuth(data.token, data.user);
    }
  } catch (err) {
    setError(err.message);
    setMode("login");
  } finally {
    setLoading(false);
  }
}

// ── Auth Screen (Variant B: split layout) ─────────────────────────────────
function AuthScreen({ onAuth }) {
  const [mode, setMode] = useState("login"); // login | sso_loading | onboarding | email | register
  const [orgs, setOrgs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [pendingUser, setPendingUser] = useState(null);
  const [pendingToken, setPendingToken] = useState(null);

  // Email/password fields
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [regName, setRegName] = useState("");

  useEffect(() => {
    fetch(`${API()}/orgs`)
      .then((r) => r.json())
      .then(setOrgs)
      .catch(() => {});
  }, []);

  // Handle SSO callback if we have a ?code= parameter
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get("code");
    if (code) {
      // Remove code from URL immediately to prevent double-processing on re-render
      window.history.replaceState({}, "", window.location.pathname);
      setMode("sso_loading");
      handleSSOCallback(
        code,
        onAuth,
        setError,
        setLoading,
        setMode,
        setPendingToken,
        setPendingUser,
        orgs,
        setOrgs,
      );
    }
  }, []);

  const handleLogin = async (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const res = await fetch(`${API()}/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || "Login failed");
      if (!data.user.squad_id && !data.user.squad_ids?.length) {
        setPendingToken(data.token);
        setPendingUser(data.user);
        setMode("onboarding");
      } else {
        localStorage.setItem("pulse_token", data.token);
        localStorage.setItem("pulse_user", JSON.stringify(data.user));
        onAuth(data.token, data.user);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    setError("");
    if (!email.trim().toLowerCase().endsWith("@centrica.com")) {
      setError("Please register with your @centrica.com email address.");
      return;
    }
    setLoading(true);
    try {
      const res = await fetch(`${API()}/register`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: regName,
          email,
          password,
          role: "",
          squad_id: null,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || "Registration failed");
      if (data.new_user === false) {
        // Admin-provisioned user with all fields complete — skip onboarding
        localStorage.setItem("pulse_token", data.token);
        localStorage.setItem("pulse_user", JSON.stringify(data.user));
        onAuth(data.token, data.user);
      } else {
        setPendingToken(data.token);
        setPendingUser(data.user);
        setMode("onboarding");
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleOnboardingComplete = (updatedUser) => {
    localStorage.setItem("pulse_token", pendingToken);
    localStorage.setItem("pulse_user", JSON.stringify(updatedUser));
    onAuth(pendingToken, updatedUser);
  };

  // ── Onboarding mode ──
  if (mode === "onboarding") {
    return (
      <OnboardingWizard
        user={pendingUser}
        token={pendingToken}
        orgs={orgs}
        setOrgs={setOrgs}
        onComplete={handleOnboardingComplete}
      />
    );
  }

  // ── Sign-in (Variant B) ──
  return (
    <div className="auth-shell variant-b">
      {/* Dark side panel */}
      <div className="auth-side">
        <div className="auth-decoration">
          <div className="auth-ring r1" />
          <div className="auth-ring r2" />
          <div className="auth-ring r3" />
          <div className="auth-mark">
            <Icon.Logo />
          </div>
        </div>

        <div className="auth-side-quote">
          <span className="auth-eyebrow">CENTRICA PULSE</span>
          <h1 className="auth-side-headline">
            Your team's operating&nbsp;rhythm, surfaced in&nbsp;seconds.
          </h1>
          <p className="auth-side-sub">
            Async check-ins, AI-powered insights, and squad-level reports — so
            squads stay in sync without another standup.
          </p>
          <div className="auth-side-pill-row">
            <span className="auth-pill">Voice check-ins</span>
            <span className="auth-pill">AI summaries</span>
            <span className="auth-pill">Squad reports</span>
            <span className="auth-pill">Real-time signals</span>
          </div>
        </div>
      </div>

      {/* Right card */}
      <div className="auth-card-wrap">
        <div className="auth-card">
          <div className="auth-mark-row">
            <div className="auth-card-mark">
              <Icon.Logo />
            </div>
            <div>
              <div className="auth-card-name">Centrica Pulse</div>
              <div className="auth-card-tag">Operating console</div>
            </div>
          </div>

          <h1 className="auth-h1">
            {mode === "register" ? "Create your account" : "Sign in to Pulse"}
          </h1>
          <p className="auth-sub">
            {mode === "register"
              ? "Set up your Pulse account to get started."
              : mode === "email"
                ? "Sign in with your existing account."
                : "Use your Centrica Microsoft account to continue."}
          </p>

          {error && (
            <div
              className="auth-error"
              style={{
                background: "var(--warn-soft)",
                color: "var(--danger)",
                borderRadius: 8,
                padding: "10px 14px",
                fontSize: 13,
                marginBottom: 16,
                display: "flex",
                alignItems: "center",
                gap: 8,
              }}
            >
              <Icon.AlertCircle
                style={{ width: 14, height: 14, flexShrink: 0 }}
              />
              {error}
            </div>
          )}

          {mode === "sso_loading" ? (
            <div style={{ textAlign: "center", padding: "32px 0" }}>
              <span className="sp" style={{ width: 20, height: 20 }} />
              <p style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 12 }}>
                Completing sign-in…
              </p>
            </div>
          ) : mode === "register" ? (
            <>
              <form onSubmit={handleRegister}>
                <div className="onb-field">
                  <label>Full name</label>
                  <input
                    type="text"
                    required
                    autoFocus
                    placeholder="Jane Smith"
                    value={regName}
                    onChange={(e) => setRegName(e.target.value)}
                  />
                </div>
                <div className="onb-field">
                  <label>Work email</label>
                  <input
                    type="email"
                    required
                    autoComplete="email"
                    placeholder="you@centrica.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
                <div className="onb-field">
                  <label>Password</label>
                  <input
                    type="password"
                    required
                    autoComplete="new-password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </div>
                <button
                  className="ms-btn"
                  type="submit"
                  disabled={loading || !regName || !email || !password}
                >
                  {loading ? (
                    <>
                      <span className="sp" /> Creating account…
                    </>
                  ) : (
                    "Create account"
                  )}
                </button>
              </form>
              <div className="auth-divider">or</div>
              <button
                type="button"
                className="auth-link"
                onClick={() => {
                  setMode("email");
                  setError("");
                }}
              >
                Already have an account? Sign in
              </button>
            </>
          ) : mode === "email" ? (
            <>
              <form onSubmit={handleLogin}>
                <div className="onb-field">
                  <label>Work email</label>
                  <input
                    type="email"
                    required
                    autoComplete="email"
                    autoFocus
                    placeholder="you@centrica.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
                <div className="onb-field">
                  <label>Password</label>
                  <input
                    type="password"
                    required
                    autoComplete="current-password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </div>
                <button
                  className="ms-btn"
                  type="submit"
                  disabled={loading || !email || !password}
                >
                  {loading ? (
                    <>
                      <span className="sp" /> Signing in…
                    </>
                  ) : (
                    "Sign in"
                  )}
                </button>
              </form>
              <div className="auth-divider">or</div>
              <button
                type="button"
                className="auth-link"
                onClick={() => {
                  setMode("register");
                  setError("");
                }}
              >
                Don't have an account? Create one
              </button>
              <button
                type="button"
                className="auth-link"
                onClick={() => {
                  setMode("login");
                  setError("");
                }}
                style={{ marginTop: 4 }}
              >
                Sign in with Microsoft instead
              </button>
            </>
          ) : (
            <>
              <button
                className="ms-btn"
                type="button"
                onClick={startSSOLogin}
                disabled={loading}
              >
                <svg
                  width="20"
                  height="20"
                  viewBox="0 0 21 21"
                  style={{ flexShrink: 0 }}
                >
                  <rect x="1" y="1" width="9" height="9" fill="#f25022" />
                  <rect x="11" y="1" width="9" height="9" fill="#7fba00" />
                  <rect x="1" y="11" width="9" height="9" fill="#00a4ef" />
                  <rect x="11" y="11" width="9" height="9" fill="#ffb900" />
                </svg>
                Sign in with Microsoft
              </button>
              <div className="auth-divider">or</div>
              <button
                type="button"
                className="auth-link"
                onClick={() => {
                  setMode("email");
                  setError("");
                }}
              >
                Sign in with email
              </button>
            </>
          )}

          <div className="auth-tenant-row">
            <span
              style={{
                width: 8,
                height: 8,
                borderRadius: "50%",
                background: "var(--ok)",
              }}
            />
            centrica.com
          </div>
        </div>

        <div className="auth-foot centered">
          <span className="auth-status">
            <span className="status-dot" /> All systems operational
          </span>
        </div>
      </div>
    </div>
  );
}

window.AuthScreen = AuthScreen;
