<%- include("partials/layout-top", { title, pageWidth: "wide", pageId: "command-policies" }) %>
<div data-command-policies>
<%
  const hasSetting = (policy, name) => Object.prototype.hasOwnProperty.call(policy || {}, name);
  const settingTokens = (policy, extra = []) => [
    hasSetting(policy, "window") && "rate",
    hasSetting(policy, "perStream") && "stream",
    hasSetting(policy, "requirement") && "access",
    hasSetting(policy, "cost") && "cost",
    ...extra
  ].filter(Boolean).join(" ");
  const commandOrigins = [...new Set(commands.map((command) => command.origin))].sort((a, b) => a.localeCompare(b));
%>
<section class="card">
  <%- include("partials/page-header", {
    eyebrow: "Chat tools",
    pageTitle: "Command access and limits",
    description: "Set a baseline once, reuse groups for related commands, and override only genuine exceptions.",
    actions: '<a class="button subtle" href="/admin/commands">Custom commands</a>'
  }) %>
  <div class="callout info">
    <strong>How settings combine</strong>
    <p>The protected default group applies to every command. Other assigned groups add their restrictions. A setting chosen directly on a command replaces every group and built-in value for that category.</p>
  </div>
</section>

<section class="card policy-collection" data-policy-search-scope="groups">
  <div class="section-header"><div><h2>Command groups</h2><p class="hint">Manage the global baseline and reusable rules for related commands.</p></div></div>
  <div class="command-policy-toolbar">
    <label class="command-policy-search">Search groups
      <input type="search" placeholder="Try moderator or currency" autocomplete="off" data-policy-search list="command-group-search-options" />
      <datalist id="command-group-search-options">
        <% if (defaultGroup) { %><option value="<%= defaultGroup.name %>"></option><% } %>
        <% groups.forEach((group) => { %><option value="<%= group.name %>"></option><% }) %>
      </datalist>
      <div class="command-policy-suggestions" data-policy-suggestions hidden></div>
    </label>
    <label>Filter by setting
      <select data-policy-setting-filter>
        <option value="">Any settings</option>
        <option value="rate">Rate-limit setting</option>
        <option value="stream">Per-stream setting</option>
        <option value="access">Access setting</option>
        <option value="cost">Currency-cost setting</option>
      </select>
    </label>
    <span class="hint command-policy-result-count" data-policy-result-count></span>
  </div>

  <% if (defaultGroup) { %>
  <details class="lumi-expandable-settings command-policy-item is-default-group" data-policy-item data-search-name="<%= defaultGroup.name %>" data-search="<%= `${defaultGroup.name} ${defaultGroup.description}`.toLowerCase() %>" data-settings="<%= settingTokens(defaultGroup.policy) %>">
    <summary>
      <span class="command-policy-summary-copy"><span class="command-policy-title"><strong><%= defaultGroup.name %></strong><span class="badge">Protected default</span></span><span class="hint"><%= defaultGroup.description %></span></span>
    </summary>
    <form method="post" action="/admin/command-policies/groups/<%= defaultGroup.id %>" class="form-grid command-policy-form" data-lumi-enhanced-form data-command-group-form data-command-group-id="<%= defaultGroup.id %>">
      <div class="field"><label>Name<input name="name" maxlength="100" required value="<%= defaultGroup.name %>" /></label></div>
      <div class="field"><label>Description<input name="description" maxlength="500" value="<%= defaultGroup.description %>" /></label></div>
      <div class="callout info field full"><strong>Inherited by every command</strong><p>“Keep command built-ins” leaves that category untouched. Choose an explicit value to replace built-in defaults globally.</p></div>
      <div class="field full"><%- include("partials/command-policy-fields", { policy: defaultGroup.policy, allowInherit: true, namePrefix: "", effective: null, inheritLabel: "Keep command built-ins" }) %></div>
      <div class="form-actions"><button class="button" type="submit">Save default settings</button></div>
    </form>
  </details>
  <% } %>

  <details class="lumi-expandable-settings command-policy-item" data-policy-create-group>
    <summary><span class="command-policy-summary-copy"><strong>Create command group</strong><span class="hint">For example: Public fun, Moderator tools, or Expensive commands</span></span></summary>
    <form method="post" action="/admin/command-policies/groups" class="form-grid command-policy-form">
      <div class="field"><label>Name<input name="name" maxlength="100" required /></label></div>
      <div class="field"><label>Description<input name="description" maxlength="500" /></label></div>
      <div class="field full"><%- include("partials/command-policy-fields", { policy: {}, allowInherit: false, namePrefix: "", effective: null }) %></div>
      <div class="form-actions"><button class="button" type="submit">Create group</button></div>
    </form>
  </details>

  <% groups.forEach((group) => { %>
  <details class="lumi-expandable-settings command-policy-item" data-policy-item data-search-name="<%= group.name %>" data-search="<%= `${group.name} ${group.description}`.toLowerCase() %>" data-settings="<%= settingTokens(group.policy) %>">
    <summary><span class="command-policy-summary-copy"><strong><%= group.name %></strong><span class="hint"><%= group.description || "Reusable command rules" %></span></span></summary>
    <form method="post" action="/admin/command-policies/groups/<%= group.id %>" class="form-grid command-policy-form" data-lumi-enhanced-form data-command-group-form data-command-group-id="<%= group.id %>">
      <div class="field"><label>Name<input name="name" maxlength="100" required value="<%= group.name %>" /></label></div>
      <div class="field"><label>Description<input name="description" maxlength="500" value="<%= group.description %>" /></label></div>
      <div class="field full"><%- include("partials/command-policy-fields", { policy: group.policy, allowInherit: false, namePrefix: "", effective: null }) %></div>
      <div class="form-actions"><button class="button" type="submit">Save group</button></div>
    </form>
    <form method="post" action="/admin/command-policies/groups/<%= group.id %>/delete" class="form-actions" data-confirm-mode="modal" data-confirm-title="Delete command group" data-confirm-text="Delete the group <%= group.name %>? Commands keep their direct settings." data-confirm-label="Delete group">
      <button class="button danger" type="submit">Delete group</button>
    </form>
  </details>
  <% }) %>
  <p class="command-policy-no-results" data-policy-no-results hidden>No command groups match that search and filter.</p>
</section>

<section class="card policy-collection" data-policy-search-scope="commands">
  <div class="section-header"><div><h2>Individual commands</h2><p class="hint">Search, compare effective values, and save every command edit together.</p></div></div>
  <div class="command-policy-toolbar command-policy-command-toolbar">
    <label class="command-policy-search">Search commands
      <input type="search" placeholder="Command, description, group, or source" autocomplete="off" data-policy-search list="command-search-options" />
      <datalist id="command-search-options"><% commands.forEach((command) => { %><option value="<%= command.label %>"></option><% }) %></datalist>
      <div class="command-policy-suggestions" data-policy-suggestions hidden></div>
    </label>
    <label>Filter by setting
      <select data-policy-setting-filter>
        <option value="">Any settings</option>
        <option value="rate">Has a rate limit</option>
        <option value="stream">Has a per-stream limit</option>
        <option value="access">Has an access requirement</option>
        <option value="cost">Has a currency cost</option>
        <option value="groups">Uses an assigned group</option>
        <option value="overrides">Has direct overrides</option>
      </select>
    </label>
    <label>Command source
      <select data-policy-origin-filter><option value="">Any source</option><% commandOrigins.forEach((origin) => { %><option value="<%= origin.toLowerCase() %>"><%= origin %></option><% }) %></select>
    </label>
    <span class="hint command-policy-result-count" data-policy-result-count></span>
  </div>

  <% if (!commands.length) { %><p>No commands are currently registered.</p><% } %>
  <% if (commands.length) { %>
  <form method="post" action="/admin/command-policies/commands" class="command-policy-batch-form" data-command-policy-batch data-lumi-enhanced-form data-lumi-form-id="command-policies">
    <input type="hidden" name="command_count" value="<%= commands.length %>" />
    <div class="command-policy-savebar">
      <span><strong>Command settings</strong><span class="hint" data-command-save-state>All displayed values are saved.</span></span>
      <button class="button" type="submit">Save all command settings</button>
    </div>
    <% commands.forEach((command, index) => { %>
    <% const prefix = `command_${index}_`; %>
    <details class="lumi-expandable-settings command-policy-item" data-policy-item data-search-name="<%= command.label %>" data-search="<%= command.searchText %>" data-settings="<%= command.settingTokens.join(' ') %>" data-origin="<%= command.origin.toLowerCase() %>">
      <summary>
        <span class="command-policy-summary-copy">
          <span class="command-policy-title"><strong><%= command.label %></strong><span class="badge"><%= command.origin %></span></span>
          <span class="hint"><%= command.description %></span>
        </span>
        <% if (command.groups.length) { %><span class="badge"><%= command.groups.length %> assigned group<%= command.groups.length === 1 ? "" : "s" %></span><% } %>
      </summary>
      <div class="form-grid command-policy-form command-policy-editor" data-command-policy-editor data-built-in-policy="<%= JSON.stringify(command.defaultPolicy || {}) %>" data-default-group-policy="<%= JSON.stringify(defaultGroup?.policy || {}) %>">
        <input type="hidden" name="<%= prefix %>key" value="<%= command.key %>" />
        <fieldset class="subsection field full command-policy-groups">
          <legend>Assigned groups</legend>
          <div class="platform-checkboxes">
            <% groups.forEach((group) => { %>
            <label class="platform-check"><input type="checkbox" name="<%= prefix %>group_ids" value="<%= group.id %>" data-group-name="<%= group.name %>" data-group-policy="<%= JSON.stringify(group.policy || {}) %>" <%= command.groups.some((item) => item.id === group.id) ? "checked" : "" %> /><span><%= group.name %></span></label>
            <% }) %>
          </div>
          <% if (!groups.length) { %><p class="hint">Create a reusable group above, or configure this command directly.</p><% } %>
          <p class="hint">The protected default group already applies automatically and does not need to be assigned.</p>
        </fieldset>
        <div class="field full"><%- include("partials/command-policy-fields", { policy: command.policy, allowInherit: true, namePrefix: prefix, effective: command.effective, inheritLabel: "Use groups/default" }) %></div>
      </div>
    </details>
    <% }) %>
    <p class="command-policy-no-results" data-policy-no-results hidden>No commands match that search and filter.</p>
    <div class="command-policy-savebar is-bottom">
      <span class="hint">Every command on this page is submitted together, including collapsed commands.</span>
      <button class="button" type="submit">Save all command settings</button>
    </div>
  </form>
  <% } %>
</section>
</div>
<%- include("partials/layout-bottom") %>
