"use strict";

import {Controller} from "@hotwired/stimulus";

/**
 * Highlights admin-list rows the current colleague has unread activity on.
 *
 * The lists are cached by user-context-hash bucket (shared across same-role
 * admins), so this per-individual state cannot live in the cached HTML. Instead
 * we fetch it from a `private, no-store` endpoint and decorate the rows
 * client-side — re-applying after Live Component morphs replace the rows.
 */
export default class extends Controller {
  static values = { url: String };

  connect() {
    this.unread = null;
    this.observer = new MutationObserver(() => this.apply());
    this.load();
  }

  disconnect() {
    if (this.observer) {
      this.observer.disconnect();
    }
  }

  async load() {
    try {
      const res = await fetch(this.urlValue, {
        headers: { Accept: "application/json" },
        credentials: "same-origin",
      });
      if (!res.ok) {
        return;
      }
      const data = await res.json();
      this.unread = new Set(Array.isArray(data.items) ? data.items : []);
      this.apply();
    } catch (e) {
      /* non-fatal — the list just renders without highlights */
    }
  }

  apply() {
    if (!this.unread) {
      return;
    }

    // Detach while we mutate so our own class changes don't re-trigger us.
    if (this.observer) {
      this.observer.disconnect();
    }

    this.element.querySelectorAll("[data-activity-item]").forEach((row) => {
      const unread = this.unread.has(row.dataset.activityItem);
      row.classList.toggle("bg-yellow-200/50", unread);

      const icon = row.querySelector("[data-activity-icon]");
      if (icon) {
        icon.classList.toggle("text-red-500", unread);
        icon.classList.toggle("text-gray-400", !unread);
      }
    });

    if (this.observer && this.element.isConnected) {
      this.observer.observe(this.element, { childList: true, subtree: true });
    }
  }
}
