class ImageGen {
  constructor() {
    this.btn = document.getElementById('generateBtn');
    this.prompt = document.getElementById('prompt');
    this.model = document.getElementById('model');
    this.imageStyle = document.getElementById('imageStyle');
    this.imageSizeInput = document.getElementById('imageSize');
    this.aspectBtns = document.querySelectorAll('.rw-aspect-btn');
    
    // UI Elements
    this.canvas = document.getElementById('rwCanvas');
    this.placeholder = document.getElementById('rwPlaceholder');
    this.resultImage = document.getElementById('resultImage');
    this.loading = document.getElementById('rwLoading');
    this.btnDownload = document.getElementById('btnDownload');
    this.historyScroll = document.getElementById('historyScroll');
    this.historyEmpty = document.getElementById('historyEmpty');
    this.historyClear = document.getElementById('historyClear');
    this.sidebarToggle = document.getElementById('sidebarToggle');
    this.sidebarOpenBtn = document.getElementById('sidebarOpenBtn');
    this.sidebar = document.getElementById('rwSidebar');

    this.initUI();
    this.loadHistory();

    this.puterModels = [
      'google/gemini-2.5-flash-preview-image',
      'google/gemini-3.1-flash-image',
      'google/gemini-3-pro-image',
      'flux',
      'flux-pro',
      'gpt-image-1.5'
    ];
  }

  initUI() {
    if (!this.btn || !this.prompt) return;

    // Generate Button
    this.btn.addEventListener('click', () => this.generate());

    // Prompt Enter key to submit
    this.prompt.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        this.generate();
      }
    });

    // Aspect Ratio Buttons
    if (this.aspectBtns) {
      this.aspectBtns.forEach(btn => {
        btn.addEventListener('click', () => {
          this.aspectBtns.forEach(b => b.classList.remove('active'));
          btn.classList.add('active');
          const ratio = btn.getAttribute('data-ratio');
          if (ratio === '16:9') {
            this.imageSizeInput.value = 'landscape';
            this.canvas.className = 'rw-canvas ar-16-9';
          } else if (ratio === '9:16') {
            this.imageSizeInput.value = 'portrait';
            this.canvas.className = 'rw-canvas ar-9-16';
          } else {
            this.imageSizeInput.value = 'square';
            this.canvas.className = 'rw-canvas ar-1-1';
          }
        });
      });
    }

    // Sidebar Toggle
    if (this.sidebarToggle && this.sidebar) {
      this.sidebarToggle.addEventListener('click', () => {
        if (window.innerWidth <= 900) {
          this.sidebar.classList.remove('mobile-open');
        } else {
          this.sidebar.classList.add('collapsed');
        }
      });
    }

    // Sidebar Open Button
    if (this.sidebarOpenBtn && this.sidebar) {
      this.sidebarOpenBtn.addEventListener('click', () => {
        if (window.innerWidth <= 900) {
          this.sidebar.classList.add('mobile-open');
        } else {
          this.sidebar.classList.remove('collapsed');
        }
      });
    }

    // History Clear
    if (this.historyClear) {
      this.historyClear.addEventListener('click', () => {
        localStorage.removeItem('peak_image_history');
        if (this.historyScroll) {
          this.historyScroll.innerHTML = '<div class="rw-history-empty" id="historyEmpty">No images generated yet</div>';
        }
        this.showToast('History cleared');
      });
    }
  }

  showToast(msg, isError = false) {
    const toast = document.getElementById('rwToast');
    if (!toast) return;
    toast.textContent = msg;
    toast.style.background = isError ? '#dc2626' : '#2563eb';
    toast.classList.add('active');
    setTimeout(() => toast.classList.remove('active'), 3000);
  }

  generate() {
    let promptText = this.prompt.value.trim();
    if (!promptText) { this.showToast('Please enter an image description', true); return; }
    
    let width = 1024, height = 1024;
    
    if (this.imageStyle && this.imageStyle.value !== 'none') {
      const styleVal = this.imageStyle.value;
      if (styleVal === 'hyper-realistic') {
        promptText += ', hyper-realistic, 100% photorealistic, 8k resolution, highly detailed, shot on DSLR camera, real life, completely indistinguishable from reality, true to life photography';
      } else {
        const styleText = this.imageStyle.options[this.imageStyle.selectedIndex].text;
        promptText += `, in ${styleText} style`;
      }
    }
    
    if (this.imageSizeInput) {
      const sizeVal = this.imageSizeInput.value;
      if (sizeVal === 'portrait') {
        width = 768; height = 1024;
        promptText += ', portrait format';
      } else if (sizeVal === 'landscape') {
        width = 1024; height = 768;
        promptText += ', landscape format';
      }
    }
    
    const model = this.model.value;

    this.startLoading();

    if (model.startsWith('pollinations/') || model === 'free') {
      const apiModel = model === 'free' ? 'flux' : model.split('/')[1];
      this.generateViaPollinations(promptText, apiModel);
    } else if (typeof puter !== 'undefined' && this.puterModels.includes(model)) {
      this.generateViaPuter(promptText, model, width, height);
    } else {
      this.generateViaAPI(promptText, model);
    }
  }

  startLoading() {
    this.btn.disabled = true;
    this.loading.classList.add('active');
    this.placeholder.style.display = 'none';
    this.resultImage.style.display = 'none';
    this.canvas.classList.remove('has-image');
  }

  stopLoading() {
    this.btn.disabled = false;
    this.loading.classList.remove('active');
  }

  showResult(url) {
    this.stopLoading();
    this.resultImage.src = url;
    this.resultImage.style.display = 'block';
    this.canvas.classList.add('has-image');
    this.btnDownload.href = url;
    this.saveToHistory(url);
  }

  generateViaPollinations(prompt, modelName) {
    const seed = Math.floor(Math.random() * 1000000000);
    const encodedPrompt = encodeURIComponent(prompt);
    
    // Adjust size based on aspect ratio selection
    let w = 1024, h = 1024;
    if(this.imageSizeInput.value === 'landscape') { w = 1280; h = 720; }
    if(this.imageSizeInput.value === 'portrait') { w = 720; h = 1280; }

    const url = `https://image.pollinations.ai/prompt/${encodedPrompt}?seed=${seed}&width=${w}&height=${h}&model=${modelName}&nologo=true`;
    
    const img = new Image();
    img.onload = () => {
      this.showResult(url);
    };
    img.onerror = () => {
      console.warn('Pollinations AI failed. Falling back...');
      if (typeof puter !== 'undefined') {
        this.generateViaPuter(prompt, 'default', w, h);
      } else {
        this.stopLoading();
        this.showToast('Generation failed. Please try again.', true);
        this.placeholder.style.display = 'flex';
      }
    };
    img.src = url;
  }

  async generateViaPuter(prompt, model, width=1024, height=1024) {
    try {
      const m = model.startsWith('google/') ? model.slice(7) : model;
      const opts = { width: width, height: height };
      if (m !== 'default') {
        opts.model = m;
      }
      const img = await puter.ai.txt2img(prompt, opts);
      const src = img.src || img;
      this.showResult(src);
    } catch (e) {
      this.stopLoading();
      this.placeholder.style.display = 'flex';
      this.showToast('Puter: ' + (e.message || 'Generation failed. You may need to sign in.'), true);
    }
  }

  generateViaAPI(prompt, model) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', (window.API_BASE || '/api.php') + '?route=/generate-image', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = () => {
      if (xhr.status < 200 || xhr.status >= 300) {
        this.stopLoading();
        this.placeholder.style.display = 'flex';
        try {
          const d = JSON.parse(xhr.responseText);
          this.showToast('Error: ' + (d.error || xhr.responseText), true);
        } catch (e) {
          this.showToast('Error: ' + xhr.status, true);
        }
        return;
      }
      try {
        const data = JSON.parse(xhr.responseText);
        const images = data.data || [];
        if (images.length === 0) { 
          this.stopLoading();
          this.placeholder.style.display = 'flex';
          this.showToast('No images were generated.', true); 
          return; 
        }
        const first = images[0];
        const url = first.b64_json ? ('data:image/png;base64,' + first.b64_json) : first.url;
        this.showResult(url);
      } catch (e) { 
        this.stopLoading();
        this.placeholder.style.display = 'flex';
        this.showToast('Error processing result', true); 
      }
    };
    xhr.onerror = () => {
      this.stopLoading();
      this.placeholder.style.display = 'flex';
      this.showToast('A connection error occurred', true);
    };
    xhr.send(JSON.stringify({ prompt, model }));
  }

  saveToHistory(url) {
    try {
      let history = JSON.parse(localStorage.getItem('peak_image_history') || '[]');
      history.unshift({ url, timestamp: Date.now() });
      if (history.length > 20) history = history.slice(0, 20);
      localStorage.setItem('peak_image_history', JSON.stringify(history));
      this.renderHistoryItem(url, true);
    } catch(e) {}
  }

  loadHistory() {
    try {
      const history = JSON.parse(localStorage.getItem('peak_image_history') || '[]');
      if (history.length > 0) {
        if(this.historyEmpty) this.historyEmpty.remove();
        history.forEach(item => this.renderHistoryItem(item.url, false));
      }
    } catch(e) {}
  }

  renderHistoryItem(url, prepend = false) {
    if (!this.historyScroll) return;
    if(this.historyEmpty && this.historyScroll.contains(this.historyEmpty)) {
      this.historyEmpty.remove();
    }
    const item = document.createElement('div');
    item.className = 'rw-history-item';
    item.innerHTML = `<img src="${url}">`;
    item.addEventListener('click', () => {
      document.querySelectorAll('.rw-history-item').forEach(el => el.classList.remove('active'));
      item.classList.add('active');
      this.showResultFromHistory(url);
    });
    
    if (prepend) {
      this.historyScroll.insertBefore(item, this.historyScroll.firstChild);
      item.classList.add('active');
      document.querySelectorAll('.rw-history-item').forEach(el => {
        if(el !== item) el.classList.remove('active');
      });
    } else {
      this.historyScroll.appendChild(item);
    }
  }

  showResultFromHistory(url) {
    this.placeholder.style.display = 'none';
    this.resultImage.src = url;
    this.resultImage.style.display = 'block';
    this.canvas.classList.add('has-image');
    this.btnDownload.href = url;
  }
}

// Auto init
document.addEventListener('DOMContentLoaded', () => {
  new ImageGen();
});
