/* Google sign-in gate for the SPIF Tracker.
 *
 * <AuthGate> wraps the app. Behavior:
 *   - No Firebase Auth available (offline / SDK blocked) → renders children
 *     so local-only use still works.
 *   - Not signed in → shows the sign-in screen.
 *   - Signed in but NOT an @partsbase.com account → access-denied screen.
 *   - Signed in with an allowed account → renders children and exposes
 *     { user, signOut } via useAuth(), surfaced in the header by <AuthMenu>.
 *
 * Server-side enforcement lives in the Realtime Database rules; this is the
 * UI half. Both must be in place to truly lock the data.
 */

const ALLOWED_DOMAIN = "partsbase.com";

/* People allowed to see the Manager SPIF. Everyone else (any other signed-in
 * @partsbase.com account) sees every program EXCEPT the Manager SPIF — both
 * the card on the landing page and the program page itself are blocked. */
const MANAGER_SPIFF_VIEWERS = [
  "crahe@partsbase.com",
  "ekoknar@partsbase.com",
  "smikov@partsbase.com",
  "ecicero@partsbase.com",
  "reffendy@partsbase.com",
  "kkoo@partsbase.com",
  "wchee@partsbase.com",
];

/* True if this user may see the Manager SPIF. When no auth layer is configured
 * at all (local/offline dev) nothing is gated, so the tracker stays usable. */
function canSeeManagerSpiff(user) {
  if (!window.FIREBASE_AUTH) return true;
  const email = ((user && user.email) || "").toLowerCase().trim();
  return MANAGER_SPIFF_VIEWERS.includes(email);
}

const AuthContext = React.createContext(null);
function useAuth() { return React.useContext(AuthContext); }

function AuthGate({ children }) {
  const auth = window.FIREBASE_AUTH || null;
  // "open" when there's no auth layer at all (keeps local dev usable)
  const [status, setStatus] = React.useState(auth ? "loading" : "open");
  const [user, setUser] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => {
    if (!auth) return;
    const unsub = auth.onAuthStateChanged((u) => {
      if (!u) { setUser(null); setStatus("out"); return; }
      const email = (u.email || "").toLowerCase();
      if (ALLOWED_DOMAIN && !email.endsWith("@" + ALLOWED_DOMAIN)) {
        setError(`${u.email} isn't a @${ALLOWED_DOMAIN} account. Use your PartsBase Google account.`);
        auth.signOut();
        setStatus("out");
        return;
      }
      setUser(u);
      setStatus("in");
    });
    return unsub;
  }, [auth]);

  const signIn = () => {
    setError(null);
    setBusy(true);
    const provider = new firebase.auth.GoogleAuthProvider();
    provider.setCustomParameters({ hd: ALLOWED_DOMAIN, prompt: "select_account" });
    auth.signInWithPopup(provider)
      .catch((e) => {
        const code = e && e.code;
        if (code === "auth/operation-not-allowed")
          setError("Google sign-in isn't switched on for this project yet. Enable the Google provider in Firebase → Authentication, then try again.");
        else if (code === "auth/popup-blocked")
          setError("Your browser blocked the sign-in popup. Allow popups for this site and try again.");
        else if (code === "auth/popup-closed-by-user" || code === "auth/cancelled-popup-request")
          setError(null);
        else
          setError(e && e.message ? e.message : "Sign-in failed. Please try again.");
      })
      .finally(() => setBusy(false));
  };

  if (status === "open" || status === "in") {
    return (
      <AuthContext.Provider value={{ user, signOut: () => auth && auth.signOut() }}>
        {children}
      </AuthContext.Provider>
    );
  }

  // Loading + signed-out both render the sign-in shell (loading shows a spinner).
  return <SignInScreen onSignIn={signIn} loading={status === "loading"} busy={busy} error={error} />;
}

function SignInScreen({ onSignIn, loading, busy, error }) {
  return (
    <div style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--gray-50)", fontFamily: "var(--font-sans-private)", padding: 24,
    }}>
      <div style={{
        width: "100%", maxWidth: 380, background: "#fff",
        border: "1px solid var(--gray-200)", borderRadius: 18,
        padding: "36px 32px", textAlign: "center",
        boxShadow: "0 16px 40px rgba(10,30,60,0.08)",
      }}>
        <img src="system/logos/pb-logo-light.svg" alt="PartsBase" style={{ height: 30, width: "auto", display: "block", margin: "0 auto 20px" }} />
        <h1 style={{ margin: "0 0 6px", fontSize: 20, fontWeight: 700, color: "var(--color-800)", letterSpacing: "-0.01em" }}>
          SPIF Tracker
        </h1>
        <p style={{ margin: "0 0 24px", fontSize: 13, color: "var(--gray-600)", lineHeight: 1.5 }}>
          Sign in with your PartsBase Google account to view and update sales incentive programs.
        </p>

        {loading ? (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, height: 44, color: "var(--gray-500)", fontSize: 13 }}>
            <Spinner /> Checking your session…
          </div>
        ) : (
          <button onClick={onSignIn} disabled={busy} style={{
            all: "unset", boxSizing: "border-box", cursor: busy ? "default" : "pointer",
            width: "100%", height: 44, borderRadius: 10,
            border: "1px solid var(--gray-300)", background: busy ? "var(--gray-50)" : "#fff",
            display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
            fontSize: 14, fontWeight: 600, color: "var(--gray-800)",
            transition: "background 0.15s, border-color 0.15s",
          }}
            onMouseEnter={(e) => { if (!busy) e.currentTarget.style.background = "var(--gray-50)"; }}
            onMouseLeave={(e) => { if (!busy) e.currentTarget.style.background = "#fff"; }}>
            <GoogleG /> {busy ? "Opening Google…" : "Continue with Google"}
          </button>
        )}

        {error && (
          <div style={{
            marginTop: 16, padding: "10px 12px", borderRadius: 10,
            background: "var(--error-50)", border: "1px solid var(--error-200)",
            color: "var(--error-700)", fontSize: 12, lineHeight: 1.45, textAlign: "left",
          }}>{error}</div>
        )}

        <div style={{ marginTop: 22, fontSize: 11, color: "var(--gray-400)", lineHeight: 1.5 }}>
          Access is limited to @{ALLOWED_DOMAIN} accounts.
        </div>
      </div>
    </div>
  );
}

function GoogleG() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true">
      <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62z"/>
      <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.33A9 9 0 0 0 9 18z"/>
      <path fill="#FBBC05" d="M3.97 10.72a5.41 5.41 0 0 1 0-3.44V4.95H.96a9 9 0 0 0 0 8.1l3.01-2.33z"/>
      <path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A9 9 0 0 0 .96 4.95l3.01 2.33C4.68 5.16 6.66 3.58 9 3.58z"/>
    </svg>
  );
}

function Spinner() {
  return (
    <span style={{
      width: 16, height: 16, borderRadius: 999,
      border: "2px solid var(--gray-300)", borderTopColor: "var(--color-600)",
      display: "inline-block", animation: "spifspin 0.7s linear infinite",
    }}>
      <style>{`@keyframes spifspin { to { transform: rotate(360deg); } }`}</style>
    </span>
  );
}

/* Header account menu — avatar + popover with email and Sign out. */
function AuthMenu() {
  const ctx = (typeof useAuth === "function") ? useAuth() : null;
  const [open, setOpen] = React.useState(false);
  const user = ctx && ctx.user;

  // No auth layer / not signed in → static placeholder avatar.
  if (!user) {
    return (
      <div style={{
        width: 32, height: 32, borderRadius: 999,
        background: "var(--color-100)", color: "var(--color-700)",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 12, fontWeight: 600, fontFamily: "var(--font-sans-private)",
      }}>SO</div>
    );
  }

  const name = user.displayName || user.email || "User";
  const initials = name.split(" ").map(w => w[0]).slice(0, 2).join("").toUpperCase();

  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} title={user.email} style={{
        all: "unset", cursor: "pointer", width: 32, height: 32, borderRadius: 999,
        overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center",
        background: "var(--color-100)", color: "var(--color-700)",
        fontSize: 12, fontWeight: 600, fontFamily: "var(--font-sans-private)",
        border: open ? "2px solid var(--color-500)" : "2px solid transparent",
      }}>
        {user.photoURL
          ? <img src={user.photoURL} alt="" referrerPolicy="no-referrer" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          : initials}
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 40 }} />
          <div style={{
            position: "absolute", top: 40, right: 0, zIndex: 41,
            width: 230, background: "#fff", borderRadius: 12,
            border: "1px solid var(--gray-200)", boxShadow: "0 12px 32px rgba(10,30,60,0.16)",
            padding: 8, fontFamily: "var(--font-sans-private)",
          }}>
            <div style={{ padding: "8px 10px 10px", borderBottom: "1px solid var(--gray-150, var(--gray-100))" }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: "var(--color-800)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{name}</div>
              <div style={{ fontSize: 11, color: "var(--gray-500)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.email}</div>
            </div>
            <button onClick={() => { setOpen(false); ctx.signOut(); }} style={{
              all: "unset", cursor: "pointer", display: "flex", alignItems: "center", gap: 8,
              width: "100%", boxSizing: "border-box", padding: "9px 10px", marginTop: 4,
              borderRadius: 8, fontSize: 13, fontWeight: 500, color: "var(--gray-700)",
            }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--gray-50)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
              Sign out
            </button>
          </div>
        </>
      )}
    </div>
  );
}

/* Hard-block screen for a program the signed-in user isn't permitted to see. */
function AccessDenied({ title, message }) {
  const ctx = (typeof useAuth === "function") ? useAuth() : null;
  const user = ctx && ctx.user;
  return (
    <div style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--gray-50)", fontFamily: "var(--font-sans-private)", padding: 24,
    }}>
      <div style={{
        width: "100%", maxWidth: 400, background: "#fff",
        border: "1px solid var(--gray-200)", borderRadius: 18,
        padding: "36px 32px", textAlign: "center",
        boxShadow: "0 16px 40px rgba(10,30,60,0.08)",
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12, margin: "0 auto 18px",
          background: "var(--error-50)", color: "var(--error-600)",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
          </svg>
        </div>
        <h1 style={{ margin: "0 0 6px", fontSize: 20, fontWeight: 700, color: "var(--color-800)", letterSpacing: "-0.01em" }}>
          {title || "Access restricted"}
        </h1>
        <p style={{ margin: "0 0 22px", fontSize: 13, color: "var(--gray-600)", lineHeight: 1.5 }}>
          {message || "This program isn't available to your account. If you think this is a mistake, contact your SPIF administrator."}
        </p>
        <a href="index.html" className="pb-button pb-button-md pb-button-primary" style={{ fontSize: 13, textDecoration: "none" }}>
          Go to all programs
        </a>
        {user && (
          <div style={{ marginTop: 18, fontSize: 11, color: "var(--gray-400)", lineHeight: 1.5 }}>
            Signed in as {user.email}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AuthGate, AuthMenu, useAuth, canSeeManagerSpiff, AccessDenied });
