const template = html`
  <div class="notifications"> 
    <div v-if="notifications.length > 0" style="text-align: right; margin-bottom: 10px;">
      <button @click="clearAll" class="btn btn-mini btn-danger">
        <i class="fa fa-check"></i> Clear All
      </button>
    </div>
    <ul>
      <li v-for="notification in notifications">
        <a @click="go(notification)">{{notification.message}}</a>
      </li>
    </ul>
  </div>
`;
///tasks/support/153587
//v-if="notification.read == 0 || showall"
import clocking from "../generic/clocking.js?v=20251013";

export default {
  data: function () {
    return {
      notifications: [],
      showall: true
    };
  },
  components: {
    clocking
  },
  mounted() {
    this.load();
  },
  methods: {
    async load() {
      const raw = await fetch("/api/v1/notifications");
      const json = await raw.json();
      this.notifications = json.data.map(el => {
        el.url = this.genURL(el);
        return el;
      });
      this.notifications = this.notifications.filter(el => el.read == 0);
      this.notifications.length = 6
    },
    genURL(notification) {
      if (notification.related_type == "repair") {
        return `/tasks/repairs/${notification.related_id}`;
      }
      return `/tasks/${notification.related_type}/${notification.related_id}`;
    },
    async read(id) {
      const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

      return await fetch(`/api/v1/notifications/read/${id}`, {
        method: "POST",
        headers: {
          "X-CSRF-TOKEN": csrfToken
        }
      });
    },
    async go(notification) {
      await this.read(notification.id);
      window.location = notification.url;
    },
    async clearAll() {
      if (!confirm('Are you sure you want to mark all notifications as read?')) {
        return;
      }

      const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

      try {
        const response = await fetch('/api/v1/notifications?clearAll=true', {
          method: 'GET',
          headers: {
            'X-CSRF-TOKEN': csrfToken
          }
        });

        if (response.ok) {
          this.notifications = [];
          // Show success message
          if (window.Messenger) {
            window.Messenger("All notifications marked as read.");
          }
        }
      } catch (error) {
        console.error('Error clearing notifications:', error);
      }
    }
  },
  template
};
