/* ===========================================================================
   Azure Helper — app shell + nav + tweaks
   =========================================================================== */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "teal",
  "density": "regular",
  "coaching": "medium",
  "method": "portal",
  "surface": "dashboard",
  "showGrid": true
}/*EDITMODE-END*/;

const ACCENTS = {
  teal: { dark: { p: "#2dd4bf", b: "#5eead4", d: "rgba(45,212,191,.12)" }, light: { p: "#0c9e8d", b: "#0bb0a0", d: "rgba(12,158,141,.12)" } },
  violet: { dark: { p: "#a78bfa", b: "#c4b5fd", d: "rgba(167,139,250,.14)" }, light: { p: "#6d4fe0", b: "#5a3dd0", d: "rgba(109,79,224,.12)" } },
  gold: { dark: { p: "#e7d24e", b: "#f3e58a", d: "rgba(231,210,78,.14)" }, light: { p: "#a8850a", b: "#c39a0c", d: "rgba(168,133,10,.14)" } },
  blue: { dark: { p: "#5aa9f0", b: "#8cc5f7", d: "rgba(90,169,240,.14)" }, light: { p: "#2173cc", b: "#1a63b8", d: "rgba(33,115,204,.12)" } },
};

const NAV = [
  { id: "home", label: "./home", icon: "home" },
  { id: "agent", label: "./guide", icon: "book" },
  { id: "graph", label: "./graph-explorer", icon: "graph" },
  { id: "learn", label: "./learn", icon: "book" },
];

function BrandTabs() {
  return (
    <div className="row" style={{ gap: 0, height: "100%" }}>
      <div className="atab" style={{ background: "var(--surface-3)", color: "var(--text)", zIndex: 3 }}>
        <div style={{ width: 20, height: 20, borderRadius: 5, background: "var(--primary)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="bolt" size={13} color="#04221d" />
        </div>
        Azure&nbsp;Helper
      </div>
      <div className="atab" style={{ background: "var(--surface-2)", color: "var(--text-2)", zIndex: 2, paddingLeft: 26 }}>
        <Icon name="graph" size={14} color="var(--text-dim)" /> Microsoft&nbsp;Graph
      </div>
      <div className="atab" style={{ background: "var(--surface)", color: "var(--primary)", zIndex: 1, paddingLeft: 26 }}>
        <Icon name="shield" size={14} color="var(--primary)" /> read-only
      </div>
    </div>
  );
}

function AuthPaywall({ user, onAuthResolved }) {
  const [email, setEmail] = useState("");
  const [token, setToken] = useState("");
  const [busy, setBusy] = useState(false);
  const [info, setInfo] = useState("");
  const [error, setError] = useState("");
  const [devMagicToken, setDevMagicToken] = useState("");
  const [entraBusy, setEntraBusy] = useState(false);
  const autoMagicHandledRef = useRef(false);

  useEffect(() => {
    function onMessage(event) {
      if (!event || !event.data || event.data.type !== "AH_ENTRA_LINKED") {
        return;
      }

      if (!event.data.ok) {
        setError(event.data.error || "Entra delegated login failed");
        return;
      }

      window.AHRuntime.getCurrentUser()
        .then((me) => onAuthResolved(me.user))
        .catch((e) => setError(e.message || "Unable to refresh user after Entra login"));
    }

    window.addEventListener("message", onMessage);
    return () => window.removeEventListener("message", onMessage);
  }, [onAuthResolved]);

  async function sendLink() {
    setBusy(true);
    setError("");
    setInfo("");
    try {
      const result = await window.AHRuntime.sendMagicLink(email);
      if (result.devToken) {
        setDevMagicToken(result.devToken);
        setInfo("Magic link sent. Use your email link or paste dev token below.");
      } else {
        setDevMagicToken("");
        setInfo("Magic link sent. Check your email and open the link.");
      }
    } catch (e) {
      setError(e.message || "Failed to send magic link");
    } finally {
      setBusy(false);
    }
  }

  async function verifyLink() {
    setBusy(true);
    setError("");
    setInfo("");
    try {
      await window.AHRuntime.verifyMagicLink(token || devMagicToken);
      const me = await window.AHRuntime.getCurrentUser();
      onAuthResolved(me.user);
    } catch (e) {
      setError(e.message || "Failed to verify token");
    } finally {
      setBusy(false);
    }
  }

  useEffect(() => {
    if (autoMagicHandledRef.current || user) {
      return;
    }

    const params = new URLSearchParams(window.location.search);
    const urlToken = String(params.get("magicToken") || "").trim();
    if (!urlToken) {
      return;
    }

    autoMagicHandledRef.current = true;
    setToken(urlToken);

    (async () => {
      setBusy(true);
      setError("");
      setInfo("Magic link detected. Signing you in...");
      try {
        await window.AHRuntime.verifyMagicLink(urlToken);
        const me = await window.AHRuntime.getCurrentUser();

        // Remove one-time token from the URL after successful verification.
        const cleanUrl = `${window.location.origin}${window.location.pathname}`;
        window.history.replaceState({}, document.title, cleanUrl);

        onAuthResolved(me.user);
      } catch (e) {
        setError(e.message || "Failed to verify magic token from link");
      } finally {
        setBusy(false);
      }
    })();
  }, [onAuthResolved, user]);

  async function startCheckout() {
    setBusy(true);
    setError("");
    try {
      const result = await window.AHRuntime.createCheckoutSession();
      if (result.checkoutUrl) {
        window.open(result.checkoutUrl, "_blank", "noopener");
      }
      setInfo("Checkout opened. Complete subscription, then click 'I've subscribed'.");
    } catch (e) {
      setError(e.message || "Unable to start checkout");
    } finally {
      setBusy(false);
    }
  }

  async function refreshSubscription() {
    setBusy(true);
    setError("");
    try {
      await window.AHRuntime.activateMockSubscription();
      const me = await window.AHRuntime.getCurrentUser();
      onAuthResolved(me.user);
    } catch (e) {
      setError(e.message || "Subscription activation failed");
    } finally {
      setBusy(false);
    }
  }

  async function logout() {
    await window.AHRuntime.logout();
    onAuthResolved(null);
  }

  async function connectEntraDelegated() {
    setEntraBusy(true);
    setError("");
    try {
      const result = await window.AHRuntime.startEntraDelegatedLogin();
      if (!result.authorizeUrl) {
        throw new Error("No authorize URL received");
      }
      window.open(result.authorizeUrl, "ahEntraLogin", "width=520,height=760");
      setInfo("Complete the Entra sign-in window to link delegated login.");
    } catch (e) {
      setError(e.message || "Unable to start Entra delegated login");
    } finally {
      setEntraBusy(false);
    }
  }

  return (
    <div className="center" style={{ height: "100%", padding: 20 }}>
      <div className="card tint" style={{ width: 560, maxWidth: "100%" }}>
        <SecLabel>academy-style access gate</SecLabel>
        <h2 className="h2" style={{ marginTop: 10 }}>Sign in and subscribe to continue</h2>
        <p className="t2" style={{ marginTop: 8, fontSize: 14 }}>
          Access is limited to authenticated users (admin or user). After magic-link sign-in and subscription, the Helper unlocks Graph, PowerShell, and guided teaching.
        </p>

        {!user && (
          <div className="col" style={{ gap: 10, marginTop: 14 }}>
            <input className="inp" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" />
            <button className="btn btn-primary" onClick={sendLink} disabled={busy || !email.includes("@")}>
              <Icon name="send" size={13} color="#04221d" /> Send magic link
            </button>
            <input className="inp" value={token} onChange={(e) => setToken(e.target.value)} placeholder="Paste magic token" />
            <button className="btn btn-ghost" onClick={verifyLink} disabled={busy || !(token || devMagicToken)}>
              <Icon name="check" size={13} color="var(--primary)" /> Verify and sign in
            </button>
            {devMagicToken && (
              <div className="chip" style={{ fontSize: 11 }}>dev token: {devMagicToken}</div>
            )}
          </div>
        )}

        {user && !user.subscriptionActive && (
          <div className="col" style={{ gap: 10, marginTop: 14 }}>
            <div className="chip gold">Signed in as {user.email}</div>
            <button className="btn btn-primary" onClick={startCheckout} disabled={busy}>
              <Icon name="bolt" size={13} color="#04221d" /> Subscribe with Stripe
            </button>
            <button className="btn btn-quiet" onClick={refreshSubscription} disabled={busy}>
              <Icon name="refresh" size={13} color="var(--primary)" /> I've subscribed
            </button>
            <button className="btn btn-danger" onClick={logout} disabled={busy}>
              <Icon name="x" size={13} color="var(--rose)" /> Logout
            </button>
          </div>
        )}

        {user && user.subscriptionActive && (
          <div className="col" style={{ gap: 10, marginTop: 14 }}>
            <div className="chip cy">Access granted for {user.email} ({user.role})</div>
            {!user.entraLinked && (
              <button className="btn btn-primary" onClick={connectEntraDelegated} disabled={entraBusy}>
                <Icon name="key" size={13} color="#04221d" /> {entraBusy ? "Opening Entra login…" : "Connect Entra delegated login"}
              </button>
            )}
            {user.entraLinked && (
              <>
                <div className="chip">Entra linked: {user.entra?.upn || user.entra?.email || user.entra?.oid}</div>
                <button className="btn btn-primary" onClick={() => onAuthResolved(user)}>
                  <Icon name="arrow" size={13} color="#04221d" /> Continue to Helper
                </button>
              </>
            )}
          </div>
        )}

        {info && <div className="chip cy" style={{ marginTop: 12 }}>{info}</div>}
        {error && <div className="chip" style={{ marginTop: 12, color: "var(--rose)", borderColor: "rgba(244,117,127,.5)" }}>{error}</div>}
      </div>
    </div>
  );
}

function DiagnosticsPanel({ user }) {
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState("");

  async function runDiagnostics(deep) {
    setLoading(true);
    setError("");
    try {
      const payload = await window.AHRuntime.preflightDiagnostics(Boolean(deep));
      setResult(payload);
    } catch (e) {
      setError(e.message || "Diagnostics failed");
    } finally {
      setLoading(false);
    }
  }

  const checks = result?.checks || {};
  const checkNames = ["graphToken", "graphOrganization", "armToken", "armSubscriptions"];

  return (
    <div className="card" style={{ margin: "10px 12px", padding: 10 }}>
      <div className="between" style={{ gap: 10 }}>
        <div className="col" style={{ gap: 4 }}>
          <SecLabel>runtime diagnostics</SecLabel>
          <div className="mono" style={{ fontSize: 11, color: "var(--text-dim)" }}>
            user: {user?.email || "unknown"}
          </div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <button className="btn btn-quiet btn-sm" onClick={() => runDiagnostics(false)} disabled={loading}>
            <Icon name="refresh" size={12} color="var(--primary)" /> config
          </button>
          <button className="btn btn-ghost btn-sm" onClick={() => runDiagnostics(true)} disabled={loading}>
            <Icon name="bolt" size={12} color="var(--primary)" /> deep
          </button>
        </div>
      </div>

      {error && <div className="chip" style={{ marginTop: 8, color: "var(--rose)", borderColor: "rgba(244,117,127,.5)" }}>{error}</div>}

      {result?.config && (
        <div className="row" style={{ gap: 8, marginTop: 8, flexWrap: "wrap" }}>
          <span className="chip">mode: {result.config.identityMode}</span>
          <span className={"chip " + (result.config.azureTenantId ? "cy" : "")}>tenant {result.config.azureTenantId ? "ok" : "missing"}</span>
          <span className={"chip " + (result.config.azureClientId ? "cy" : "")}>client {result.config.azureClientId ? "ok" : "missing"}</span>
          <span className={"chip " + (result.config.azureClientSecret ? "cy" : "")}>secret {result.config.azureClientSecret ? "ok" : "missing"}</span>
        </div>
      )}

      {result?.mode === "deep" && (
        <div className="row" style={{ gap: 8, marginTop: 8, flexWrap: "wrap" }}>
          {checkNames.map((name) => {
            const ok = Boolean(checks[name]?.ok);
            return (
              <span key={name} className={"chip " + (ok ? "cy" : "")}>{name}: {ok ? "ok" : "fail"}</span>
            );
          })}
        </div>
      )}
    </div>
  );
}

function getExtensionContextFromUrl() {
  const params = new URLSearchParams(window.location.search);
  const pageUrl = String(params.get("extPageUrl") || "").trim();
  const pageTitle = String(params.get("extPageTitle") || "").trim();
  if (!pageUrl) {
    return null;
  }

  try {
    const parsed = new URL(pageUrl);
    return {
      pageUrl,
      pageTitle,
      host: parsed.host,
      pathname: parsed.pathname,
    };
  } catch (_error) {
    return {
      pageUrl,
      pageTitle,
      host: "",
      pathname: "",
    };
  }
}

function App() {
  const forcedSurface = new URLSearchParams(window.location.search).get("surface") === "extension" ? "extension" : "";
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState("home");
  const [seed, setSeed] = useState(null);
  const [showConnect, setShowConnect] = useState(false);
  const [runtimeReady, setRuntimeReady] = useState(false);
  const [authChecking, setAuthChecking] = useState(true);
  const [user, setUser] = useState(null);
  const [tenantReady, setTenantReady] = useState(false);
  const [tenantConnected, setTenantConnected] = useState(false);
  const [showDiagnostics, setShowDiagnostics] = useState(false);
  const [extensionContext, setExtensionContext] = useState(null);

  // apply theme + accent + density to :root
  useEffect(() => {
    const root = document.documentElement;
    root.setAttribute("data-theme", t.theme || "dark");
    const set = (ACCENTS[t.accent] || ACCENTS.teal)[t.theme === "light" ? "light" : "dark"];
    const r = root.style;
    r.setProperty("--primary", set.p);
    r.setProperty("--primary-bright", set.b);
    r.setProperty("--primary-dim", set.d);
    r.setProperty("--density", t.density === "compact" ? "0.78" : t.density === "comfy" ? "1.15" : "1");
  }, [t.theme, t.accent, t.density]);

  useEffect(() => {
    document.body.style.backgroundImage = t.showGrid ? "" : "none";
  }, [t.showGrid]);

  useEffect(() => {
    setExtensionContext(getExtensionContextFromUrl());
  }, []);

  useEffect(() => {
    function onNavigate(event) {
      const detail = event?.detail || {};
      if (detail.seed) {
        setSeed(detail.seed);
      }
      if (detail.view) {
        setView(detail.view);
      }
    }

    window.addEventListener("AH_NAVIGATE", onNavigate);
    return () => window.removeEventListener("AH_NAVIGATE", onNavigate);
  }, []);

  useEffect(() => {
    let cancelled = false;

    async function initRuntime() {
      if (!window.AHRuntime) {
        setRuntimeReady(true);
        setAuthChecking(false);
        setTenantReady(true);
        return;
      }

      try {
        if (window.AHRuntime.getSessionToken()) {
          const me = await window.AHRuntime.getCurrentUser();
          if (!cancelled) {
            setUser(me.user);
            if (me.user?.email) {
              AH.tenant.connectedAs = me.user.email;
            }
          }
        }
      } catch (_error) {
        // No active session yet.
      } finally {
        if (!cancelled) {
          setAuthChecking(false);
          setRuntimeReady(true);
        }
      }
    }

    initRuntime();
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    let cancelled = false;

    async function loadTenant() {
      if (!runtimeReady) {
        return;
      }

      if (!window.AHRuntime || !user || !user.subscriptionActive) {
        setTenantConnected(false);
        setTenantReady(true);
        return;
      }

      setTenantReady(false);
      try {
        if (user?.email) {
          AH.tenant.connectedAs = user.email;
        }
        await window.AHRuntime.applyTenantContext(user);
        if (!cancelled) {
          setTenantConnected(true);
        }
      } catch (_error) {
        if (!cancelled) {
          setTenantConnected(false);
        }
      } finally {
        if (!cancelled) {
          setTenantReady(true);
        }
      }
    }

    loadTenant();
    return () => {
      cancelled = true;
    };
  }, [runtimeReady, user?.email, user?.subscriptionActive]);

  function ask(s) { setView("agent"); if (s) setSeed(s); }

  async function signOut() {
    try {
      if (window.AHRuntime) {
        await window.AHRuntime.logout();
      }
    } finally {
      setUser(null);
      setTenantConnected(false);
      setView("home");
    }
  }

  async function handleConnected(updatedUser) {
    const nextUser = updatedUser || user;
    if (nextUser) {
      setUser(nextUser);
      if (nextUser.email) {
        AH.tenant.connectedAs = nextUser.email;
      }
    }

    try {
      await window.AHRuntime.applyTenantContext(nextUser);
      setTenantConnected(true);
    } catch (_error) {
      setTenantConnected(false);
    }
  }

  const ext = forcedSurface === "extension" || t.surface === "extension";
  const hasAccess = Boolean(user && user.subscriptionActive);
  const canUseViews = hasAccess;
  const isConnected = Boolean(hasAccess && tenantConnected);
  const tenantDomainLabel = isConnected ? AH.tenant.domain : "not connected";

  const shell = (
    <div className={"col" + (ext ? " ext" : "")} style={{ height: "100%", minHeight: 0, background: "var(--bg)", overflow: "hidden" }}>
      {/* brand bar */}
      <div className="between" style={{ height: 50, paddingRight: 16, borderBottom: "1px solid var(--border)", background: "var(--bg)", flexShrink: 0 }}>
        {!ext ? (
          <BrandTabs />
        ) : (
          <div className="row" style={{ gap: 8, paddingLeft: 14 }}>
            <div style={{ width: 20, height: 20, borderRadius: 5, background: "var(--primary)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="bolt" size={13} color="#04221d" />
            </div>
            <span className="mono" style={{ fontSize: 12.5, color: "var(--text)" }}>Azure Helper</span>
          </div>
        )}
        {!ext && (
          <div className="row" style={{ gap: 12 }}>
            <span className="live"><span className={"dot " + (isConnected ? "on" : "off")} /> {tenantDomainLabel}</span>
            <button className="btn btn-quiet btn-sm" onClick={() => setTweak("theme", t.theme === "light" ? "dark" : "light")} title="Toggle theme">
              <Icon name={t.theme === "light" ? "shield" : "spark"} size={13} color="var(--primary)" /> {t.theme === "light" ? "dark" : "light"}
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => setShowConnect(true)}>
              <Icon name="plug" size={13} color="var(--primary)" /> Connection
            </button>
            {isConnected && (
              <button className="btn btn-ghost btn-sm" onClick={() => setShowDiagnostics((v) => !v)}>
                <Icon name="shield" size={13} color="var(--primary)" /> Diagnostics
              </button>
            )}
          </div>
        )}
        {ext && (
          <div className="row" style={{ gap: 8, paddingRight: 4 }}>
            <button className="btn btn-quiet btn-sm" onClick={() => setTweak("theme", t.theme === "light" ? "dark" : "light")} style={{ padding: 6 }}>
              <Icon name={t.theme === "light" ? "shield" : "spark"} size={13} color="var(--primary)" />
            </button>
            <span className="mono dim" style={{ fontSize: 11 }}>⊟ side panel</span>
          </div>
        )}
      </div>

      {/* nav bar */}
      <div className="row" style={{ height: 42, padding: "0 14px", borderBottom: "1px solid var(--border)", background: "var(--bg)", gap: ext ? 4 : 6, flexShrink: 0, overflowX: "auto" }}>
        {(ext ? NAV.filter((n) => n.id === "home" || n.id === "agent") : NAV).map(n => (
          <button key={n.id} onClick={() => setView(n.id)} className="row mono" style={{
            gap: 7, padding: "6px 12px", borderRadius: 6, cursor: "pointer", fontSize: 12.5, fontWeight: 600,
            background: view === n.id ? "var(--surface-2)" : "transparent",
            color: view === n.id ? "var(--primary)" : "var(--text-2)",
            border: "1px solid " + (view === n.id ? "var(--border-2)" : "transparent"),
            whiteSpace: "nowrap"
          }}>
            <Icon name={n.icon} size={14} color={view === n.id ? "var(--primary)" : "var(--text-dim)"} />
            {ext ? n.label.replace("./", "").replace("-explorer", "") : n.label}
          </button>
        ))}
        <div className="grow" />
        {!ext && (
          <div className="row" style={{ gap: 12, paddingRight: 4 }}>
            <span className="chip cy"><span className="dot on" style={{ width: 6, height: 6 }} /> read-only · no writes</span>
            <span className="mono dim" style={{ fontSize: 11.5 }}>v1.0 · 23 walkthroughs</span>
          </div>
        )}
      </div>

      {/* view */}
      <div className="grow" style={{ minHeight: 0 }}>
        {runtimeReady && !authChecking && tenantReady && hasAccess && !tenantConnected && view !== "home" && (
          <div style={{ padding: "10px 12px" }}>
            <span className="chip">Tenant context not fully linked. You can still use the views, but live reads may fail until you reconnect.</span>
          </div>
        )}
        {runtimeReady && !authChecking && tenantReady && isConnected && showDiagnostics && (
          <DiagnosticsPanel user={user} />
        )}
        {(!runtimeReady || authChecking || !tenantReady) && (
          <div className="center" style={{ height: "100%" }}>
            <Thinking label="initializing runtime" />
          </div>
        )}
        {runtimeReady && !authChecking && tenantReady && !user && <AuthPaywall user={null} onAuthResolved={setUser} />}
        {runtimeReady && !authChecking && tenantReady && user && !user.subscriptionActive && <AuthPaywall user={user} onAuthResolved={setUser} />}
        {runtimeReady && !authChecking && tenantReady && hasAccess && view === "home" && (
          <HomeView connected={tenantConnected} onAsk={ask} onConnect={() => setShowConnect(true)} onSignOut={signOut} extensionContext={extensionContext} isExtensionPanel={ext} />
        )}
        {runtimeReady && !authChecking && tenantReady && canUseViews && view === "agent" && <AgentView coaching={t.coaching} defaultMethod={t.method} seed={seed} onConsumeSeed={() => setSeed(null)} onOpenLearn={() => setView("learn")} />}
        {runtimeReady && !authChecking && tenantReady && canUseViews && view === "graph" && <GraphView />}
        {runtimeReady && !authChecking && tenantReady && canUseViews && view === "learn" && <LearnView />}
      </div>
    </div>
  );

  return (
    <>
      {ext ? (
        <div style={{ height: "100vh", width: "100vw", position: "relative", overflow: "hidden", background: "#0a0f14" }}>
          {/* faux portal backdrop */}
          <FauxPortal />
          <div style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: 448, maxWidth: "100%", boxShadow: "-30px 0 80px rgba(0,0,0,.55)", borderLeft: "1px solid var(--border-2)" }}>
            {shell}
          </div>
        </div>
      ) : (
        <div style={{ height: "100vh", width: "100vw" }}>{shell}</div>
      )}

      {showConnect && <ConnectFlow onClose={() => setShowConnect(false)} onConnected={handleConnected} />}

      <TweaksPanel>
        <TweakSection label="Appearance" />
        <TweakRadio label="Theme" value={t.theme} options={["dark", "light"]} onChange={(v) => setTweak("theme", v)} />
        <TweakColor label="Accent" value={t.accent === "teal" ? "#2dd4bf" : t.accent === "violet" ? "#a78bfa" : t.accent === "gold" ? "#e7d24e" : "#5aa9f0"}
          options={["#2dd4bf", "#a78bfa", "#e7d24e", "#5aa9f0"]}
          onChange={(v) => setTweak("accent", v === "#2dd4bf" ? "teal" : v === "#a78bfa" ? "violet" : v === "#e7d24e" ? "gold" : "blue")} />
        <TweakRadio label="Density" value={t.density} options={["compact", "regular", "comfy"]} onChange={(v) => setTweak("density", v)} />
        <TweakToggle label="Terminal grid" value={t.showGrid} onChange={(v) => setTweak("showGrid", v)} />
        <TweakSection label="Learning" />
        <TweakRadio label="Coaching depth" value={t.coaching} options={["light", "medium", "heavy"]} onChange={(v) => setTweak("coaching", v)} />
        <TweakRow label=""><span style={{ fontSize: 11, color: "var(--text-dim)", lineHeight: 1.45 }}>how much teach-as-you-go shows in each agent step</span></TweakRow>
        <TweakSection label="Guide" />
        <TweakRadio label="Preferred method" value={t.method} options={["portal", "graph", "powershell"]} onChange={(v) => setTweak("method", v)} />
        <TweakRow label=""><span style={{ fontSize: 11, color: "var(--text-dim)", lineHeight: 1.45 }}>which way each step opens to first — you can switch per step</span></TweakRow>
        <TweakSection label="Surface" />
        <TweakRadio label="Form factor" value={t.surface} options={["dashboard", "extension"]} onChange={(v) => setTweak("surface", v)} />
        <TweakRow label=""><span style={{ fontSize: 11, color: "var(--text-dim)", lineHeight: 1.45 }}>extension = the Helper docked as a browser side-panel over the Azure portal</span></TweakRow>
      </TweaksPanel>
    </>
  );
}

/* faux Azure portal behind the extension side-panel */
function FauxPortal() {
  return (
    <div style={{ position: "absolute", inset: 0, padding: 0, filter: "saturate(.7)", opacity: .5 }}>
      <div style={{ height: 44, background: "#0d1b26", borderBottom: "1px solid #18303f", display: "flex", alignItems: "center", padding: "0 18px", gap: 16 }}>
        <span className="mono" style={{ color: "#7fb4d6", fontWeight: 700, fontSize: 13 }}>Microsoft Azure</span>
        <span className="mono" style={{ color: "#456", fontSize: 12 }}>Home &gt; Users</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "200px 1fr", height: "calc(100% - 44px)" }}>
        <div style={{ background: "#0b1620", borderRight: "1px solid #18303f", padding: 16 }}>
          {["Overview", "Users", "Groups", "Roles", "Licenses", "Conditional Access", "Devices"].map((x, i) => (
            <div key={i} className="mono" style={{ color: "#567", fontSize: 12.5, padding: "9px 0" }}>{x}</div>
          ))}
        </div>
        <div style={{ padding: 24 }}>
          <div style={{ height: 26, width: 180, background: "#13212c", borderRadius: 4, marginBottom: 20 }} />
          {[...Array(9)].map((_, i) => (
            <div key={i} style={{ height: 38, background: "#0f1c25", borderBottom: "1px solid #16293480", borderRadius: 3, marginBottom: 6, display: "flex", alignItems: "center", padding: "0 14px", gap: 14 }}>
              <div style={{ width: 24, height: 24, borderRadius: "50%", background: "#1b3140" }} />
              <div style={{ height: 10, width: 160 + (i % 3) * 40, background: "#19303d", borderRadius: 3 }} />
              <div style={{ height: 10, width: 90, background: "#152732", borderRadius: 3, marginLeft: "auto" }} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

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