importScripts('https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js');

firebase.initializeApp({
  apiKey: 'AIzaSyB1FFg7GzLA28Gp9Ic0wOo29J3VA1jO_II',
  authDomain: 'tabis2.firebaseapp.com',
  projectId: 'tabis2',
  storageBucket: 'tabis2.firebasestorage.app',
  messagingSenderId: '1058254535666',
  appId: '1:1058254535666:web:540cdef039d1e2c0a0096b',
});

const messaging = firebase.messaging();

const gameLabels = {
  chess: 'Šachy',
  piskvorky: 'Piškvorky',
  battleship: 'Lodě',
  reversi: 'Reversi',
  dama: 'Dáma',
};

const notifTitles = {
  game_invitation: (label) => `Nová výzva — ${label}`,
  game_move: (label) => `Jsi na tahu! — ${label}`,
  game_over: (label) => `Hra skončila — ${label}`,
  game_abandoned: (label) => `Soupeř odešel — ${label}`,
  game_setup_ready: (label) => `Rozmístění hotovo — ${label}`,
};

// Deduplicata: server posílá notify() + sendGameDataMessage() za sebou pro stejnou session.
// Uchováme sessionId+type na 5s aby se nezobrazily 2 notifikace najednou.
const _recentlyShown = new Map();

function _dedupKey(sessionId, type) { return `${sessionId}:${type}`; }

function _shouldShow(sessionId, type) {
  const key = _dedupKey(sessionId, type);
  const now = Date.now();
  const last = _recentlyShown.get(key);
  if (last && now - last < 5000) return false;
  _recentlyShown.set(key, now);
  return true;
}

messaging.onBackgroundMessage((payload) => {
  const data = payload.data ?? {};
  const type = data.sType;
  const sessionId = data.nSessionId;

  const gameTypes = new Set([
    'game_invitation', 'game_move', 'game_over', 'game_abandoned', 'game_setup_ready',
  ]);

  if (type && gameTypes.has(type)) {
    if (!_shouldShow(sessionId, type)) return;
    const gameLabel = gameLabels[data.sGameType] ?? data.sGameType ?? '';
    const titleFn = notifTitles[type];
    const title = titleFn ? titleFn(gameLabel) : 'TabIS Hry';
    const body = type === 'game_move' && data.sMove ? `Soupeř táhl: ${data.sMove}` : '';
    return self.registration.showNotification(title, {
      body,
      icon: '/icons/Icon-192.png',
      data: { sessionId, sType: type },
    });
  }

  // Fallback pro notify() zprávy bez sType — Safari jinak tiše zahodí.
  // onBackgroundMessage interceptuje VŠECHNY zprávy, takže musíme zobrazit explicitně.
  const notif = payload.notification;
  if (notif?.title && notif.title !== 'TabIS') {
    if (!_shouldShow(sessionId, notif.title)) return;
    return self.registration.showNotification(notif.title, {
      body: notif.body ?? '',
      icon: '/icons/Icon-192.png',
      data: { sessionId },
    });
  }
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();

  const { sessionId, sType } = event.notification.data ?? {};

  const path = sType === 'game_invitation'
    ? '/home/games/multiplayer'
    : sessionId
      ? `/home/games/multiplayer/${sessionId}`
      : '/home/games/multiplayer';

  const url = self.location.origin + path;

  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
      for (const client of windowClients) {
        if (client.url.startsWith(self.location.origin) && 'focus' in client) {
          return client.focus().then((c) => {
            // Safari nepodporuje client.navigate() — openWindow jako fallback
            if (c && 'navigate' in c) return c.navigate(url);
            return clients.openWindow(url);
          });
        }
      }
      return clients.openWindow(url);
    })
  );
});
