// resources/js/admin-notifications.js
import './bootstrap';

(function () {
  const bell       = document.getElementById('notifBell');
  const menu       = document.getElementById('notifMenu');
  const list       = document.getElementById('notifList');
  const countBadge = document.getElementById('notifCount');
  const markAllBtn = document.getElementById('markAllRead');

  if (!bell || !menu || !list || !countBadge) return;

  // ---------- Helpers ----------
  function setCount(n) {
    const num = Number(n || 0);
    countBadge.textContent = num;
    countBadge.style.display = num > 0 ? '' : 'none';
  }

  function formatTime(iso) {
    if (!iso) return '';
    const d = new Date(iso);
    if (isNaN(d.getTime())) return '';

    const now  = new Date();
    const diff = (now - d) / 1000;

    if (diff < 60)   return 'Just now';
    if (diff < 3600) return `${Math.round(diff / 60)} min ago`;
    if (diff < 86400) return `${Math.round(diff / 3600)}h ago`;
    return d.toLocaleString();
  }

  function normalizeMeta(meta) {
    if (!meta) return {};
    if (typeof meta === 'string') {
      try {
        return JSON.parse(meta);
      } catch (e) {
        return {};
      }
    }
    return meta;
  }

  function buildMetaLine(rawMeta = {}) {
    const meta  = normalizeMeta(rawMeta);
    const parts = [];

    if (meta.amount)    parts.push(`Amount: ৳${meta.amount}`);
    if (meta.model && meta.id) parts.push(`${meta.model} #${meta.id}`);
    if (meta.reference) parts.push(`Ref: ${meta.reference}`);

    return parts.length
      ? `<div class="mt-1 text-[11px] text-slate-500">${parts.join(' • ')}</div>`
      : '';
  }

  function badgeColor(meta) {
    const m = normalizeMeta(meta);
    const type = (m.model || '').toLowerCase();

    if (type === 'deposit')      return 'bg-emerald-100 text-emerald-700';
    if (type === 'withdraw')    return 'bg-sky-100 text-sky-700';
    if (type === 'transfer')    return 'bg-violet-100 text-violet-700';
    return 'bg-slate-100 text-slate-600';
  }

  function liTemplate(item) {
    const title    = item.title ?? 'New notification';
    const message  = item.message ?? '';
    const timeStr  = formatTime(item.time);
    const metaHtml = buildMetaLine(item.meta);
    const initials = title.trim().charAt(0).toUpperCase() || 'N';
    const badgeCls = badgeColor(item.meta);

    return `
      <li data-id="${item.id || ''}"
          class="group flex gap-3 px-3 py-3 bg-white hover:bg-slate-50 transition rounded-none">
        <div class="mt-0.5">
          <span class="inline-flex h-9 w-9 items-center justify-center rounded-full 
                       ${item.read ? 'bg-slate-100 text-slate-500' : 'bg-emerald-500/10 text-emerald-500'}
                       text-xs font-bold ring-1 ring-emerald-500/20">
            ${initials}
          </span>
        </div>

        <div class="flex-1 min-w-0">
          <div class="flex items-start justify-between gap-2">
            <div class="min-w-0">
              <p class="text-xs font-semibold text-slate-800 truncate">${title}</p>
              <p class="mt-0.5 text-[13px] leading-snug text-slate-600 line-clamp-2">${message}</p>
            </div>
            <p class="ml-2 text-[10px] text-slate-400 whitespace-nowrap">${timeStr}</p>
          </div>

          <div class="mt-1 flex flex-wrap items-center gap-1">
            <span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ${badgeCls}">
              ${normalizeMeta(item.meta).model || 'Info'}
            </span>
            ${metaHtml}
          </div>

          ${item.id
            ? `<button class="mt-2 inline-flex items-center text-[11px] font-semibold text-sky-600 hover:text-sky-700 markRead">
                 Mark read
               </button>`
            : ''
          }
        </div>
      </li>
    `;
  }

  // ---------- Initial load ----------
  async function loadInitial() {
    try {
      const res  = await fetch('/admin/notifications', { credentials: 'same-origin' });
      const data = await res.json();
      list.innerHTML = (data.items || []).map(liTemplate).join('');
      setCount(data.unread_count ?? 0);
    } catch (e) {
      console.error('Failed to load notifications', e);
    }
  }

  // ---------- Mark single read ----------
  async function markRead(id, liEl) {
    if (!id) return;
    try {
      await fetch(`/admin/notifications/${id}/read`, {
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
        },
        credentials: 'same-origin',
      });
      if (liEl) liEl.classList.add('opacity-60');
      const current = Number(countBadge?.textContent || 0);
      if (current > 0) setCount(current - 1);
    } catch (e) {
      console.error('Failed to mark read', e);
    }
  }

  // ---------- Mark all read ----------
  markAllBtn?.addEventListener('click', async () => {
    try {
      await fetch('/admin/notifications/read-all', {
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
        },
        credentials: 'same-origin',
      });
      document.querySelectorAll('#notifList li').forEach(li =>
        li.classList.add('opacity-60')
      );
      setCount(0);
    } catch (e) {
      console.error('Failed to mark all read', e);
    }
  });

  // ---------- Events ----------
  list.addEventListener('click', (e) => {
    const btn = e.target.closest?.('.markRead');
    if (!btn) return;
    const li = btn.closest('li');
    const id = li?.dataset?.id;
    if (id) markRead(id, li);
  });

  bell.addEventListener('click', () => {
    menu.classList.toggle('hidden');
  });

  // ---------- Small toast ----------
  window.showToast = function (msg) {
    const t = document.createElement('div');
    t.textContent = msg;
    Object.assign(t.style, {
      position: 'fixed',
      right: '16px',
      bottom: '16px',
      padding: '10px 14px',
      background: 'rgba(15,23,42,0.96)',
      color: '#fff',
      borderRadius: '12px',
      fontSize: '13px',
      zIndex: 9999,
      boxShadow: '0 18px 45px rgba(15,23,42,.6)',
      maxWidth: '260px',
      lineHeight: '1.3',
    });
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 2600);
  };

  // ---------- Initial fetch ----------
  loadInitial();

  // ---------- Realtime via Echo ----------
  if (window.Echo) {
    window.Echo.private('admin.notifications')
      .listen('.admin.action', (e) => {
        const item = {
          id: '',        // broadcast থেকে id না এলে ফাঁকা রাখি
          read: false,
          title:   e.title   || 'New notification',
          message: e.message || '',
          meta:    e.meta    || {},
          time:    e.time    || new Date().toISOString(),
        };

        const wrapper = document.createElement('div');
        wrapper.innerHTML = liTemplate(item);
        const li = wrapper.firstElementChild;
        if (li) list.prepend(li);

        const current = Number(countBadge?.textContent || 0);
        setCount(current + 1);

        window.showToast(`${item.title}: ${item.message}`);
      });
  }
})();
