import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
import './index.css';
import './main.css';

// PWA Installation Handler
let deferredPrompt = null;
let installBanner = null;

function createInstallBanner() {
  const banner = document.createElement('div');
  banner.className = 'pwa-install-banner';
  banner.setAttribute('role', 'dialog');
  banner.setAttribute('aria-label', 'Install NEETUGmocks App');
  banner.innerHTML = `
    <div style="flex: 1">
      <strong style="font-size: 16px">Install NEETUGmocks App</strong>
      <p style="font-size: 12px; margin: 4px 0 0; opacity: 0.9">Get faster access to NEET mock tests & offline support</p>
    </div>
    <button id="install-btn" aria-label="Install NEETUGmocks app" style="background: white; color: #4f46e5; border: none; padding: 10px 20px; border-radius: 12px; font-weight: 600; cursor: pointer;">Install</button>
    <button id="close-banner" aria-label="Close install banner" class="close-btn" style="background: rgba(255,255,255,0.2); color: white; padding: 8px; border-radius: 8px;">✕</button>
  `;
  return banner;
}

function showInstallBanner() {
  if (installBanner || !deferredPrompt) return;
  
  installBanner = createInstallBanner();
  document.body.appendChild(installBanner);
  
  const installBtn = installBanner.querySelector('#install-btn');
  const closeBtn = installBanner.querySelector('#close-banner');
  
  installBtn.addEventListener('click', async () => {
    if (deferredPrompt) {
      deferredPrompt.prompt();
      const { outcome } = await deferredPrompt.userChoice;
      console.log(`User response to install prompt: ${outcome}`);
      deferredPrompt = null;
      
      if (typeof window.gtag !== 'undefined') {
        window.gtag('event', 'pwa_install', {
          'event_category': 'pwa',
          'event_label': outcome
        });
      }
    }
    if (installBanner) {
      installBanner.remove();
      installBanner = null;
    }
  });
  
  closeBtn.addEventListener('click', () => {
    if (installBanner) {
      installBanner.remove();
      installBanner = null;
    }
    localStorage.setItem('pwa-banner-dismissed', Date.now());
  });
}

// Register Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js', { scope: '/' })
      .then(registration => {
        console.log('NEETUGmocks SW registered: ', registration.scope);
        
        setInterval(() => {
          registration.update();
        }, 60 * 60 * 1000);
        
        registration.addEventListener('updatefound', () => {
          const newWorker = registration.installing;
          if (newWorker) {
            newWorker.addEventListener('statechange', () => {
              if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                const shouldUpdate = confirm('New NEETUGmocks version available! Update for better experience?');
                if (shouldUpdate) {
                  newWorker.postMessage('skipWaiting');
                  window.location.reload();
                }
              }
            });
          }
        });
      })
      .catch(err => console.log('SW registration failed: ', err));
    
    let refreshing = false;
    navigator.serviceWorker.addEventListener('controllerchange', () => {
      if (!refreshing) {
        refreshing = true;
        window.location.reload();
      }
    });
  });
}

// Handle PWA installation prompt
window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  deferredPrompt = e;
  
  const lastDismissed = localStorage.getItem('pwa-banner-dismissed');
  const oneWeek = 7 * 24 * 60 * 60 * 1000;
  const shouldShowBanner = !lastDismissed || (Date.now() - parseInt(lastDismissed) > oneWeek);
  
  if (shouldShowBanner) {
    setTimeout(showInstallBanner, 2000);
  }
});

window.addEventListener('appinstalled', () => {
  console.log('NEETUGmocks app installed');
  
  if (typeof window.gtag !== 'undefined') {
    window.gtag('event', 'app_installed', {
      'event_category': 'pwa',
      'event_label': 'success'
    });
  }
  
  if (installBanner) {
    installBanner.remove();
    installBanner = null;
  }
  deferredPrompt = null;
});

// Root rendering
const rootElement = document.getElementById('root');

if (rootElement) {
  ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
}

/**
 * Update meta tags dynamically for SEO
 * @param {Object} options
 * @param {string} options.title - Page title (without suffix)
 * @param {string} options.description - Meta description
 * @param {string} options.keywords - Additional keywords
 * @param {string} options.canonical - Canonical URL
 */
export function updateMetaTags({ title, description, keywords, canonical }) {
  const baseKeywords = 'NEET mock test, free NEET mock test, NEET UG preparation, NEET online practice, NEETUGmocks';
  
  if (title) {
    const fullTitle = `${title} | NEETUGmocks`;
    document.title = fullTitle;
    document.querySelector('meta[name="title"]')?.setAttribute('content', fullTitle);
    document.querySelector('meta[property="og:title"]')?.setAttribute('content', fullTitle);
    document.querySelector('meta[name="twitter:title"]')?.setAttribute('content', fullTitle);
  }
  
  if (description) {
    document.querySelector('meta[name="description"]')?.setAttribute('content', description);
    document.querySelector('meta[property="og:description"]')?.setAttribute('content', description);
    document.querySelector('meta[name="twitter:description"]')?.setAttribute('content', description);
  }
  
  if (keywords) {
    document.querySelector('meta[name="keywords"]')?.setAttribute('content', `${keywords}, ${baseKeywords}`);
  }
  
  if (canonical) {
    let canonicalLink = document.querySelector('link[rel="canonical"]');
    if (canonicalLink) {
      canonicalLink.setAttribute('href', canonical);
    } else {
      canonicalLink = document.createElement('link');
      canonicalLink.rel = 'canonical';
      canonicalLink.href = canonical;
      document.head.appendChild(canonicalLink);
    }
  }
}
