
import React, { useState, Suspense, lazy } from 'react';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '../components/ui/resizable';
import Header from '../components/Header';
import Footer from '../components/Footer';
import SEO from '../components/SEO';
import FeedbackButton from '../components/FeedbackButton';
import { useHtmlToImage } from '../hooks/useHtmlToImage';
import { useAuth } from '../contexts/AuthContext';
import { applyWatermark, applySiteWatermark } from '../utils/watermark';
import { useI18n } from '../contexts/I18nContext';
import type { ExportSettings } from '../components/SettingsPanel';
import type { WatermarkSettings } from '../types/watermark';
import type { SplitSettings } from '../types/split';
import { getDefaultSplitSettings, SPLIT_PRESETS } from '../types/split';
import { splitImage, downloadSlicesAsZip } from '../utils/imageSplitter';
import html2canvas from 'html2canvas';

// Prioritized lazy loading - load CodeEditor first as it's most critical for LCP
const CodeEditor = lazy(() =>
  import('../components/CodeEditor').then(module => ({ default: module.default }))
);

// Load PreviewPanel with high priority as it contains the main visual content
const PreviewPanel = lazy(() =>
  import('../components/PreviewPanel').then(module => ({ default: module.default }))
);

// Settings panel has lower priority as it's not critical for initial paint
const SettingsPanel = lazy(() =>
  import('../components/SettingsPanel').then(module => ({ default: module.default }))
);

// Optimized component loader that matches critical CSS and improves LCP
const ComponentLoader = () => (
  <div className="h-full flex items-center justify-center bg-card">
    <div className="w-6 h-6 border-2 border-border border-t-primary rounded-full animate-spin"></div>
  </div>
);

const Index = () => {
  const { t } = useI18n();
  const [htmlContent, setHtmlContent] = useState('');
  const [safeMode, setSafeMode] = useState(false);

  // Shared device and size state
  const [selectedDevice, setSelectedDevice] = useState<'desktop' | 'tablet' | 'mobile'>('desktop');
  const [customWidth, setCustomWidth] = useState(1200);
  const [customHeight, setCustomHeight] = useState(800);

  // Watermark state - updated with default preset values (enabled remains false)
  const [watermarkSettings, setWatermarkSettings] = useState<WatermarkSettings>({
    enabled: false,
    type: 'text',
    content: '',
    position: 'bottom-right',
    opacity: 30,
    size: 45,
    repeat: 'tile',
    color: '#ff0000',
    fontFamily: 'Inter',
    fontWeight: 'bold',
    density: 3,
    angle: -45,
    offsetX: 10,
    offsetY: 0,
  });

  // Split settings state
  const [splitSettings, setSplitSettings] = useState<SplitSettings>(getDefaultSplitSettings());
  const [isSplitExporting, setIsSplitExporting] = useState(false);

  // Get premium status from auth context
  const { isPremium } = useAuth();

  const { exportToImage, isExporting } = useHtmlToImage({ isPremium });

  // Updated device size mapping with better defaults
  const deviceSizes = {
    desktop: { width: 1200, height: 800 },
    tablet: { width: 1024, height: 768 },
    mobile: { width: 375, height: 812 },
  };

  // Always return custom dimensions (removed device-specific logic)
  const getCurrentDimensions = () => {
    return { width: customWidth, height: customHeight };
  };

  // Updated thresholds: mobile ≤600, tablet ≤1024, desktop >1024
  const detectDeviceFromWidth = (width: number): 'desktop' | 'tablet' | 'mobile' => {
    if (width <= 600) return 'mobile';
    if (width <= 1024) return 'tablet';
    return 'desktop';
  };

  // Handle device change - set default size but allow further customization
  const handleDeviceChange = (device: 'desktop' | 'tablet' | 'mobile') => {
    setSelectedDevice(device);
    // Only set default size when device changes, don't force it
    const size = deviceSizes[device];
    setCustomWidth(size.width);
    setCustomHeight(size.height);
  };

  // Handle size change from SettingsPanel
  const handleSizeChange = (width: number, height: number) => {
    setCustomWidth(width);
    setCustomHeight(height);

    // Auto-detect and update device based on width only when crossing boundaries
    const detectedDevice = detectDeviceFromWidth(width);
    if (detectedDevice !== selectedDevice) {
      setSelectedDevice(detectedDevice);
    }
  };

  const handleExport = async (settings: ExportSettings) => {
    if (!htmlContent.trim()) {
      return;
    }

    await exportToImage(htmlContent, settings);
  };

  // Handle split export
  const handleExportSplit = async () => {
    if (!htmlContent.trim() || !splitSettings.enabled) {
      return;
    }

    setIsSplitExporting(true);
    try {
      // Get the preview iframe
      const iframe = document.getElementById('preview-frame') as HTMLIFrameElement;
      if (!iframe || !iframe.contentDocument) {
        throw new Error('Preview not available');
      }

      // Render to canvas
      const canvas = await html2canvas(iframe.contentDocument.body, {
        width: customWidth,
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
        scale: 2,
      });

      // Apply user's custom watermark if enabled
      let finalCanvas = canvas;
      if (watermarkSettings.enabled) {
        finalCanvas = applyWatermark(canvas, watermarkSettings);
      }

      // Apply site watermark only for free users
      if (!isPremium) {
        finalCanvas = applySiteWatermark(finalCanvas);
      }

      // Split the image
      const result = splitImage(
        finalCanvas,
        splitSettings.preset,
        splitSettings.customRatio,
        splitSettings.customMaxSlices,
        splitSettings.overlap,
        splitSettings.outputWidth
      );

      // Download as ZIP
      await downloadSlicesAsZip(result.slices, 'split-images', 'png', 0.95);
    } catch (error) {
      console.error('Split export error:', error);
    } finally {
      setIsSplitExporting(false);
    }
  };

  const currentDimensions = getCurrentDimensions();

  return (
    <>
      <SEO />
      <div className="min-h-screen bg-background">
        <Header />

        <main className="mx-auto w-full max-w-none px-4 md:px-6 lg:px-8 py-6">
          <div className="h-[calc(100vh-12rem)]">
            <ResizablePanelGroup direction="horizontal" className="w-full rounded-lg border border-border">
              <ResizablePanel defaultSize={30} minSize={25}>
                <Suspense fallback={<ComponentLoader />}>
                  <CodeEditor
                    value={htmlContent}
                    onChange={setHtmlContent}
                  />
                </Suspense>
              </ResizablePanel>

              <ResizableHandle withHandle />

              <ResizablePanel defaultSize={45} minSize={30}>
                <Suspense fallback={<ComponentLoader />}>
                  <PreviewPanel
                    htmlContent={htmlContent}
                    width={currentDimensions.width}
                    height={currentDimensions.height}
                    safeMode={safeMode}
                    onSafeModeChange={setSafeMode}
                    selectedDevice={selectedDevice}
                    onDeviceChange={handleDeviceChange}
                    watermarkSettings={watermarkSettings}
                  />
                </Suspense>
              </ResizablePanel>

              <ResizableHandle withHandle />

              <ResizablePanel defaultSize={25} minSize={20}>
                <Suspense fallback={<ComponentLoader />}>
                  <SettingsPanel
                    onExport={handleExport}
                    width={currentDimensions.width}
                    height={currentDimensions.height}
                    onSizeChange={handleSizeChange}
                    selectedDevice={selectedDevice}
                    watermarkSettings={watermarkSettings}
                    onWatermarkChange={setWatermarkSettings}
                    splitSettings={splitSettings}
                    onSplitChange={setSplitSettings}
                    onExportSplit={handleExportSplit}
                    isSplitExporting={isSplitExporting}
                  />
                </Suspense>
              </ResizablePanel>
            </ResizablePanelGroup>
          </div>

          {/* Removed bottom FAQ section as requested */}
          {/* Previously:
          <div className="mt-8 max-w-4xl mx-auto">
            <FAQSection variant="compact" />
          </div>
          */}
        </main>

        <FeedbackButton />
        <Footer />
      </div>
    </>
  );
};

export default Index;
