import {StrictMode} from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { supabase } from './lib/supabase';
import { getCachedData, setCachedData } from './lib/cache';

import { buildCloudinaryUrl } from './lib/cloudinary';

// Prefetch critical data to improve LCP and TBT for first-time users
const prefetchCriticalData = async () => {
  try {
    const cachedBanners = getCachedData('home_banners_cache');
    if (!cachedBanners) {
      supabase.from('banners').select('*').eq('is_active', true).order('created_at', { ascending: false }).then(({ data }) => {
        if (data && data.length > 0) {
          setCachedData('home_banners_cache', data, 60);
          if (data[0] && data[0].image_url) {
            const width = window.innerWidth <= 640 ? 'w_640' : 'w_1600';
            const img = new Image();
            img.src = buildCloudinaryUrl(data[0].image_url, `${width},f_auto,q_auto`);
          }
        }
      });
    }

    const cachedSettings = getCachedData('site_settings_cache');
    if (!cachedSettings) {
      supabase.from('settings').select('*').then(({ data }) => {
        if (data) {
          const newSettings: any = { allow_guest_checkout: 'true' };
          data.forEach((item) => { newSettings[item.key] = item.value; });
          setCachedData('site_settings_cache', newSettings, 120);
        }
      });
    }
  } catch (e) {}
};

prefetchCriticalData();

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