// Azan + Announcement Service Worker - runs in background even when page is closed

const AZAN_CHECK_INTERVAL = 30 * 1000;
let prayerTimesData = null;
let notifiedToday = {};
let announcementsData = [];
let notifiedAnnouncements = {};

self.addEventListener("install", (e) => {
  self.skipWaiting();
});

self.addEventListener("activate", (e) => {
  e.waitUntil(self.clients.claim());
});

self.addEventListener("message", (event) => {
  const { type, data } = event.data;

  if (type === "SET_PRAYER_TIMES") {
    prayerTimesData = data.prayerTimes;
    notifiedToday = data.notified || {};
    checkAzan();
  }

  if (type === "AZAN_DISABLED") {
    prayerTimesData = null;
  }

  if (type === "SET_ANNOUNCEMENTS") {
    const oldIds = new Set(announcementsData.map((a) => a.id));
    announcementsData = data.announcements || [];
    notifiedAnnouncements = data.notifiedAnnouncements || {};

    // Check for new announcements immediately
    announcementsData.forEach((ann) => {
      if (!notifiedAnnouncements[ann.id] && !oldIds.has(ann.id)) {
        notifiedAnnouncements[ann.id] = true;

        self.registration.showNotification("📢 নতুন বিজ্ঞপ্তি", {
          body: ann.message,
          icon: "/favicon.ico",
          tag: `ann-${ann.id}`,
          requireInteraction: true,
          vibrate: [200, 100, 200],
          data: { type: "announcement", id: ann.id },
        });
        // Play sound in client
        self.clients.matchAll().then((clients) => {
          clients.forEach((client) => client.postMessage({ type: "PLAY_NOTIFICATION_SOUND" }));
        });
      }
    });
  }

  if (type === "SET_WITHDRAWAL_UPDATE") {
    const { withdrawal } = data;
    const statusText = {
      approved: "✅ উইথড্র অনুমোদিত হয়েছে!",
      rejected: "❌ উইথড্র রিজেক্ট হয়েছে",
    };

    if (withdrawal.status === "approved" || withdrawal.status === "rejected") {
      self.registration.showNotification(statusText[withdrawal.status], {
        body: `৳${withdrawal.amount} — ${withdrawal.method} (${withdrawal.accountNumber})`,
        icon: "/favicon.ico",
        tag: `wd-${withdrawal.id}`,
        requireInteraction: true,
        vibrate: [200, 100, 200],
        data: { type: "withdrawal", id: withdrawal.id },
      });
      // Play sound in client
      self.clients.matchAll().then((clients) => {
        clients.forEach((client) => client.postMessage({ type: "PLAY_NOTIFICATION_SOUND" }));
      });
    }
  }
});

function timeToMinutes(time) {
  const [h, m] = time.split(":").map(Number);
  return h * 60 + m;
}

const prayerNamesBn = {
  Fajr: "ফজর",
  Dhuhr: "যোহর",
  Asr: "আসর",
  Maghrib: "মাগরিব",
  Isha: "ইশা",
};

const azanPrayers = ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"];

function checkAzan() {
  if (!prayerTimesData) return;

  const now = new Date();
  const today = now.toDateString();
  const nowMins = now.getHours() * 60 + now.getMinutes();

  if (notifiedToday._date !== today) {
    notifiedToday = { _date: today };
  }

  for (const key of azanPrayers) {
    const prayerMins = timeToMinutes(prayerTimesData[key]);
    if (nowMins === prayerMins && !notifiedToday[key]) {
      notifiedToday[key] = true;

      self.registration.showNotification(`🕌 ${prayerNamesBn[key]} এর সময় হয়েছে`, {
        body: `এখন ${prayerNamesBn[key]} নামাজের ওয়াক্ত শুরু হয়েছে।`,
        icon: "/favicon.ico",
        tag: `azan-${key}`,
        requireInteraction: true,
        vibrate: [200, 100, 200, 100, 200],
        data: { prayer: key },
      });

      self.clients.matchAll().then((clients) => {
        clients.forEach((client) => {
          client.postMessage({ type: "PLAY_AZAN", prayer: key });
        });
      });
    }
  }

  setTimeout(checkAzan, AZAN_CHECK_INTERVAL);
}

// Handle notification click - open the app
self.addEventListener("notificationclick", (event) => {
  event.notification.close();
  event.waitUntil(
    self.clients.matchAll({ type: "window" }).then((clients) => {
      if (clients.length > 0) {
        clients[0].focus();
      } else {
        self.clients.openWindow("/dashboard");
      }
    })
  );
});
