(function($){
  function setStatus(html, type){
    $('#ardisplay-ai-status').attr('class', type || '').html(html);
  }
  function showLoading(message){
    const gif = $('#ardisplay-ai-panel').data('loading-gif') || (window.location.origin + '/wp-content/plugins/ar-for-wordpress/assets/images/3dloading.gif');
    // Message on left
    setStatus('<div style="font-weight:600;font-size:14px;">' + (message || '') + '</div>');
    // Large loading image pinned to top-right overlay
    // Stretch image to match the panel content height while keeping aspect
    const wrap = $('#ardisplay-ai-loading');
    const h = wrap.height() || $('#ai_generator_content').height();
    const w = wrap.width() || 600;
    $('#ardisplay-ai-loading').html('<img src="' + gif + '" alt="Generating 3D Model" style="max-height:100%;max-width:100%;height:auto;width:auto;object-fit:contain;" />');
    
    // Update building image to show loading state
    updateBuildingImage();
  }

  // Render idle image on first load
  $(function(){
    const idle = $('#ardisplay-ai-panel').data('idle-img');
    if (idle) {
      $('#ardisplay-ai-loading').css({overflow: 'hidden'}).html('<img src="' + idle + '" alt="AI Model" style="max-height:100%;max-width:100%;height:auto;width:auto;object-fit:contain;display:block;" />');
    }
    
    // Initialize credit status
    updateCreditStatus();
    
    // Set up observer to watch for loading state changes
    var loadingObserver = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if (mutation.type === 'childList' || mutation.type === 'attributes') {
          updateBuildingImage();
        }
      });
    });
    
    // Start observing the loading div
    var loadingDiv = document.getElementById('ardisplay-ai-loading');
    if (loadingDiv) {
      loadingObserver.observe(loadingDiv, {
        childList: true,
        attributes: true,
        subtree: true
      });
    }
    
    // Initial building image update
    updateBuildingImage();
  });

  // Function to update credit status and button state
  function updateCreditStatus() {
    const generateBtn = $('#ardisplay-ai-generate');
    const creditNotice = $('#ardisplay-ai-credit-notice');
    
    // Check if user has enough credits
    let hasEnoughCredits = true;
    if (creditNotice.length > 0) {
      const noticeText = creditNotice.text();
      if (noticeText.includes('You need') || noticeText.includes('Insufficient')) {
        hasEnoughCredits = false;
      }
    }
    
    // Check if images are selected
    const hasImages = selectedIds.length > 0;
    
    // Button is enabled only if both conditions are met
    if (hasEnoughCredits && hasImages) {
      generateBtn.prop('disabled', false).css({
        'opacity': '1',
        'cursor': 'pointer'
      });
    } else {
      generateBtn.prop('disabled', true).css({
        'opacity': '0.6',
        'cursor': 'not-allowed'
      });
    }
  }
  
  // Function to update building image based on state
  function updateBuildingImage() {
    const buildingImage = $('#ardisplay-ai-building-image img');
    const idleImg = $('#ardisplay-ai-panel').data('idle-img');
    const loadingGif = $('#ardisplay-ai-panel').data('loading-gif');
    
    if (buildingImage.length > 0) {
      if (loadingGif && $('#ardisplay-ai-loading').is(':visible') && $('#ardisplay-ai-loading img').length > 0) {
        buildingImage.attr('src', loadingGif);
      } else if (idleImg) {
        buildingImage.attr('src', idleImg);
      }
    }
  }

  // Handle credit refresh button click
  $(document).on('click', '.credit-actions button[onclick*="location.reload"]', function(e) {
    e.preventDefault();
    // Remove the onclick attribute to prevent page reload
    $(this).removeAttr('onclick');
    // Add a loading state
    const originalText = $(this).html();
    $(this).html('<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite; margin-right: 4px;"></span>Refreshing...');
    $(this).prop('disabled', true);
    
    // Simulate a refresh by updating the credit status
    setTimeout(() => {
      updateCreditStatus();
      $(this).html(originalText);
      $(this).prop('disabled', false);
      // Add the reload functionality back
      $(this).attr('onclick', 'location.reload();');
    }, 1000);
  });

  let selectedIds = [];
  const allowedMimeTypes = ['image/jpeg', 'image/png'];

  $(document).on('click', '#ardisplay-ai-select-images', function(){
    const frame = wp.media({
      title: 'Select reference images',
      button: { text: 'Use images' },
      library: { type: allowedMimeTypes },
      multiple: true
    });
    frame.on('select', function(){
      const selection = frame.state().get('selection');
      const filtered = selection.filter(att => allowedMimeTypes.includes(att.get('mime')));
      
      if (filtered.length !== selection.length) {
        setStatus('Only JPG or PNG images are supported.');
      }
      
      if (!filtered.length) {
        selectedIds = [];
        updateCreditStatus();
        const uploadIcon = $('#ardisplay-ai-panel').data('upload-icon') || $('#ardisplay-ai-image-trigger').data('upload-icon');
        const defaultSrc = $('#ardisplay-ai-image-trigger').attr('data-default-src');
        if (uploadIcon || defaultSrc) {
          $('#ardisplay-ai-image-trigger').attr('src', uploadIcon || defaultSrc);
        }
        $('#ardisplay-ai-clear').hide();
        $('#ardisplay-ai-preview').empty();
        return;
      }
      
      selectedIds = filtered.map(att => att.id);
      
      // Update button state based on selection and credits
      updateCreditStatus();
      
      // Render thumbnails in preview area
      try {
        const first = filtered[0];
        const a = first.toJSON ? first.toJSON() : first.attributes;
        const url = (a.sizes && a.sizes.large && a.sizes.large.url) ? a.sizes.large.url : a.url;
        // Replace upload icon with big selected thumbnail (keep ratio using object-fit)
        $('#ardisplay-ai-image-trigger').attr('src', url).css({paddingTop: '0'});
        $('#ardisplay-ai-clear').show();
        // Hide small thumbnail strip
        $('#ardisplay-ai-preview').empty();
        setStatus('');
      } catch(e){
        setStatus(selectedIds.length + ' image(s) selected');
      }
    });
    frame.open();
  });

  // Clear selection handler
  $(document).on('click', '#ardisplay-ai-clear', function(e){
    e.stopPropagation();
    selectedIds = [];
    // restore upload image
    const uploadIcon = $('#ardisplay-ai-panel').data('upload-icon') || $('#ardisplay-ai-image-trigger').data('upload-icon');
    // fallback to original URL in src attribute if stored
    const defaultSrc = $('#ardisplay-ai-image-trigger').attr('data-default-src');
    if (!uploadIcon && !defaultSrc) return;
    $('#ardisplay-ai-image-trigger').attr('src', uploadIcon || defaultSrc);
    $('#ardisplay-ai-clear').hide();
    // clear thumbnails/status
    $('#ardisplay-ai-preview').empty();
    // Update button state
    updateCreditStatus();
  });

  $(document).on('click', '#ardisplay-ai-generate', async function(){
    // Check if user has enough credits
    const creditNotice = $('#ardisplay-ai-credit-notice');
    if (creditNotice.length > 0) {
      const noticeText = creditNotice.text();
      if (noticeText.includes('You need') || noticeText.includes('Insufficient')) {
        setStatus('Insufficient credits to generate model. Please purchase more credits.', 'error');
        return;
      }
    }
    
    // Check if images are selected
    if (selectedIds.length === 0) {
      setStatus('Please select at least one image before generating a model.', 'error');
      return;
    }
    
    const root = $('#ardisplay-ai-panel').data('rest-root');
    const nonce = $('#ardisplay-ai-panel').data('nonce');
    const postId = parseInt($('#ardisplay-ai-panel').data('post-id'), 10);
    const textureResolution = parseInt($('#ardisplay-ai-texture-resolution').val(), 10) || 1024;
    // Clamp to allowed values per Stability API
    const allowedTR = [512, 1024, 2048];
    const safeTextureRes = allowedTR.includes(textureResolution) ? textureResolution : 1024;
    const foregroundRatio = parseFloat($('#ardisplay-ai-foreground-ratio').val());
    if (!root || !nonce || !postId) {
      return setStatus('Missing REST setup', 'error');
    }
    showLoading('Generating 3D Model');
    $('#ardisplay-ai-generate').prop('disabled', true);
    try {
      const res = await fetch(root + '/ardisplay_ai/jobs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
        body: JSON.stringify({ post_id: postId, image_ids: selectedIds, params: { texture_resolution: safeTextureRes, foreground_ratio: foregroundRatio } })
      });
      const rawBody = await res.text();
      let data = {};
      try {
        data = rawBody ? JSON.parse(rawBody) : {};
      } catch (parseErr) {
        data = { message: rawBody };
      }
      if (!res.ok) {
        const errorDetails = {
          url: res.url,
          status: res.status,
          statusText: res.statusText,
          body: rawBody
        };
        if (data.attempted_endpoints && Array.isArray(data.attempted_endpoints)) {
          errorDetails.attemptedEndpoints = data.attempted_endpoints;
          console.log('AR Display AI attempted proxy endpoints:', data.attempted_endpoints);
        }
        console.error('AR Display AI job creation failed', errorDetails);
        throw new Error(data.message || res.statusText || 'Unknown error');
      }
      // Handle immediate success
      if (data.status === 'succeeded' && data.result && data.result.glb_url){
        const glbUrl = data.result.glb_url;
        setStatus('Done');
        // Update preview
        $('#ardisplay-ai-preview').html('<model-viewer src="' + glbUrl + '" camera-controls auto-rotate></model-viewer>');
        // Update hidden field so saving the post preserves the URL
        const glbField = document.getElementById('_glb_file');
        if (glbField) { glbField.value = glbUrl; }
        // Update the existing admin viewer instance if present
        const adminViewer = document.querySelector('#ar_admin_modelviewer model-viewer');
        if (adminViewer) {
          adminViewer.setAttribute('src', glbUrl);
        }
        // Switch to Model Files tab to show viewer and fields
        const filesTabBtn = document.getElementById('model_files_tab');
        if (filesTabBtn) { filesTabBtn.click(); }
        updateCreditStatus();
        return;
      }
      setStatus('Job queued: ' + (data.job_id || ''));
      if (data.job_id) {
        pollJob(root, nonce, data.job_id);
      }
    } catch (e){
      console.error('AR Display AI generation error', e);
      setStatus('Error: ' + e.message, 'error');
      updateCreditStatus();
    }
  });

  async function pollJob(root, nonce, jobId){
    if (!jobId) return;
    const el = $('#ardisplay-ai-status');
    const poll = async function(){
      try {
        const res = await fetch(root + '/ardisplay_ai/jobs/' + encodeURIComponent(jobId), { headers: { 'X-WP-Nonce': nonce } });
        const rawBody = await res.text();
        let data = {};
        try {
          data = rawBody ? JSON.parse(rawBody) : {};
        } catch (parseErr) {
          data = { message: rawBody };
        }
        if (!res.ok) {
          console.error('AR Display AI job poll failed', {
            url: res.url,
            status: res.status,
            statusText: res.statusText,
            body: rawBody
          });
          throw new Error(data.message || res.statusText || 'Unknown error');
        }
        const status = data.status || data.state || 'unknown';
        setStatus('Status: ' + status);
        if (status === 'succeeded' && data.result && data.result.glb_url){
          const glbUrl = data.result.glb_url;
          $('#ardisplay-ai-preview').html('<model-viewer src="' + glbUrl + '" camera-controls auto-rotate></model-viewer>');
          const glbField = document.getElementById('_glb_file');
          if (glbField) { glbField.value = glbUrl; }
          const filesTabBtn = document.getElementById('model_files_tab');
          if (filesTabBtn) { filesTabBtn.click(); }
          return;
        }
        if (status === 'failed' || status === 'canceled') return;
        setTimeout(poll, 3000);
      } catch(e){
        console.error('AR Display AI poll error', e);
        setStatus('Error: ' + e.message, 'error');
      }
    };
    poll();
  }
})(jQuery);


