/* BasedMTA — Panels batch 2: Scripts, Resources, Events */

const { useState: useState2, useEffect: useEffect2, useMemo: useMemo2 } = React;

// ====================================================================
// SCRIPTS PANEL
// ====================================================================
const SCRIPT_TREE = [
{ name: "cheats", count: 2, dots: 2, children: [
  { name: "__loadstring/", folder: true },
  { name: "chunk_9206da70599b82ca.luac", size: "1.5K" }]
},
{ name: "cinezone", count: 1, dots: 1 },
{ name: "ingame-map-editor", count: 1, dots: 1 },
{ name: "mcafee", count: 1, dots: 1, children: [
  { name: "__loadstring/", folder: true },
  { name: "chunk_177f201f2024647e.luac", size: "4.6K", selected: true }]
},
{ name: "mfker", count: 2, dots: 2 },
{ name: "misc", count: 2, dots: 2 },
{ name: "punish", count: 1, dots: 1 },
{ name: "skidmarks", count: 6, dots: 2, children: [
  { name: "__loadstring/", folder: true },
  { name: "chunk_b524aabf8c3207a7.luac", size: "1.6K" },
  { name: "chunk_fb8969da6b301901.luac", size: "4.6K" },
  { name: "chunk_da7d1c70303d13af.luac", size: "2.7K" }]
}];


const MCAFEE_DECOMPILED = `        end
    for r6_pr1, r7_pr1 in ipairs(r2_pr1) do
      if r1_pr1 == r7_pr1 then
        return true
      end
    end
    return false
  end
  local r3_rt = addDebugHook("preFunction", function(r0_pr2, r1_pr2, r2_pr2, r3_pr2, r4_pr)
    if mcMainAuthorize(r1_pr2, getResourceName(r0_pr2)) then
      return
    end
    triggerServerEvent("mcafee.violation", resourceRoot, getResourceName(r0_pr2), r1_pr2)
  end, r1_rt)
  if not r3_rt or type(r3_rt) ~= "boolean" then
    triggerServerEvent("mcafee.violation", resourceRoot, getResourceName(resource), "addD")
  end
  local r4_rt = {
    "load",
    "loadstring",
    "executeBrowserJavascript",
    "triggerLatentServerEvent",
    "triggerServerEvent"
  }
  local r5_rt = addDebugHook("preFunction", function(r0_pr3, r1_pr3, r2_pr3, r3_pr3, r4_p)
    triggerServerEvent("mcafee.validate", resourceRoot, getResourceName(r0_pr3), r1_pr3)
      ...
    })
  end, r4_rt)
  if not r5_rt or type(r5_rt) ~= "boolean" then
    triggerServerEvent("mcafee.violation", resourceRoot, getResourceName(resource), "addD")
  end`;

function ScriptsPanel() {
  const [filterTab, setFilterTab] = useState2("Compiled");
  const [search, setSearch] = useState2("");
  const [expanded, setExpanded] = useState2({ cheats: true, mcafee: true, skidmarks: true });
  const [selected, setSelected] = useState2("chunk_177f201f2024647e.luac");

  const toggle = (n) => setExpanded((e) => ({ ...e, [n]: !e[n] }));

  const filtered = SCRIPT_TREE.filter(
    (r) => !search || r.name.toLowerCase().includes(search.toLowerCase()) ||
    (r.children || []).some((c) => c.name.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div>
      <div style={{ display: "flex", gap: 16, color: "var(--bmta-text-dim)", marginBottom: 6, fontSize: 12 }}>
        <span style={{ color: "var(--bmta-accent)" }}>208 resources</span>
        <span><span className="bmta-dot info" />10 compiled</span>
        <span><span className="bmta-dot info" />368 source</span>
      </div>
      <div style={{ display: "flex", gap: 0, marginBottom: 6 }}>
        {["All", "Compiled", "Source"].map((t) =>
        <div
          key={t}
          onClick={() => setFilterTab(t)}
          className={"bmta-subtab" + (t === filterTab ? " active" : "")}
          style={{ paddingLeft: 14, paddingRight: 14 }}>
          {t}</div>
        )}
        <div style={{ flex: 1, marginLeft: 8 }}>
          <BmtaInput placeholder="Search resources and files…" value={search} onChange={setSearch} />
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "260px minmax(0, 1fr)", gap: 8, height: 410 }}>
        <div style={{ background: "var(--bmta-bg-2)", border: "1px solid var(--bmta-border)", overflow: "auto", fontSize: 12, minWidth: 0 }}>
          {filtered.map((r) =>
          <div key={r.name}>
              <div
              onClick={() => toggle(r.name)}
              style={{ display: "flex", alignItems: "center", padding: "3px 6px", cursor: "pointer", color: "var(--bmta-text-strong)" }}>
              
                <span style={{ color: "var(--bmta-text-faint)", width: 12 }}>{r.children ? expanded[r.name] ? "v" : ">" : ""}</span>
                <span style={{ marginRight: 4 }}>{"●".repeat(r.dots)}</span>
                <span style={{ flex: 1, color: r.name === "mcafee" ? "var(--bmta-text-strong)" : "var(--bmta-text)" }}>{r.name}</span>
                <span style={{ color: "var(--bmta-text-faint)" }}>{r.count}</span>
              </div>
              {r.children && expanded[r.name] && r.children.map((c, i) =>
            <div
              key={i}
              onClick={() => !c.folder && setSelected(c.name)}
              style={{
                display: "flex", padding: "2px 6px 2px 28px", cursor: c.folder ? "default" : "pointer",
                color: c.folder ? "var(--bmta-text-faint)" : c.name === selected ? "var(--bmta-accent)" : "var(--bmta-text)",
                background: c.name === selected ? "var(--bmta-accent-soft)" : "transparent"
              }}>
              
                  {!c.folder && <span style={{ color: "var(--bmta-accent)", marginRight: 6 }}>●</span>}
                  <span style={{ flex: 1 }}>{c.name}</span>
                  {c.size && <span style={{ color: "var(--bmta-text-faint)" }}>{c.size}</span>}
                </div>
            )}
            </div>
          )}
        </div>

        <div style={{ background: "var(--bmta-bg-2)", border: "1px solid var(--bmta-border)", display: "flex", flexDirection: "column", minWidth: 0, minHeight: 0, overflow: "hidden" }}>
          <div style={{ display: "flex", gap: 14, padding: "5px 8px", borderBottom: "1px solid var(--bmta-border)", fontSize: 12, color: "var(--bmta-text-dim)", flexShrink: 0 }}>
            <span style={{ color: "var(--bmta-text-strong)" }}>__loadstring/{selected}</span>
            <span>4.6 KB</span>
            <span>|</span>
            <span>217 lines</span>
            <span>|</span>
            <span style={{ color: "var(--bmta-warn)" }}>decompiled</span>
          </div>
          <div className="bmta-code" style={{ flex: 1, overflow: "auto", padding: "6px 8px", fontSize: 12, minWidth: 0, minHeight: 0 }}>
            {MCAFEE_DECOMPILED.split("\n").map((line, i) =>
            <div key={i}>
                <span className="ln">{String(184 + i).padStart(3, " ")}</span>
                <span dangerouslySetInnerHTML={{ __html: colorLua(line) }} />
              </div>
            )}
          </div>
        </div>
      </div>

      <div style={{ display: "flex", gap: 6, marginTop: 8, alignItems: "center" }}>
        <BmtaButton>Copy to Clipboard</BmtaButton>
        <BmtaButton>Export Script</BmtaButton>
        <BmtaButton>Export Resource</BmtaButton>
        <BmtaButton variant="green">Export All</BmtaButton>
        <span style={{ color: "var(--bmta-text-faint)", marginLeft: 6 }}>→ C:\BasedMTA_Dump</span>
      </div>
    </div>);

}

function colorLua(line) {
  const KW = /\b(local|function|end|if|then|else|for|in|do|return|true|false|nil|and|or|not|while)\b/g;
  const FN = /\b(triggerServerEvent|getResourceName|addDebugHook|ipairs|pairs|type|load|loadstring|executeBrowserJavascript|triggerLatentServerEvent|mcMainAuthorize|addEventHandler)\b/g;
  const STR = /(".*?")/g;
  const NUM = /\b(\d+(?:\.\d+)?)\b/g;
  const COM = /(--[^\n]*)/g;
  const VAR = /\b(r\d+_\w+|resourceRoot|resource)\b/g;
  return line.
  replace(/&/g, "&amp;").
  replace(/</g, "&lt;").
  replace(/>/g, "&gt;").
  replace(COM, '<span class="com">$1</span>').
  replace(STR, '<span class="str">$1</span>').
  replace(KW, '<span class="kw">$1</span>').
  replace(FN, '<span class="fn">$1</span>').
  replace(VAR, '<span class="var">$1</span>').
  replace(NUM, '<span class="num">$1</span>');
}

// ====================================================================
// RESOURCES PANEL
// ====================================================================
const RESOURCE_NAMES = [
"NRGmod", "admin", "adminfeatures", "admingod", "ae86", "agentskin", "airbomb", "aircraftkillcam",
"airtarg", "airvel", "akina", "alienpack", "alpha", "amogus-car", "antiHipfire", "area_zombies",
"at400", "autobusmod", "backtoschool", "bansh", "bentley", "blimp", "bloodharvest", "bloodpool",
"bouncingbetty", "bounty_hunt", "cheats", "cinezone", "mcafee", "mfker", "misc", "punish",
"skidmarks", "ingame-map-editor", "voice_frp", "disabledm", "logmanager", "hedit"];

function ResourcesPanel() {
  const [search, setSearch] = useState2("");
  const [running, setRunning] = useState2(() => Object.fromEntries(RESOURCE_NAMES.map((n) => [n, true])));
  const total = RESOURCE_NAMES.length;
  const live = Object.values(running).filter(Boolean).length;
  const list = RESOURCE_NAMES.filter((n) => n.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="bmta-panel">
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8 }}>
        <span style={{ color: "var(--bmta-accent)" }}>{total} resources</span>
        <span><span className="bmta-dot ok" />{live} running</span>
        <div style={{ flex: 1 }} />
        <BmtaButton variant="ghost">Refresh</BmtaButton>
      </div>
      <div style={{ marginBottom: 8 }}>
        <BmtaInput placeholder="Search resources…" value={search} onChange={setSearch} />
      </div>
      <div style={{ background: "var(--bmta-bg-2)", border: "1px solid var(--bmta-border)", flex: 1, overflow: "auto" }}>
        {list.map((n) => {
          const on = !!running[n];
          return (
            <div key={n} style={{ display: "flex", gap: 8, padding: "4px 12px", alignItems: "center", borderBottom: "1px solid rgba(255,255,255,0.02)" }}>
              <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                <span className={"bmta-dot " + (on ? "ok" : "bad")} />{n}
              </span>
              <BmtaButton variant={on ? "red" : "green"} onClick={() => setRunning((r) => ({ ...r, [n]: !on }))}>
                {on ? "Stop" : "Start"}
              </BmtaButton>
              <BmtaButton onClick={() => {}}>Restart</BmtaButton>
            </div>);

        })}
      </div>
    </div>);

}

// ====================================================================
// EVENTS PANEL
// ====================================================================
const EVENT_TEMPLATES = [
{ evt: "mcafee.validate", res: "mcafee", file: "mcHooks.luac:139", args: ['"hedit"', '"triggerServerEvent"', '"logmanager.lua"', "150", '{[1]="requestMiniLog", [2]=root, [3]=vehicle, [4]=3}'], argTags: ["str", "str", "str", "num", "args"] },
{ evt: "requestMiniLog", res: "hedit", file: "logmanager.lua:150", args: ["vehicle", "3"], argTags: ["id", "num"] },
{ evt: "mcafee.validate", res: "mcafee", file: "mcHooks.luac:139", args: ['"misc"', '"triggerServerEvent"', '"client.luac"', "32", '{[1]="onToggleHeadlights", [2]=player, [3]=vehicle}'], argTags: ["str", "str", "str", "num", "args"] },
{ evt: "onToggleHeadlights", res: "misc", file: "client.luac:32", args: ["vehicle"], argTags: ["id"] },
{ evt: "mcafee.validate", res: "mcafee", file: "mcHooks.luac:139", args: ['"voice_frp"', '"triggerServerEvent"', '"client.lua"', "93", '{[1]="voice:addToPlayerBroadcast", [2]=resource, [3]=player, [4]=p…'], argTags: ["str", "str", "str", "num", "args"] },
{ evt: "voice:addToPlayerBroadcast", res: "voice_frp", file: "client.lua:93", args: ["player", "player"], argTags: ["id", "id"] },
{ evt: "mcafee.validate", res: "mcafee", file: "mcHooks.luac:139", args: ['"disabledm"', '"triggerServerEvent"', '"client.lua"', "47", '{[1]="server:toggleDMMode", [2]=player, [3]=true}'], argTags: ["str", "str", "str", "num", "args"] },
{ evt: "server:toggleDMMode", res: "disabledm", file: "client.lua:47", args: ["true"], argTags: ["str"] },
{ evt: "mcafee.validate", res: "mcafee", file: "mcHooks.luac:139", args: ['"voice_frp"', '"triggerServerEvent"', '"client.lua"', "107", '{[1]="voice:removePlayerBroadcast", [2]=resource, [3]=player, [4]=…'], argTags: ["str", "str", "str", "num", "args"] },
{ evt: "voice:removePlayerBroadcast", res: "voice_frp", file: "client.lua:107", args: ["player", "player"], argTags: ["id", "id"] }];


function EventsPanel() {
  const [tab, setTab] = useState2("Logger");
  const [running, setRunning] = useState2(true);
  const [dir, setDir] = useState2("C->S");
  const [autoScroll, setAutoScroll] = useState2(true);
  const [hideBuiltin, setHideBuiltin] = useState2(false);
  const [clearOnLeave, setClearOnLeave] = useState2(true);
  const [filter, setFilter] = useState2("");
  const [rows, setRows] = useState2(() => EVENT_TEMPLATES.slice());

  useEffect2(() => {
    if (!running) return;
    const id = setInterval(() => {
      setRows((r) => {
        const next = EVENT_TEMPLATES[Math.floor(Math.random() * EVENT_TEMPLATES.length)];
        return [...r.slice(-60), next];
      });
    }, 700);
    return () => clearInterval(id);
  }, [running]);

  const list = filter ? rows.filter((r) => (r.evt + r.res + r.file).toLowerCase().includes(filter.toLowerCase())) : rows;

  return (
    <div className="bmta-panel">
      <BmtaSubtabs tabs={["Logger", "Intercept", "Trigger", "Repeater"]} active={tab} onSelect={setTab} />

      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6, fontSize: 12, color: "var(--bmta-text-dim)" }}>
        <BmtaButton variant={running ? "red" : "green"} onClick={() => setRunning(!running)}>{running ? "Stop" : "Start"}</BmtaButton>
        <BmtaSelect value={dir} options={["C->S", "S->C", "Both"]} onChange={setDir} width={80} />
        <BmtaCheck checked={autoScroll} onChange={setAutoScroll} label="Auto-scroll" />
        <BmtaCheck checked={hideBuiltin} onChange={setHideBuiltin} label="Hide built-in" />
        <BmtaCheck checked={clearOnLeave} onChange={setClearOnLeave} label="Clear on leave" />
        <BmtaButton onClick={() => setRows([])}>Clear</BmtaButton>
        <div style={{ flex: 1 }} />
        <span>70ms</span><span>815K/3.7M</span><span>{(20000 + rows.length).toLocaleString()}pkt/24030pkt</span><span style={{ color: "var(--bmta-warn)" }}>loss 1.0%</span><span>8kbps</span>
        <span>* {rows.length}</span><BmtaButton>Save</BmtaButton>
      </div>

      <div style={{ marginBottom: 6 }}>
        <BmtaInput placeholder="Filter events…" value={filter} onChange={setFilter} />
      </div>

      <div style={{ background: "var(--bmta-bg-2)", border: "1px solid var(--bmta-border)", flex: 1, overflow: "auto", display: "flex", flexDirection: "column-reverse" }}>
        <div>
          {list.map((r, i) =>
          <div key={i} className="bmta-event-row">
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ color: "rgb(226, 125, 48)" }}>[C-&gt;S]</span>
                <span style={{ color: "rgb(253, 253, 101)" }}>{r.evt}</span>
                <span className="bmta-badge tag-blue" style={{ borderColor: "rgb(52, 70, 91)" }}>{r.res}</span>
                <span style={{ color: "var(--bmta-text-dim)" }}>{r.file}</span>
                <div style={{ flex: 1 }} />
                <BmtaButton>Copy</BmtaButton>
                <BmtaButton>Mute</BmtaButton>
                <BmtaButton>Replay</BmtaButton>
              </div>
              <div className="args">
                {r.args.map((a, j) =>
              <span key={j} className={"arg-" + r.argTags[j]} style={{ marginRight: 6 }}>
                    {a}{j < r.args.length - 1 ? "," : ""}
                  </span>
              )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>);

}

Object.assign(window, { ScriptsPanel, ResourcesPanel, EventsPanel });