// ─────────────────────────────────────────────────────────────────────────────
// Ultra Image Cropper Library — Main Entry Component
// Frontend-only. No backend required. AI via user-provided API keys.
// ─────────────────────────────────────────────────────────────────────────────

import React, { useEffect } from 'react';
import type { UltraImageCropperProps } from '@/types';
import { useLicense } from '@/hooks/useLicense';
import { useFileInput } from '@/hooks/useFileInput';
import { useCanvasStore, useToastStore, useAIConfigStore } from '@/store';
import { getContextPreset } from '@/utils/contextPresets';
import { ModalOverlay } from './modal/ModalOverlay';
import { ToastContainer } from './ui/ToastContainer';
import '@/styles/ultraimage.css';

export const UltraImageCropper: React.FC<UltraImageCropperProps> = ({
  licenseKey,
  aiConfig,
  context = 'general',
  ratio,
  shape,
  minWidth,
  outputFormat,
  quality = 85,
  ai = false,
  tools = 'all',
  watermark = false,
  watermarkPreset = 'default',
  theme = 'light',
  locale = 'en',
  uploadEndpoint,
  onUploadSuccess,
  onCancel,
  onError,
  className = '',
  triggerLabel = 'Upload Image',
  maxSize = '10MB',
}) => {
  // ── License (frontend-only, synchronous) ──────────────────────────────────
  const { isValid, isValidating, hasAI } = useLicense(licenseKey);

  // ── Sync aiConfig + locale into global store ─────────────────────────────
  const { setAIConfig } = useAIConfigStore();
  const { setLocale } = useCanvasStore();
  useEffect(() => { setAIConfig(aiConfig ?? {}); }, [aiConfig, setAIConfig]);
  useEffect(() => { setLocale(locale); }, [locale, setLocale]);

  // ── File input ────────────────────────────────────────────────────────────
  const { fileInputRef, handleFileChange, handleDrop, triggerFileInput } =
    useFileInput(maxSize, onError);

  // ── Canvas / Toast stores ─────────────────────────────────────────────────
  const { isModalOpen, setOutputFormat, setQuality, closeModal, setCrop } = useCanvasStore();
  const { addToast } = useToastStore();

  // ── Apply context preset + prop overrides ─────────────────────────────────
  useEffect(() => {
    const preset = getContextPreset(context);
    setOutputFormat(outputFormat ?? preset.outputFormat);
    setQuality(quality ?? preset.quality);
    setCrop({ ratio: ratio ?? preset.ratio, shape: shape ?? preset.shape });
  }, [context, ratio, shape, outputFormat, quality, setOutputFormat, setQuality, setCrop]);

  // ── Theme attribute ───────────────────────────────────────────────────────
  useEffect(() => {
    const apply = (dark: boolean) =>
      document.documentElement.setAttribute('data-ultra-theme', dark ? 'dark' : 'light');

    if (theme === 'auto') {
      const mq = window.matchMedia('(prefers-color-scheme: dark)');
      apply(mq.matches);
      const onChange = (e: MediaQueryListEvent) => apply(e.matches);
      mq.addEventListener('change', onChange);
      return () => mq.removeEventListener('change', onChange);
    }

    apply(theme === 'dark');
  }, [theme]);

  const handleTriggerClick = () => {
    if (isValidating) { addToast('Validating license…', 'info', 2000); return; }
    if (!isValid) {
      addToast('Invalid or expired license key.', 'error', 5000);
      onError?.(new Error('Invalid license key'));
      return;
    }
    triggerFileInput();
  };

  const handleCancel = () => { closeModal(); onCancel?.(); };

  const preset = getContextPreset(context);
  const resolvedTools = tools === 'all' ? preset.tools : tools;
  // AI panel is enabled when: `ai` prop is true AND aiConfig with at least one provider is provided
  const canUseAI = ai && !!(aiConfig && Object.keys(aiConfig).length > 0);

  return (
    <div
      className={`ultra-trigger-wrapper ${className}`}
      data-testid="ultra-image-cropper"
      dir={locale === 'ar' ? 'rtl' : 'ltr'}
    >
      {/* Hidden file input */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/jpeg,image/png,image/gif,image/webp,image/avif,image/heic,image/heif"
        style={{ display: 'none' }}
        onChange={handleFileChange}
      />

      {/* Trigger Button */}
      <button
        className="ultra-trigger-btn"
        onClick={handleTriggerClick}
        onDragOver={(e) => e.preventDefault()}
        onDrop={handleDrop}
        disabled={isValidating}
        aria-label={triggerLabel}
        title={isValidating ? 'Validating license…' : triggerLabel}
      >
        <span className="ultra-trigger-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <rect x="3" y="3" width="18" height="18" rx="2" />
            <circle cx="8.5" cy="8.5" r="1.5" />
            <polyline points="21 15 16 10 5 21" />
          </svg>
        </span>
        <span className="ultra-trigger-label">
          {isValidating ? 'Loading…' : triggerLabel}
        </span>
      </button>

      {/* License warning — shown when key is invalid */}
      {!isValid && !isValidating && (
        <div className="ultra-license-gate">
          <span className="ultra-license-badge">⚠ Invalid License</span>
          <p className="ultra-hint" style={{ marginTop: 4, fontSize: 11 }}>
            Check your <code>licenseKey</code> prop. Generate keys with <code>generateLicenseKey()</code>.
          </p>
        </div>
      )}

      {/* AI config missing warning — shown when ai=true but no aiConfig */}
      {isValid && ai && !canUseAI && (
        <div className="ultra-license-gate">
          <span className="ultra-license-badge ultra-license-badge--info">⚙ AI Not Configured</span>
          <p className="ultra-hint" style={{ marginTop: 4, fontSize: 11 }}>
            Pass an <code>aiConfig</code> prop with provider API keys to enable AI tools.
          </p>
        </div>
      )}

      {/* Full-screen Editor Modal */}
      {isModalOpen && (
        <ModalOverlay
          context={context}
          tools={resolvedTools}
          canUseAI={canUseAI}
          watermark={watermark}
          watermarkPreset={watermarkPreset}
          uploadEndpoint={uploadEndpoint}
          onUploadSuccess={onUploadSuccess}
          onCancel={handleCancel}
          onError={onError}
          locale={locale}
          minWidth={minWidth ?? preset.minWidth}
        />
      )}

      <ToastContainer />
    </div>
  );
};

export default UltraImageCropper;
