const { useState, useEffect, useRef, useCallback, useMemo } = React;

const ROLE_TREE = {
  purple: {
    key: "purple",
    label: "Purple Team",
    icon: "fas fa-eye",
    cssClass: "purple",
  },
  red: {
    key: "red",
    label: "Red Team",
    icon: "fas fa-bullseye",
    cssClass: "red",
    children: ["pentesting", "web", "bugbounty", "network", "se", "exploitdev", "re", "hardware", "ctf", "aipentest", "malwaredev", "vulnres", "automotive", "space"],
  },
  blue: {
    key: "blue",
    label: "Blue Team",
    icon: "fas fa-shield-alt",
    cssClass: "blue",
    children: ["soc", "forensics", "threathunt", "threatintel", "ir", "appsec", "cloudsec", "gsoc", "secauto", "grc", "osint", "medical", "malware"],
  },
};

const getRoleTeam = (key) => {
  if (key === "red") return "red";
  if (key === "blue") return "blue";
  if (key === "purple") return "purple";
  if (ROLE_TREE.red.children.includes(key)) return "red";
  if (ROLE_TREE.blue.children.includes(key)) return "blue";
  return "red";
};

const DATABASE = {
  web:       { label: "Web Pentest",       icon: "fas fa-globe", data: window.CHECKLIST_WEB },
  pentesting:{ label: "Penetration Testing", icon: "fas fa-file-contract", data: window.CHECKLIST_PENTESTING },
  bugbounty: { label: "Bug Bounty",        icon: "fas fa-crosshairs", data: window.CHECKLIST_BUGBOUNTY },
  malware:   { label: "Malware Analysis",  icon: "fas fa-biohazard", data: window.CHECKLIST_MALWARE },
  network:   { label: "Network Pentest",   icon: "fas fa-satellite-dish", data: window.CHECKLIST_NETWORK },
  se:        { label: "Social Engineering", icon: "fas fa-user-secret", data: window.CHECKLIST_SOCIAL_ENGINEERING },
  exploitdev:{ label: "Exploit Dev",       icon: "fas fa-terminal", data: window.CHECKLIST_EXPLOIT_DEV },
  re:        { label: "Reverse Engineering", icon: "fas fa-cogs", data: window.CHECKLIST_RE },
  hardware:  { label: "Hardware Hacking",  icon: "fas fa-bolt", data: window.CHECKLIST_HARDWARE },
  ctf:       { label: "CTF Player",        icon: "fas fa-flag", data: window.CHECKLIST_CTF },
  blue:      { label: "Blue Team",         icon: "fas fa-shield-alt", data: window.CHECKLIST_BLUE },
  red:       { label: "Red Team",          icon: "fas fa-bullseye", data: window.CHECKLIST_RED },
  purple:    { label: "Purple Team",       icon: "fas fa-eye", data: window.CHECKLIST_PURPLE },
  forensics: { label: "Digital Forensics", icon: "fas fa-balance-scale", data: window.CHECKLIST_FORENSICS },
  soc:       { label: "SOC Analyst",       icon: "fas fa-desktop", data: window.CHECKLIST_SOC_ANALYST },
  appsec:    { label: "AppSec Engineer",   icon: "fas fa-code", data: window.CHECKLIST_APPSEC },
  threatintel:{ label: "Threat Intelligence", icon: "fas fa-brain", data: window.CHECKLIST_THREAT_INTEL },
  ir:        { label: "Incident Response", icon: "fas fa-fire-extinguisher", data: window.CHECKLIST_INCIDENT_RESPONSE },
  threathunt:{ label: "Threat Hunting",    icon: "fas fa-search", data: window.CHECKLIST_THREAT_HUNTING },
  vulnres:   { label: "Vuln Research",     icon: "fas fa-microscope", data: window.CHECKLIST_VULN_RESEARCH },
  automotive:{ label: "Automotive Security", icon: "fas fa-car", data: window.CHECKLIST_AUTOMOTIVE },
  space:     { label: "Space Security",    icon: "fas fa-rocket", data: window.CHECKLIST_SPACE },
  medical:   { label: "Medical Device Security", icon: "fas fa-heartbeat", data: window.CHECKLIST_MEDICAL },
  cloudsec:  { label: "Cloud Security", icon: "fas fa-cloud", data: window.CHECKLIST_CLOUD_SECURITY },
  grc:       { label: "GRC",               icon: "fas fa-clipboard-check", data: window.CHECKLIST_GRC },
  osint:     { label: "OSINT",             icon: "fas fa-globe-americas", data: window.CHECKLIST_OSINT },
  malwaredev:{ label: "Malware Dev",       icon: "fas fa-virus", data: window.CHECKLIST_MALWARE_DEV },
  secauto:   { label: "Security Automation", icon: "fas fa-robot", data: window.CHECKLIST_SECURITY_AUTO },
  gsoc:      { label: "GSOC",              icon: "fas fa-globe", data: window.CHECKLIST_GSOC },
  aipentest: { label: "AI Pentesting",     icon: "fas fa-brain", data: window.CHECKLIST_AI_PENTESTING },
};

const SEVERITY_COLORS = {
  critical: { bg: "#fdfaf1", border: "#e14e2c", text: "#e14e2c", badge: "#e14e2c" },
  high:     { bg: "#fdfaf1", border: "#ffda47", text: "#ffda47", badge: "#ffda47" },
  low:      { bg: "#fdfaf1", border: "#5cd19c", text: "#5cd19c", badge: "#5cd19c" },
  info:     { bg: "#fdfaf1", border: "#000000", text: "#000000", badge: "#000000" },
};

function collectLeafIds(node) {
  if (!node.children) return [node.id];
  return node.children.flatMap(collectLeafIds);
}

function CustomModal({ title, content, onOk, onCancel, okText = "Confirm", cancelText = "Cancel" }) {
  return (
    <div className="custom-modal-overlay" onClick={onCancel}>
      <div className="custom-modal" onClick={e => e.stopPropagation()}>
        <div className="custom-modal-title">
          <i className="fas fa-exclamation-triangle" /> {title}
        </div>
        <div className="custom-modal-content" dangerouslySetInnerHTML={{ __html: content }} />
        <div className="custom-modal-actions">
          <button className="modal-btn modal-btn-cancel" onClick={onCancel}>{cancelText}</button>
          <button className="modal-btn modal-btn-ok" onClick={onOk}>{okText}</button>
        </div>
      </div>
    </div>
  );
}

function TreeNode({ node, checked, onToggle, onTogglePhase, depth = 0, phaseIndex = -1, activePhaseIndex = 0 }) {
  const isLeaf = !node.children;
  const [open, setOpen] = useState(false);
  const [userToggled, setUserToggled] = useState(false);
  const leaves = collectLeafIds(node);
  const checkedCount = leaves.filter(id => checked[id]).length;
  const total = leaves.length;
  const allDone = total > 0 && checkedCount === total;
  const sc = SEVERITY_COLORS[node.severity] || null;

  useEffect(() => {
    if (depth !== 0) return;
    if (!userToggled) {
      setOpen(phaseIndex === activePhaseIndex);
    }
  }, [activePhaseIndex, phaseIndex, depth, userToggled]);

  const handleToggle = useCallback(() => {
    setOpen(o => !o);
    setUserToggled(true);
  }, []);

  if (isLeaf) {
    return (
      <div
        className="tree-leaf"
        style={{
          display: "flex", alignItems: "flex-start", gap: "10px",
          padding: "10px 15px",
          marginLeft: `${depth * 20}px`,
          border: "3px solid #000",
          background: checked[node.id] ? "var(--secondary)" : "var(--white)",
          boxShadow: checked[node.id] ? "2px 2px 0px 0px #000" : "4px 4px 0px 0px #000",
          marginBottom: "10px",
          borderRadius: "var(--radius)",
          cursor: "pointer",
          transition: "all 0.1s"
        }}
        onClick={() => onToggle(node.id)}
      >
        <div style={{
          width: "20px", height: "20px", minWidth: "20px",
          border: `3px solid #000`,
          borderRadius: "5px",
          background: checked[node.id] ? "#000" : "var(--white)",
          display: "flex", alignItems: "center", justifyContent: "center",
          marginTop: "1px"
        }}>
          {checked[node.id] && <span style={{ color: "var(--secondary)", fontSize: "13px", fontWeight: "900" }}>✓</span>}
        </div>
        <span style={{
          color: "#000",
          fontSize: "13px",
          fontWeight: "700",
          textDecoration: checked[node.id] ? "line-through" : "none",
          fontFamily: "var(--font-mono)",
        }}>{node.label}</span>
      </div>
    );
  }

  return (
    <div style={{ marginBottom: "18px" }}>
      <div style={{
        display: "flex", alignItems: "center", gap: "12px",
        padding: "14px 18px",
        borderRadius: "var(--radius)",
        cursor: "pointer",
        background: depth === 0 ? "var(--white)" : "var(--white)",
        border: depth === 0 && sc ? `4px solid ${sc.border}` : "3px solid #000",
        boxShadow: depth === 0 ? "var(--shadow)" : "4px 4px 0px 0px #000",
        marginBottom: "12px",
        userSelect: "none",
        transition: "all 0.2s"
      }}
        onClick={() => depth === 0 && handleToggle()}
      >
        {depth === 0 ? (
          <div
            onClick={(e) => { e.stopPropagation(); onTogglePhase(node.id, leaves, allDone); }}
            style={{
              width: "24px", height: "24px", minWidth: "24px",
              border: `3px solid #000`,
              borderRadius: "6px",
              background: allDone ? "#000" : "var(--white)",
              display: "flex", alignItems: "center", justifyContent: "center",
              cursor: "pointer",
              transition: "all 0.15s"
            }}
          >
            {allDone && <span style={{ color: "var(--secondary)", fontSize: "14px", fontWeight: "900" }}>✓</span>}
          </div>
        ) : null}

        <span
          onClick={(e) => { e.stopPropagation(); handleToggle(); }}
          style={{
            fontSize: "13px",
            transition: "transform 0.2s",
            display: "inline-block",
            transform: open ? "rotate(90deg)" : "rotate(0deg)",
            fontWeight: "900",
            cursor: "pointer"
          }}
        >▶</span>

        {depth === 0 && node.icon && (
          <i className={node.icon} style={{ fontSize: "18px", color: "#000" }} />
        )}

        <span style={{
          fontWeight: "900",
          fontSize: depth === 0 ? "1.1rem" : "0.95rem",
          flex: 1,
          cursor: "pointer"
        }} onClick={(e) => { e.stopPropagation(); handleToggle(); }}>{node.label}</span>

        <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
          {depth === 0 && sc && (
            <span style={{
                background: sc.badge, color: "#fff",
                fontSize: "9px", padding: "2px 7px", borderRadius: "4px",
                fontWeight: "900", textTransform: "uppercase"
            }}>{node.severity}</span>
          )}
          <span style={{
            background: allDone ? "var(--secondary)" : "var(--white)",
            border: "2px solid #000",
            padding: "2px 8px", borderRadius: "5px", fontSize: "11px", fontWeight: "900"
          }}>{checkedCount}/{total}</span>
        </div>
      </div>

      {open && (
        <div style={{
          paddingLeft: "20px",
          borderLeft: "4px solid #000",
          marginLeft: "18px"
        }}>
          {node.children.map(child => (
            <TreeNode key={child.id} node={child} checked={checked} onToggle={onToggle} onTogglePhase={onTogglePhase} depth={depth + 1} phaseIndex={phaseIndex} activePhaseIndex={activePhaseIndex} />
          ))}
        </div>
      )}
    </div>
  );
}

function ProgressSidebar({ pct, onExit }) {
  const gradientColors = pct < 25
    ? "linear-gradient(to top, #e14e2c, #ffda47)"
    : pct < 50
    ? "linear-gradient(to top, #e14e2c, #ffda47, #f0a500)"
    : pct < 75
    ? "linear-gradient(to top, #e14e2c, #ffda47, #f0a500, #5cd19c)"
    : "linear-gradient(to top, #e14e2c, #ffda47, #f0a500, #5cd19c, #00c853)";

  return (
    <div className="progress-sidebar">
      <div className="progress-label">Progress</div>
      <div className="progress-bar-track">
        <div className="progress-bar-fill" style={{ height: `${pct}%`, background: gradientColors }} />
      </div>
      <div className="progress-circle">
        <span key={pct} style={{ animation: "popIn 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)" }}>{pct}</span>
      </div>
      <button className="progress-exit-btn" onClick={onExit} title="Back to Roles">
        <i className="fas fa-exclamation"></i>
      </button>
    </div>
  );
}

function PentestChecklist() {
  const [role, setRole] = useState(() => localStorage.getItem('0warn_checklist_role') || null);
  const [ptScopes, setPtScopes] = useState(() => {
    const saved = localStorage.getItem('0warn_checklist_pt_scopes');
    return saved ? JSON.parse(saved) : [];
  });
  const [checked, setChecked] = useState(() => {
    if (!role) return {};
    const saved = localStorage.getItem(`0warn_checklist_progress_${role}`);
    return saved ? JSON.parse(saved) : {};
  });
  const [target, setTarget] = useState(() => {
    if (!role) return "";
    return localStorage.getItem(`0warn_checklist_target_${role}`) || "";
  });
  const [notes, setNotes] = useState(() => {
    if (!role) return "";
    return localStorage.getItem(`0warn_checklist_notes_${role}`) || "";
  });
  const [filter, setFilter] = useState("all");
  const [stage, setStage] = useState("roleSelect");
  const [commanderSliding, setCommanderSliding] = useState(false);
  const [hiddenRoles, setHiddenRoles] = useState(() => {
    const saved = localStorage.getItem('0warn_checklist_hidden_roles');
    return saved ? JSON.parse(saved) : [];
  });
  const [notesMode, setNotesMode] = useState("edit");

  // Custom Modal State
  const [modal, setModal] = useState({ show: false, title: "", content: "", onOk: null, type: "" });

  useEffect(() => {
    if (!role) return;
    localStorage.setItem('0warn_checklist_role', role);
    const savedChecked = localStorage.getItem(`0warn_checklist_progress_${role}`);
    setChecked(savedChecked ? JSON.parse(savedChecked) : {});
    setTarget(localStorage.getItem(`0warn_checklist_target_${role}`) || "");
    setNotes(localStorage.getItem(`0warn_checklist_notes_${role}`) || "");
  }, [role]);

  useEffect(() => {
    if (!role) return;
    localStorage.setItem(`0warn_checklist_progress_${role}`, JSON.stringify(checked));
  }, [checked, role]);

  useEffect(() => {
    if (!role) return;
    localStorage.setItem(`0warn_checklist_target_${role}`, target);
  }, [target, role]);

  useEffect(() => {
    if (!role) return;
    localStorage.setItem(`0warn_checklist_notes_${role}`, notes);
  }, [notes, role]);

  useEffect(() => {
    localStorage.setItem('0warn_checklist_pt_scopes', JSON.stringify(ptScopes));
  }, [ptScopes]);

  useEffect(() => {
    localStorage.setItem('0warn_checklist_hidden_roles', JSON.stringify(hiddenRoles));
  }, [hiddenRoles]);

  const handleRoleSelect = (key) => setRole(key);

  const handleInitializeMission = () => {
    if (!role) return;
    if (role === "pentesting") {
      setStage("scopeSelect");
    } else {
      setStage("commander");
    }
  };

  const handleConfirmScopes = () => {
    if (ptScopes.length > 0) {
      setStage("commander");
    }
  };

  const handleBackToRoles = () => setStage("roleSelect");

  const handleChooseRole = () => { setHiddenRoles([]); setRole(null); setStage("roleSelect"); };

  const handleResumeMission = (roleKey) => { setRole(roleKey); setStage("workspace"); setModal({ show: false }); };

  const handleLaunch = () => {
    setCommanderSliding(true);
    setTimeout(() => { setStage("workspace"); setCommanderSliding(false); }, 600);
  };

  const showResetModal = () => {
    setModal({
      show: true,
      title: "Confirm Reset",
      content: `Are you sure you want to reset all progress for <b>${DATABASE[role]?.label}</b>? This action cannot be undone.`,
      onOk: () => {
        setChecked({}); setTarget(""); setNotes("");
        localStorage.removeItem(`0warn_checklist_progress_${role}`);
        localStorage.removeItem(`0warn_checklist_target_${role}`);
        localStorage.removeItem(`0warn_checklist_notes_${role}`);
        localStorage.removeItem('0warn_checklist_role');
        setRole(null); setStage("roleSelect");
        setModal({ show: false });
      },
      type: "reset"
    });
  };

  const triggerResume = (key, pct) => {
    setModal({
      show: true,
      title: "Incomplete Mission Detected",
      content: `Role: <b>${DATABASE[key]?.label}</b><br>Progress: <b>${pct}%</b><br><br>Would you like to resume this mission?`,
      onOk: () => handleResumeMission(key),
      type: "resume"
    });
  };

  if (!DATABASE) return <div>Loading Database...</div>;

  let currentData = [];
  if (role === 'pentesting' && window.CHECKLIST_PENTESTING) {
    const ptData = window.CHECKLIST_PENTESTING;
    if (ptScopes.length > 0) {
      const combined = [];
      ptScopes.forEach(scopeKey => {
        if (ptData.scopes[scopeKey]) {
          ptData.scopes[scopeKey].phases.forEach(phase => combined.push(phase));
        }
      });
      currentData = combined;
    }
  } else {
    currentData = DATABASE[role]?.data || [];
  }

  const filtered = currentData && (filter === "all" ? currentData : currentData.filter(c => c.severity === filter));

  const activePhaseIndex = (() => {
    if (!filtered || filtered.length === 0) return 0;
    for (let i = 0; i < filtered.length; i++) {
      const leaves = collectLeafIds(filtered[i]);
      if (!leaves.every(id => checked[id])) return i;
    }
    return filtered.length - 1;
  })();

  const allLeaves = currentData.flatMap(collectLeafIds);
  const totalCount = allLeaves.length;
  const doneCount = allLeaves.filter(id => checked[id]).length;
  const pct = totalCount > 0 ? Math.round((doneCount / totalCount) * 100) : 0;

  const toggle = (id) => setChecked(prev => ({ ...prev, [id]: !prev[id] }));

  const togglePhase = (phaseId, leafIds, allDone) => {
    setChecked(prev => {
      const next = { ...prev };
      leafIds.forEach(id => { next[id] = !allDone; });
      return next;
    });
  };

  const toggleScope = (key) => setPtScopes(prev => prev.includes(key) ? prev.filter(s => s !== key) : [...prev, key]);
  const selectAllScopes = () => setPtScopes(Object.keys(window.CHECKLIST_PENTESTING?.scopes || {}));
  const deselectAllScopes = () => setPtScopes([]);

  const severityFilters = ["all", "critical", "high", "low", "info"];

  const savedRole = localStorage.getItem('0warn_checklist_role');
  let savedRoleInfo = null;
  if (savedRole && DATABASE[savedRole]) {
    const sChecked = localStorage.getItem(`0warn_checklist_progress_${savedRole}`);
    if (sChecked) {
      const cData = JSON.parse(sChecked);
      let rData = DATABASE[savedRole].data;
      if (savedRole === 'pentesting' && rData && rData.scopes) {
        const all = [];
        Object.values(rData.scopes).forEach(sc => { if (sc.phases) sc.phases.forEach(p => all.push(p)); });
        rData = all;
      } else if (!Array.isArray(rData)) {
        rData = [];
      }
      const lvs = rData.flatMap(collectLeafIds);
      if (lvs.length > 0) {
        const dCount = lvs.filter(id => cData[id]).length;
        const pVal = Math.round((dCount / lvs.length) * 100);
        if (pVal > 0) {
          savedRoleInfo = { key: savedRole, label: DATABASE[savedRole].label, icon: DATABASE[savedRole].icon, team: getRoleTeam(savedRole), pct: pVal, doneCount: dCount, totalCount: lvs.length };
        }
      }
    }
  }

  const redChildren = ROLE_TREE.red.children;
  const blueChildren = ROLE_TREE.blue.children;
  const redIdx = redChildren.indexOf(role);
  const blueIdx = blueChildren.indexOf(role);

  const buildGrid = (keys, team, activeIdx) => {
    const visibleKeys = keys.filter(k => !hiddenRoles.includes(k));
    return visibleKeys.map((key) => {
      const originalIdx = keys.indexOf(key);
      const isActive = originalIdx === activeIdx;

      let hasProgress = false;
      let pctValue = 0;
      const sChecked = localStorage.getItem(`0warn_checklist_progress_${key}`);
      const sTarget = localStorage.getItem(`0warn_checklist_target_${key}`);
      
      if (sChecked || sTarget) {
        const cData = sChecked ? JSON.parse(sChecked) : {};
        let rData = DATABASE[key]?.data || [];
        if (key === 'pentesting' && rData.scopes) {
          const all = [];
          Object.values(rData.scopes).forEach(sc => { if (sc.phases) sc.phases.forEach(p => all.push(p)); });
          rData = all;
        }
        if (!Array.isArray(rData)) rData = [];
        const lvs = rData.flatMap(collectLeafIds);
        const dCount = lvs.filter(id => cData[id]).length;
        pctValue = lvs.length > 0 ? Math.round((dCount / lvs.length) * 100) : 0;
        if (pctValue > 0 || (sTarget && sTarget.trim() !== "")) hasProgress = true;
      }

      return (
        <div key={key} className={`role-node-btn sub-${team} ${isActive ? "active" : ""}`} onClick={() => handleRoleSelect(key)}>
          <i className={DATABASE[key]?.icon || "fas fa-terminal"} /> {DATABASE[key]?.label || key}
          {hasProgress && (
            <div className="role-bell" onClick={(e) => { e.stopPropagation(); triggerResume(key, pctValue); }}>
              <i className="fas fa-bell" />
            </div>
          )}
        </div>
      );
    });
  };

  const roleLabel = role ? DATABASE[role]?.label : "";
  const roleIcon = role ? DATABASE[role]?.icon : "";
  const roleTeam = role ? getRoleTeam(role) : "";

  return (
    <div className="checklist-container">
      {modal.show && <CustomModal title={modal.title} content={modal.content} onOk={modal.onOk} onCancel={() => setModal({ show: false })} okText={modal.type === "resume" ? "Resume" : "Reset"} />}
      
      {stage === "roleSelect" && (
      <div className="role-select-card">
          <h2 className="section-title"><i className="fas fa-user-shield"></i> SELECT YOUR ROLE</h2>
          <div className="purple-team-center">
            {!hiddenRoles.includes("purple") && (
            <div className={`role-node-btn purple-btn ${role === "purple" ? "active" : ""}`} onClick={() => handleRoleSelect("purple")}>
              <i className={ROLE_TREE.purple.icon} /> {ROLE_TREE.purple.label}
            </div>
            )}
          </div>
          <div className="teams-grid">
            <div className="team-panel">
              <div className={`role-node-btn red-team-btn team-header-btn ${roleTeam === "red" && role === "red" ? "active" : ""}`} onClick={() => handleRoleSelect("red")}><i className={ROLE_TREE.red.icon} /> {ROLE_TREE.red.label}</div>
              <div className="team-label red-label">▾ Offensive Roles</div>
              <div className="role-grid-2col">{buildGrid(redChildren, "red", redIdx)}</div>
            </div>
            <div className="team-panel">
              <div className={`role-node-btn blue-team-btn team-header-btn ${roleTeam === "blue" && role === "blue" ? "active" : ""}`} onClick={() => handleRoleSelect("blue")}><i className={ROLE_TREE.blue.icon} /> {ROLE_TREE.blue.label}</div>
              <div className="team-label blue-label">▾ Defensive Roles</div>
              <div className="role-grid-2col">{buildGrid(blueChildren, "blue", blueIdx)}</div>
            </div>
          </div>
          {role && (
            savedRoleInfo && savedRoleInfo.key === role && savedRoleInfo.pct > 0 ? (
              <div className="active-mission-card" onClick={() => handleResumeMission(role)}>
                <div className="active-mission-header">
                  <div className="active-mission-badge">IN PROGRESS</div>
                  <div className="active-mission-pct">{savedRoleInfo.pct}%</div>
                </div>
                <div className="active-mission-body">
                  <div className="active-mission-title"><i className={roleIcon} /> {savedRoleInfo.label}</div>
                  <div className="active-mission-progress">
                    <div className="active-progress-bar"><div className="active-progress-fill" style={{ width: `${savedRoleInfo.pct}%` }} /></div>
                    <span className="active-pct-text">{savedRoleInfo.doneCount}/{savedRoleInfo.totalCount} tasks completed</span>
                  </div>
                  {target && target.trim() && <div className="active-mission-target"><i className="fas fa-crosshairs" /> {target}</div>}
                </div>
                <button className="active-mission-resume">Resume Mission <i className="fas fa-arrow-right" /></button>
              </div>
            ) : (
              <div className="init-mission-container">
                <button className="init-mission-btn" onClick={handleInitializeMission}>
                  <i className="fas fa-rocket" /> Initialize {DATABASE[role]?.label} Mission
                </button>
              </div>
            )
          )}
      </div>
      )}

      {stage === "scopeSelect" && role === 'pentesting' && window.CHECKLIST_PENTESTING && (
        <div className="scope-selector-card scope-select-overlay">
          <button className="scope-back-btn" onClick={handleBackToRoles}><i className="fas fa-arrow-left" /> BACK</button>
          <h2><i className="fas fa-crosshairs"></i> DEFINE ENGAGEMENT SCOPE</h2>
          <div className="scope-actions">
            <button className="scope-action-btn" onClick={selectAllScopes}>Select All</button>
            <button className="scope-action-btn dark" onClick={deselectAllScopes}>Deselect All</button>
          </div>
          <div className="scope-grid">
            {Object.keys(window.CHECKLIST_PENTESTING.scopes).map(key => {
              const s = window.CHECKLIST_PENTESTING.scopes[key];
              const active = ptScopes.includes(key);
              return (
                <div key={key} className={`scope-card ${active ? "active" : ""}`} onClick={() => toggleScope(key)}>
                  <div className="scope-card-header">
                    <div className="scope-check">{active && <span style={{color: "#fff", fontSize: "12px", fontWeight: "900"}}>✓</span>}</div>
                    <i className={s.icon} style={{fontSize: "16px"}} />
                    <span style={{fontWeight: "900", fontSize: "13px"}}>{s.label}</span>
                  </div>
                  <p style={{fontSize: "11px", margin: 0, opacity: 0.8, paddingLeft: "30px"}}>{s.description}</p>
                </div>
              );
            })}
          </div>
          <button className="scope-continue-btn" disabled={ptScopes.length === 0} onClick={handleConfirmScopes}>
            <i className="fas fa-arrow-right" /> Continue to Commander
          </button>
        </div>
      )}

      {stage === "commander" && role && (
        <div className={`commander-overlay ${commanderSliding ? "slide-out" : ""}`}>
          <div className="commander-inner">
            <button className="commander-back-btn" onClick={handleBackToRoles}><i className="fas fa-arrow-left" /> BACK</button>
            <div className="commander-title" style={{color: roleTeam === "red" ? "#dc2626" : "#2563eb"}}><i className={roleIcon} style={{marginRight: "12px"}} />{roleLabel}</div>
            <div className="commander-subtitle">Command Interface — Initialize Engagement Parameters</div>
            <label className="commander-label">Target / Scope / Domain</label>
            <input type="text" className="commander-input" value={target} onChange={(e) => setTarget(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && target.trim()) handleLaunch(); }} placeholder="Enter target..." autoFocus />
            <button className="commander-launch-btn" disabled={!target.trim()} onClick={handleLaunch}><i className="fas fa-rocket" /> Launch Mission</button>
          </div>
        </div>
      )}

      {stage === "workspace" && role && (
        <div className="workspace-view">
          {currentData.length > 0 && <ProgressSidebar pct={pct} onExit={handleChooseRole} />}
          <div className="workspace-main">
            <div className="workspace-top-bar">
              <h2><i className={roleIcon} style={{marginRight: "10px", color: roleTeam === "red" ? "#dc2626" : "#2563eb"}} />{roleLabel} <span style={{color: "var(--primary)"}}>Mission Objectives</span></h2>
              {target && <div className="target-line"><i className="fas fa-crosshairs" /> Target: <span style={{color: "#000", fontWeight: "700"}}>{target}</span></div>}
              <div className="severity-filters">{severityFilters.map(s => <button key={s} className={`severity-btn ${filter === s ? "active" : ""}`} onClick={() => setFilter(s)}>{s}</button>)}</div>
            </div>
            {currentData.length > 0 ? (
              <div className="objectives-box">
                <div className="objectives-box-header">
                  <i className="fas fa-list-ul" /> Mission Objectives
                </div>
                <div className="objectives-box-body">
                  {filtered.map((section, idx) => <TreeNode key={section.id} node={section} checked={checked} onToggle={toggle} onTogglePhase={togglePhase} depth={0} phaseIndex={idx} activePhaseIndex={activePhaseIndex} />)}
                </div>
              </div>
            ) : null}
          </div>
          <div className="notes-panel-fixed">
            <div className="notes-panel-header"><h4><i className="fas fa-edit" /> Field Notes</h4><div className="notes-mode-toggle"><button className={`notes-mode-btn ${notesMode === "edit" ? "active" : ""}`} onClick={() => setNotesMode("edit")}>Edit</button><button className={`notes-mode-btn ${notesMode === "preview" ? "active" : ""}`} onClick={() => setNotesMode("preview")}>Preview</button></div></div>
            <div className="notes-body">{notesMode === "edit" ? <textarea className="notes-textarea" value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="# Write findings..." /> : <div className="notes-preview" dangerouslySetInnerHTML={{__html: typeof window.marked !== 'undefined' ? window.marked.parse(notes || "*No notes yet*") : notes}} />}</div>
            <div className="notes-panel-footer"><div className="notes-actions"><button className="notes-btn-reset" onClick={showResetModal}>Reset Progress</button></div><div className="notes-progress"><span className="notes-pct-value">{pct}%</span><span className="notes-pct-label">{doneCount}/{totalCount} tasks</span></div></div>
          </div>
        </div>
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('checklist-root'));
root.render(<PentestChecklist />);
