class LogoGen {
  constructor(config) {
    config = config || {};
    this.btn = document.getElementById(config.btnId || 'generateBtn');
    this.brandName = document.getElementById(config.brandId || 'brandName');
    this.slogan = document.getElementById(config.sloganId || 'slogan');
    this.prompt = document.getElementById(config.promptId || 'prompt');
    this.style = document.getElementById(config.styleId || 'logoStyle');
    this.colors = document.getElementById(config.colorsId || 'logoColors');
    this.model = document.getElementById(config.modelId || 'model');
    this.spinner = document.getElementById(config.spinnerId || 'loadingSpinner');
    this.errorMsg = document.getElementById(config.errorId || 'errorMsg');
    this.results = document.getElementById(config.resultsId || 'genResults');
    if (!this.btn) return;
    this.btn.addEventListener('click', () => this.generate());
    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'
    ];
  }

  showError(msg) {
    this.errorMsg.textContent = msg;
    this.errorMsg.classList.add('active');
  }

  generate() {
    const brand = this.brandName ? this.brandName.value.trim() : '';
    const slogan = this.slogan ? this.slogan.value.trim() : '';
    const desc = this.prompt ? this.prompt.value.trim() : '';
    const style = this.style ? this.style.value : 'modern';
    const colors = this.colors ? this.colors.value.trim() : '';
    if (!brand && !desc) { this.showError('Please enter a brand name or logo description'); return; }

    let fullPrompt = 'Professional logo design';
    if (brand) fullPrompt += ' for brand "' + brand + '"';
    if (slogan) fullPrompt += ' with tagline "' + slogan + '"';
    fullPrompt += '. Style: ' + style + '.';
    if (colors) fullPrompt += ' Colors: ' + colors + '.';
    if (desc) fullPrompt += ' ' + desc;
    fullPrompt += '. The logo should be a clean, professional design suitable for a modern brand. Use a transparent background.';

    this.btn.disabled = true;
    this.spinner.classList.add('active');
    this.errorMsg.classList.remove('active');
    this.results.innerHTML = '';

    const modelName = this.model.value;

    if (modelName.startsWith('pollinations/')) {
      this.generateViaPollinations(fullPrompt, modelName.split('/')[1]);
    } else if (typeof puter !== 'undefined' && this.puterModels.includes(modelName)) {
      this.generateViaPuter(fullPrompt, modelName);
    } else {
      this.generateViaAPI(fullPrompt, modelName);
    }
  }

  generateViaPollinations(prompt, modelName) {
    // Create random seed for uniqueness
    const seed = Math.floor(Math.random() * 1000000000);
    const encodedPrompt = encodeURIComponent(prompt);
    // use pollinations directly
    const url = `https://image.pollinations.ai/prompt/${encodedPrompt}?seed=${seed}&width=1024&height=1024&model=${modelName}`;
    
    const img = new Image();
    img.onload = () => {
      this.spinner.classList.remove('active');
      this.btn.disabled = false;
      this.results.innerHTML = '<h3>Logo</h3><div class="image-grid"><div class="img-card"><img src="' + url + '" alt="Logo" style="aspect-ratio:1;object-fit:contain;padding:20px;box-sizing:border-box;"><div class="img-actions"><a href="' + url + '" target="_blank">View</a><a href="' + url + '" download="peak-ai-logo.jpg">Download</a></div></div></div>';
    };
    img.onerror = () => {
      console.warn('Pollinations AI rate limited or failed. Falling back to Puter AI...');
      if (typeof puter !== 'undefined') {
        this.generateViaPuter(prompt, 'default');
      } else {
        this.spinner.classList.remove('active');
        this.btn.disabled = false;
        this.showError('Pollinations AI is currently busy. Please try again later.');
      }
    };
    img.src = url;
  }

  async generateViaPuter(prompt, model) {
    try {
      const m = model.startsWith('google/') ? model.slice(7) : model;
      let img;
      if (m === 'default') {
        img = await puter.ai.txt2img(prompt);
      } else {
        img = await puter.ai.txt2img(prompt, { model: m });
      }
      this.spinner.classList.remove('active');
      this.btn.disabled = false;
      const src = img.src || img;
      this.results.innerHTML = '<h3>Logo</h3><div class="image-grid"><div class="img-card"><img src="' + src + '" alt="Logo" style="aspect-ratio:1;object-fit:contain;padding:20px;box-sizing:border-box;"><div class="img-actions"><a href="' + src + '" target="_blank">View</a><a href="' + src + '" download="peak-ai-logo.png">Download</a></div></div></div>';
    } catch (e) {
      this.spinner.classList.remove('active');
      this.btn.disabled = false;
      this.showError('Puter: ' + (e.message || 'Generation failed. You may need to sign in to Puter.'));
    }
  }

  generateViaAPI(fullPrompt, modelName) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', (window.API_BASE || '/api.php') + '?route=/generate-image', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = () => {
      this.btn.disabled = false;
      this.spinner.classList.remove('active');
      if (xhr.status < 200 || xhr.status >= 300) {
        try {
          const d = JSON.parse(xhr.responseText);
          this.showError(d.error || xhr.responseText);
        } catch (e) { this.showError('Connection error'); }
        return;
      }
      try {
        const data = JSON.parse(xhr.responseText);
        const imgs = data.data || [];
        if (!imgs.length) { this.showError('No logo was generated. Try again.'); return; }
        let html = '<h3>Logo</h3><div class="image-grid">';
        for (let i = 0; i < imgs.length; i++) {
          const u = imgs[i].url || imgs[i].b64_json || '';
          if (imgs[i].b64_json) {
            html += '<div class="img-card"><img src="data:image/png;base64,' + imgs[i].b64_json + '" alt="Logo" style="aspect-ratio:1;object-fit:contain;padding:20px;box-sizing:border-box;"><div class="img-actions"><a href="data:image/png;base64,' + imgs[i].b64_json + '" download="peak-ai-logo.png">Download</a></div></div>';
          } else {
            html += '<div class="img-card"><img src="' + u + '" alt="Logo" style="aspect-ratio:1;object-fit:contain;padding:20px;box-sizing:border-box;"><div class="img-actions"><a href="' + u + '" target="_blank">View</a><a href="' + u + '" download="peak-ai-logo.png">Download</a></div></div>';
          }
        }
        html += '</div>';
        this.results.innerHTML = html;
      } catch (e) { this.showError('Error processing result'); }
    };
    xhr.onerror = () => {
      this.btn.disabled = false;
      this.spinner.classList.remove('active');
      this.showError('A connection error occurred');
    };
    xhr.send(JSON.stringify({ prompt: fullPrompt, model: modelName }));
  }
}
