// Email Marketing - Contacts & Campaign Management

function renderContactsTab() {
  const container = document.getElementById('email-tab-contacts');
  if (!container) return;
  
  container.innerHTML = `
    <div class="email-addon-header">
      <div>
        <h3 data-i18n="email.contacts_title">Email Contacts & Groups</h3>
        <p class="email-small" data-i18n="email.contacts_hint">Manage contact groups for email campaigns.</p>
      </div>
      <div class="email-editor-actions">
        <button class="btn btn-secondary" id="emailAddContact" data-i18n="email.add_contact">Add Contact</button>
        <button class="btn btn-secondary" id="emailCreateGroup" data-i18n="email.create_group">Create Group</button>
      </div>
    </div>
    
    <div class="email-contacts-layout">
      <div class="email-contacts-sidebar">
        <h4 data-i18n="email.groups">Groups</h4>
        <div id="emailContactGroupsList" class="email-contact-groups-list"></div>
      </div>
      
      <div class="email-contacts-main">
        <div class="email-contacts-header">
          <input type="text" id="emailContactSearch" class="form-control" placeholder="Search contacts..." data-i18n-placeholder="email.search_contacts">
          <button class="btn btn-secondary" id="emailSyncContacts" data-i18n="email.sync_contacts">Sync from Contacts</button>
        </div>
        <div id="emailContactsList" class="email-contacts-list"></div>
      </div>
    </div>
    
    <!-- Add/Edit Contact Modal -->
    <div id="emailContactModal" class="modal" style="display:none;">
      <div class="modal-content" style="max-width: 600px;">
        <div class="modal-header">
          <h3 id="emailContactModalTitle" data-i18n="email.add_contact">Add Contact</h3>
          <button class="btn btn-danger btn-sm modal-close">×</button>
        </div>
        <div class="modal-body">
          <input type="hidden" id="emailContactId">
          <div class="form-group">
            <label data-i18n="email.contact_name">Name <span style="color: #dc3545;">*</span></label>
            <input type="text" id="emailContactName" class="form-control" required data-i18n-placeholder="contacts.name_placeholder">
          </div>
          <div class="form-group">
            <label data-i18n="email.contact_email">Email <span style="color: #dc3545;">*</span></label>
            <input type="email" id="emailContactEmail" class="form-control" required data-i18n-placeholder="contacts.email_placeholder">
          </div>
          <div class="form-group">
            <label data-i18n="email.contact_group">Group</label>
            <select id="emailContactGroup" class="form-control">
              <option value="" data-i18n="contacts.no_group">No Group</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary modal-close" data-i18n="common.cancel">Cancel</button>
          <button class="btn btn-primary" id="emailSaveContact" data-i18n="common.save">Save</button>
        </div>
      </div>
    </div>
    
    
    <!-- Group Modal -->
    <div id="emailGroupModal" class="modal" style="display:none;">
      <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
          <h3 data-i18n="email.create_group">Create Group</h3>
          <button class="btn btn-danger btn-sm modal-close">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label data-i18n="email.group_name">Group Name</label>
            <input type="text" id="emailGroupName" class="form-control" required>
          </div>
          <div class="form-group">
            <label data-i18n="email.group_description">Description</label>
            <textarea id="emailGroupDescription" class="form-control" rows="3"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary modal-close" data-i18n="common.cancel">Cancel</button>
          <button class="btn btn-primary" id="emailSaveGroup" data-i18n="common.save">Save</button>
        </div>
      </div>
    </div>
  `;
  
  // Event listeners
  document.getElementById('emailAddContact')?.addEventListener('click', openAddEmailContactModal);
  document.getElementById('emailCreateGroup')?.addEventListener('click', openGroupModal);
  document.getElementById('emailSyncContacts')?.addEventListener('click', syncContactsFromMain);
  document.getElementById('emailContactSearch')?.addEventListener('input', filterEmailContacts);
  document.getElementById('emailSaveContact')?.addEventListener('click', saveEmailContact);
  
  
  // Modal close handlers
  document.querySelectorAll('.modal-close').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('emailGroupModal').style.display = 'none';
    });
  });
}

async function loadEmailContactGroups() {
  try {
    const response = await EmailAddonAPI.get('/contact-groups');
    EmailAddonState.contactGroups = response.data || [];
    renderContactGroups();
  } catch (error) {
    console.error('Error loading contact groups:', error);
    showNotification('Error loading groups', 'error');
  }
}

async function loadEmailContacts() {
  try {
    const params = {};
    if (EmailAddonState.selectedContactGroupId) {
      params.group_id = EmailAddonState.selectedContactGroupId;
    }
    const search = document.getElementById('emailContactSearch')?.value;
    if (search) params.search = search;
    
    const response = await EmailAddonAPI.get('/contacts', params);
    EmailAddonState.emailContacts = response.data || [];
    renderEmailContacts();
  } catch (error) {
    console.error('Error loading contacts:', error);
    showNotification('Error loading contacts', 'error');
  }
}

function renderContactGroups() {
  const container = document.getElementById('emailContactGroupsList');
  if (!container) return;
  
  const groups = EmailAddonState.contactGroups;
  if (groups.length === 0) {
    container.innerHTML = '<p class="email-small" data-i18n="email.no_groups">No groups yet</p>';
    return;
  }
  
  container.innerHTML = `
    <div class="email-contact-group ${!EmailAddonState.selectedContactGroupId ? 'active' : ''}" data-group-id="">
      <i class="fas fa-users"></i>
      <span data-i18n="email.all_contacts">All Contacts</span>
      <span class="group-count">${EmailAddonState.emailContacts.length}</span>
    </div>
    ${groups.map(group => `
      <div class="email-contact-group ${EmailAddonState.selectedContactGroupId === group.id ? 'active' : ''}" data-group-id="${group.id}">
        <i class="fas fa-folder"></i>
        <span>${escapeHtml(group.name)}</span>
        <span class="group-count">${group.contact_count || 0}</span>
      </div>
    `).join('')}
  `;
  
  container.querySelectorAll('.email-contact-group').forEach(el => {
    el.addEventListener('click', () => {
      EmailAddonState.selectedContactGroupId = el.dataset.groupId || null;
      loadEmailContacts();
    });
  });
}

function renderEmailContacts() {
  const container = document.getElementById('emailContactsList');
  if (!container) return;
  
  const contacts = EmailAddonState.emailContacts;
  if (contacts.length === 0) {
    container.innerHTML = '<p class="email-small" data-i18n="email.no_contacts">No contacts found</p>';
    return;
  }
  
  container.innerHTML = `
    <table class="email-addon-table">
      <thead>
        <tr>
          <th data-i18n="email.contact_name">Name</th>
          <th data-i18n="email.contact_email">Email</th>
          <th data-i18n="email.contact_group">Group</th>
          <th data-i18n="common.actions">Actions</th>
        </tr>
      </thead>
      <tbody>
        ${contacts.map(contact => `
          <tr>
            <td>${escapeHtml(contact.name || '-')}</td>
            <td>${escapeHtml(contact.email || '-')}</td>
            <td>${escapeHtml(contact.group_name || '-')}</td>
            <td>
              <button class="btn btn-secondary btn-sm" onclick="openEditEmailContactModal(${contact.id})" title="Edit">
                <i class="fas fa-edit"></i>
              </button>
              <button class="btn btn-danger btn-sm" onclick="deleteEmailContact(${contact.id})" title="Delete">
                <i class="fas fa-trash"></i>
              </button>
            </td>
          </tr>
        `).join('')}
      </tbody>
    </table>
  `;
  
  // Apply translations
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function filterEmailContacts() {
  loadEmailContacts();
}

async function syncContactsFromMain() {
  try {
    const response = await EmailAddonAPI.post('/contacts/sync');
    showNotification(response.message || 'Contacts synced successfully', 'success');
    await loadEmailContacts();
  } catch (error) {
    console.error('Error syncing contacts:', error);
    showNotification(error.message || 'Error syncing contacts', 'error');
  }
}

function openGroupModal() {
  document.getElementById('emailGroupName').value = '';
  document.getElementById('emailGroupDescription').value = '';
  document.getElementById('emailGroupModal').style.display = 'block';
  
  document.getElementById('emailSaveGroup').onclick = async () => {
    const name = document.getElementById('emailGroupName').value.trim();
    if (!name) {
      showNotification('Group name is required', 'error');
      return;
    }
    
    try {
      await EmailAddonAPI.post('/contact-groups', {
        name,
        description: document.getElementById('emailGroupDescription').value.trim()
      });
      showNotification('Group created successfully', 'success');
      document.getElementById('emailGroupModal').style.display = 'none';
      await loadEmailContactGroups();
    } catch (error) {
      showNotification(error.message || 'Error creating group', 'error');
    }
  };
}



/**
 * Open add email contact modal
 */
async function openAddEmailContactModal() {
  try {
    // Load groups for dropdown
    const response = await EmailAddonAPI.get('/contact-groups');
    const groups = response.data || [];
    
    const groupSelect = document.getElementById('emailContactGroup');
    if (groupSelect) {
      groupSelect.innerHTML = `
        <option value="" data-i18n="contacts.no_group">No Group</option>
        ${groups.map(g => `<option value="${g.id}">${escapeHtml(g.name)}</option>`).join('')}
      `;
    }
    
    // Reset form
    document.getElementById('emailContactId').value = '';
    document.getElementById('emailContactName').value = '';
    document.getElementById('emailContactEmail').value = '';
    document.getElementById('emailContactGroup').value = '';
    document.getElementById('emailContactModalTitle').setAttribute('data-i18n', 'email.add_contact');
    document.getElementById('emailContactModalTitle').textContent = 'Add Contact';
    
    // Show modal
    const modal = document.getElementById('emailContactModal');
    if (modal) {
      modal.style.display = 'block';
      
      // Apply translations
      if (window.applyLanguage) {
        window.applyLanguage(localStorage.getItem('language') || 'en');
      }
    }
  } catch (error) {
    showNotification(error.message || 'Error loading groups', 'error');
  }
}

/**
 * Open edit email contact modal
 */
async function openEditEmailContactModal(contactId) {
  try {
    // Load groups for dropdown
    const groupsResponse = await EmailAddonAPI.get('/contact-groups');
    const groups = groupsResponse.data || [];
    
    // Load contact data
    const contactsResponse = await EmailAddonAPI.get('/contacts');
    const contacts = contactsResponse.data || [];
    const contact = contacts.find(c => c.id === contactId);
    
    if (!contact) {
      showNotification('Contact not found', 'error');
      return;
    }
    
    const groupSelect = document.getElementById('emailContactGroup');
    if (groupSelect) {
      groupSelect.innerHTML = `
        <option value="" data-i18n="contacts.no_group">No Group</option>
        ${groups.map(g => `<option value="${g.id}">${escapeHtml(g.name)}</option>`).join('')}
      `;
    }
    
    // Fill form
    document.getElementById('emailContactId').value = contact.id;
    document.getElementById('emailContactName').value = contact.name;
    document.getElementById('emailContactEmail').value = contact.email;
    document.getElementById('emailContactGroup').value = contact.group_id || '';
    document.getElementById('emailContactModalTitle').setAttribute('data-i18n', 'email.edit_contact');
    document.getElementById('emailContactModalTitle').textContent = 'Edit Contact';
    
    // Show modal
    const modal = document.getElementById('emailContactModal');
    if (modal) {
      modal.style.display = 'block';
      
      // Apply translations
      if (window.applyLanguage) {
        window.applyLanguage(localStorage.getItem('language') || 'en');
      }
    }
  } catch (error) {
    showNotification(error.message || 'Error loading contact', 'error');
  }
}

/**
 * Save email contact (create or update)
 */
async function saveEmailContact() {
  try {
    const contactId = document.getElementById('emailContactId').value;
    const name = document.getElementById('emailContactName').value.trim();
    const email = document.getElementById('emailContactEmail').value.trim();
    const group_id = document.getElementById('emailContactGroup').value || null;
    
    // Validation
    if (!name) {
      showNotification(emailT('email.name_required', 'Name is required'), 'error');
      return;
    }
    
    if (!email) {
      showNotification(emailT('email.email_required', 'Email is required'), 'error');
      return;
    }
    
    // Email format validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      showNotification(emailT('email.invalid_email_format', 'Invalid email format'), 'error');
      return;
    }
    
    const data = { name, email, group_id };
    
    if (contactId) {
      // Update existing contact
      await EmailAddonAPI.put(`/contacts/${contactId}`, data);
      showNotification(emailT('email.contact_updated', 'Contact updated successfully'), 'success');
    } else {
      // Create new contact
      await EmailAddonAPI.post('/contacts', data);
      showNotification(emailT('email.contact_created', 'Contact created successfully'), 'success');
    }
    
    // Close modal
    const modal = document.getElementById('emailContactModal');
    if (modal) {
      modal.style.display = 'none';
    }
    
    // Reload contacts
    await loadEmailContacts();
  } catch (error) {
    showNotification(error.message || 'Error saving contact', 'error');
  }
}

/**
 * Delete email contact
 */
async function deleteEmailContact(contactId) {
  if (!confirm(emailT('email.confirm_delete_contact', 'Are you sure you want to delete this contact?'))) {
    return;
  }
  
  try {
    await EmailAddonAPI.delete(`/contacts/${contactId}`);
    showNotification(emailT('email.contact_deleted', 'Contact deleted successfully'), 'success');
    await loadEmailContacts();
  } catch (error) {
    showNotification(error.message || 'Error deleting contact', 'error');
  }
}

// Make functions globally available
window.openAddEmailContactModal = openAddEmailContactModal;
window.openEditEmailContactModal = openEditEmailContactModal;
window.saveEmailContact = saveEmailContact;
window.deleteEmailContact = deleteEmailContact;
