jQuery(document).ready(function($) {
    const uploadForm = document.getElementById('cc-upload-form');
    const noteForm = document.getElementById('cc-note-form');
    const itemList = document.getElementById('cc-item-list');
  
    // 1. Fetch Items (AJAX to WP)
    const fetchItems = () => {
      $.ajax({
        url: DIYSEO_CC.ajaxurl,
        method: 'POST',
        data: {
          action: 'diyseo_cc_get_items',
          nonce: DIYSEO_CC.nonce
        },
        success: function(response) {
          if (response.success) {
            renderList(response.data);
          } else {
            console.error('Failed to load items');
          }
        },
        error: function() {
            console.error('AJAX error fetching items');
        }
      });
    };
  
    // 2. Render List
    const renderList = (items) => {
      itemList.innerHTML = '';
      if (!items || items.length === 0) {
        itemList.innerHTML = '<li style="color:#aaa;">No items yet. Add a note or file.</li>';
        return;
      }
  
      items.forEach(item => {
        const li = document.createElement('li');
        // Styles are handled in CSS mostly, but keeping structure
        li.style.background = 'rgba(255, 255, 255, 0.05)';
        li.style.marginBottom = '10px';
        li.style.padding = '10px';
        li.style.borderRadius = '8px';
        li.style.color = '#fff';
  
        // Header row
        const header = document.createElement('div');
        header.style.display = 'flex';
        header.style.justifyContent = 'space-between';
        
        const titleSpan = document.createElement('strong');
        titleSpan.textContent = (item.type === 'file' ? '📎 ' : '🧠 ') + item.title;
        
        const delBtn = document.createElement('button');
        delBtn.textContent = '🗑️';
        delBtn.style.border = 'none';
        delBtn.style.background = 'transparent';
        delBtn.style.cursor = 'pointer';
        delBtn.onclick = () => deleteItem(item.id);
  
        header.appendChild(titleSpan);
        header.appendChild(delBtn);
        li.appendChild(header);
  
        // Content Preview
        const p = document.createElement('p');
        p.style.fontSize = '13px';
        p.style.opacity = '0.8';
        p.style.marginTop = '5px';
        
        // Truncate long content
        const preview = item.content.length > 100 ? item.content.substring(0, 100) + '...' : item.content;
        p.textContent = preview;
        li.appendChild(p);
  
        itemList.appendChild(li);
      });
    };
  
    // 3. Delete Item
    const deleteItem = (id) => {
      if (!confirm('Are you sure?')) return;
      
      $.ajax({
        url: DIYSEO_CC.ajaxurl,
        method: 'POST',
        data: {
          action: 'diyseo_cc_delete_item',
          id: id,
          nonce: DIYSEO_CC.nonce
        },
        success: function(response) {
          if(response.success) fetchItems();
        }
      });
    };
  
    // 4. Handle Note Submission
    if (noteForm) {
        noteForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const title = noteForm.querySelector('input[name="title"]').value;
        const content = noteForm.querySelector('textarea[name="content"]').value;
    
        $.ajax({
            url: DIYSEO_CC.ajaxurl,
            method: 'POST',
            data: {
            action: 'diyseo_cc_save_item',
            title: title,
            content: content,
            type: 'note',
            nonce: DIYSEO_CC.nonce
            },
            success: function(response) {
            if (response.success) {
                alert('Note Saved!');
                noteForm.reset();
                fetchItems();
            }
            }
        });
        });
    }
  
    // 5. Handle File Upload (Client-Side Read -> WP Save)
    if (uploadForm) {
        uploadForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const fileInput = uploadForm.querySelector('input[name="file"]');
        const title = uploadForm.querySelector('input[name="title"]').value;
        const file = fileInput.files[0];
    
        if (!file) return;
    
        // Use FileReader to read text/csv content directly in browser
        const reader = new FileReader();
        
        reader.onload = function(e) {
            const textContent = e.target.result;
            
            $.ajax({
            url: DIYSEO_CC.ajaxurl,
            method: 'POST',
            data: {
                action: 'diyseo_cc_save_item',
                title: title,
                content: textContent, // Sending the extracted text
                type: 'file',
                file_type: file.type,
                nonce: DIYSEO_CC.nonce
            },
            success: function(response) {
                if (response.success) {
                alert('File Data Saved!');
                uploadForm.reset();
                fetchItems();
                } else {
                    alert('Error saving file data.');
                }
            }
            });
        };
    
        // Read the file as text
        reader.readAsText(file);
        });
    }
  
    // Initial Load
    fetchItems();
});