/* ===========================================================================
   Azure Helper — Guide mode  (read-only tutor)
   Teaches every step three ways: Portal · Graph · PowerShell.
   Reads can run live; changes are instruction-only (the Helper never writes).
   =========================================================================== */

/* copy-to-clipboard button */
function CopyBtn({ text, label = "Copy" }) {
  const [done, setDone] = useState(false);
  function copy() {
    try { navigator.clipboard && navigator.clipboard.writeText(text); } catch (e) { }
    setDone(true); setTimeout(() => setDone(false), 1300);
  }
  return (
    <button className="btn btn-quiet btn-sm" onClick={copy} style={{ padding: "5px 10px" }}>
      <Icon name={done ? "check" : "copy"} size={12} color={done ? "var(--primary)" : "var(--text-dim)"} />
      {done ? "Copied" : label}
    </button>
  );
}

/* method toggle: Portal · Graph · PowerShell */
const METHODS = [
  { id: "portal", label: "Portal", icon: "eye" },
  { id: "graph", label: "Graph", icon: "graph" },
  { id: "powershell", label: "PowerShell", icon: "bolt" },
];
function MethodTabs({ value, onChange, avail }) {
  return (
    <div className="row" style={{ gap: 4, background: "var(--inset)", padding: 4, borderRadius: 8, border: "1px solid var(--border)" }}>
      {METHODS.filter(m => avail[m.id]).map(m => (
        <button key={m.id} onClick={() => onChange(m.id)} className="row mono" style={{
          gap: 6, padding: "6px 12px", borderRadius: 5, cursor: "pointer", fontSize: 12, fontWeight: 600,
          background: value === m.id ? "var(--surface-3)" : "transparent",
          color: value === m.id ? "var(--text)" : "var(--text-dim)",
          border: "1px solid " + (value === m.id ? "var(--border-2)" : "transparent")
        }}>
          <Icon name={m.icon} size={13} color={value === m.id ? "var(--primary)" : "var(--text-dim)"} /> {m.label}
        </button>
      ))}
    </div>
  );
}

/* the three "how" views */
function PortalGuide({ steps }) {
  return (
    <div className="code" style={{ padding: 0, overflow: "hidden" }}>
      <div className="row" style={{ gap: 8, padding: "9px 13px", borderBottom: "1px solid var(--border)", background: "var(--surface-2)" }}>
        <span className="dot" style={{ background: "#ec5c5c", width: 9, height: 9 }} />
        <span className="dot" style={{ background: "#e8c14e", width: 9, height: 9 }} />
        <span className="dot" style={{ background: "#5fc46a", width: 9, height: 9 }} />
        <span className="mono dim" style={{ fontSize: 11.5, marginLeft: 6 }}>entra.microsoft.com</span>
      </div>
      <ol style={{ margin: 0, padding: "12px 14px 12px 0", listStyle: "none", counterReset: "s" }}>
        {steps.map((s, i) => (
          <li key={i} className="row" style={{ gap: 11, padding: "5px 16px", alignItems: "flex-start" }}>
            <span className="mono" style={{ color: "var(--primary)", fontSize: 12, fontWeight: 700, minWidth: 16, textAlign: "right" }}>{i + 1}</span>
            <span style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.55, fontFamily: "var(--sans)" }}>{s}</span>
          </li>
        ))}
      </ol>
    </div>
  );
}

function StepHow({ step, m }) {
  if (m === "portal") return <PortalGuide steps={step.gui} />;
  if (m === "powershell") {
    return <pre className="code" style={{ margin: 0 }}><span className="tok-cmd">{step.powershell}</span></pre>;
  }
  // graph
  return <CmdLine method={step.method} url={step.url} body={step.body} />;
}

/* teach-as-you-go block (tolerant of missing fields) */
function TeachBlock({ step, coaching }) {
  if (coaching === "light") return null;
  const article = AH.articles[step.concept];
  if (!step.learn && !step.tip && !article) return null;
  return (
    <div style={{ background: "var(--violet-dim)", border: "1px solid rgba(167,139,250,.22)", borderRadius: 6, padding: "12px 13px" }}>
      {step.learn && (
        <>
          <div className="row" style={{ gap: 7, marginBottom: 6 }}>
            <Icon name="book" size={14} color="var(--violet)" />
            <span className="mono" style={{ fontSize: 11, letterSpacing: ".5px", color: "var(--violet)", fontWeight: 700, textTransform: "uppercase" }}>Learn</span>
            {step.concept && <span className="chip vi" style={{ marginLeft: "auto" }}>{step.concept}</span>}
          </div>
          <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.6 }}>{step.learn}</div>
        </>
      )}
      {step.tip && (
        <div style={{ display: "flex", gap: 8, marginTop: step.learn ? 11 : 0, paddingTop: step.learn ? 11 : 0, borderTop: step.learn ? "1px solid rgba(167,139,250,.18)" : "none" }}>
          <Icon name="spark" size={14} color="var(--gold)" style={{ flexShrink: 0, marginTop: 2 }} />
          <div style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.55 }}>
            <span className="mono" style={{ color: "var(--gold)", fontWeight: 700, fontSize: 11 }}>PRO TIP&nbsp;&nbsp;</span>{step.tip}
          </div>
        </div>
      )}
      {article && (
        <a href={article.url} target="_blank" rel="noopener" className="between" style={{ marginTop: 11, padding: "9px 11px", borderRadius: 6, textDecoration: "none", background: "var(--inset)", border: "1px solid var(--border)" }}>
          <span className="row" style={{ gap: 9, minWidth: 0 }}>
            <Icon name="book" size={14} color="var(--primary)" />
            <span style={{ minWidth: 0 }}>
              <span className="mono" style={{ fontSize: 12.5, color: "var(--text)", display: "block", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{article.title}</span>
              <span className="mono" style={{ fontSize: 10.5, color: "var(--text-dim)" }}>learn.cloudpartner.fi · {article.read} read</span>
            </span>
          </span>
          <Icon name="arrow" size={14} color="var(--primary)" />
        </a>
      )}
    </div>
  );
}

/* one teaching step */
function StepRow({ step, idx, open, onToggle, done, onDone, coaching, defaultMethod }) {
  const avail = { portal: !!step.gui, graph: !!step.url, powershell: !!step.powershell };
  const firstAvail = avail[defaultMethod] ? defaultMethod : (avail.portal ? "portal" : avail.graph ? "graph" : "powershell");
  const [m, setM] = useState(firstAvail);
  const [ran, setRan] = useState(false);
  const [running, setRunning] = useState(false);
  const [resultData, setResultData] = useState(step.result || null);
  const [runError, setRunError] = useState("");
  const isRead = step.risk === "read";

  async function runRead() {
    setRunning(true);
    setRunError("");

    try {
      if (window.AHRuntime && step.url) {
        const response = await window.AHRuntime.queryGraph({
          method: step.method,
          url: step.url,
          body: step.body || undefined,
        });
        setResultData(response.data);
      } else {
        await new Promise((resolve) => setTimeout(resolve, 850));
        setResultData(step.result || null);
      }
      setRan(true);
    } catch (error) {
      setRunError(error.message || "Read operation failed");
      setResultData({ error: error.message || "Read operation failed" });
      setRan(true);
    } finally {
      setRunning(false);
    }
  }
  const copyText = m === "portal" ? step.gui.map((g, i) => `${i + 1}. ${g}`).join("\n")
    : m === "powershell" ? step.powershell
      : `${step.method} https://graph.microsoft.com${step.url}` + (step.body ? "\n\n" + JSON.stringify(step.body, null, 2) : "");

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden", borderColor: done ? "var(--border-2)" : "var(--border)" }}>
      <div className="between" style={{ padding: "13px 15px", cursor: "pointer" }} onClick={onToggle}>
        <div className="row" style={{ gap: 12, minWidth: 0 }}>
          <div style={{
            width: 26, height: 26, borderRadius: 6, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center",
            fontFamily: "var(--mono)", fontWeight: 700, fontSize: 12.5,
            background: done ? "var(--primary)" : "var(--inset)", color: done ? "#04221d" : "var(--text-dim)",
            border: "1px solid " + (done ? "var(--primary)" : "var(--border)")
          }}>{done ? <Icon name="check" size={15} color="#04221d" /> : idx + 1}</div>
          <div style={{ minWidth: 0 }}>
            <div className="mono" style={{ fontWeight: 600, fontSize: 13.5, color: "var(--text)" }}>{step.title}</div>
            <div className="row" style={{ gap: 8, marginTop: 4 }}>
              {isRead
                ? <span className="chip cy">○ safe read · I can run this</span>
                : <span className="chip gold">▸ you run this · Helper never writes</span>}
              {step.concept && coaching !== "light" && <span className="chip vi" style={{ display: window.innerWidth < 640 ? "none" : "inline-flex" }}>{step.concept}</span>}
            </div>
          </div>
        </div>
        <Icon name="chevron" size={15} color="var(--text-dim)" style={{ transform: open ? "rotate(90deg)" : "none", transition: "transform .15s", flexShrink: 0 }} />
      </div>

      {open && (
        <div style={{ padding: "2px 15px 16px", borderTop: "1px solid var(--border)" }}>
          <div className="col" style={{ gap: 14, marginTop: 14 }}>
            <div style={{ fontSize: 13.5, color: "var(--text-2)", lineHeight: 1.6 }}>{step.why}</div>

            {/* how-to with three ways */}
            <div className="col" style={{ gap: 10 }}>
              <div className="between wrap" style={{ gap: 10 }}>
                <MethodTabs value={m} onChange={setM} avail={avail} />
                <CopyBtn text={copyText} label={m === "portal" ? "Copy steps" : "Copy"} />
              </div>
              <StepHow step={step} m={m} />
            </div>

            {/* read: run live; change: instruction-only banner */}
            {isRead ? (
              <div>
                {!ran ? (
                  <button className="btn btn-ghost btn-sm" onClick={runRead} disabled={running}>
                    {running ? <><Icon name="refresh" size={13} color="var(--primary)" className="spin" /> Reading your tenant…</> : <><Icon name="play" size={13} color="var(--primary)" /> Run this read (safe)</>}
                  </button>
                ) : (
                  <div className="fade">
                    <div className="row" style={{ gap: 7, marginBottom: 7 }}>
                      <span className="live"><span className="dot on" /> live from {AH.tenant.domain}</span>
                    </div>
                    {runError && (
                      <div className="chip" style={{ color: "var(--rose)", borderColor: "rgba(244,117,127,.4)", marginBottom: 8 }}>
                        {runError}
                      </div>
                    )}
                    <JsonView data={resultData} style={{ margin: 0 }} />
                  </div>
                )}
              </div>
            ) : (
              <div className="row" style={{ gap: 9, padding: "10px 12px", background: "var(--gold-dim)", border: "1px solid rgba(231,210,78,.22)", borderRadius: 6 }}>
                <Icon name="shield" size={15} color="var(--gold)" />
                <span className="t2" style={{ fontSize: 12.5, lineHeight: 1.5 }}>
                  This step <b>changes your tenant</b>, so the Helper won't run it. Copy the method you prefer above and run it yourself — then tick it off.
                </span>
              </div>
            )}

            <TeachBlock step={step} coaching={coaching} />

            {/* mark done */}
            <button className="row" onClick={() => onDone(!done)} style={{
              gap: 9, alignSelf: "flex-start", cursor: "pointer", background: "transparent", border: "none", padding: 0, fontFamily: "var(--sans)"
            }}>
              <span style={{
                width: 20, height: 20, borderRadius: 5, display: "flex", alignItems: "center", justifyContent: "center",
                border: "1px solid " + (done ? "var(--primary)" : "var(--border-2)"), background: done ? "var(--primary)" : "transparent"
              }}>{done && <Icon name="check" size={13} color="#04221d" />}</span>
              <span style={{ fontSize: 13, color: done ? "var(--text-2)" : "var(--text)" }}>{done ? "Done" : "Mark this step done"}</span>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

/* page-aware AI Tutor inline response — used when extension suggests an action */
function AiTutorRun({ prompt, pageContext }) {
  const [status, setStatus] = useState("loading");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    let cancelled = false;
    async function run() {
      try {
        if (!window.AHRuntime) throw new Error("Runtime not available — try refreshing.");
        const ctx = pageContext
          ? `You are helping an Azure/M365 admin who currently has this page open:\nTitle: ${pageContext.pageTitle || "unknown"}\nURL: ${pageContext.pageUrl}\n\nProvide a concise, page-specific read-only answer. Explain what this page/resource is, what an admin would normally check here, and what safe read-only actions or Graph/PowerShell commands are most useful. Do NOT describe generic Azure topics unrelated to this specific page.`
          : "Guide mode — read-only answers only.";
        const result = await window.AHRuntime.tutor(prompt, ctx);
        if (!cancelled) { setMessage(result.message || "No response returned."); setStatus("done"); }
      } catch (e) {
        if (!cancelled) { setError(e.message || "AI request failed"); setStatus("error"); }
      }
    }
    run();
    return () => { cancelled = true; };
  }, []);

  return (
    <div className="card tint fade">
      <div className="row" style={{ gap: 9, marginBottom: 10 }}>
        <div style={{ width: 24, height: 24, borderRadius: 6, background: "var(--violet-dim)", border: "1px solid rgba(167,139,250,.3)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="spark" size={14} color="var(--violet)" />
        </div>
        <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: "var(--violet)" }}>AI Tutor</span>
        {pageContext?.pageTitle && (
          <span className="chip cy" style={{ fontSize: 11, maxWidth: 190, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {pageContext.pageTitle}
          </span>
        )}
        <span className="chip cy" style={{ marginLeft: "auto" }}>read-only</span>
      </div>
      {status === "loading" && <Thinking label="reading page context and preparing your answer" />}
      {status === "done" && (
        <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.65, whiteSpace: "pre-wrap" }}>{message}</div>
      )}
      {status === "error" && (
        <div className="chip" style={{ color: "var(--rose)", borderColor: "rgba(244,117,127,.4)" }}>{error}</div>
      )}
    </div>
  );
}

/* a full walkthrough for one scenario */
function GuideRun({ scenario, coaching, defaultMethod, onOpenLearn }) {
  const steps = scenario.steps;
  const [phase, setPhase] = useState("understanding");   // understanding | guide
  const [open, setOpen] = useState(new Set(coaching === "heavy" ? steps.map((_, i) => i) : [0]));
  const [doneSet, setDoneSet] = useState(new Set());
  const [showFollow, setShowFollow] = useState(false);
  useEffect(() => { const t = setTimeout(() => setPhase("guide"), 950); return () => clearTimeout(t); }, []);

  const toggle = (i) => setOpen(s => { const n = new Set(s); n.has(i) ? n.delete(i) : n.add(i); return n; });
  const setDone = (i, v) => setDoneSet(s => { const n = new Set(s); v ? n.add(i) : n.delete(i); return n; });
  const allDone = doneSet.size >= steps.length;

  return (
    <div className="col" style={{ gap: 14 }}>
      {/* understanding */}
      <div className="card tint fade">
        <div className="row" style={{ gap: 9, marginBottom: 10 }}>
          <div style={{ width: 24, height: 24, borderRadius: 6, background: "var(--violet-dim)", border: "1px solid rgba(167,139,250,.3)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="book" size={14} color="var(--violet)" />
          </div>
          <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: "var(--violet)" }}>Helper coach</span>
          <span className="chip vi">{scenario.intent}</span>
          <span className="chip cy" style={{ marginLeft: "auto" }}>read-only</span>
        </div>
        {phase === "understanding"
          ? <Thinking label="reading your tenant & preparing the walkthrough" />
          : <div style={{ fontSize: 14.5, color: "var(--text)", lineHeight: 1.6 }}>{scenario.summary}</div>}
        {phase !== "understanding" && (
          <div className="row wrap" style={{ gap: 8, marginTop: 13 }}>
            {scenario.entities.map((e, i) => (
              <span key={i} className="chip"><span className="dim">{e.k}:</span>&nbsp;<span style={{ color: "var(--text)" }}>{e.v}</span></span>
            ))}
          </div>
        )}
      </div>

      {phase === "guide" && (
        <div className="card fade" style={{ padding: 0 }}>
          <div className="between" style={{ padding: "13px 16px", borderBottom: "1px solid var(--border)" }}>
            <PS path="Helper" cmd={"Show-HowTo -Steps " + steps.length} />
            <span className="mono dim" style={{ fontSize: 12 }}>{doneSet.size}/{steps.length} done</span>
          </div>
          <div className="col" style={{ gap: 10, padding: 14 }}>
            {steps.map((s, i) => (
              <StepRow key={i} step={s} idx={i} open={open.has(i)} onToggle={() => toggle(i)}
                done={doneSet.has(i)} onDone={(v) => setDone(i, v)} coaching={coaching} defaultMethod={defaultMethod} />
            ))}
          </div>

          {/* follow-up "your turn" + recap */}
          <div style={{ padding: "0 16px 16px" }}>
            {scenario.followUp && (
              <div className="col" style={{ gap: 10 }}>
                <button className="btn btn-quiet btn-sm" style={{ alignSelf: "flex-start" }} onClick={() => setShowFollow(s => !s)}>
                  <Icon name={showFollow ? "chevron" : "arrow"} size={13} color="var(--primary)" style={showFollow ? { transform: "rotate(90deg)" } : null} /> {scenario.followUp.label}
                </button>
                {showFollow && (
                  <div className="fade">
                    <StepRow step={scenario.followUp} idx={steps.length} open={true} onToggle={() => { }}
                      done={doneSet.has(99)} onDone={(v) => setDone(99, v)} coaching={coaching} defaultMethod={defaultMethod} />
                  </div>
                )}
              </div>
            )}
          </div>

          {allDone && coaching !== "light" && scenario.learned && (
            <div className="fade" style={{ padding: "14px 16px", borderTop: "1px solid var(--border)", background: "linear-gradient(180deg, rgba(167,139,250,.08), transparent)" }}>
              <div className="row" style={{ gap: 8, marginBottom: 8 }}>
                <Icon name="check" size={16} color="var(--primary)" />
                <span className="mono" style={{ fontWeight: 700, color: "var(--primary)", fontSize: 13.5 }}>Walkthrough complete — nice work</span>
              </div>
              <div className="mono dim" style={{ fontSize: 11.5, marginBottom: 8, textTransform: "uppercase", letterSpacing: ".5px" }}>// what you learned</div>
              <div className="row wrap" style={{ gap: 7 }}>
                {scenario.learned.map((c, i) => <span key={i} className="chip vi">✓ {c}</span>)}
              </div>
              <button className="btn btn-quiet btn-sm" style={{ marginTop: 13 }} onClick={onOpenLearn}>
                <Icon name="arrow" size={13} color="var(--primary)" /> Go deeper in the Learning hub
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* whole guide surface */
function getAiDiagnostic(error) {
  const details = error?.details || error?.payload?.details || {};
  const status = Number(error?.status || details?.status || 0);
  const code = String(error?.code || error?.payload?.code || "");
  const message = String(error?.message || "").toLowerCase();
  const raw = JSON.stringify(details || {}).toLowerCase();

  if (code === "AZURE_OPENAI_NOT_CONFIGURED") {
    return "Tutor status: not configured";
  }
  if (status === 401 || status === 403 || /unauthorized|permission|access denied|forbidden/.test(`${message} ${raw}`)) {
    return "Tutor status: unauthorized";
  }
  if (status === 404 || /deploymentnotfound|deployment not found/.test(raw)) {
    return "Tutor status: deployment not found";
  }
  return "Tutor status: request failed";
}

function AgentView({ coaching, defaultMethod, seed, onConsumeSeed, onOpenLearn, extensionContext = null }) {
  const extensionSurface = new URLSearchParams(window.location.search).get("surface") === "extension";
  const [runs, setRuns] = useState([]);
  const [text, setText] = useState("");
  const [aiBusy, setAiBusy] = useState(false);
  const [aiMessage, setAiMessage] = useState("");
  const [aiError, setAiError] = useState("");
  const [aiDiagnostic, setAiDiagnostic] = useState("");
  const scrollRef = useRef(null);

  function launch(prompt, scenarioId, opts = {}) {
    if (opts.useAiTutor) {
      setRuns(r => [...r, { prompt, useAiTutor: true, pageContext: opts.pageContext, key: Date.now() + Math.random() }]);
      setText("");
      return;
    }
    const sid = scenarioId || AH.routePrompt(prompt);
    setRuns(r => [...r, { prompt, scenarioId: sid, key: Date.now() + Math.random() }]);
    setText("");
  }
  useEffect(() => {
    if (seed) {
      if (seed.useAiTutor) {
        launch(seed.prompt, null, { useAiTutor: true, pageContext: seed.pageContext });
      } else {
        launch(seed.prompt, seed.scenarioId);
      }
      onConsumeSeed && onConsumeSeed();
    }
  }, [seed]);
  useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [runs.length]);

  function submit(e) { e && e.preventDefault(); const t = text.trim(); if (t) launch(t); }
  async function askAiTutor() {
    const latest = text.trim() || (runs[runs.length - 1] ? runs[runs.length - 1].prompt : "How should I proceed with this task?");
    setAiBusy(true);
    setAiError("");
    setAiDiagnostic("");
    try {
      if (!window.AHRuntime) {
        throw new Error("Runtime API not available");
      }
      const pageCtx = extensionContext?.pageUrl
        ? `You are helping an admin viewing: ${extensionContext.pageTitle || extensionContext.pageUrl}\nURL: ${extensionContext.pageUrl}\nGuide mode coach — read-only answers only.`
        : "Guide mode coach";
      const response = await window.AHRuntime.tutor(latest, pageCtx);
      setAiMessage(response.message || "No AI message returned");
    } catch (e) {
      setAiError(e.message || "AI tutor request failed");
      setAiDiagnostic(getAiDiagnostic(e));
      setAiMessage("");
    } finally {
      setAiBusy(false);
    }
  }
  const empty = runs.length === 0;

  return (
    <div className="col" style={{ height: "100%", minHeight: 0 }}>
      <div ref={scrollRef} className="grow" style={{ overflowY: "auto", padding: "26px 0" }}>
        <div style={{ maxWidth: 880, margin: "0 auto", padding: "0 26px" }}>
          {empty ? (
            extensionSurface && extensionContext ? (
              <div className="fade">
                <Crumbs items={[{ label: "Guide", on: true }, { label: "page-aware" }]} />
                <h1 className="h1" style={{ marginTop: 18, fontSize: 26 }}>
                  Ask about <span className="gold">{extensionContext.pageTitle || "this page"}</span>.
                </h1>
                <p style={{ color: "var(--text-2)", fontSize: 14, maxWidth: 500, marginTop: 10, lineHeight: 1.55 }}>
                  The AI Tutor will answer specifically about what you see on this page — read-only guidance only.
                </p>
                <button
                  className="btn btn-primary"
                  style={{ marginTop: 14 }}
                  onClick={() => launch(
                    `I am on this page: "${extensionContext.pageTitle || extensionContext.pageUrl}" (${extensionContext.pageUrl}). Explain what this page is for, what an admin usually checks here, and what safe read-only actions, Graph queries, or PowerShell commands are most relevant.`,
                    null,
                    { useAiTutor: true, pageContext: extensionContext }
                  )}
                >
                  <Icon name="spark" size={14} color="#04221d" /> Ask about this page
                </button>
              </div>
            ) : (
              <div className="fade">
                <Crumbs items={[{ label: "Guide", on: true }, { label: "your real tenant" }, { label: "I show, you run" }]} />
                <h1 className="h1" style={{ marginTop: 18, fontSize: 33 }}>
                  Ask how to do anything.<br />I'll <span className="gold">show you</span> — without touching a thing.
                </h1>
                <p style={{ color: "var(--text-2)", fontSize: 15, maxWidth: 600, marginTop: 14 }}>
                  Every task, explained three ways — the <b>Portal</b>, <b>Microsoft Graph</b>, and <b>PowerShell</b> — using your real data from <span className="mono cy">{AH.tenant.domain}</span>. The Helper reads to teach, and <b>never changes your tenant</b>. You run the steps.
                </p>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gap: 10, marginTop: 18 }}>
                  {[
                    {
                      title: "Onboard a new employee",
                      blurb: "Create user, assign license, group and team membership, then verify handoff.",
                      sid: "onboard",
                      prompt: AH.scenarios.onboard.prompt,
                    },
                    {
                      title: "Audit stale guest accounts",
                      blurb: "Run safe guest reads and identify external users inactive for 90+ days.",
                      sid: "guests",
                      prompt: AH.scenarios.guests.prompt,
                    },
                    {
                      title: "Verify admin MFA coverage",
                      blurb: "Cross-check privileged roles against Conditional Access MFA protections.",
                      sid: "mfa",
                      prompt: AH.scenarios.mfa.prompt,
                    },
                  ].map((m, i) => (
                    <button
                      key={i}
                      className="card hover"
                      onClick={() => launch(m.prompt, m.sid)}
                      style={{ textAlign: "left", cursor: "pointer", padding: "12px 13px", display: "block" }}
                    >
                      <div className="row" style={{ gap: 8 }}>
                        <Icon name="spark" size={14} color="var(--primary)" />
                        <span className="mono" style={{ fontWeight: 700, fontSize: 12.5, color: "var(--text)" }}>{m.title}</span>
                      </div>
                      <p style={{ color: "var(--text-2)", fontSize: 12.5, lineHeight: 1.55, marginTop: 8 }}>{m.blurb}</p>
                      <div className="row" style={{ gap: 7, marginTop: 8 }}>
                        <span className="chip cy">Guide</span>
                        <span className="chip">Portal + Graph + PowerShell</span>
                      </div>
                    </button>
                  ))}
                </div>
                <div className="col" style={{ gap: 9, marginTop: 26 }}>
                  <SecLabel>ask me how to…</SecLabel>
                  {AH.suggestions.slice(0, 6).map((s, i) => (
                    <button key={i} className="card hover" onClick={() => launch(s)} style={{
                      textAlign: "left", cursor: "pointer", padding: "13px 15px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
                      fontFamily: "var(--sans)", color: "var(--text)", fontSize: 14
                    }}>
                      <span className="row" style={{ gap: 11 }}><Icon name="spark" size={15} color="var(--primary)" /> {s}</span>
                      <Icon name="arrow" size={15} color="var(--text-dim)" />
                    </button>
                  ))}
                </div>
              </div>
            )
          ) : (
            <div className="col" style={{ gap: 30 }}>
              {runs.map((r) => (
                <div key={r.key} className="col" style={{ gap: 14 }}>
                  <div style={{ alignSelf: "flex-end", maxWidth: "82%" }}>
                    <div className="card" style={{ background: "var(--surface-3)", borderColor: "var(--border-2)", padding: "12px 15px" }}>
                      <div className="row" style={{ gap: 8, marginBottom: 5 }}>
                        <Icon name="user" size={13} color="var(--text-dim)" />
                        <span className="mono dim" style={{ fontSize: 11 }}>you</span>
                      </div>
                      <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.55 }}>{r.prompt}</div>
                    </div>
                  </div>
                  {r.useAiTutor
                    ? <AiTutorRun prompt={r.prompt} pageContext={r.pageContext} />
                    : <GuideRun scenario={AH.scenarios[r.scenarioId]} coaching={coaching} defaultMethod={defaultMethod} onOpenLearn={onOpenLearn} />}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div style={{ borderTop: "1px solid var(--border)", background: "var(--bg)", padding: extensionSurface ? "10px 14px" : "14px 26px" }}>
        <form onSubmit={submit} style={{ maxWidth: 880, margin: "0 auto" }}>
          <div style={{ position: "relative" }}>
            <div className="ps" style={{ position: "absolute", top: -22, left: 2 }}>
              <span className="ps-user">PS jamie@contoso</span><span style={{ color: "var(--text-faint)" }}>:~/Helper&gt;</span>
            </div>
            <input className="inp" value={text} onChange={e => setText(e.target.value)}
              placeholder="Ask how to do something — e.g. 'how do I block legacy auth?'"
              style={{ paddingRight: 46, fontFamily: "var(--mono)" }} />
            <button type="submit" className="btn btn-primary" style={{ position: "absolute", right: 5, top: 5, padding: "6px 9px" }}>
              <Icon name="send" size={15} color="#04221d" />
            </button>
          </div>
          <div className="between wrap" style={{ gap: 10, marginTop: 11, alignItems: "center" }}>
            {!extensionSurface ? (
              <div className="row wrap" style={{ gap: 7, flex: "1 1 520px" }}>
                {AH.suggestions.slice(0, 4).map((s, i) => (
                  <button key={i} type="button" className="chip click" onClick={() => launch(s)}>
                    {s.length > 42 ? s.slice(0, 40) + "…" : s}
                  </button>
                ))}
              </div>
            ) : <div className="grow" />}
            <button type="button" className="btn btn-quiet btn-sm" onClick={askAiTutor} disabled={aiBusy} style={{ marginLeft: "auto", flexShrink: 0 }}>
              <Icon name="spark" size={13} color="var(--violet)" /> {aiBusy ? "AI thinking…" : "Ask AI tutor"}
            </button>
          </div>
          {aiMessage && (
            <div className="card" style={{ marginTop: 10, background: "var(--violet-dim)", borderColor: "rgba(167,139,250,.25)", padding: "10px 12px" }}>
              <div className="mono" style={{ fontSize: 11, color: "var(--violet)", marginBottom: 6 }}>AI tutor response</div>
              <div style={{ whiteSpace: "pre-wrap", fontSize: 13.5, color: "var(--text-2)", lineHeight: 1.55 }}>{aiMessage}</div>
            </div>
          )}
          {aiError && (
            <div className="col" style={{ gap: 7, marginTop: 10 }}>
              {aiDiagnostic && (
                <div className="mono" style={{ fontSize: 11.5, color: "var(--gold)" }}>
                  {aiDiagnostic}
                </div>
              )}
              <div className="chip" style={{ color: "var(--rose)", borderColor: "rgba(244,117,127,.5)" }}>
                {aiError}
              </div>
            </div>
          )}
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { AgentView });
