/* ===========================================================================
   Azure Helper — Home dashboard
   =========================================================================== */
function getExtensionSuggestions(extensionContext) {
  if (!extensionContext?.pageUrl) {
    return [];
  }

  const pageUrl = extensionContext.pageUrl.toLowerCase();
  const pageTitle = String(extensionContext.pageTitle || "");

  if (pageUrl.includes("portal.azure.com") && pageUrl.includes("microsoft_aad_registeredapps")) {
    return [
      {
        title: "Review this app registration",
        detail: "Inspect the app registration you already have open: redirect URIs, secrets, certificates, and ownership.",
        prompt: `I am on the Azure portal App registrations page for \"${pageTitle || "this app"}\". Show me how to review redirect URIs, credentials, ownership, and app basics safely from this page.`,
        sid: "onboard",
      },
      {
        title: "Check risky Graph permissions",
        detail: "Use this page as the starting point for delegated/application permission review and admin-consent risk checks.",
        prompt: `I am looking at an Azure app registration in the portal. Show me how to review risky Microsoft Graph permissions for this application, what permissions should raise concern, and what to document.`,
        sid: "mfa",
      },
      {
        title: "Audit client secrets and certificates",
        detail: "Walk through credential hygiene, expiration review, and what to flag without changing anything.",
        prompt: `I am on an app registration page in Azure. Show me how to inspect certificates and client secrets, what counts as risky, and how to document findings without making changes.`,
        sid: "mfa",
      },
    ];
  }

  if (pageUrl.includes("portal.azure.com") && pageUrl.includes("microsoft_aad")) {
    return [
      {
        title: "Explain this Entra page",
        detail: "Turn the current Azure/Entra blade into a guided read-only walkthrough.",
        prompt: `I am on this Azure/Entra portal page: ${pageTitle || extensionContext.pathname}. Explain what this page is for, what an admin usually checks here, and what safe read-only actions I can do next.`,
        sid: "mfa",
      },
    ];
  }

  if (pageUrl.includes("admin.microsoft.com")) {
    return [
      {
        title: "Guide me through this M365 admin page",
        detail: "Explain the current Microsoft 365 admin page and the next safe checks to perform from it.",
        prompt: `I am on the Microsoft 365 admin center page \"${pageTitle || extensionContext.pathname}\". Explain what this page controls and what I can review safely from here.`,
        sid: "onboard",
      },
    ];
  }

  return [
    {
      title: "Explain the current page",
      detail: "Use the current browser location as the context for a read-only walkthrough.",
      prompt: `I am on this page: ${pageTitle || extensionContext.pathname} (${extensionContext.pageUrl}). Explain what it is and what I can safely do from here.`,
      sid: "onboard",
    },
  ];
}

function getAzureResourceIdFromPortalUrl(pageUrl) {
  const value = String(pageUrl || "");
  const marker = "/resource/";
  const markerIndex = value.indexOf(marker);
  if (markerIndex === -1) {
    return "";
  }

  const tail = value.slice(markerIndex + marker.length);
  const clean = tail.split("?")[0].replace(/#\/.*/, "").trim();
  if (!clean) {
    return "";
  }

  return clean.startsWith("/") ? clean : `/${clean}`;
}

function getExtensionPullCommands(extensionContext) {
  if (!extensionContext?.pageUrl) {
    return null;
  }

  const pageUrl = String(extensionContext.pageUrl || "");
  const lower = pageUrl.toLowerCase();

  if (lower.includes("microsoft_aad_registeredapps")) {
    const appIdMatch = pageUrl.match(/appId\/([^/?#]+)/i);
    const appId = appIdMatch ? decodeURIComponent(appIdMatch[1]) : "<application-id>";
    return {
      graphLabel: "Microsoft Graph",
      graph: `GET https://graph.microsoft.com/v1.0/applications?$filter=appId eq '${appId}'&$select=id,appId,displayName,requiredResourceAccess,keyCredentials,passwordCredentials`,
      powershellLabel: "PowerShell",
      powershell: `Connect-MgGraph -Scopes 'Application.Read.All'\nGet-MgApplication -Filter \"appId eq '${appId}'\" -Property Id,AppId,DisplayName,RequiredResourceAccess,KeyCredentials,PasswordCredentials`,
    };
  }

  const resourceId = getAzureResourceIdFromPortalUrl(pageUrl);
  if (resourceId) {
    return {
      graphLabel: "Azure Resource Graph",
      graph: `Resources\n| where id =~ '${resourceId.toLowerCase()}'\n| project name, type, location, resourceGroup, subscriptionId, tags`,
      powershellLabel: "PowerShell",
      powershell: `Connect-AzAccount\nGet-AzResource -ResourceId '${resourceId}' | Format-List Name,ResourceGroupName,Location,ResourceType,Tags`,
    };
  }

  return {
    graphLabel: "Azure Resource Graph",
    graph: "Resources | project name, type, location, resourceGroup, subscriptionId | take 20",
    powershellLabel: "PowerShell",
    powershell: "Connect-AzAccount\nGet-AzResource | Select-Object Name,ResourceType,ResourceGroupName,Location -First 20",
  };
}

function HomeView({ connected = true, onAsk, onConnect, onSignOut, extensionContext = null, isExtensionPanel = false }) {
  const t = AH.tenant;
  const [topics, setTopics] = useState([]);
  const [summary, setSummary] = useState(null);
  const [summaryError, setSummaryError] = useState("");

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

    async function loadTopics() {
      if (!window.AHRuntime) {
        const fallback = Object.values(AH.articles || {}).slice(0, 4).map((a, idx) => ({
          key: `fallback-${idx}`,
          title: a.title,
          url: a.url,
        }));
        setTopics(fallback);
        return;
      }

      try {
        const result = await window.AHRuntime.fetchLearnTopics();
        if (!cancelled) {
          setTopics(result.topics || []);
        }
      } catch (_error) {
        if (!cancelled) {
          setTopics([]);
        }
      }
    }

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

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

    async function loadSummary() {
      if (!connected || !window.AHRuntime?.getDashboardSummary) {
        return;
      }
      try {
        setSummaryError("");
        const result = await window.AHRuntime.getDashboardSummary();
        if (!cancelled) {
          setSummary(result.summary || null);
        }
      } catch (error) {
        if (!cancelled) {
          setSummary(null);
          setSummaryError(error?.message || "Unable to load tenant summary");
        }
      }
    }

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

  const tenantInfo = summary?.tenant || {};
  const metrics = summary?.metrics || {};
  const extensionSuggestions = getExtensionSuggestions(extensionContext);
  const extensionCommands = getExtensionPullCommands(extensionContext);
  const statCards = [
    { lab: "Users", num: metrics.users, sub: "member accounts" },
    { lab: "Guests", num: metrics.guests, sub: "external identities" },
    { lab: "Licenses", num: metrics.licensed, sub: "consumed seats" },
    { lab: "Free seats", num: metrics.freeSeats, sub: "available in tenant" },
    { lab: "CA policies", num: metrics.conditionalAccessPolicies, sub: "conditional access" },
    { lab: "Messages", num: metrics.serviceMessages, sub: "service announcements" },
  ];
  const insights = [
    metrics.freeSeats > 0
      ? {
        prompt: `We have ${metrics.freeSeats} unassigned M365 seats. Show how to find inactive users and reclaim licenses safely.`,
        why: "Unused seats found",
        sid: "guests",
      }
      : null,
    metrics.guests > 0
      ? {
        prompt: `We have ${metrics.guests} guest users. Show a secure review process with portal, Graph, and PowerShell steps.`,
        why: "Guest footprint present",
        sid: "guests",
      }
      : null,
    metrics.conditionalAccessPolicies === 0
      ? {
        prompt: "No Conditional Access policies were detected. Show a baseline policy rollout with read-only validation steps.",
        why: "Missing CA baseline",
        sid: "mfa",
      }
      : null,
    {
      prompt: "Show me a complete onboarding flow for a new employee with least-privilege defaults.",
      why: "Common day-one task",
      sid: "onboard",
    },
  ].filter(Boolean);

  if (!connected) {
    return (
      <div style={{ overflowY: "auto", height: "100%" }}>
        <div style={{ maxWidth: 900, margin: "0 auto", padding: "34px 26px 50px" }}>
          <div className="card tint" style={{ padding: "26px 24px" }}>
            <SecLabel>connection required</SecLabel>
            <h1 className="h1" style={{ marginTop: 12, fontSize: 34 }}>Not connected to your tenant.</h1>
            <p style={{ color: "var(--text-2)", fontSize: 15, marginTop: 12, maxWidth: 620 }}>
              Connect your Microsoft tenant to unlock real data. Until then, the dashboard, stats, and walkthrough history stay hidden.
            </p>
            <div className="row wrap" style={{ gap: 10, marginTop: 20 }}>
              <button className="btn btn-primary btn-lg" onClick={onConnect}>
                <Icon name="key" size={16} color="#04221d" /> Connect and sign in
              </button>
              <button className="btn btn-ghost btn-lg" onClick={onSignOut}>
                <Icon name="x" size={15} color="var(--primary)" /> Sign out
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (isExtensionPanel && extensionContext) {
    return (
      <div style={{ overflowY: "auto", height: "100%" }}>
        <div style={{ maxWidth: 860, margin: "0 auto", padding: "14px 14px 20px" }}>
          <div className="card" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div className="between" style={{ gap: 10 }}>
              <SecLabel>session</SecLabel>
              <span className="chip cy">{extensionContext.host || "browser"}</span>
            </div>
            <div className="col" style={{ gap: 8 }}>
              {[["Tenant", tenantInfo.name || t.name], ["Signed in", tenantInfo.connectedAs || t.connectedAs], ["Access", t.method]].map(([k, v], i) => (
                <div key={i} className="between" style={{ fontSize: 12.5 }}>
                  <span className="mono dim">{k}</span>
                  <span className="mono" style={{ color: "var(--text)", maxWidth: 220, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{v}</span>
                </div>
              ))}
            </div>
            <div className="row" style={{ gap: 8 }}>
              <button className="btn btn-quiet btn-sm" onClick={onConnect}>
                <Icon name="key" size={13} color="var(--primary)" /> Connection
              </button>
              <button className="btn btn-quiet btn-sm" onClick={onSignOut}>
                <Icon name="x" size={13} color="var(--primary)" /> Logout
              </button>
            </div>
          </div>

          <div className="card" style={{ marginTop: 12 }}>
            <div className="between" style={{ gap: 12, marginBottom: 10 }}>
              <SecLabel>what can i do on this page?</SecLabel>
              <span className="chip cy">live</span>
            </div>
            <div className="mono dim" style={{ fontSize: 11.5, marginBottom: 10 }}>
              {extensionContext.pageTitle || extensionContext.pathname || extensionContext.pageUrl}
            </div>
            <div className="col" style={{ gap: 8 }}>
              {extensionSuggestions.map((item, index) => (
                <button key={index} className="between" onClick={() => onAsk({ prompt: item.prompt, useAiTutor: true, pageContext: extensionContext })} style={{
                  padding: "10px 12px", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 8,
                  textAlign: "left", cursor: "pointer", gap: 12
                }}>
                  <div>
                    <div style={{ fontSize: 13.5, color: "var(--text)" }}>{item.title}</div>
                    <div className="mono" style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 4 }}>{item.detail}</div>
                  </div>
                  <Icon name="arrow" size={15} color="var(--primary)" />
                </button>
              ))}
            </div>
          </div>

          {extensionCommands && (
            <div className="card" style={{ marginTop: 12 }}>
              <SecLabel>pull this setup (read-only)</SecLabel>
              <div className="col" style={{ gap: 10, marginTop: 10 }}>
                <div>
                  <div className="mono" style={{ fontSize: 11.5, color: "var(--text-dim)", marginBottom: 6 }}>{extensionCommands.graphLabel}</div>
                  <pre className="code" style={{ margin: 0 }}>{extensionCommands.graph}</pre>
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 11.5, color: "var(--text-dim)", marginBottom: 6 }}>{extensionCommands.powershellLabel}</div>
                  <pre className="code" style={{ margin: 0 }}>{extensionCommands.powershell}</pre>
                </div>
                <div className="row" style={{ gap: 8 }}>
                  <button className="btn btn-primary btn-sm" onClick={() => onAsk({ prompt: extensionSuggestions[0]?.prompt || "Explain this page and the safest next read-only checks.", useAiTutor: true, pageContext: extensionContext })}>
                    <Icon name="spark" size={13} color="#04221d" /> Open in Guide + Tutor
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div style={{ overflowY: "auto", height: "100%" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "26px 26px 50px" }}>
        <PS path="Helper" cmd="Get-TenantSnapshot | Format-Dashboard" caret />

        {/* hero row: tenant + headline */}
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18, marginTop: 18 }}>
          <div className="card tint" style={{ display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
            <div>
              <Crumbs items={[{ label: "Home", on: true }, { label: "connected" }, { label: t.region }]} />
              <h1 className="h1" style={{ marginTop: 16, fontSize: 32 }}>
                Learn Azure &amp; M365<br />in your <span className="gold">real tenant</span>.
              </h1>
              <p style={{ color: "var(--text-2)", fontSize: 14.5, marginTop: 12, maxWidth: 480 }}>
                Ask how to do anything. The Helper reads your tenant to teach with real examples and shows every step three ways — Portal, Graph, PowerShell. It <b>never changes a thing</b>; you run the steps.
              </p>
            </div>
            <div className="row wrap" style={{ gap: 10, marginTop: 22 }}>
              <button className="btn btn-primary btn-lg" onClick={() => onAsk(null)}>
                <Icon name="book" size={16} color="#04221d" /> Open the guide
              </button>
              <button className="btn btn-ghost btn-lg" onClick={() => onAsk({ scenarioId: "onboard", prompt: AH.scenarios.onboard.prompt })}>
                <Icon name="bolt" size={15} color="var(--primary)" /> Show me: onboard a user
              </button>
            </div>
          </div>

          {/* connection card */}
          <div className="card" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="between">
              <SecLabel>connection</SecLabel>
              <span className="live"><span className="dot on" /> connected</span>
            </div>
            <div className="row" style={{ gap: 13 }}>
              <div style={{ width: 44, height: 44, borderRadius: 9, background: "var(--surface-3)", border: "1px solid var(--border-2)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Icon name="layers" size={22} color="var(--primary)" />
              </div>
              <div style={{ minWidth: 0 }}>
                <div className="mono" style={{ fontWeight: 700, fontSize: 15, color: "var(--text)" }}>{tenantInfo.name || t.name}</div>
                <div className="mono dim" style={{ fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{tenantInfo.domain || t.domain}</div>
              </div>
            </div>
            <div className="col" style={{ gap: 9 }}>
              {[["Plan", tenantInfo.plan || t.plan], ["Signed in as", tenantInfo.connectedAs || t.connectedAs], ["Access", t.method]].map(([k, v], i) => (
                <div key={i} className="between" style={{ fontSize: 12.5 }}>
                  <span className="mono dim">{k}</span>
                  <span className="mono" style={{ color: i === 2 ? "var(--primary)" : "var(--text)", minWidth: 0, flexShrink: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v}</span>
                </div>
              ))}
            </div>
            <div className="row" style={{ gap: 8, padding: "9px 11px", background: "var(--primary-dim)", border: "1px solid var(--border-2)", borderRadius: 6 }}>
              <Icon name="shield" size={15} color="var(--primary)" />
              <span className="t2" style={{ fontSize: 12 }}>No write permissions requested — the Helper <b>cannot</b> modify your tenant.</span>
            </div>
            <button className="btn btn-quiet btn-sm" onClick={onConnect} style={{ marginTop: 2 }}>
              <Icon name="key" size={13} color="var(--primary)" /> Manage connection &amp; permissions
            </button>
          </div>
        </div>

        {extensionSuggestions.length > 0 && (
          <div className="card" style={{ marginTop: 18 }}>
            <div className="between" style={{ gap: 12, marginBottom: 12 }}>
              <div>
                <SecLabel>what can i do on this page?</SecLabel>
                <div className="mono dim" style={{ fontSize: 11.5, marginTop: 6 }}>
                  {extensionContext?.pageTitle || extensionContext?.pathname || extensionContext?.pageUrl}
                </div>
              </div>
              <span className="chip cy">{extensionContext?.host || "context"}</span>
            </div>
            <div className="col" style={{ gap: 8 }}>
              {extensionSuggestions.map((item, index) => (
                <button key={index} className="between" onClick={() => onAsk({ prompt: item.prompt, useAiTutor: true, pageContext: extensionContext })} style={{
                  padding: "12px 14px", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 8,
                  textAlign: "left", cursor: "pointer", gap: 12
                }}>
                  <div>
                    <div style={{ fontSize: 13.5, color: "var(--text)" }}>{item.title}</div>
                    <div className="mono" style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 4 }}>{item.detail}</div>
                  </div>
                  <Icon name="arrow" size={15} color="var(--primary)" />
                </button>
              ))}
            </div>
          </div>
        )}

        {/* stats */}
        <div style={{ marginTop: 26 }}>
          <SecLabel>tenant at a glance</SecLabel>
          {summaryError ? (
            <div className="mono" style={{ fontSize: 12, color: "var(--warn)", marginTop: 10 }}>{summaryError}</div>
          ) : null}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 12, marginTop: 13 }}>
            {statCards.map((s, i) => (
              <div key={i} className="card stat hover" style={{ padding: "16px 15px" }}>
                <div className="num">{s.num ?? "-"}</div>
                <div className="lab">{s.lab}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 6 }}>{s.sub}</div>
              </div>
            ))}
          </div>
        </div>

        {/* two columns: suggested + activity */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginTop: 26 }}>
          {/* suggested tasks */}
          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--border)" }}>
              <SecLabel>learn from your tenant</SecLabel>
              <div className="mono dim" style={{ fontSize: 12, marginTop: 6 }}>Live recommendations generated from your current tenant numbers.</div>
            </div>
            <div className="col">
              {insights.map((it, i) => (
                <button key={i} className="between" onClick={() => onAsk({ prompt: it.prompt, scenarioId: it.sid })} style={{
                  padding: "13px 18px", borderBottom: i < insights.length - 1 ? "1px solid var(--border)" : "none",
                  background: "transparent", cursor: "pointer", textAlign: "left", gap: 12,
                  transition: "background .14s"
                }} onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, color: "var(--text)" }}>{it.prompt}</div>
                    <div className="mono" style={{ fontSize: 11.5, color: "var(--gold)", marginTop: 4 }}>↳ {it.why}</div>
                  </div>
                  <Icon name="arrow" size={15} color="var(--text-dim)" />
                </button>
              ))}
            </div>
          </div>

          {/* live snapshot */}
          <div className="card" style={{ padding: 0 }}>
            <div className="between" style={{ padding: "16px 18px", borderBottom: "1px solid var(--border)" }}>
              <SecLabel>live tenant snapshot</SecLabel>
              <span className="live"><span className="dot on" /> read-only</span>
            </div>
            <div className="col">
              {[
                { title: "Directory users", detail: `${metrics.users ?? "-"} member users`, tag: "users" },
                { title: "External guests", detail: `${metrics.guests ?? "-"} guest users`, tag: "guests" },
                { title: "Conditional Access", detail: `${metrics.conditionalAccessPolicies ?? "-"} policies detected`, tag: "security" },
                { title: "Service announcements", detail: `${metrics.serviceMessages ?? "-"} current messages`, tag: "ops" },
              ].map((a, i) => (
                <div key={i} className="between" style={{ padding: "12px 18px", borderBottom: i < 3 ? "1px solid var(--border)" : "none", gap: 12 }}>
                  <div className="row" style={{ gap: 11, minWidth: 0 }}>
                    <Icon name="book" size={15} color="var(--violet)" />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.title}</div>
                      <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 3 }}>{a.detail}</div>
                    </div>
                  </div>
                  <span className="chip" style={{ flexShrink: 0 }}>{a.tag}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card" style={{ marginTop: 18 }}>
          <div className="between" style={{ marginBottom: 12 }}>
            <SecLabel>official microsoft learn links</SecLabel>
            <span className="chip cy">learn.microsoft.com</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 10 }}>
            {(topics.length ? topics : [{ key: "none", title: "No topics loaded yet", url: "https://learn.microsoft.com" }]).map((topic) => (
              <a
                key={topic.key}
                href={topic.url}
                target="_blank"
                rel="noopener"
                className="card hover"
                style={{ textDecoration: "none", padding: "12px 13px", display: "block" }}
              >
                <div className="row" style={{ justifyContent: "space-between", gap: 12 }}>
                  <span style={{ color: "var(--text)", fontSize: 13.5 }}>{topic.title}</span>
                  <Icon name="arrow" size={14} color="var(--primary)" />
                </div>
              </a>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeView });
