import { useState, useEffect } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import '../styles/PWAInstall.css';

export function PWAInstall() {
  const [deferredPrompt, setDeferredPrompt] = useState(null);
  const [showInstall, setShowInstall] = useState(false);

  // Service worker registration + update detection. With registerType: 'prompt'
  // in vite.config.js, the user has to opt in to applying an update — this hook
  // exposes the state and the trigger function in one place.
  const {
    needRefresh: [needRefresh, setNeedRefresh],
    updateServiceWorker,
  } = useRegisterSW({
    onRegisterError(error) {
      // eslint-disable-next-line no-console
      console.warn('Service worker registration failed:', error);
    },
  });

  useEffect(() => {
    const handleBeforeInstallPrompt = (e) => {
      e.preventDefault();
      setDeferredPrompt(e);
      setShowInstall(true);
    };
    window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
    return () => window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
  }, []);

  const handleInstall = async () => {
    if (!deferredPrompt) return;
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    if (outcome === 'accepted') {
      setShowInstall(false);
      setDeferredPrompt(null);
    }
  };

  const handleUpdate = () => {
    // updateServiceWorker(true) skips the waiting state, activates the new SW,
    // and reloads the page. The plugin handles the reload internally.
    updateServiceWorker(true);
  };

  if (!showInstall && !needRefresh) return null;

  return (
    <>
      {showInstall && (
        <div className="pwa-install-banner">
          <p>Install Apparel Designer for offline access!</p>
          <div className="pwa-install-actions">
            <button onClick={handleInstall} className="install-btn">Install</button>
            <button onClick={() => setShowInstall(false)} className="dismiss-btn">Later</button>
          </div>
        </div>
      )}
      {needRefresh && (
        <div className="pwa-update-banner">
          <span>🔄 New version available!</span>
          <button onClick={handleUpdate} className="refresh-btn">Refresh</button>
          <button onClick={() => setNeedRefresh(false)} className="close-btn">✕</button>
        </div>
      )}
    </>
  );
}
