import React, {
  useState,
  useCallback,
  useEffect,
  useMemo,
  DragEvent,
} from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleGenAI, Modality } from '@google/genai';

// ====================== TYPES ======================
interface Config {
  basePrompt: string;
  ethnicity: string;
  bodyShape: string;
  eyeColor: string;
  hairStyle: string;
  hairColor: string;
  style: string;
  expression: string;
  background: string;
  skinTexture: string;
  accessories: string;
  aspectRatio: string;
  numImages: number;
}

interface Toast {
  id: number;
  message: string;
  type: 'success' | 'error';
}

// ====================== HELPER ======================
const fileToGenerativePart = async (file: File): Promise<any> => {
  const base64 = await new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () =>
      resolve((reader.result as string).split(',')[1]);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
  return { inlineData: { data: base64, mimeType: file.type } };
};

// ====================== CONSTANTS ======================
const PRESETS: Record<string, string> = {
  Cyberpunk:
    'Neon-lit cyberpunk city, high-tech interface, chrome accents, futuristic streetwear, rain-slicked streets, vibrant blue and pink rim lights.',
  Editorial:
    'High-fashion vogue editorial, studio lighting, neutral background, sharp focus, minimalist styling, haute couture.',
  Cinematic:
    'Movie still, dramatic lighting, shallow depth of field, anamorphic lens flares, color graded, atmospheric smoke.',
  Ethereal:
    'Soft dreamy atmosphere, blooming light, pastel colors, floating particles, fantasy elements, angelic glow.',
  Noir: 'Black and white photography, high contrast, dramatic shadows, venetian blind lighting, mysterious atmosphere, detective aesthetic.',
};

const RANDOM_DATA = {
  ethnicity: ['African', 'Asian', 'Caucasian', 'Hispanic/Latin', 'Middle Eastern', 'Pacific Islander', 'Mixed Race'],
  bodyShape: ['Curvy', 'Athletic', 'Slim', 'Petite', 'Plus Size', 'Hourglass'],
  eyeColor: ['Brown', 'Blue', 'Green', 'Hazel', 'Grey', 'Amber'],
  hairStyle: ['Sleek Bob', 'Long Waves', 'Pixie Cut', 'Braids', 'Messy Bun', 'Straight', 'Curly Afro'],
  hairColor: ['Black', 'Brunette', 'Blonde', 'Platinum', 'Red', 'Pastel Pink', 'Silver'],
  style: ['Streetwear', 'Business', 'Bohemian', 'Minimalist', 'Grunge', 'Luxury', 'Techwear'],
  expression: ['Confident', 'Mysterious', 'Joyful', 'Serious', 'Seductive', 'Calm'],
  background: ['Studio', 'Urban Night', 'Forest', 'Beach Sunset', 'Cyberpunk City', 'Minimal White', 'Dark Moody'],
};

const ASPECT_RATIOS = [
  { label: '1:1 Square', value: '1:1' },
  { label: '4:5 Portrait', value: '4:5' },
  { label: '9:16 Vertical', value: '9:16' },
  { label: '16:9 Landscape', value: '16:9' },
];

// ====================== TOAST COMPONENT ======================
const ToastContainer: React.FC<{ toasts: Toast[]; removeToast: (id: number) => void }> = ({ toasts, removeToast }) => {
  return (
    <div style={{
      position: 'fixed',
      bottom: '30px',
      left: '50%',
      transform: 'translateX(-50%)',
      zIndex: 1000,
      display: 'flex',
      flexDirection: 'column',
      gap: '10px',
    }}>
      {toasts.map((t) => (
        <div
          key={t.id}
          style={{
            background: t.type === 'error' ? '#ff3366' : '#00f0ff',
            color: '#000',
            padding: '1rem 2rem',
            borderRadius: '50px',
            fontWeight: '600',
            boxShadow: '0 10px 30px rgba(0,0,0,0.5)',
            animation: 'slideUp 0.4s ease',
          }}
          onClick={() => removeToast(t.id)}
        >
          {t.message}
        </div>
      ))}
    </div>
  );
};

// ====================== STYLES ======================
const Style = () => (
  <style>{`
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Orbitron:wght@400;600;800&display=swap');
    
    :root {
      --bg-dark: #09090b;
      --bg-panel: #121215;
      --border-color: rgba(255, 255, 255, 0.08);
      --primary: #00f0ff;
      --primary-dim: rgba(0, 240, 255, 0.15);
      --accent: #7000ff;
      --text-main: #ffffff;
      --text-muted: #a1a1aa;
      --gradient-main: linear-gradient(135deg, #00f0ff 0%, #7000ff 100%);
      --radius: 16px;
      --shadow-lg: 0 10px 40px -10px rgba(0,0,0,0.5);
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      font-family: 'Inter', sans-serif;
      background-color: var(--bg-dark);
      background-image: 
        radial-gradient(circle at 10% 20%, rgba(112, 0, 255, 0.08) 0%, transparent 40%), 
        radial-gradient(circle at 90% 80%, rgba(0, 240, 255, 0.08) 0%, transparent 40%);
      color: var(--text-main);
      min-height: 100vh;
    }

    h1, h2, h3 { font-family: 'Orbitron', sans-serif; letter-spacing: 0.05em; }

    .container { max-width: 1600px; margin: 0 auto; padding: 2rem; }

    header { text-align: center; margin-bottom: 3rem; padding-top: 2rem; }
    header h1 {
      font-size: 4rem;
      background: linear-gradient(to bottom right, #fff, #999);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin-bottom: 0.5rem;
      filter: drop-shadow(0 0 15px rgba(255,255,255,0.2));
    }
    header p { color: var(--primary); letter-spacing: 0.3em; font-size: 0.85rem; text-transform: uppercase; font-weight: 600; opacity: 0.8; }

    .tabs {
      margin-top: 2.5rem;
      display: inline-flex;
      background: rgba(255,255,255,0.03);
      border: 1px solid var(--border-color);
      border-radius: 100px;
      padding: 6px;
      backdrop-filter: blur(10px);
    }
    .tabs button {
      padding: 0.8rem 2.5rem;
      border: none;
      background: transparent;
      color: var(--text-muted);
      cursor: pointer;
      border-radius: 100px;
      font-size: 0.85rem;
      font-weight: 600;
      font-family: 'Orbitron', sans-serif;
      transition: all 0.3s ease;
    }
    .tabs button.active {
      background: var(--text-main);
      color: #000;
      box-shadow: 0 0 20px rgba(255,255,255,0.3);
    }
    .tabs button:hover:not(.active) { color: var(--text-main); }

    .view-container {
      display: grid;
      gap: 2rem;
      opacity: 0;
      animation: fadeIn 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards;
    }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }

    .generate-view { grid-template-columns: 520px 1fr; }

    .controls-panel, .output-panel {
      background: var(--bg-panel);
      border: 1px solid var(--border-color);
      border-radius: var(--radius);
      padding: 2.5rem;
      box-shadow: var(--shadow-lg);
      backdrop-filter: blur(12px);
    }
    .output-panel {
      min-height: 800px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: radial-gradient(circle at center, #1a1a20 0%, var(--bg-panel) 100%);
    }

    .step-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 2rem 0 1.5rem;
      padding-top: 2rem;
      border-top: 1px solid var(--border-color);
    }
    .step-header.first { margin-top: 0; padding-top: 0; border-top: none; }
    .step-num {
      font-family: 'Orbitron', sans-serif;
      font-size: 0.9rem;
      color: var(--bg-dark);
      background: var(--primary);
      width: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 6px;
      margin-right: 12px;
      font-weight: 800;
    }
    .step-title { color: var(--text-main); font-size: 1rem; font-weight: 600; letter-spacing: 0.05em; }

    label { display: block; font-size: 0.75rem; color: var(--text-muted); margin-bottom: 0.5rem; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 600; }
    select, input[type="text"], textarea {
      width: 100%;
      background: rgba(0,0,0,0.3);
      border: 1px solid var(--border-color);
      color: var(--text-main);
      padding: 0.9rem;
      border-radius: 8px;
      font-size: 0.9rem;
      transition: all 0.2s;
    }
    select:focus, input:focus, textarea:focus {
      border-color: var(--primary);
      box-shadow: 0 0 0 2px var(--primary-dim);
    }
    textarea { min-height: 100px; resize: vertical; line-height: 1.5; }

    select {
      appearance: none;
      background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
      background-repeat: no-repeat;
      background-position: right 1rem center;
      background-size: 1em;
    }

    .control-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem; }
    .control-full { margin-bottom: 1.5rem; }

    .btn-group { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-top: 0.5rem; }
    .btn-pill {
      background: rgba(255,255,255,0.05);
      border: 1px solid var(--border-color);
      color: var(--text-muted);
      padding: 0.5rem 1rem;
      border-radius: 20px;
      font-size: 0.8rem;
      cursor: pointer;
      transition: all 0.2s;
    }
    .btn-pill:hover { background: rgba(255,255,255,0.1); color: var(--text-main); }
    .btn-pill.active { background: var(--primary); color: var(--bg-dark); border-color: var(--primary); }
    
    .btn-link {
        background: none;
        border: none;
        color: var(--primary);
        font-size: 0.7rem;
        cursor: pointer;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        padding: 0;
    }
    .btn-link:hover { text-decoration: underline; }

    .btn-primary {
      width: 100%;
      background: var(--gradient-main);
      color: white;
      border: none;
      padding: 1.25rem;
      font-family: 'Orbitron', sans-serif;
      font-size: 1.1rem;
      font-weight: 800;
      letter-spacing: 0.1em;
      border-radius: 12px;
      cursor: pointer;
      margin-top: 2rem;
      transition: all 0.3s;
      text-transform: uppercase;
    }
    .btn-primary:hover:not(:disabled) { transform: translateY(-3px); box-shadow: 0 0 40px rgba(0, 240, 255, 0.5); }
    .btn-primary:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

    .btn-random {
      width: 100%;
      margin-bottom: 1.5rem;
      background: rgba(112, 0, 255, 0.1);
      border: 1px solid rgba(112, 0, 255, 0.3);
      color: #d8b4fe;
      padding: 0.75rem;
      border-radius: 8px;
      font-size: 0.85rem;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      font-weight: 600;
    }
    .btn-random:hover { background: rgba(112, 0, 255, 0.2); box-shadow: 0 0 20px rgba(112, 0, 255, 0.3); color: white; }

    .upload-area {
      border: 2px dashed var(--border-color);
      border-radius: 12px;
      padding: 2rem;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s;
      background: rgba(0,0,0,0.2);
    }
    .upload-area:hover, .upload-area.drag-over { border-color: var(--primary); background: rgba(0, 240, 255, 0.08); }
    .upload-area p { color: var(--text-main); font-weight: 600; margin-bottom: 0.5rem; }
    .upload-area span { color: var(--text-muted); font-size: 0.8rem; }

    .thumbnails { display: grid; grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)); gap: 12px; margin-top: 1rem; }
    .thumb-wrap { position: relative; aspect-ratio: 1; }
    .thumb-img { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; border: 1px solid var(--border-color); }
    .thumb-remove { position: absolute; top: -8px; right: -8px; background: #ff3366; color: white; width: 24px; height: 24px; border-radius: 50%; border: none; cursor: pointer; font-size: 14px; font-weight: bold; }

    .output-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap: 2rem; width: 100%; padding: 2rem; }
    .output-card { position: relative; border-radius: 16px; overflow: hidden; box-shadow: 0 15px 40px rgba(0,0,0,0.6); border: 1px solid var(--border-color); transition: all 0.4s; }
    .output-card:hover { transform: translateY(-10px) scale(1.02); border-color: var(--primary); }
    .output-img { width: 100%; display: block; }
    .output-actions {
      position: absolute; bottom: 0; left: 0; right: 0;
      padding: 1.5rem;
      background: linear-gradient(to top, rgba(0,0,0,0.95), transparent);
      display: flex; gap: 1rem; justify-content: center;
      opacity: 0; transition: opacity 0.4s;
    }
    .output-card:hover .output-actions { opacity: 1; }

    .loading-overlay {
      position: fixed; inset: 0; background: rgba(0,0,0,0.9); backdrop-filter: blur(12px);
      display: flex; flex-direction: column; align-items: center; justify-content: center; zIndex: 1000;
    }
    .loading-spinner {
      width: 60px; height: 60px; border: 4px solid rgba(255,255,255,0.1);
      border-top-color: var(--primary); border-radius: 50%; animation: spin 1s linear infinite;
    }
    .loading-text { margin-top: 1.5rem; font-family: 'Orbitron', sans-serif; letter-spacing: 0.3em; color: var(--primary); font-size: 1rem; }

    @keyframes spin { to { transform: rotate(360deg); } }
    @keyframes slideUp { from { transform: translateY(100px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

    @media (max-width: 1200px) { .generate-view { grid-template-columns: 1fr; } }
    @media (max-width: 768px) {
      header h1 { font-size: 2.8rem; }
      .control-grid { grid-template-columns: 1fr; }
      .tabs button { padding: 0.7rem 1.5rem; font-size: 0.8rem; }
    }
  `}</style>
);

// ====================== COMPONENTS ======================

const GalleryView: React.FC<{ images: string[]; setGallery: React.Dispatch<React.SetStateAction<string[]>> }> = ({ images, setGallery }) => {
  return (
    <div className="view-container">
      {images.length === 0 ? (
        <div className="output-panel" style={{ width: '100%', background: 'transparent', border: 'none' }}>
          <p style={{ color: 'var(--text-muted)', textAlign: 'center', fontSize: '1.2rem' }}>
            No archived identities yet. Generate some to see them here.
          </p>
        </div>
      ) : (
        <div className="output-grid">
          {images.map((src, i) => (
            <div key={i} className="output-card">
              <img src={src} alt={`Archive ${i + 1}`} className="output-img" />
              <div className="output-actions">
                <button className="btn-pill" onClick={() => {
                  const a = document.createElement('a');
                  a.href = src;
                  a.download = `AlterEgo_${Date.now()}_${i}.png`;
                  a.click();
                }}>DOWNLOAD</button>
                <button className="btn-pill" style={{ background: '#ff3366', borderColor: '#ff3366' }} onClick={() => setGallery(prev => prev.filter((_, idx) => idx !== i))}>
                  DELETE
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const GenerateTwinView: React.FC<{
  ai: GoogleGenAI;
  addToast: (msg: string, type: 'success' | 'error') => void;
  isGenerating: boolean;
  setIsGenerating: React.Dispatch<React.SetStateAction<boolean>>;
  onImageGenerated: (imgs: string[]) => void;
  config: Config;
  setConfig: React.Dispatch<React.SetStateAction<Config>>;
  refFiles: File[];
  setRefFiles: React.Dispatch<React.SetStateAction<File[]>>;
  previews: string[];
  setPreviews: React.Dispatch<React.SetStateAction<string[]>>;
}> = ({ ai, addToast, isGenerating, setIsGenerating, onImageGenerated, config, setConfig, refFiles, setRefFiles, previews, setPreviews }) => {
  const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  const [dragOver, setDragOver] = useState(false);

  const updateConfig = useCallback((key: keyof Config, value: any) => {
    setConfig(prev => ({ ...prev, [key]: value }));
  }, [setConfig]);

  const randomize = useCallback(() => {
    const r = (arr: string[]) => arr[Math.floor(Math.random() * arr.length)];
    setConfig(prev => ({
      ...prev,
      ethnicity: r(RANDOM_DATA.ethnicity),
      bodyShape: r(RANDOM_DATA.bodyShape),
      eyeColor: r(RANDOM_DATA.eyeColor),
      hairStyle: r(RANDOM_DATA.hairStyle),
      hairColor: r(RANDOM_DATA.hairColor),
      style: r(RANDOM_DATA.style),
      expression: r(RANDOM_DATA.expression),
      background: r(RANDOM_DATA.background),
    }));
  }, []);

  const handleDrop = useCallback((e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setDragOver(false);
    const files = Array.from(e.dataTransfer.files).filter(f => f.type.startsWith('image/')).slice(0, 5);
    setRefFiles(files);
    setPreviews(files.map(f => URL.createObjectURL(f)));
  }, [setRefFiles, setPreviews]);

  const handleFiles = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) return;
    const files = Array.from(e.target.files).slice(0, 5);
    setRefFiles(files);
    setPreviews(files.map(f => URL.createObjectURL(f)));
  }, [setRefFiles, setPreviews]);

  const removeRef = useCallback((index: number) => {
    setRefFiles(prev => prev.filter((_, i) => i !== index));
    setPreviews(prev => {
      // Note: We don't strictly revoke here because we might re-use, 
      // but for proper cleanup, revoking the removed one is good practice.
      // However, since state is lifted, be careful not to revoke if it's still needed elsewhere.
      // For simplicity in this persist-mode, we just filter.
      return prev.filter((_, i) => i !== index);
    });
  }, [setRefFiles, setPreviews]);

  const clearRefs = useCallback(() => {
    setRefFiles([]);
    setPreviews([]);
  }, [setRefFiles, setPreviews]);

  const generate = async () => {
    if (refFiles.length === 0 && config.numImages > 1) {
      addToast('Imagen currently supports only 1 image without reference. Using 1.', 'error');
    }
    setIsGenerating(true);
    setGeneratedImages([]);

    try {
      let prompt = refFiles.length > 0
        ? `CRITICAL: Generate an IDENTICAL TWIN of the reference person(s). Preserve exact facial structure, identity, and features. `
        : `${config.basePrompt}, `;

      prompt += `${config.ethnicity} ethnicity, ${config.bodyShape} physique, ${config.eyeColor} eyes, `;
      prompt += `${config.hairStyle} ${config.hairColor} hair, wearing ${config.style} fashion, ${config.expression} expression. `;
      prompt += `Setting: ${config.background}. `;
      if (config.accessories) prompt += `Accessories: ${config.accessories}. `;
      prompt += `Skin: ${config.skinTexture}. Hyper-realistic, 8k, cinematic lighting, masterpiece, sharp focus.`;

      let results: string[] = [];

      if (refFiles.length > 0) {
        const parts = await Promise.all(refFiles.map(fileToGenerativePart));
        parts.push({ text: prompt });

        for (let i = 0; i < config.numImages; i++) {
          const resp = await ai.models.generateContent({
            model: 'gemini-2.5-flash-image', 
            contents: { parts },
            config: { responseModalities: [Modality.IMAGE] },
          });
          const imgPart = resp.candidates?.[0]?.content?.parts?.find((p: any) => p.inlineData);
          if (imgPart) results.push(`data:image/png;base64,${imgPart.inlineData.data}`);
        }
      } else {
        const resp = await ai.models.generateImages({
          model: 'imagen-4.0-generate-001', 
          prompt,
          config: { numberOfImages: config.numImages, aspectRatio: config.aspectRatio },
        });
        resp.generatedImages?.forEach(g => {
          if (g.image?.imageBytes) results.push(`data:image/png;base64,${g.image.imageBytes}`);
        });
      }

      if (results.length > 0) {
        setGeneratedImages(results);
        onImageGenerated(results);
        addToast(`Successfully generated ${results.length} image(s)!`, 'success');
      } else {
        throw new Error('No images returned');
      }
    } catch (err: any) {
      addToast(err.message || 'Generation failed', 'error');
    } finally {
      setIsGenerating(false);
    }
  };

  return (
    <div className="view-container generate-view">
      <div className="controls-panel">
        <button className="btn-random" onClick={randomize}>
          <span>🎲</span> SURPRISE ME
        </button>

        {/* Reference Upload */}
        <div className="step-header first">
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div className="step-num">01</div>
            <div className="step-title">SOURCE IDENTITY (OPTIONAL)</div>
          </div>
          {refFiles.length > 0 && <button className="btn-link" onClick={clearRefs}>CLEAR SELECTION</button>}
        </div>

        <div
          className={`upload-area ${dragOver ? 'drag-over' : ''}`}
          onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={handleDrop}
        >
          <input type="file" id="ref-files" multiple accept="image/*" onChange={handleFiles} style={{ display: 'none' }} />
          <label htmlFor="ref-files" style={{ cursor: 'pointer', width: '100%', height: '100%' }}>
            <p>DROP IMAGES HERE OR CLICK</p>
            <span>Up to 5 reference photos for perfect digital twin</span>
          </label>
        </div>

        {previews.length > 0 && (
          <div className="thumbnails">
            {previews.map((src, i) => (
              <div key={i} className="thumb-wrap">
                <img src={src} className="thumb-img" alt={`ref ${i + 1}`} />
                <button className="thumb-remove" onClick={() => removeRef(i)}>×</button>
              </div>
            ))}
          </div>
        )}

        {/* Physical Attributes */}
        <div className="step-header">
          <div className="step-num">02</div>
          <div className="step-title">PHYSICAL ATTRIBUTES</div>
        </div>
        <div className="control-grid">
          <div>
            <label>Ethnicity</label>
            <select value={config.ethnicity} onChange={e => updateConfig('ethnicity', e.target.value)}>
              {RANDOM_DATA.ethnicity.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Physique</label>
            <select value={config.bodyShape} onChange={e => updateConfig('bodyShape', e.target.value)}>
              {RANDOM_DATA.bodyShape.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Eye Color</label>
            <select value={config.eyeColor} onChange={e => updateConfig('eyeColor', e.target.value)}>
              {RANDOM_DATA.eyeColor.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Skin Detail</label>
            <select value={config.skinTexture} onChange={e => updateConfig('skinTexture', e.target.value)}>
              <option>Hyper-Realistic</option>
              <option>Porcelain</option>
              <option>Dewy Glow</option>
              <option>Matte</option>
              <option>Freckled</option>
            </select>
          </div>
        </div>

        {/* Style & Hair */}
        <div className="step-header">
          <div className="step-num">03</div>
          <div className="step-title">STYLE & ENVIRONMENT</div>
        </div>
        <div className="control-grid">
          <div>
            <label>Hair Style</label>
            <select value={config.hairStyle} onChange={e => updateConfig('hairStyle', e.target.value)}>
              {RANDOM_DATA.hairStyle.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Hair Color</label>
            <select value={config.hairColor} onChange={e => updateConfig('hairColor', e.target.value)}>
              {RANDOM_DATA.hairColor.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Fashion Style</label>
            <select value={config.style} onChange={e => updateConfig('style', e.target.value)}>
              {RANDOM_DATA.style.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Mood / Expression</label>
            <select value={config.expression} onChange={e => updateConfig('expression', e.target.value)}>
              {RANDOM_DATA.expression.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Background</label>
            <select value={config.background} onChange={e => updateConfig('background', e.target.value)}>
              {RANDOM_DATA.background.map(o => <option key={o}>{o}</option>)}
            </select>
          </div>
          <div>
            <label>Aspect Ratio</label>
            <select value={config.aspectRatio} onChange={e => updateConfig('aspectRatio', e.target.value)}>
              {ASPECT_RATIOS.map(ar => <option key={ar.value} value={ar.value}>{ar.label}</option>)}
            </select>
          </div>
        </div>

        {/* Variants Selection */}
        <div className="control-full">
          <label>Number of Variants</label>
          <select value={config.numImages} onChange={e => updateConfig('numImages', Number(e.target.value))}>
            <option value={1}>1</option>
            <option value={2}>2</option>
            <option value={3}>3</option>
            <option value={4}>4</option>
          </select>
        </div>

        <div className="control-full">
          <label>Quick Presets</label>
          <div className="btn-group">
            {Object.keys(PRESETS).map(k => (
              <button key={k} className="btn-pill" onClick={() => updateConfig('basePrompt', PRESETS[k])}>
                {k}
              </button>
            ))}
          </div>
        </div>

        <div className="control-full">
          <label>Custom Prompt Override</label>
          <textarea
            placeholder="Extra instructions..."
            value={config.basePrompt}
            onChange={e => updateConfig('basePrompt', e.target.value)}
          />
        </div>

        <button className="btn-primary" onClick={generate} disabled={isGenerating}>
          INITIALIZE SYNTHESIS
        </button>
      </div>

      <div className="output-panel">
        {generatedImages.length > 0 ? (
          <div className="output-grid">
            {generatedImages.map((src, i) => (
              <div key={i} className="output-card">
                <img src={src} className="output-img" alt={`Result ${i + 1}`} />
                <div className="output-actions">
                  <button className="btn-pill" onClick={() => {
                    const a = document.createElement('a');
                    a.href = src;
                    a.download = `AlterEgo_${Date.now()}_${i}.png`;
                    a.click();
                  }}>DOWNLOAD</button>
                  <button className="btn-pill" onClick={() => onImageGenerated([src])}>ARCHIVE</button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ textAlign: 'center', opacity: 0.6 }}>
            <h3>AWAITING SYNTHESIS</h3>
            <p>Configure parameters and press the button to begin.</p>
          </div>
        )}
      </div>
    </div>
  );
};

// Edit view remains similar but with toast feedback
const EditImageView: React.FC<{
  ai: GoogleGenAI;
  addToast: (msg: string, type: 'success' | 'error') => void;
  isGenerating: boolean;
  setIsGenerating: React.Dispatch<React.SetStateAction<boolean>>;
  onImageGenerated: (imgs: string[]) => void;
}> = ({ ai, addToast, isGenerating, setIsGenerating, onImageGenerated }) => {
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [prompt, setPrompt] = useState('');
  const [result, setResult] = useState<string | null>(null);

  const handleEdit = async () => {
    if (!file || !prompt) return;
    setIsGenerating(true);
    try {
      const part = await fileToGenerativePart(file);
      const resp = await ai.models.generateContent({
        model: 'gemini-2.5-flash-image',
        contents: { parts: [part, { text: prompt }] },
        config: { responseModalities: [Modality.IMAGE] },
      });
      const img = resp.candidates?.[0]?.content?.parts?.find((p: any) => p.inlineData);
      if (img) {
        const url = `data:image/png;base64,${img.inlineData.data}`;
        setResult(url);
        onImageGenerated([url]);
        addToast('Image edited successfully!', 'success');
      } else {
        throw new Error('No image generated');
      }
    } catch (e: any) {
      addToast(e.message || 'Edit failed', 'error');
    } finally {
      setIsGenerating(false);
    }
  };

  useEffect(() => () => preview && URL.revokeObjectURL(preview), [preview]);

  return (
    <div className="view-container" style={{ maxWidth: '900px', margin: '0 auto' }}>
      <div className="controls-panel">
        <div className="step-header first">
          <div className="step-title">UPLOAD SOURCE IMAGE</div>
        </div>
        <input
          type="file"
          accept="image/*"
          id="edit-file"
          style={{ display: 'none' }}
          onChange={(e) => {
            const f = e.target.files?.[0];
            if (f) {
              setFile(f);
              setPreview(URL.createObjectURL(f));
              setResult(null);
            }
          }}
        />
        <label htmlFor="edit-file" className="upload-area">
          {preview ? <img src={preview} style={{ maxHeight: '300px', borderRadius: '12px' }} alt="preview" /> : <p>CLICK TO UPLOAD</p>}
        </label>

        <div className="step-header">
          <div className="step-title">EDIT INSTRUCTIONS</div>
        </div>
        <textarea
          placeholder="e.g., Change hair to blonde, add sunglasses, cyberpunk background..."
          value={prompt}
          onChange={e => setPrompt(e.target.value)}
          style={{ minHeight: '120px' }}
        />

        <button className="btn-primary" onClick={handleEdit} disabled={!file || !prompt || isGenerating}>
          MODIFY REALITY
        </button>
      </div>

      {result && (
        <div className="output-panel" style={{ marginTop: '2rem' }}>
          <img src={result} style={{ width: '100%', borderRadius: '16px' }} alt="Edited result" />
          <div className="output-actions" style={{ position: 'relative', opacity: 1, marginTop: '1rem' }}>
            <button className="btn-pill" onClick={() => {
              const a = document.createElement('a');
              a.href = result;
              a.download = `Edited_${Date.now()}.png`;
              a.click();
            }}>DOWNLOAD</button>
            <button className="btn-pill" onClick={() => onImageGenerated([result])}>ARCHIVE</button>
          </div>
        </div>
      )}
    </div>
  );
};

// ====================== MAIN APP ======================
const App = () => {
  const [tab, setTab] = useState<'generate' | 'edit' | 'gallery'>('generate');
  const [isGenerating, setIsGenerating] = useState(false);
  const [gallery, setGallery] = useState<string[]>([]);
  const [toasts, setToasts] = useState<Toast[]>([]);
  
  // Persistent State for Generate View
  const [config, setConfig] = useState<Config>({
    basePrompt: 'A photorealistic portrait of a stunning individual',
    ethnicity: 'Caucasian',
    bodyShape: 'Athletic',
    eyeColor: 'Green',
    hairStyle: 'Long Waves',
    hairColor: 'Brunette',
    style: 'Luxury',
    expression: 'Mysterious',
    background: 'Studio',
    skinTexture: 'Hyper-Realistic',
    accessories: '',
    aspectRatio: '1:1',
    numImages: 2,
  });
  const [refFiles, setRefFiles] = useState<File[]>([]);
  const [previews, setPreviews] = useState<string[]>([]);

  // Correct initialization for this environment: strictly process.env.API_KEY
  const ai = useMemo(() => new GoogleGenAI({ apiKey: process.env.API_KEY }), []);

  const addToast = useCallback((message: string, type: 'success' | 'error' = 'success') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 5000);
  }, []);

  const removeToast = useCallback((id: number) => {
    setToasts(prev => prev.filter(t => t.id !== id));
  }, []);

  useEffect(() => {
    try {
      const saved = localStorage.getItem('alterEgoGallery');
      if (saved) setGallery(JSON.parse(saved));
    } catch (_) { }
  }, []);

  useEffect(() => {
    localStorage.setItem('alterEgoGallery', JSON.stringify(gallery));
  }, [gallery]);

  const handleImageGenerated = useCallback((imgs: string[]) => {
    setGallery(prev => [...imgs, ...prev]);
  }, []);

  return (
    <>
      <Style />
      <div className="container">
        {isGenerating && (
          <div className="loading-overlay">
            <div className="loading-spinner"></div>
            <div className="loading-text">SYNTHESIZING REALITY...</div>
          </div>
        )}

        <ToastContainer toasts={toasts} removeToast={removeToast} />

        <header>
          <h1>AlterEgo</h1>
          <p>PREMIUM DIGITAL IDENTITY STUDIO</p>
          <div className="tabs">
            <button className={tab === 'generate' ? 'active' : ''} onClick={() => setTab('generate')} aria-current={tab === 'generate'}>
              SYNTHESIZE
            </button>
            <button className={tab === 'edit' ? 'active' : ''} onClick={() => setTab('edit')}>
              MODIFY
            </button>
            <button className={tab === 'gallery' ? 'active' : ''} onClick={() => setTab('gallery')}>
              ARCHIVES
            </button>
          </div>
        </header>

        <main>
          {tab === 'generate' && (
            <GenerateTwinView
              ai={ai}
              addToast={addToast}
              isGenerating={isGenerating}
              setIsGenerating={setIsGenerating}
              onImageGenerated={handleImageGenerated}
              config={config}
              setConfig={setConfig}
              refFiles={refFiles}
              setRefFiles={setRefFiles}
              previews={previews}
              setPreviews={setPreviews}
            />
          )}
          {tab === 'edit' && (
            <EditImageView
              ai={ai}
              addToast={addToast}
              isGenerating={isGenerating}
              setIsGenerating={setIsGenerating}
              onImageGenerated={handleImageGenerated}
            />
          )}
          {tab === 'gallery' && <GalleryView images={gallery} setGallery={setGallery} />}
        </main>
      </div>
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);