import React from 'react';
import { createRoot } from 'react-dom/client';
import { flushSync } from 'react-dom';
import App from './App.jsx';
import './styles.css';

const hadServiceWorkerControllerAtLoad = 'serviceWorker' in navigator
  ? Boolean(navigator.serviceWorker.controller)
  : false;
let hasReloadedForServiceWorkerUpdate = false;

function setupServiceWorker() {
  if (!('serviceWorker' in navigator)) {
    return;
  }

  if (import.meta.env.DEV) {
    navigator.serviceWorker.getRegistrations()
      .then((registrations) => Promise.all(registrations.map((reg) => reg.unregister())))
      .catch((err) => console.debug('ServiceWorker dev cleanup failed:', err));

    if ('caches' in window) {
      caches.keys()
        .then((keys) => Promise.all(keys.map((key) => caches.delete(key))))
        .catch((err) => console.debug('Cache dev cleanup failed:', err));
    }

    return;
  }

  const swUrl = `${import.meta.env.BASE_URL}sw.js`;
  navigator.serviceWorker.register(swUrl, { updateViaCache: 'none' })
    .then(async (reg) => {
      try {
        await reg.update();
      } catch (e) {
        console.debug('ServiceWorker update check failed:', e);
      }
      console.log('ServiceWorker registered:', reg.scope);
    })
    .catch((err) => console.debug('ServiceWorker registration failed:', err));

  navigator.serviceWorker.addEventListener('controllerchange', () => {
    if (!hadServiceWorkerControllerAtLoad || hasReloadedForServiceWorkerUpdate) {
      return;
    }

    hasReloadedForServiceWorkerUpdate = true;
    window.location.reload();
  });
}

setupServiceWorker();

const rootEl = document.getElementById('root');
const root = createRoot(rootEl);

flushSync(() => {
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
  );
});

document.getElementById('app-loading')?.remove();

import('./player.js')
  .then(({ initPlayer }) => initPlayer())
  .catch((err) => {
    console.error('Failed to initialise player controller', err);
  });
