import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";

const STORAGE_KEY = 'crypto-wallet-storage';

// Register service worker for offline support
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then((registration) => {
      console.log('[SW] Registered:', registration.scope);
    }).catch((err) => {
      console.warn('[SW] Registration failed:', err);
    });
  });
}

// Remove splash screen after app mounts
function removeSplashScreen() {
  const splash = document.getElementById('splash-screen');
  if (splash) {
    splash.classList.add('fade-out');
    setTimeout(() => splash.remove(), 400);
  }
}

// Always wipe wallet state on every page load.
// The preview should always boot into the onboarding flow — there is no meaningful
// persistent state to preserve in a demo/preview context, and keeping stale state
// is the root cause of the dashboard showing instead of onboarding.
// ?reset=1 is kept as an explicit URL-based override for convenience.
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('reset') === '1') {
  urlParams.delete('reset');
  const clean = window.location.pathname + (urlParams.toString() ? '?' + urlParams.toString() : '');
  localStorage.removeItem(STORAGE_KEY);
  window.location.replace(clean);
} else {
  // Unconditionally clear wallet storage before mounting so every page load is clean
  localStorage.removeItem(STORAGE_KEY);

  createRoot(document.getElementById("root")!).render(
    <StrictMode>
      <App />
    </StrictMode>
  );

  // Remove splash screen once app is rendered
  removeSplashScreen();
}
