// ─────────────────────────────────────────────────────────────────────────────
// Ultra Image Cropper Library — Dev Demo App
// Run: npm run dev   → opens at http://localhost:3002
// ─────────────────────────────────────────────────────────────────────────────

import React, { useState, useRef, useEffect } from 'react';
import { UltraImageCropper } from './components/UltraImageCropper';
import { generateLicenseKey } from './license/LicenseManager';
import { useFileInput } from './hooks/useFileInput';
import type { AIConfig, UILocale, UploadSuccessResult } from './types';

const DEMO_LICENSE_KEY = generateLicenseKey('DEV', new Date('2030-01-01'));

const AZURE_SMART_CROP_CONFIG = {
  provider: 'azure-openai' as const,
  apiKey:     import.meta.env.VITE_AZURE_GPT_KEY         ?? '',
  endpoint:   import.meta.env.VITE_AZURE_GPT_ENDPOINT    ?? '',
  deployment: import.meta.env.VITE_AZURE_GPT_DEPLOYMENT  ?? 'gpt-4o',
  apiVersion: import.meta.env.VITE_AZURE_GPT_API_VERSION ?? '2025-04-01-preview',
};

const AI_CONFIG: AIConfig = {
  backgroundRemoval: { provider: 'local' },
  upscaling:         { provider: 'local' },
  smartCrop:         AZURE_SMART_CROP_CONFIG,
};

const LOCALES: { code: UILocale; label: string }[] = [
  { code: 'en', label: 'EN' },
  { code: 'ar', label: 'AR' },
  { code: 'fr', label: 'FR' },
  { code: 'de', label: 'DE' },
  { code: 'es', label: 'ES' },
  { code: 'zh', label: 'ZH' },
  { code: 'jp', label: 'JP' },
];

export const DemoApp: React.FC = () => {
  const [result, setResult]       = useState<UploadSuccessResult | null>(null);
  const [theme, setTheme]         = useState<'light' | 'dark'>('light');
  const [locale, setLocale]       = useState<UILocale>('en');
  const [isDragging, setIsDragging] = useState(false);
  const [localeOpen, setLocaleOpen] = useState(false);
  const localeRef                   = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (localeRef.current && !localeRef.current.contains(e.target as Node)) {
        setLocaleOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const { fileInputRef, handleFileChange, handleDrop, triggerFileInput } =
    useFileInput('20MB', (err) => console.error('[Demo] Error:', err));

  const dark = theme === 'dark';

  const c = {
    bg:        dark ? '#0f1117' : '#eef2ff',
    dot:       dark ? '#2a3050' : '#b8c5f5',
    card:      dark ? '#1a1d2e' : '#ffffff',
    text:      dark ? '#f1f5f9' : '#1e293b',
    sub:       dark ? '#94a3b8' : '#64748b',
    border:    dark ? '#2d3246' : '#e2e8f0',
    ctrlBg:    dark ? 'rgba(30,34,53,0.85)' : 'rgba(255,255,255,0.75)',
    ctrlBorder: dark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)',
  };

  const themeBtn = (active: boolean) => ({
    width: 32,
    height: 32,
    borderRadius: '50%' as const,
    border: `1px solid ${active ? '#6366f1' : c.ctrlBorder}`,
    background: active ? '#6366f1' : c.ctrlBg,
    color: active ? '#ffffff' : c.sub,
    cursor: 'pointer' as const,
    display: 'flex' as const,
    alignItems: 'center' as const,
    justifyContent: 'center' as const,
    transition: 'all 180ms ease',
    flexShrink: 0 as const,
  });

  return (
    <div
      data-ultra-theme={theme}
      style={{
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: c.bg,
        backgroundImage: [
          `radial-gradient(ellipse 75% 60% at 50% 50%, rgba(${dark ? '15,17,23' : '238,242,255'}, 1) 0%, rgba(${dark ? '15,17,23' : '238,242,255'}, 0.85) 35%, rgba(${dark ? '15,17,23' : '238,242,255'}, 0) 70%)`,
          `radial-gradient(circle, ${c.dot} 1.5px, transparent 1.5px)`,
        ].join(', '),
        backgroundSize: '100% 100%, 24px 24px',
        fontFamily: 'Inter, system-ui, -apple-system, sans-serif',
      }}
    >
      {/* 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}
      />

      {/* ── Top nav — transparent, part of page flow ───────────────────────── */}
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '22px 32px',
      }}>
        <img src="/logo.png" alt="Ultra Image Cropper" style={{ height: 36, objectFit: 'contain' }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>

          {/* ── Locale dropdown ──────────────────────────────────────────── */}
          <div ref={localeRef} style={{ position: 'relative' }}>
            <button
              onClick={() => setLocaleOpen(o => !o)}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 6,
                padding: '0 10px',
                height: 32,
                borderRadius: 100,
                border: `1px solid ${localeOpen ? '#6366f1' : c.ctrlBorder}`,
                background: localeOpen ? (dark ? '#2a3050' : '#eef0ff') : c.ctrlBg,
                color: c.text,
                cursor: 'pointer',
                fontFamily: 'inherit',
                fontSize: 13,
                fontWeight: 500,
                transition: 'border-color 150ms, background 150ms',
                outline: 'none',
              }}
            >
              {/* Globe */}
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={c.sub} strokeWidth="2" strokeLinecap="round">
                <circle cx="12" cy="12" r="10"/>
                <line x1="2" y1="12" x2="22" y2="12"/>
                <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
              </svg>
              <span>{locale.toUpperCase()}</span>
              {/* Chevron */}
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={c.sub} strokeWidth="2.5" strokeLinecap="round"
                style={{ transition: 'transform 200ms ease', transform: localeOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}>
                <polyline points="6 9 12 15 18 9"/>
              </svg>
            </button>

            {localeOpen && (
              <div style={{
                position: 'absolute',
                top: 'calc(100% + 8px)',
                right: 0,
                minWidth: 110,
                background: c.ctrlBg,
                border: `1px solid ${c.ctrlBorder}`,
                borderRadius: 10,
                boxShadow: dark ? '0 8px 24px rgba(0,0,0,0.45)' : '0 8px 24px rgba(0,0,0,0.11)',
                overflow: 'hidden',
                zIndex: 50,
              }}>
                {LOCALES.map((l) => {
                  const active = locale === l.code;
                  return (
                    <button
                      key={l.code}
                      onClick={() => { setLocale(l.code); setLocaleOpen(false); }}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        width: '100%',
                        padding: '9px 14px',
                        border: 'none',
                        background: active
                          ? (dark ? 'rgba(99,102,241,0.18)' : 'rgba(99,102,241,0.09)')
                          : 'transparent',
                        color: active ? '#6366f1' : c.text,
                        fontWeight: active ? 600 : 400,
                        fontSize: 13,
                        cursor: 'pointer',
                        fontFamily: 'inherit',
                        textAlign: 'left',
                      }}
                      onMouseEnter={(e) => {
                        if (!active) e.currentTarget.style.background = dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)';
                      }}
                      onMouseLeave={(e) => {
                        if (!active) e.currentTarget.style.background = 'transparent';
                      }}
                    >
                      {l.label}
                      {active && (
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#6366f1" strokeWidth="2.5" strokeLinecap="round">
                          <polyline points="20 6 9 17 4 12"/>
                        </svg>
                      )}
                    </button>
                  );
                })}
              </div>
            )}
          </div>

          {/* ── Theme — sun + moon two-button toggle ─────────────────────── */}
          {/* Sun / Light */}
          <div className = "mode-btn-group" style={{border: `1px solid ${c.border}`}}>
          <button onClick={() => setTheme('light')} title="Light mode" style={themeBtn(!dark)}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <circle cx="12" cy="12" r="5"/>
              <line x1="12" y1="1" x2="12" y2="3"/>
              <line x1="12" y1="21" x2="12" y2="23"/>
              <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
              <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
              <line x1="1" y1="12" x2="3" y2="12"/>
              <line x1="21" y1="12" x2="23" y2="12"/>
              <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
              <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
            </svg>
          </button>
          {/* Moon / Dark */}
          <button onClick={() => setTheme('dark')} title="Dark mode" style={themeBtn(dark)}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
            </svg>
          </button>
</div>
        </div>
      </div>

      {/* ── Main content ───────────────────────────────────────────────────── */}
      <main style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '0 24px 48px',
      }}>
        <div style={{
          background: c.card,
          borderRadius: 16,
          border: `1px solid ${c.border}`,
          boxShadow: dark
            ? '0 4px 40px rgba(0,0,0,0.5), 0 1px 0 rgba(255,255,255,0.04)'
            : '0 4px 40px rgba(100,120,200,0.1), 0 1px 3px rgba(0,0,0,0.05)',
          padding: '40px',
          width: '100%',
          maxWidth: 640,
        }}>
          <h1 style={{
            fontSize: 28,
            fontWeight: 700,
            color: c.text,
            margin: '0 0 10px',
            textAlign: 'center',
            letterSpacing: '-0.02em',
          }}>
            Transform Your Images
          </h1>
          <p style={{
            fontSize: 14,
            color: c.sub,
            textAlign: 'center',
            margin: '0 0 28px',
            lineHeight: 1.6,
          }}>
            Professional grade image enhancement, Upscale, and editing powered by cutting edge
          </p>

          {/* Drop zone */}
          <div
            onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
            onDragLeave={() => setIsDragging(false)}
            onDrop={(e) => { setIsDragging(false); handleDrop(e); }}
            onClick={triggerFileInput}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => e.key === 'Enter' && triggerFileInput()}
            style={{
              border: `2px dashed ${isDragging ? '#6366f1' : c.border}`,
              borderRadius: 12,
              padding: '40px 24px',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: 8,
              cursor: 'pointer',
              background: isDragging
                ? (dark ? 'rgba(99,102,241,0.08)' : 'rgba(99,102,241,0.04)')
                : (dark ? 'rgba(255,255,255,0.02)' : 'transparent'),
              transition: 'border-color 150ms ease, background 150ms ease',
              marginBottom: 20,
              outline: 'none',
            }}
          >
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none"
              stroke={isDragging ? '#6366f1' : c.sub}
              strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
              <polyline points="17 8 12 3 7 8"/>
              <line x1="12" y1="3" x2="12" y2="15"/>
            </svg>
            <p style={{ margin: 0, fontSize: 14, color: c.text, textAlign: 'center' }}>
              Drag & Drop or{' '}
              <span style={{ color: '#6366f1', fontWeight: 500 }}>Choose file</span>
              {' '}to upload
            </p>
            <p style={{ margin: 0, fontSize: 12, color: c.sub }}>
              Max file size : 20 MB
            </p>
          </div>

          {/* Open Image Editor button */}
          <button
            onClick={triggerFileInput}
            style={{
              width: '100%',
              padding: '13px',
              borderRadius: 10,
              border: 'none',
              background: 'linear-gradient(135deg, #4f46e5 0%, #6366f1 100%)',
              color: '#fff',
              fontSize: 15,
              fontWeight: 600,
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 8,
              fontFamily: 'inherit',
              letterSpacing: '-0.01em',
              transition: 'opacity 150ms ease',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.opacity = '0.88'; }}
            onMouseLeave={(e) => { e.currentTarget.style.opacity = '1'; }}
          >
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor"
              strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <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>
            Open Image Editor
          </button>
        </div>

        {/* Result preview */}
        {result && (
          <div style={{
            marginTop: 20,
            background: c.card,
            border: `1px solid ${c.border}`,
            borderRadius: 12,
            padding: 20,
            maxWidth: 640,
            width: '100%',
          }}>
            <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 600, color: c.text }}>Last Export</h3>
            <img
              src={result.url}
              alt="Export result"
              style={{ maxWidth: '100%', maxHeight: 280, objectFit: 'contain', borderRadius: 8, display: 'block' }}
            />
            <p style={{ margin: '8px 0 0', color: c.sub, fontSize: 12 }}>
              {result.width} × {result.height}px · {result.format.toUpperCase()} · {(result.size / 1024).toFixed(1)} KB
            </p>
          </div>
        )}
      </main>

      {/* ── Footer ─────────────────────────────────────────────────────────── */}
      <footer style={{
        textAlign: 'center',
        padding: '16px 24px',
        color: c.sub,
        fontSize: 13,
      }}>
        © 2026 Ultra Image Cropper. All rights reserved.
      </footer>

      {/*
        Ultra Image Cropper off-screen: its modal (position:fixed, z-index:9000) stays
        visible. Files are processed by useFileInput above which writes to the
        shared Zustand store; Ultra Image Cropper reads that store and renders the modal.
      */}
      <div style={{ position: 'fixed', left: '-9999px', top: 0, width: 0, height: 0, overflow: 'visible', zIndex: 9999 }}>
        <UltraImageCropper
          licenseKey={DEMO_LICENSE_KEY}
          aiConfig={AI_CONFIG}
          ai={true}
          context="general"
          theme={theme}
          locale={locale}
          tools="all"
          maxSize="20MB"
          onUploadSuccess={(res) => setResult(res)}
          onError={(err) => console.error('[Demo] Error:', err)}
        />
      </div>
    </div>
  );
};

export default DemoApp;
