// OpenClaw Detector - Static HTML JavaScript

// Mock endpoint data (used when opening template locally without injected data)
const MOCK_ENDPOINTS = {
  "laptop-023": {
    name: "laptop-023",
    user: "j.smith",
    osType: "macOS",
    firstDetected: "Feb 1, 2026 10:14",
    lastSeen: "Feb 4, 2026 09:02",
    evidence: "Docker: openclaw",
    edrSource: "CrowdStrike",
    status: "Installed",
    installationEvidence: {
      commandline: "Docker container `openclaw`",
      path: "~/.openclaw/",
      confidence: "High",
    },
    skills: ["web-browsing", "filesystem-access", "slack-notify"],
  },
  "prod-vm-12": {
    name: "prod-vm-12",
    user: "svc-agent",
    osType: "Linux",
    firstDetected: "Jan 28, 2026 16:40",
    lastSeen: "Feb 3, 2026 22:11",
    evidence: "~/.openclaw",
    edrSource: "SentinelOne",
    status: "Installed",
    installationEvidence: {
      commandline: "Configuration directory",
      path: "~/.openclaw/config",
      confidence: "High",
    },
    skills: [
      "os-command",
      "sql-data-analyzer",
      "python-data-tools",
      "github-pr",
    ],
  },
  "dev-ws-007": {
    name: "dev-ws-007",
    user: "a.johnson",
    osType: "Windows",
    firstDetected: "Feb 2, 2026 09:00",
    lastSeen: "Feb 4, 2026 11:30",
    evidence: "npm: @openclaw/cli",
    edrSource: "Defender",
    status: "Installed",
    installationEvidence: {
      commandline: "NPM package @openclaw/cli",
      path: "/home/ajohnson/node_modules/@openclaw",
      confidence: "High",
    },
    skills: ["filesystem-access", "github-pr", "notion-sync", "linear-issues"],
  },
  "staging-01": {
    name: "staging-01",
    user: "deploy-bot",
    osType: "Linux",
    firstDetected: "Jan 30, 2026 14:22",
    lastSeen: "Feb 4, 2026 08:45",
    evidence: "Process: openclaw-agent",
    edrSource: "CrowdStrike",
    status: "Installed",
    installationEvidence: {
      commandline: "Running process `openclaw-agent`",
      path: "/opt/openclaw/",
      confidence: "High",
    },
    skills: ["os-command", "python-data-tools", "email-automation"],
  },
  "workstation-15": {
    name: "workstation-15",
    user: "m.chen",
    osType: "Windows",
    firstDetected: "Feb 3, 2026 16:00",
    lastSeen: "Feb 3, 2026 16:05",
    evidence: "Suspicious network traffic",
    edrSource: "SentinelOne",
    status: "Suspected",
    installationEvidence: {
      commandline: "Outbound connection to openclaw.io",
      path: "N/A",
      confidence: "Medium",
    },
    skills: [],
  },
  "qa-machine-03": {
    name: "qa-machine-03",
    user: "test-user",
    osType: "macOS",
    firstDetected: "Feb 1, 2026 11:00",
    lastSeen: "Feb 2, 2026 15:30",
    evidence: "Config file detected",
    edrSource: "Defender",
    status: "Suspected",
    installationEvidence: {
      commandline: "openclaw.config.json",
      path: "~/projects/test-app/",
      confidence: "Low",
    },
    skills: [],
  },
};

// Use injected report data when present (from generator), otherwise mock data for local preview
const endpoints =
  typeof window.REPORT_ENDPOINTS !== "undefined" &&
  Object.keys(window.REPORT_ENDPOINTS || {}).length > 0
    ? window.REPORT_ENDPOINTS
    : MOCK_ENDPOINTS;

// Theme toggle
const themeToggle = document.getElementById("themeToggle");
themeToggle.addEventListener("click", () => {
  document.documentElement.classList.toggle("dark");
  localStorage.setItem(
    "theme",
    document.documentElement.classList.contains("dark") ? "dark" : "light",
  );
});

// Load saved theme
if (localStorage.getItem("theme") === "light") {
  document.documentElement.classList.remove("dark");
} else {
  document.documentElement.classList.add("dark");
}

// Track which endpoint is shown so we can return from Remediation Guide
let currentDrawerEndpointId = null;

// Drawer functions
function openDrawer(endpointId) {
  const endpoint = endpoints[endpointId];
  if (!endpoint) return;

  currentDrawerEndpointId = endpointId;

  const drawer = document.getElementById("drawer");
  const overlay = document.getElementById("drawerOverlay");
  const title = document.getElementById("drawerTitle");
  const content = document.getElementById("drawerContent");

  title.textContent = endpoint.name;
  content.innerHTML = generateDrawerContent(endpoint);

  drawer.classList.add("open");
  overlay.classList.add("open");
  document.body.style.overflow = "hidden";
}

function openRemediationGuide() {
  const title = document.getElementById("drawerTitle");
  const content = document.getElementById("drawerContent");
  title.textContent = "Remediation Guide";
  content.innerHTML = getRemediationGuideContent();
}

function backToEndpointDetails() {
  if (currentDrawerEndpointId == null) return;
  const endpoint = endpoints[currentDrawerEndpointId];
  if (!endpoint) return;
  const title = document.getElementById("drawerTitle");
  const content = document.getElementById("drawerContent");
  title.textContent = endpoint.name;
  content.innerHTML = generateDrawerContent(endpoint);
}

function getRemediationGuideContent() {
  return `
    <button type="button" class="btn-back" onclick="backToEndpointDetails()">
      <svg class="icon icon-sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"></polyline></svg>
      Back to endpoint details
    </button>
    <div class="remediation-guide">
      <p class="remediation-intro">Follow these steps to safely remove the OpenClaw AI agent and contain the threat on the affected endpoint.</p>
      <ol class="remediation-steps">
        <li class="remediation-step">
          <strong>Isolate the endpoint</strong> — Disconnect the device from the network (or move it to an isolated VLAN) to prevent further lateral movement or data exfiltration while you remediate.
        </li>
        <li class="remediation-step">
          <strong>Terminate OpenClaw processes</strong> — Use your EDR console or local task manager to kill any running OpenClaw-related processes (e.g. <code>openclaw</code>, <code>openclaw-agent</code>). Check for child processes and background services.
        </li>
        <li class="remediation-step">
          <strong>Remove installation artifacts</strong> — Delete the installation directory and config files (paths may include <code>~/.openclaw</code>, <code>AppData\\Local\\openclaw</code>, or <code>/opt/openclaw</code>). Remove any scheduled tasks, cron jobs, or launch agents that persist the agent.
        </li>
        <li class="remediation-step">
          <strong>Revoke credentials and API keys</strong> — Invalidate any API keys, tokens, or service accounts that the OpenClaw agent may have used (e.g. cloud providers, Slack, GitHub, email). Rotate user passwords if the agent had access to sensitive credentials.
        </li>
        <li class="remediation-step">
          <strong>Review and contain impact</strong> — Check audit logs, EDR alerts, and access logs for actions performed by the agent (files accessed, commands run, data sent). Notify affected teams and apply additional containment if needed.
        </li>
        <li class="remediation-step">
          <strong>Re-image or harden the endpoint</strong> — Consider re-imaging the machine for high-confidence compromises, or run a full AV/EDR scan and apply security updates before reconnecting to the network.
        </li>
        <li class="remediation-step">
          <strong>Communicate policy to the end user</strong> — Inform the end user that OpenClaw is not approved for use in the organization because it can introduce security, compliance, and data exposure risk (including unauthorized access to internal systems and possible exfiltration of sensitive data). Direct the user to use only approved AI tools and to request alternatives through IT/Security.
        </li>
      </ol>
      <p class="remediation-note">For environment-specific or approved procedures, refer to your organization’s incident response playbook.</p>
    </div>
  `;
}

function closeDrawer() {
  const drawer = document.getElementById("drawer");
  const overlay = document.getElementById("drawerOverlay");

  drawer.classList.remove("open");
  overlay.classList.remove("open");
  document.body.style.overflow = "";
}

function generateDrawerContent(endpoint) {
  const name = endpoint.name ?? endpoint.endpoint ?? "—";
  const user = endpoint.user ?? endpoint.username ?? "—";
  const osType = endpoint.osType ?? endpoint.os ?? "—";
  const edrSource = endpoint.edrSource ?? endpoint.edr_source ?? "—";
  const lastSeen = endpoint.lastSeen ?? endpoint.last_seen ?? "—";
  const ev =
    endpoint.installationEvidence ?? endpoint.installation_evidence ?? {};
  const commandline = ev.commandline ?? ev.found ?? "—";
  const commandlineEscaped = String(commandline)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");

  return `
      <div class="detail-section">
        <h3>Overview</h3>
        <div class="detail-row">
          <span class="detail-label">Endpoint</span>
          <span class="detail-value">${name}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">User</span>
          <span class="detail-value">${user}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">OS</span>
          <span class="detail-value">${osType}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">EDR Source</span>
          <span class="detail-value">${edrSource}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">Last Seen</span>
          <span class="detail-value">${lastSeen}</span>
        </div>
        <div class="detail-row detail-row-block">
          <span class="detail-label">Last Match</span>
          <code class="detail-value-code">${commandlineEscaped}</code>
        </div>
      </div>
      <div class="drawer-footer-actions">
        <button type="button" class="btn-remediation" onclick="openRemediationGuide()">
          Remediation Guide
        </button>
      </div>
    `;
}

// Close drawer on Escape key
document.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    closeDrawer();
  }
});
