{% include 'mixins/partials/notify.html' %}
<div
  id="{{ osint_table_id }}"
  class="osint-table-shell {% if osint_shell_borderless %}osint-table-shell--borderless{% endif %}"
  {% if osint_event_name %}
    hx-get="{{ osint_refresh_url }}"
    hx-target="#{{ osint_table_id }}"
    hx-swap="outerHTML"
    hx-trigger="{{ osint_event_name }} from:body"
  {% endif %}>

  {% if osint_show_search %}
    <form
      method="get"
      action="{{ osint_search_url }}"
      class="osint-table-toolbar"
      hx-get="{{ osint_search_url }}"
      hx-target="#{{ osint_table_id }}"
      hx-swap="outerHTML">
      <div class="field has-addons is-flex-wrap-wrap">
        <div class="control is-expanded" style="min-width: 14rem;">
          <input
            class="input"
            type="text"
            name="q"
            value="{{ osint_search_query }}"
            placeholder="Search {{ osint_title|lower }}...">
        </div>
        <div class="control">
          <div class="select">
            <select name="field">
              {% for field in osint_search_fields %}
                <option
                  value="{{ field.value }}"
                  {% if field.value == osint_search_field %}selected{% endif %}>
                  {{ field.label }}
                </option>
              {% endfor %}
            </select>
          </div>
        </div>
        <div class="control">
          <button class="button is-link is-light" type="submit">
            Search
          </button>
        </div>
        <div class="control">
          <a class="button is-light" href="{{ osint_search_url }}">
            Reset
          </a>
        </div>
      </div>
    </form>
  {% endif %}

  <div class="osint-results-meta">
    <div class="osint-results-meta-left">
      <div class="dropdown" id="{{ osint_table_id }}-columns-dropdown" hx-disable>
        <div class="dropdown-trigger">
          <button
            class="button is-small is-light"
            type="button"
            data-role="columns-toggle-trigger"
            aria-haspopup="true"
            aria-expanded="false"
            aria-controls="{{ osint_table_id }}-columns-menu">
            <span>Show/Hide Fields</span>
            <span class="icon is-small"><i class="fa-solid fa-angle-down"></i></span>
          </button>
        </div>
        <div class="dropdown-menu" id="{{ osint_table_id }}-columns-menu" role="menu">
          <div class="dropdown-content">
            {% for column in osint_columns %}
              <button
                type="button"
                class="dropdown-item osint-col-toggle"
                data-col-index="{{ forloop.counter0 }}"
                aria-pressed="false">
                <span class="icon is-small"><i class="fa-solid fa-check"></i></span>
                <span>{{ column.label }}</span>
                <span class="is-size-7 has-text-grey ml-2">({{ column.field_name }})</span>
              </button>
            {% endfor %}
          </div>
        </div>
      </div>
      <button class="button is-small is-light" type="button" disabled>
        <span class="icon is-small"><i class="fa-solid fa-database"></i></span>
        <span>Static</span>
      </button>
    </div>
    <p class="osint-results-count">
      fetched {{ osint_result_count }} result{% if osint_result_count != 1 %}s{% endif %}
    </p>
  </div>

  <div class="table-container osint-results-table-wrap">
    <table class="table is-fullwidth is-hoverable osint-results-table">
      <thead>
        <tr>
          {% for column in osint_columns %}
            <th data-osint-col="{{ forloop.counter0 }}" class="osint-col-{{ forloop.counter0 }}">
              {% if column.sortable %}
                <a
                  class="osint-sort-link"
                  href="{{ column.sort_url }}"
                  hx-get="{{ column.sort_url }}"
                  hx-target="#{{ osint_table_id }}"
                  hx-swap="outerHTML">
                  <span>{{ column.label }}</span>
                  <span class="icon is-small">
                    {% if column.is_sorted and column.is_desc %}
                      <i class="fa-solid fa-sort-down"></i>
                    {% elif column.is_sorted %}
                      <i class="fa-solid fa-sort-up"></i>
                    {% else %}
                      <i class="fa-solid fa-sort"></i>
                    {% endif %}
                  </span>
                </a>
              {% else %}
                {{ column.label }}
              {% endif %}
            </th>
          {% endfor %}
          {% if osint_show_actions %}<th>Actions</th>{% endif %}
        </tr>
      </thead>
      <tbody>
        {% for row in osint_rows %}
          <tr>
            {% for cell in row.cells %}
              <td data-osint-col="{{ forloop.counter0 }}" class="osint-col-{{ forloop.counter0 }}">
                {% if cell.kind == "id_copy" %}
                  <a
                    class="button is-small has-text-grey"
                    title="Copy value"
                    onclick="window.prompt('Copy to clipboard: Ctrl+C, Enter', '{{ cell.value }}');">
                    <span class="icon">
                      <i class="fa-solid fa-copy"></i>
                    </span>
                  </a>
                {% elif cell.kind == "chat_ref" %}
                  {% if cell.value.copy %}
                    <a
                      class="button is-small has-text-grey"
                      title="Copy chat id"
                      onclick="window.prompt('Copy to clipboard: Ctrl+C, Enter', '{{ cell.value.copy }}');">
                      <span class="icon">
                        <i class="fa-solid fa-copy"></i>
                      </span>
                    </a>
                  {% else %}
                    <span class="has-text-grey">-</span>
                  {% endif %}
                {% elif cell.value.copy %}
                  <a
                    class="button is-small has-text-grey"
                    title="Copy value"
                    onclick="window.prompt('Copy to clipboard: Ctrl+C, Enter', '{{ cell.value.copy }}');">
                    <span class="icon">
                      <i class="fa-solid fa-copy"></i>
                    </span>
                  </a>
                {% elif cell.kind == "bool" %}
                  {% if cell.value %}
                    <span class="icon has-text-success">
                      <i class="fa-solid fa-check"></i>
                    </span>
                  {% else %}
                    <span class="icon has-text-grey">
                      <i class="fa-solid fa-xmark"></i>
                    </span>
                  {% endif %}
                {% elif cell.kind == "datetime" %}
                  {% if cell.value %}
                    {{ cell.value|date:"M j, Y P" }}
                  {% else %}
                    <span class="has-text-grey">-</span>
                  {% endif %}
                {% else %}
                  {% if cell.value or cell.value == 0 %}
                    {{ cell.value }}
                  {% else %}
                    <span class="has-text-grey">-</span>
                  {% endif %}
                {% endif %}
              </td>
            {% endfor %}
            {% if osint_show_actions %}
              <td>
                <div class="buttons are-small">
                  {% for action in row.actions %}
                    {% if action.mode == "hx-get" %}
                      <button
                        class="button"
                        hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
                        hx-get="{{ action.url }}"
                        hx-target="{{ action.target }}"
                        hx-swap="innerHTML"
                        {% if action.target == "#windows-here" %}onclick="if (window.giaPrepareWindowAnchor) { window.giaPrepareWindowAnchor(this); }"{% endif %}
                        title="{{ action.title }}">
                        <span class="icon"><i class="{{ action.icon }}"></i></span>
                      </button>
                    {% elif action.mode == "hx-delete" %}
                      <button
                        class="button"
                        hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
                        hx-delete="{{ action.url }}"
                        hx-target="{{ action.target }}"
                        hx-swap="innerHTML"
                        {% if action.confirm %}hx-confirm="{{ action.confirm }}"{% endif %}
                        title="{{ action.title }}">
                        <span class="icon"><i class="{{ action.icon }}"></i></span>
                      </button>
                    {% elif action.mode == "link" %}
                      <a class="button" href="{{ action.url }}" title="{{ action.title }}">
                        <span class="icon"><i class="{{ action.icon }}"></i></span>
                      </a>
                    {% endif %}
                  {% endfor %}
                </div>
              </td>
            {% endif %}
          </tr>
        {% empty %}
          <tr>
            <td colspan="{% if osint_show_actions %}{{ osint_columns|length|add:'1' }}{% else %}{{ osint_columns|length }}{% endif %}">
              <p class="has-text-grey">No results found.</p>
            </td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>

  {% if osint_pagination.enabled %}
    <nav class="pagination is-small" role="navigation" aria-label="pagination">
      {% if osint_pagination.has_previous %}
        <a
          class="pagination-previous"
          href="{{ osint_pagination.previous_url }}"
          hx-get="{{ osint_pagination.previous_url }}"
          hx-target="#{{ osint_table_id }}"
          hx-swap="outerHTML">
          Previous
        </a>
      {% else %}
        <a class="pagination-previous is-disabled">Previous</a>
      {% endif %}

      {% if osint_pagination.has_next %}
        <a
          class="pagination-next"
          href="{{ osint_pagination.next_url }}"
          hx-get="{{ osint_pagination.next_url }}"
          hx-target="#{{ osint_table_id }}"
          hx-swap="outerHTML">
          Next
        </a>
      {% else %}
        <a class="pagination-next is-disabled">Next</a>
      {% endif %}

      <ul class="pagination-list">
        {% for page in osint_pagination.pages %}
          {% if page.ellipsis %}
            <li><span class="pagination-ellipsis">&hellip;</span></li>
          {% elif page.current %}
            <li><a class="pagination-link is-current">{{ page.number }}</a></li>
          {% else %}
            <li>
              <a
                class="pagination-link"
                href="{{ page.url }}"
                hx-get="{{ page.url }}"
                hx-target="#{{ osint_table_id }}"
                hx-swap="outerHTML">
                {{ page.number }}
              </a>
            </li>
          {% endif %}
        {% endfor %}
      </ul>
    </nav>
  {% endif %}

  <style>
    #{{ osint_table_id }} .osint-results-meta {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 0.6rem;
      flex-wrap: wrap;
      margin-bottom: 0.6rem;
    }
    #{{ osint_table_id }} .osint-results-meta-left {
      display: inline-flex;
      align-items: center;
      gap: 0.42rem;
      flex-wrap: wrap;
    }
    #{{ osint_table_id }} .osint-results-count {
      margin: 0;
      color: #6c757d;
      font-size: 0.75rem;
    }
    #{{ osint_table_id }} .osint-col-toggle .icon {
      color: #3273dc;
    }
    #{{ osint_table_id }} .osint-col-toggle.is-hidden-col .icon {
      color: #b5b5b5;
    }
    #{{ osint_table_id }} .osint-col-toggle {
      width: 100%;
      text-align: left;
      border: 0;
      background: transparent;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 0.35rem;
    }
    #{{ osint_table_id }}.osint-table-shell--borderless {
      border: 0;
      border-radius: 0;
      padding: 0;
      background: transparent;
    }
  </style>

  <script>
    (function () {
      const tableId = "{{ osint_table_id|escapejs }}";
      const scopeKey = "{{ osint_scope|default:'global'|escapejs }}";
      const columnSignature = "{{ osint_columns|length }}:{% for column in osint_columns %}{{ column.key|escapejs }}|{% endfor %}";
      const shell = document.getElementById(tableId);
      if (!shell) {
        return;
      }
      const dropdown = document.getElementById(tableId + "-columns-dropdown");
      const trigger = dropdown
        ? dropdown.querySelector("[data-role='columns-toggle-trigger']")
        : null;
      const dropdownMenu = dropdown
        ? dropdown.querySelector(".dropdown-menu")
        : null;
      const storageKey = [
        "gia_osint_hidden_cols_v2",
        tableId,
        scopeKey,
        columnSignature,
      ].join(":");
      let hidden = [];
      try {
        hidden = JSON.parse(localStorage.getItem(storageKey) || "[]");
      } catch (e) {
        hidden = [];
      }
      if (!Array.isArray(hidden)) {
        hidden = [];
      }
      hidden = hidden.map(String);

      const applyVisibility = function () {
        const hiddenSet = new Set(hidden);
        shell.querySelectorAll("[data-osint-col]").forEach(function (node) {
          const idx = String(node.getAttribute("data-osint-col") || "");
          node.style.display = hiddenSet.has(idx) ? "none" : "";
        });
        shell.querySelectorAll(".osint-col-toggle").forEach(function (toggle) {
          const idx = String(toggle.getAttribute("data-col-index") || "");
          const isHidden = hiddenSet.has(idx);
          toggle.classList.toggle("is-hidden-col", isHidden);
          toggle.setAttribute("aria-pressed", isHidden ? "true" : "false");
          const icon = toggle.querySelector("i");
          if (icon) {
            icon.className = isHidden ? "fa-solid fa-xmark" : "fa-solid fa-check";
          }
        });
      };

      const persist = function () {
        try {
          localStorage.setItem(storageKey, JSON.stringify(hidden));
        } catch (e) {
          // Ignore storage failures.
        }
      };

      shell.querySelectorAll(".osint-col-toggle").forEach(function (toggle) {
        toggle.addEventListener("click", function (event) {
          event.preventDefault();
          event.stopPropagation();
          const idx = String(toggle.getAttribute("data-col-index") || "");
          if (!idx) {
            return;
          }
          if (hidden.includes(idx)) {
            hidden = hidden.filter(function (item) { return item !== idx; });
          } else {
            hidden.push(idx);
          }
          persist();
          applyVisibility();
          if (dropdown) {
            dropdown.classList.remove("is-active");
          }
          if (trigger) {
            trigger.setAttribute("aria-expanded", "false");
          }
        });
      });

      if (trigger && dropdown) {
        trigger.addEventListener("click", function (event) {
          event.preventDefault();
          event.stopPropagation();
          const nextActive = !dropdown.classList.contains("is-active");
          dropdown.classList.toggle("is-active", nextActive);
          trigger.setAttribute("aria-expanded", nextActive ? "true" : "false");
        });
      }
      if (dropdownMenu) {
        dropdownMenu.addEventListener("click", function (event) {
          event.stopPropagation();
        });
      }
      document.addEventListener("click", function (event) {
        if (!dropdown) {
          return;
        }
        if (dropdown.contains(event.target)) {
          return;
        }
        dropdown.classList.remove("is-active");
        if (trigger) {
          trigger.setAttribute("aria-expanded", "false");
        }
      });
      document.addEventListener("keydown", function (event) {
        if (event.key !== "Escape" || !dropdown) {
          return;
        }
        dropdown.classList.remove("is-active");
        if (trigger) {
          trigger.setAttribute("aria-expanded", "false");
        }
      });

      applyVisibility();
    })();
  </script>
</div>
