const EmailAddonAPI = {
  getHeaders() {
    const headers = { 'Content-Type': 'application/json' };
    const token = localStorage.getItem('token');
    if (token) headers.Authorization = `Bearer ${token}`;
    return headers;
  },
  async request(path, options = {}) {
    const response = await fetch(`/api/addons/email-marketing${path}`, {
      ...options,
      headers: { ...this.getHeaders(), ...(options.headers || {}) }
    });
    const data = await response.json();
    if (!response.ok || data.success === false) {
      throw new Error(data.message || 'Request failed');
    }
    return data;
  },
  get(path, params = {}, options = {}) {
    const resolvedPath = path.startsWith('/') ? path : `/${path}`;
    const url = new URL(resolvedPath, window.location.origin);
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null) {
        url.searchParams.set(key, params[key]);
      }
    });
    return this.request(resolvedPath + url.search, options);
  },
  post(path, body = {}) {
    return this.request(path, {
      method: 'POST',
      body: JSON.stringify(body)
    });
  },
  put(path, body = {}) {
    return this.request(path, {
      method: 'PUT',
      body: JSON.stringify(body)
    });
  },
  delete(path) {
    return this.request(path, { method: 'DELETE' });
  },
  async postForm(path, formData) {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/addons/email-marketing${path}`, {
      method: 'POST',
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      body: formData
    });
    const data = await response.json();
    if (!response.ok || data.success === false) {
      throw new Error(data.message || 'Request failed');
    }
    return data;
  }
};

const EmailAddonState = {
  accounts: [],
  selectedAccountId: null,
  activeTab: 'inbox',
  inboxPage: 1,
  sentPage: 1,
  selectedInboxUid: null,
  replyAttachments: [],
  templates: [],
  selectedTemplateId: null,
  templateEditor: null,
  inboxCache: new Map(),
  messageCache: new Map(),
  inboxAbort: null,
  messageAbort: null,
  prefetching: new Set(),
  prefetchingMessages: new Set(),
  sentsCache: new Map(),
  sentsAbort: null,
  contactGroups: [],
  emailContacts: [],
  marketingContacts: [],
  selectedContactGroupId: null,
  campaignStep: 1,
  campaignData: {
    details: {},
    recipients: [],
    template: null,
    schedule: null
  }
};

const EmailAddonCacheTTL = {
  inbox: 30000,
  message: 120000,
  sents: 30000
};

function emailT(key, fallback = '') {
  if (typeof i18n !== 'undefined' && i18n.t) {
    const translated = i18n.t(key);
    if (!translated || translated === key) {
      return fallback;
    }
    return translated;
  }
  return fallback;
}

function getCachedValue(cacheMap, key, ttl) {
  const cached = cacheMap.get(key);
  if (!cached) return null;
  if (Date.now() - cached.timestamp > ttl) {
    cacheMap.delete(key);
    return null;
  }
  return cached.value;
}

function setCachedValue(cacheMap, key, value) {
  cacheMap.set(key, { value, timestamp: Date.now() });
}

function escapeHtmlAttribute(value) {
  return String(value || '')
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

function escapeHtml(value) {
  return String(value || '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

function sanitizeEmailHtml(html) {
  return String(html || '').replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, '');
}

function updateEmailIframeHeight() {
  const iframe = document.getElementById('emailBodyIframe');
  if (!iframe) return;
  try {
    const doc = iframe.contentDocument || iframe.contentWindow?.document;
    if (!doc) return;
    const height = Math.max(doc.body?.scrollHeight || 0, doc.documentElement?.scrollHeight || 0);
    if (height) {
      iframe.style.height = `${height}px`;
    }
  } catch (error) {
  }
}

function loadEmailAddonPage() {
  const page = document.getElementById('email-page');
  if (!page) return;
  if (typeof isAddonActive === 'function' && !isAddonActive('email-marketing')) {
    page.innerHTML = `
      <div class="feature-disabled-message">
        <h3 data-i18n="email.addon_required">Email addon required</h3>
        <p data-i18n="email.addon_required_desc">Contact your superadmin to enable Email Marketing.</p>
      </div>
    `;
    if (window.applyLanguage) {
      window.applyLanguage(localStorage.getItem('language') || 'en');
    }
    return;
  }
  if (!page.dataset.initialized) {
    page.innerHTML = `
      <div class="page-header">
        <h1 data-i18n="email.title">Email Marketing</h1>
      </div>
      <div class="email-addon-container">
        <div class="email-addon-sidebar">
          <button class="email-tab-btn active" data-tab="inbox">
            <i class="fas fa-inbox"></i> <span data-i18n="email.inbox">Inbox</span>
          </button>
          <button class="email-tab-btn" data-tab="sents">
            <i class="fas fa-paper-plane"></i> <span data-i18n="email.sents">Sents</span>
          </button>
          <button class="email-tab-btn" data-tab="contacts">
            <i class="fas fa-users"></i> <span data-i18n="email.contacts">Contacts</span>
          </button>
          <button class="email-tab-btn" data-tab="templates">
            <i class="fas fa-layer-group"></i> <span data-i18n="email.templates">Templates</span>
          </button>
          <button class="email-tab-btn" data-tab="marketing">
            <i class="fas fa-bullhorn"></i> <span data-i18n="email.marketing">Marketing</span>
          </button>
          <button class="email-tab-btn" data-tab="settings">
            <i class="fas fa-cog"></i> <span data-i18n="email.settings">Settings</span>
          </button>
        </div>
        <div class="email-addon-content">
          <div id="email-tab-inbox" class="email-addon-tab active"></div>
          <div id="email-tab-sents" class="email-addon-tab"></div>
          <div id="email-tab-contacts" class="email-addon-tab"></div>
          <div id="email-tab-templates" class="email-addon-tab"></div>
          <div id="email-tab-marketing" class="email-addon-tab"></div>
          <div id="email-tab-settings" class="email-addon-tab"></div>
        </div>
      </div>

      <div id="email-html-modal" class="modal" style="display:none;">
        <div class="modal-content" style="max-width: 900px;">
          <div class="modal-header">
            <h3 data-i18n="email.html_editor">HTML Editor</h3>
            <span class="close" id="emailHtmlClose">&times;</span>
          </div>
          <div class="modal-body">
            <textarea id="emailHtmlTextarea" style="width: 100%; min-height: 400px;"></textarea>
            <div style="margin-top: 12px; display: flex; justify-content: flex-end; gap: 8px;">
              <button class="btn btn-secondary" id="emailHtmlCancel" data-i18n="common.cancel">Cancel</button>
              <button class="btn btn-primary" id="emailHtmlApply" data-i18n="common.apply">Apply</button>
            </div>
          </div>
        </div>
      </div>
    `;
    page.dataset.initialized = '1';
    setupEmailAddonUI();
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
  EmailAddonState.activeTab = 'inbox';
  renderEmailTab();
}

function setupEmailAddonUI() {
  document.querySelectorAll('.email-tab-btn').forEach(button => {
    button.addEventListener('click', () => {
      document.querySelectorAll('.email-tab-btn').forEach(btn => btn.classList.remove('active'));
      button.classList.add('active');
      EmailAddonState.activeTab = button.dataset.tab;
      setActiveEmailTab(EmailAddonState.activeTab);
      renderEmailTab();
    });
  });

  const modal = document.getElementById('email-html-modal');
  const closeModal = () => {
    if (modal) modal.style.display = 'none';
  };
  const closeBtn = document.getElementById('emailHtmlClose');
  const cancelBtn = document.getElementById('emailHtmlCancel');
  if (closeBtn) closeBtn.addEventListener('click', closeModal);
  if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
  window.addEventListener('click', event => {
    if (event.target === modal) closeModal();
  });
}

function setActiveEmailTab(tabKey) {
  document.querySelectorAll('.email-addon-tab').forEach(tab => tab.classList.remove('active'));
  const activeTab = document.getElementById(`email-tab-${tabKey}`);
  if (activeTab) {
    activeTab.classList.add('active');
  }
}

async function renderEmailTab() {
  setActiveEmailTab(EmailAddonState.activeTab);
  switch (EmailAddonState.activeTab) {
    case 'inbox':
      renderInboxTab();
      await loadAccountsIfNeeded();
      await loadInbox();
      break;
    case 'sents':
      renderSentsTab();
      await loadAccountsIfNeeded();
      await loadSents();
      break;
    case 'contacts':
      renderContactsTab();
      await loadEmailContactGroups();
      await loadEmailContacts();
      break;
    case 'templates':
      renderTemplatesTab();
      await loadTemplates();
      break;
    case 'marketing':
      renderMarketingTab();
      await loadAccountsIfNeeded();
      await loadTemplates();
      break;
    case 'settings':
      renderSettingsTab();
      await loadAccountsIfNeeded();
      await loadAccessOptions();
      renderAccountsList();
      break;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function renderInboxTab() {
  const container = document.getElementById('email-tab-inbox');
  if (!container) return;
  container.innerHTML = `
    <div class="email-addon-header">
      <div class="email-account-selector">
        <label data-i18n="email.account">Account</label>
        <select class="email-account-select"></select>
      </div>
      <button class="btn btn-secondary" id="emailInboxRefresh" data-i18n="common.refresh">Refresh</button>
    </div>
    <div class="email-inbox-layout" id="emailInboxLayout">
      <div class="email-inbox-list">
        <div id="emailInboxPaginationTop" class="email-addon-pagination email-pagination-tabs"></div>
        <div id="emailInboxList">
          <p data-i18n="common.loading">Loading...</p>
        </div>
        <div id="emailInboxPagination" class="email-addon-pagination"></div>
      </div>
      <div class="email-inbox-message">
        <div id="emailInboxMessage" class="email-inbox-empty">
          <div class="email-inbox-empty-title" data-i18n="email.inbox_empty_title">Select a message to read</div>
          <div class="email-small" data-i18n="email.inbox_empty_desc">Click any message on the left to open it.</div>
        </div>
      </div>
    </div>
  `;
  const refreshBtn = document.getElementById('emailInboxRefresh');
  if (refreshBtn) refreshBtn.addEventListener('click', () => loadInbox());
}

function renderSentsTab() {
  const container = document.getElementById('email-tab-sents');
  if (!container) return;
  container.innerHTML = `
    <div class="email-addon-header">
      <div class="email-account-selector">
        <label data-i18n="email.account">Account</label>
        <select class="email-account-select"></select>
      </div>
      <div class="email-editor-actions">
        <button class="btn btn-secondary" id="emailSentsRefresh" data-i18n="common.refresh">Refresh</button>
        <button class="btn btn-primary" id="emailNewMessage" data-i18n="common.new">New</button>
      </div>
    </div>
    <div id="emailSentsList">
      <p data-i18n="common.loading">Loading...</p>
    </div>
    <div id="emailSentsPagination" class="email-addon-pagination"></div>
    <div id="emailSentsMessage"></div>
    <div id="emailNewMessageModal" class="modal" style="display:none;">
      <div class="modal-content" style="max-width: 720px;">
        <div class="modal-header">
          <h3 data-i18n="email.reply_title">Reply</h3>
          <button class="btn btn-danger btn-sm modal-close">×</button>
        </div>
        <div class="modal-body" style="display:grid; gap:10px;">
          <div>
            <label data-i18n="email.to">To</label>
            <input type="email" id="newEmailTo" class="form-control" placeholder="user@domain.com">
          </div>
          <div>
            <label data-i18n="email.subject">Subject</label>
            <input type="text" id="newEmailSubject" class="form-control">
          </div>
          <div id="newEmailEditor" class="email-reply-editor" contenteditable="true" data-i18n-placeholder="email.reply_placeholder"></div>
          <div class="email-reply-toolbar email-reply-toolbar-bottom">
            <button type="button" class="btn btn-secondary btn-sm" data-command="bold" data-i18n-title="email.toolbar_bold"><i class="fas fa-bold"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="italic" data-i18n-title="email.toolbar_italic"><i class="fas fa-italic"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="underline" data-i18n-title="email.toolbar_underline"><i class="fas fa-underline"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="insertUnorderedList" data-i18n-title="email.toolbar_bulleted"><i class="fas fa-list-ul"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="insertOrderedList" data-i18n-title="email.toolbar_numbered"><i class="fas fa-list-ol"></i></button>
            <span class="email-reply-toolbar-divider"></span>
            <button type="button" class="btn btn-secondary btn-sm email-reply-attach-btn" id="newEmailAttachBtn" data-i18n-title="email.add_attachment"><i class="fas fa-paperclip"></i></button>
          </div>
          <input type="file" id="newEmailFiles" multiple style="display:none;" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv">
          <div id="newEmailAttachments" class="email-reply-attachments"></div>
        </div>
        <div class="modal-footer" style="display:flex; justify-content:flex-end; gap:8px;">
          <button class="btn btn-secondary modal-close" data-i18n="common.cancel">Cancel</button>
          <button class="btn btn-primary" id="newEmailSend" data-i18n="email.send_reply">Send Reply</button>
        </div>
      </div>
    </div>
  `;
  const refreshBtn = document.getElementById('emailSentsRefresh');
  if (refreshBtn) refreshBtn.addEventListener('click', () => loadSents());
  const newBtn = document.getElementById('emailNewMessage');
  if (newBtn) {
    newBtn.addEventListener('click', () => {
      openNewEmailModal();
    });
  }
}

function renderTemplatesTab() {
  const container = document.getElementById('email-tab-templates');
  if (!container) return;
  container.innerHTML = `
    <div class="email-addon-header">
      <div>
        <h3 data-i18n="email.templates_builder">Templates Builder</h3>
        <p class="email-small" data-i18n="email.templates_hint">Design responsive templates with drag and drop tools.</p>
      </div>
      <div class="email-editor-actions">
        <button class="btn btn-primary" id="emailTemplateNew" data-i18n="common.new">New Template</button>
      </div>
    </div>
    <div class="email-template-list" id="emailTemplateList"></div>
    <div id="email-template-modal" class="modal" style="display:none;">
      <div class="modal-content template-modal-new">
        <div class="modal-header-new">
          <input type="text" id="emailTemplateName" placeholder="${emailT('email.editor.template_name', 'Template name')}" class="template-name-input">
          <div class="modal-header-actions">
            <button class="btn btn-secondary btn-sm" id="emailTemplateExport" data-i18n="email.export_html">Export HTML</button>
            <button class="btn btn-primary btn-sm" id="emailTemplateModalSave" data-i18n="common.save">Save</button>
            <button class="btn btn-danger btn-sm modal-close">×</button>
          </div>
        </div>
        <div class="modal-body-new">
          <div id="emailTemplateBlocks" class="email-template-blocks-new"></div>
          <div id="emailTemplateEditorCanvas" class="email-template-canvas-new"></div>
          <div id="emailTemplateProperties" class="email-template-properties"></div>
        </div>
      </div>
    </div>
  `;
  initTemplateEditor();
  const newBtn = document.getElementById('emailTemplateNew');
  if (newBtn) newBtn.addEventListener('click', createNewTemplate);
}

function renderMarketingTab() {
  const container = document.getElementById('email-tab-marketing');
  if (!container) return;
  container.innerHTML = `
    <div class="email-addon-header">
      <div>
        <h3 data-i18n="email.marketing_title">Marketing Campaigns</h3>
        <p class="email-small" data-i18n="email.marketing_hint">Send campaigns using saved templates.</p>
      </div>
      <div class="email-editor-actions">
        <button class="btn btn-primary" id="emailMarketingCreateCampaign" data-i18n="email.create_campaign">Create Campaign</button>
      </div>
    </div>
    <div id="emailCampaignHistory"></div>
  `;
  
  const createBtn = document.getElementById('emailMarketingCreateCampaign');
  if (createBtn) {
    createBtn.addEventListener('click', () => {
      openMarketingCampaignModal();
    });
  }
  
  loadCampaigns();
}

function renderSettingsTab() {
  const container = document.getElementById('email-tab-settings');
  if (!container) return;
  container.innerHTML = `
    <div class="email-addon-header">
      <div>
        <h3 data-i18n="email.settings_title">Email Accounts</h3>
        <p class="email-small" data-i18n="email.settings_hint">Connect SMTP and IMAP accounts with access control.</p>
      </div>
    </div>
    <div class="email-settings-grid">
      <div>
        <div id="emailAccountForm" class="email-marketing-form">
          <input type="hidden" id="emailAccountId">
          <div>
            <label data-i18n="email.account_name">Account Name</label>
            <input type="text" id="emailAccountName" class="form-control">
          </div>
          <div>
            <label data-i18n="email.address">Email Address</label>
            <input type="email" id="emailAccountAddress" class="form-control" required>
          </div>
          <div class="email-settings-grid">
            <div>
              <label data-i18n="email.imap_host">IMAP Host</label>
              <input type="text" id="emailImapHost" class="form-control" required>
            </div>
            <div>
              <label data-i18n="email.imap_port">IMAP Port</label>
              <input type="number" id="emailImapPort" class="form-control" value="993" required>
            </div>
            <div>
              <label data-i18n="email.imap_user">IMAP User</label>
              <input type="text" id="emailImapUser" class="form-control" required>
            </div>
            <div>
              <label data-i18n="email.imap_password">IMAP Password</label>
              <input type="password" id="emailImapPassword" class="form-control">
            </div>
            <div>
              <label data-i18n="email.imap_secure">IMAP Secure</label>
              <select id="emailImapSecure" class="form-control">
                <option value="1">TLS/SSL</option>
                <option value="0">STARTTLS</option>
              </select>
            </div>
            <div>
              <label data-i18n="email.imap_allow_self_signed">Allow Self-signed</label>
              <div>
                <input type="checkbox" id="emailImapAllowSelfSigned">
              </div>
            </div>
            <div>
              <label data-i18n="email.sent_folder">Sent Folder</label>
              <input type="text" id="emailImapSentFolder" class="form-control" value="Sent">
            </div>
          </div>
          <div class="email-settings-grid">
            <div>
              <label data-i18n="email.smtp_host">SMTP Host</label>
              <input type="text" id="emailSmtpHost" class="form-control" required>
            </div>
            <div>
              <label data-i18n="email.smtp_port">SMTP Port</label>
              <input type="number" id="emailSmtpPort" class="form-control" value="465" required>
            </div>
            <div>
              <label data-i18n="email.smtp_user">SMTP User</label>
              <input type="text" id="emailSmtpUser" class="form-control" required>
            </div>
            <div>
              <label data-i18n="email.smtp_password">SMTP Password</label>
              <input type="password" id="emailSmtpPassword" class="form-control">
            </div>
            <div>
              <label data-i18n="email.smtp_secure">SMTP Secure</label>
              <select id="emailSmtpSecure" class="form-control">
                <option value="1">TLS/SSL</option>
                <option value="0">STARTTLS</option>
              </select>
            </div>
          </div>
          <div>
            <label data-i18n="email.access_stores">Stores Access</label>
            <select id="emailAccessStores" class="form-control" multiple></select>
          </div>
          <div>
            <label data-i18n="email.access_departments">Departments Access</label>
            <select id="emailAccessDepartments" class="form-control" multiple></select>
          </div>
          <div>
            <label data-i18n="email.access_users">Users Access</label>
            <select id="emailAccessUsers" class="form-control" multiple></select>
          </div>
          <div style="display: flex; gap: 8px;">
            <button type="button" class="btn btn-primary" id="emailAccountSave" data-i18n="common.save">Save</button>
            <button type="button" class="btn btn-secondary" id="emailAccountReset" data-i18n="common.reset">Reset</button>
          </div>
        </div>
      </div>
      <div>
        <h4 data-i18n="email.connected_accounts">Connected Accounts</h4>
        <div id="emailAccountsList" class="email-account-list"></div>
      </div>
    </div>
  `;
  const saveBtn = document.getElementById('emailAccountSave');
  const resetBtn = document.getElementById('emailAccountReset');
  if (saveBtn) {
    saveBtn.addEventListener('click', async () => {
      await saveAccount();
    });
  }
  if (resetBtn) {
    resetBtn.addEventListener('click', resetAccountForm);
  }
}

async function loadAccountsIfNeeded() {
  if (!EmailAddonState.accounts.length) {
    await loadAccounts();
  } else {
    renderAccountSelectors();
  }
}

async function loadAccounts() {
  try {
    const response = await EmailAddonAPI.get('/accounts');
    EmailAddonState.accounts = response.data || [];
    const storedId = localStorage.getItem('emailAddonAccountId');
    if (!EmailAddonState.selectedAccountId && storedId) {
      EmailAddonState.selectedAccountId = storedId;
    }
    if (!EmailAddonState.selectedAccountId && EmailAddonState.accounts.length) {
      EmailAddonState.selectedAccountId = EmailAddonState.accounts[0].id;
    }
    renderAccountSelectors();
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

function renderAccountSelectors() {
  document.querySelectorAll('.email-account-select').forEach(select => {
    select.innerHTML = EmailAddonState.accounts
      .map(account => `<option value="${account.id}">${account.email_address}</option>`)
      .join('');
    if (EmailAddonState.selectedAccountId) {
      select.value = EmailAddonState.selectedAccountId;
    }
    select.onchange = () => {
      EmailAddonState.selectedAccountId = select.value;
      localStorage.setItem('emailAddonAccountId', select.value);
      EmailAddonState.inboxCache.clear();
      EmailAddonState.messageCache.clear();
      EmailAddonState.prefetching.clear();
      EmailAddonState.prefetchingMessages.clear();
      EmailAddonState.sentsCache.clear();
      EmailAddonState.selectedInboxUid = null;
      document.querySelectorAll('.email-account-select').forEach(other => {
        if (other.value !== select.value) other.value = select.value;
      });
      if (EmailAddonState.activeTab === 'inbox') loadInbox();
      if (EmailAddonState.activeTab === 'sents') loadSents();
      if (EmailAddonState.activeTab === 'marketing') loadCampaigns();
    };
  });
}

function setInboxMode(isReading) {
  const layout = document.getElementById('emailInboxLayout');
  if (!layout) return;
  if (isReading) {
    layout.classList.add('is-reading');
  } else {
    layout.classList.remove('is-reading');
  }
}

function renderInboxEmptyState() {
  const messageContainer = document.getElementById('emailInboxMessage');
  if (!messageContainer) return;
  messageContainer.className = 'email-inbox-empty';
  messageContainer.innerHTML = `
    <div class="email-inbox-empty-title" data-i18n="email.inbox_empty_title">Select a message to read</div>
    <div class="email-small" data-i18n="email.inbox_empty_desc">Click any message on the left to open it.</div>
  `;
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function renderInboxList(items, total, page, list, paginationTop, paginationBottom) {
  if (!list) return;
  list.innerHTML = `
      <table class="email-addon-table email-inbox-table">
        <thead>
          <tr>
            <th data-i18n="email.from">From</th>
            <th data-i18n="email.subject">Subject</th>
            <th data-i18n="email.date">Date</th>
          </tr>
        </thead>
        <tbody>
          ${items.map(item => `
            <tr class="email-row ${EmailAddonState.selectedInboxUid === String(item.uid) ? 'active' : ''}" data-uid="${item.uid}" data-subject="${escapeHtmlAttribute(item.subject || '-')}" data-from="${escapeHtmlAttribute(item.from || '-')}" data-date="${escapeHtmlAttribute(item.date || '')}">
              <td>${item.from || '-'}</td>
              <td>${item.subject || '-'}</td>
              <td>${item.date ? new Date(item.date).toLocaleString() : '-'}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;
  list.querySelectorAll('.email-row').forEach(row => {
    row.addEventListener('click', () => {
      EmailAddonState.selectedInboxUid = String(row.dataset.uid);
      list.querySelectorAll('.email-row').forEach(item => item.classList.remove('active'));
      row.classList.add('active');
      setInboxMode(true);
      renderInboxPreview({
        subject: row.dataset.subject || '-',
        from: row.dataset.from || '-',
        to: EmailAddonState.selectedAccountId ? getSelectedAccountAddress() : '-',
        date: row.dataset.date || ''
      });
      loadInboxMessage(row.dataset.uid, false, true);
    });
  });
  const onChange = newPage => loadInbox(newPage);
  if (paginationTop) renderPagination(paginationTop, total || 0, page, onChange);
  if (paginationBottom) renderPagination(paginationBottom, total || 0, page, onChange);
  prefetchMessageDetails(items.slice(0, 5));
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadInbox(page = EmailAddonState.inboxPage, force = false, silent = false) {
  const list = document.getElementById('emailInboxList');
  const paginationTop = document.getElementById('emailInboxPaginationTop');
  const paginationBottom = document.getElementById('emailInboxPagination');
  if (!list) return;
  if (!EmailAddonState.selectedAccountId) {
    list.innerHTML = `<p data-i18n="email.no_accounts">No accounts connected.</p>`;
    return;
  }
  const cacheKey = `${EmailAddonState.selectedAccountId}:${page}`;
  const cached = getCachedValue(EmailAddonState.inboxCache, cacheKey, EmailAddonCacheTTL.inbox);
  if (cached && !force) {
    EmailAddonState.inboxPage = page;
    renderInboxList(cached.items || [], cached.total || 0, page, list, paginationTop, paginationBottom);
    loadInbox(page, true, true);
    return;
  }
  if (!silent) {
    list.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  }
  try {
    if (EmailAddonState.inboxAbort) {
      EmailAddonState.inboxAbort.abort();
    }
    EmailAddonState.inboxAbort = new AbortController();
    const response = await EmailAddonAPI.get('/messages/inbox', {
      account_id: EmailAddonState.selectedAccountId,
      page
    }, { signal: EmailAddonState.inboxAbort.signal });
    const items = response.data.items || [];
    EmailAddonState.inboxPage = page;
    setCachedValue(EmailAddonState.inboxCache, cacheKey, {
      items,
      total: response.data.total || 0
    });
    renderInboxList(items, response.data.total || 0, page, list, paginationTop, paginationBottom);
    const totalPages = Math.max(Math.ceil((response.data.total || 0) / 35), 1);
    if (page < totalPages) {
      prefetchInboxPage(page + 1);
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      list.innerHTML = `<p>${error.message}</p>`;
    }
  }
}

async function prefetchInboxPage(page) {
  const cacheKey = `${EmailAddonState.selectedAccountId}:${page}`;
  if (EmailAddonState.prefetching.has(cacheKey)) return;
  const cached = getCachedValue(EmailAddonState.inboxCache, cacheKey, EmailAddonCacheTTL.inbox);
  if (cached) return;
  EmailAddonState.prefetching.add(cacheKey);
  try {
    const response = await EmailAddonAPI.get('/messages/inbox', {
      account_id: EmailAddonState.selectedAccountId,
      page
    });
    setCachedValue(EmailAddonState.inboxCache, cacheKey, {
      items: response.data.items || [],
      total: response.data.total || 0
    });
  } catch (error) {
  } finally {
    EmailAddonState.prefetching.delete(cacheKey);
  }
}

function renderInboxMessage(message, messageContainer) {
  const htmlContent = message.html ? sanitizeEmailHtml(message.html) : '';
  const bodyContent = htmlContent
    ? `<iframe id="emailBodyIframe" class="email-body-iframe" sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox" srcdoc="${escapeHtmlAttribute(htmlContent)}"></iframe>`
    : `<div class="email-body-text">${escapeHtml(message.text || '')}</div>`;
  messageContainer.innerHTML = `
      <div class="email-message-card">
        <div class="email-message-toolbar">
          <button class="btn btn-secondary btn-sm" id="emailInboxBack" data-i18n="email.back_to_list">Back to list</button>
        </div>
        <div class="email-message-title">${message.subject || '-'}</div>
        <div class="email-body">
          <div class="email-message-meta">
            <div><strong data-i18n="email.from">From</strong>: ${message.from || '-'}</div>
            <div><strong data-i18n="email.to">To</strong>: ${message.to || '-'}</div>
            <div><strong data-i18n="email.date">Date</strong>: ${message.date ? new Date(message.date).toLocaleString() : '-'}</div>
          </div>
          <div class="email-body-content">${bodyContent}</div>
        </div>
        <div class="email-message-footer">
          <button class="btn btn-primary" id="emailReplyToggle" data-i18n="email.reply_button">Reply</button>
        </div>
        <div id="emailReplyComposer" class="email-reply-composer" style="display:none;">
          <div class="email-reply-header">
            <div class="email-reply-title" data-i18n="email.reply_title">Reply</div>
            <div class="email-reply-hint" data-i18n="email.reply_hint">Compose your response</div>
          </div>
          <input type="text" id="emailReplySubject" class="form-control" value="Re: ${message.subject || ''}" data-i18n-placeholder="email.reply_subject_placeholder">
          <div id="emailReplyEditor" class="email-reply-editor" contenteditable="true" data-i18n-placeholder="email.reply_placeholder"></div>
          <div class="email-reply-toolbar email-reply-toolbar-bottom">
            <button type="button" class="btn btn-secondary btn-sm" data-command="bold" data-i18n-title="email.toolbar_bold"><i class="fas fa-bold"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="italic" data-i18n-title="email.toolbar_italic"><i class="fas fa-italic"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="underline" data-i18n-title="email.toolbar_underline"><i class="fas fa-underline"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="strikeThrough" data-i18n-title="email.toolbar_strike"><i class="fas fa-strikethrough"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="insertUnorderedList" data-i18n-title="email.toolbar_bulleted"><i class="fas fa-list-ul"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="insertOrderedList" data-i18n-title="email.toolbar_numbered"><i class="fas fa-list-ol"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="formatBlock" data-value="h2" data-i18n-title="email.toolbar_heading"><i class="fas fa-heading"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="formatBlock" data-value="blockquote" data-i18n-title="email.toolbar_quote"><i class="fas fa-quote-right"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="createLink" data-i18n-title="email.toolbar_link"><i class="fas fa-link"></i></button>
            <button type="button" class="btn btn-secondary btn-sm" data-command="removeFormat" data-i18n-title="email.toolbar_clear"><i class="fas fa-eraser"></i></button>
            <span class="email-reply-toolbar-divider"></span>
            <button type="button" class="btn btn-secondary btn-sm email-reply-attach-btn" id="emailReplyAttachBtn" data-i18n-title="email.add_attachment"><i class="fas fa-paperclip"></i></button>
          </div>
          <input type="file" id="emailReplyFiles" multiple style="display:none;" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv">
          <div id="emailReplyAttachments" class="email-reply-attachments"></div>
          <div class="email-reply-footer">
            <button class="btn btn-secondary" id="emailReplyDiscard" data-i18n="common.cancel">Cancel</button>
            <button class="btn btn-primary" id="emailReplySend" data-i18n="email.send_reply">Send Reply</button>
          </div>
        </div>
      </div>
    `;
  const backBtn = document.getElementById('emailInboxBack');
  if (backBtn) {
    backBtn.addEventListener('click', () => {
      EmailAddonState.selectedInboxUid = null;
      setInboxMode(false);
      renderInboxEmptyState();
      const list = document.getElementById('emailInboxList');
      if (list) {
        list.querySelectorAll('.email-row').forEach(item => item.classList.remove('active'));
      }
    });
  }
  setupReplyComposer(message);
  const iframe = document.getElementById('emailBodyIframe');
  if (iframe) {
    iframe.addEventListener('load', () => {
      updateEmailIframeHeight();
    });
    setTimeout(updateEmailIframeHeight, 80);
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadInboxMessage(uid, force = false, silent = false) {
  const messageContainer = document.getElementById('emailInboxMessage');
  if (!messageContainer) return;
  if (!silent) {
    messageContainer.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  }
  setInboxMode(true);
  const normalizedUid = parseInt(uid, 10);
  if (Number.isNaN(normalizedUid)) {
    messageContainer.innerHTML = `<div class="email-message-card"><div class="email-message-toolbar"><button class="btn btn-secondary btn-sm" id="emailInboxBack" data-i18n="email.back_to_list">Back to list</button></div><div class="email-small" data-i18n="email.invalid_message_id">Invalid message id</div></div>`;
    const backBtn = document.getElementById('emailInboxBack');
    if (backBtn) {
      backBtn.addEventListener('click', () => {
        EmailAddonState.selectedInboxUid = null;
        setInboxMode(false);
        renderInboxEmptyState();
        const list = document.getElementById('emailInboxList');
        if (list) {
          list.querySelectorAll('.email-row').forEach(item => item.classList.remove('active'));
        }
      });
    }
    if (window.applyLanguage) {
      window.applyLanguage(localStorage.getItem('language') || 'en');
    }
    return;
  }
  const cacheKey = `${EmailAddonState.selectedAccountId}:${normalizedUid}`;
  const cached = getCachedValue(EmailAddonState.messageCache, cacheKey, EmailAddonCacheTTL.message);
  if (cached && !force) {
    renderInboxMessage(cached, messageContainer);
    loadInboxMessage(normalizedUid, true, true);
    return;
  }
  try {
    if (EmailAddonState.messageAbort) {
      EmailAddonState.messageAbort.abort();
    }
    EmailAddonState.messageAbort = new AbortController();
    const response = await EmailAddonAPI.get(`/messages/${normalizedUid}`, {
      account_id: EmailAddonState.selectedAccountId,
      folder: 'inbox'
    }, { signal: EmailAddonState.messageAbort.signal });
    const message = response.data;
    EmailAddonState.replyAttachments = [];
    setCachedValue(EmailAddonState.messageCache, cacheKey, message);
    renderInboxMessage(message, messageContainer);
  } catch (error) {
    if (error.name !== 'AbortError') {
      messageContainer.innerHTML = `
        <div class="email-message-card">
          <div class="email-message-toolbar">
            <button class="btn btn-secondary btn-sm" id="emailInboxBack" data-i18n="email.back_to_list">Back to list</button>
          </div>
          <div class="email-small">${error.message}</div>
        </div>
      `;
      const backBtn = document.getElementById('emailInboxBack');
      if (backBtn) {
        backBtn.addEventListener('click', () => {
          EmailAddonState.selectedInboxUid = null;
          setInboxMode(false);
          renderInboxEmptyState();
          const list = document.getElementById('emailInboxList');
          if (list) {
            list.querySelectorAll('.email-row').forEach(item => item.classList.remove('active'));
          }
        });
      }
    }
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function renderInboxPreview(preview) {
  const messageContainer = document.getElementById('emailInboxMessage');
  if (!messageContainer) return;
  messageContainer.innerHTML = `
      <div class="email-message-card">
        <div class="email-message-toolbar">
          <button class="btn btn-secondary btn-sm" id="emailInboxBack" data-i18n="email.back_to_list">Back to list</button>
        </div>
        <div class="email-message-title">${preview.subject || '-'}</div>
        <div class="email-body">
          <div class="email-message-meta">
            <div><strong data-i18n="email.from">From</strong>: ${preview.from || '-'}</div>
            <div><strong data-i18n="email.to">To</strong>: ${preview.to || '-'}</div>
            <div><strong data-i18n="email.date">Date</strong>: ${preview.date ? new Date(preview.date).toLocaleString() : '-'}</div>
          </div>
          <div class="email-body-content">
            <div class="email-small" data-i18n="common.loading">Loading...</div>
          </div>
        </div>
      </div>
    `;
  const backBtn = document.getElementById('emailInboxBack');
  if (backBtn) {
    backBtn.addEventListener('click', () => {
      EmailAddonState.selectedInboxUid = null;
      setInboxMode(false);
      renderInboxEmptyState();
      const list = document.getElementById('emailInboxList');
      if (list) {
        list.querySelectorAll('.email-row').forEach(item => item.classList.remove('active'));
      }
    });
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function getSelectedAccountAddress() {
  const selected = EmailAddonState.accounts.find(account => String(account.id) === String(EmailAddonState.selectedAccountId));
  return selected?.email_address || '-';
}

async function prefetchMessageDetails(items) {
  if (!items?.length || !EmailAddonState.selectedAccountId) return;
  const queue = items
    .map(item => item?.uid)
    .filter(uid => uid !== undefined && uid !== null)
    .slice(0, 5);
  const limit = 2;
  let index = 0;
  const runNext = async () => {
    if (index >= queue.length) return;
    const uid = queue[index];
    index += 1;
    const cacheKey = `${EmailAddonState.selectedAccountId}:${uid}`;
    if (EmailAddonState.prefetchingMessages.has(cacheKey)) return runNext();
    const cached = getCachedValue(EmailAddonState.messageCache, cacheKey, EmailAddonCacheTTL.message);
    if (cached) return runNext();
    EmailAddonState.prefetchingMessages.add(cacheKey);
    try {
      const response = await EmailAddonAPI.get(`/messages/${uid}`, {
        account_id: EmailAddonState.selectedAccountId,
        folder: 'inbox'
      });
      setCachedValue(EmailAddonState.messageCache, cacheKey, response.data);
    } catch (error) {
    } finally {
      EmailAddonState.prefetchingMessages.delete(cacheKey);
    }
    return runNext();
  };
  await Promise.all(Array.from({ length: limit }).map(() => runNext()));
}

function setupReplyComposer(message) {
  const toggleBtn = document.getElementById('emailReplyToggle');
  const composer = document.getElementById('emailReplyComposer');
  const editor = document.getElementById('emailReplyEditor');
  const attachBtn = document.getElementById('emailReplyAttachBtn');
  const fileInput = document.getElementById('emailReplyFiles');
  const discardBtn = document.getElementById('emailReplyDiscard');
  const sendBtn = document.getElementById('emailReplySend');
  if (editor) {
    editor.setAttribute('data-placeholder', emailT('email.reply_placeholder', 'Write your reply...'));
  }
  if (toggleBtn && composer) {
    toggleBtn.addEventListener('click', () => {
      composer.style.display = 'grid';
      if (editor) editor.focus();
    });
  }
  if (discardBtn && composer) {
    discardBtn.addEventListener('click', () => {
      composer.style.display = 'none';
      if (editor) editor.innerHTML = '';
      EmailAddonState.replyAttachments = [];
      renderReplyAttachments();
    });
  }
  const addAttachment = file => {
    if (!file) return null;
    const exists = EmailAddonState.replyAttachments.find(item => (
      item.file.name === file.name &&
      item.file.size === file.size &&
      item.file.lastModified === file.lastModified
    ));
    if (exists) return exists;
    const item = {
      id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
      file,
      previewUrl: file.type.startsWith('image/') ? URL.createObjectURL(file) : null
    };
    EmailAddonState.replyAttachments.push(item);
    return item;
  };
  const handleFiles = (files, insertInline = false) => {
    const list = Array.from(files || []);
    if (!list.length) return;
    list.forEach(file => {
      const item = addAttachment(file);
      if (insertInline && item?.file?.type?.startsWith('image/')) {
        insertInlineImage(item.file);
      }
    });
    renderReplyAttachments();
  };
  if (attachBtn && fileInput) {
    attachBtn.addEventListener('click', () => fileInput.click());
  }
  if (fileInput) {
    fileInput.addEventListener('change', event => {
      handleFiles(event.target.files, false);
      fileInput.value = '';
    });
  }
  if (editor) {
    editor.addEventListener('paste', event => {
      const files = Array.from(event.clipboardData?.files || []);
      if (files.length) {
        event.preventDefault();
        handleFiles(files, true);
      }
    });
    editor.addEventListener('drop', event => {
      event.preventDefault();
      handleFiles(event.dataTransfer?.files, true);
    });
  }
  document.querySelectorAll('.email-reply-toolbar [data-command]').forEach(btn => {
    btn.addEventListener('click', () => {
      const command = btn.dataset.command;
      if (!editor) return;
      if (command === 'createLink') {
        const url = window.prompt(emailT('email.reply_link_prompt', 'Paste a link'));
        if (url) {
          document.execCommand('createLink', false, url);
        }
      } else if (command === 'formatBlock') {
        document.execCommand(command, false, btn.dataset.value || 'p');
      } else {
        document.execCommand(command, false, null);
      }
      editor.focus();
    });
  });
  if (sendBtn) {
    sendBtn.addEventListener('click', async () => {
      await sendReplyWithAttachments(message.from, message.subject);
    });
  }
}

function renderReplyAttachments() {
  const container = document.getElementById('emailReplyAttachments');
  if (!container) return;
  if (!EmailAddonState.replyAttachments.length) {
    container.innerHTML = '';
    return;
  }
  container.innerHTML = EmailAddonState.replyAttachments.map(item => `
    <div class="email-attachment-card" data-id="${item.id}">
      <div class="email-attachment-info">
        ${item.previewUrl ? `<img src="${item.previewUrl}" alt="preview">` : `<div class="email-attachment-icon"><i class="fas fa-file"></i></div>`}
        <div>
          <div class="email-attachment-name">${item.file.name}</div>
          <div class="email-small">${formatFileSize(item.file.size)}</div>
        </div>
      </div>
      <div class="email-attachment-actions">
        ${item.previewUrl ? `<button class="btn btn-secondary btn-sm email-attachment-insert" data-id="${item.id}" data-i18n="email.insert_image">Insert</button>` : ''}
        <button class="btn btn-danger btn-sm email-attachment-remove" data-id="${item.id}" data-i18n="email.remove_attachment">Remove</button>
      </div>
    </div>
  `).join('');
  container.querySelectorAll('.email-attachment-remove').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.dataset.id;
      const item = EmailAddonState.replyAttachments.find(file => file.id === id);
      if (item?.previewUrl) URL.revokeObjectURL(item.previewUrl);
      EmailAddonState.replyAttachments = EmailAddonState.replyAttachments.filter(file => file.id !== id);
      renderReplyAttachments();
    });
  });
  container.querySelectorAll('.email-attachment-insert').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.dataset.id;
      const item = EmailAddonState.replyAttachments.find(file => file.id === id);
      if (!item) return;
      insertInlineImage(item.file);
    });
  });
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function insertInlineImage(file) {
  const editor = document.getElementById('emailReplyEditor');
  if (!editor || !file) return;
  const reader = new FileReader();
  reader.onload = () => {
    document.execCommand('insertImage', false, reader.result);
    editor.focus();
  };
  reader.readAsDataURL(file);
}

function formatFileSize(size) {
  if (!size) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  let index = 0;
  let value = size;
  while (value >= 1024 && index < units.length - 1) {
    value /= 1024;
    index += 1;
  }
  return `${value.toFixed(value >= 10 || index === 0 ? 0 : 1)} ${units[index]}`;
}

async function sendReplyWithAttachments(to, subject) {
  const editor = document.getElementById('emailReplyEditor');
  const replySubject = document.getElementById('emailReplySubject')?.value || subject || '';
  const html = editor?.innerHTML || '';
  if (!html.trim()) {
    showNotification(emailT('email.reply_body_required', 'Message body is required'), 'error');
    return;
  }
  const formData = new FormData();
  formData.append('account_id', EmailAddonState.selectedAccountId || '');
  formData.append('to', to || '');
  formData.append('subject', replySubject);
  formData.append('html', html);
  EmailAddonState.replyAttachments.forEach(item => {
    formData.append('attachments', item.file, item.file.name);
  });
  try {
    await EmailAddonAPI.postForm('/messages/reply', formData);
    showNotification(emailT('email.reply_sent', 'Reply sent'), 'success');
    EmailAddonState.replyAttachments = [];
    renderReplyAttachments();
    if (editor) editor.innerHTML = '';
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

function openNewEmailModal() {
  const modal = document.getElementById('emailNewMessageModal');
  const editor = document.getElementById('newEmailEditor');
  if (!modal) return;
  modal.style.display = 'flex';
  if (editor) {
    editor.setAttribute('data-placeholder', emailT('email.reply_placeholder', 'Write your reply...'));
    editor.focus();
  }
  modal.querySelectorAll('.modal-close').forEach(btn => {
    btn.addEventListener('click', () => closeNewEmailModal());
  });
  const attachBtn = document.getElementById('newEmailAttachBtn');
  const fileInput = document.getElementById('newEmailFiles');
  if (attachBtn && fileInput) {
    attachBtn.onclick = () => fileInput.click();
  }
  if (fileInput) {
    fileInput.onchange = event => {
      handleNewEmailFiles(event.target.files);
      fileInput.value = '';
    };
  }
  modal.querySelectorAll('.email-reply-toolbar [data-command]').forEach(btn => {
    btn.onclick = () => {
      const command = btn.dataset.command;
      if (!editor) return;
      if (command === 'formatBlock') {
        document.execCommand(command, false, btn.dataset.value || 'p');
      } else {
        document.execCommand(command, false, null);
      }
      editor.focus();
    };
  });
  const sendBtn = document.getElementById('newEmailSend');
  if (sendBtn) {
    sendBtn.onclick = () => sendNewEmail();
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function closeNewEmailModal() {
  const modal = document.getElementById('emailNewMessageModal');
  if (!modal) return;
  modal.style.display = 'none';
  const editor = document.getElementById('newEmailEditor');
  if (editor) editor.innerHTML = '';
  EmailAddonState.replyAttachments = [];
  renderNewEmailAttachments();
}

function handleNewEmailFiles(files) {
  const list = Array.from(files || []);
  if (!list.length) return;
  list.forEach(file => {
    const exists = EmailAddonState.replyAttachments.find(item => (
      item.file.name === file.name &&
      item.file.size === file.size &&
      item.file.lastModified === file.lastModified
    ));
    if (exists) return;
    const item = {
      id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
      file,
      previewUrl: file.type.startsWith('image/') ? URL.createObjectURL(file) : null
    };
    EmailAddonState.replyAttachments.push(item);
  });
  renderNewEmailAttachments();
}

function renderNewEmailAttachments() {
  const container = document.getElementById('newEmailAttachments');
  if (!container) return;
  if (!EmailAddonState.replyAttachments.length) {
    container.innerHTML = '';
    return;
  }
  container.innerHTML = EmailAddonState.replyAttachments.map(item => `
    <div class="email-attachment-card" data-id="${item.id}">
      <div class="email-attachment-info">
        ${item.previewUrl ? `<img src="${item.previewUrl}" alt="preview">` : `<div class="email-attachment-icon"><i class="fas fa-file"></i></div>`}
        <div>
          <div class="email-attachment-name">${item.file.name}</div>
          <div class="email-small">${formatFileSize(item.file.size)}</div>
        </div>
      </div>
      <div class="email-attachment-actions">
        <button class="btn btn-danger btn-sm email-attachment-remove" data-id="${item.id}" data-i18n="email.remove_attachment">Remove</button>
      </div>
    </div>
  `).join('');
  container.querySelectorAll('.email-attachment-remove').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.dataset.id;
      const item = EmailAddonState.replyAttachments.find(file => file.id === id);
      if (item?.previewUrl) URL.revokeObjectURL(item.previewUrl);
      EmailAddonState.replyAttachments = EmailAddonState.replyAttachments.filter(file => file.id !== id);
      renderNewEmailAttachments();
    });
  });
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function sendNewEmail() {
  const to = document.getElementById('newEmailTo')?.value || '';
  const subject = document.getElementById('newEmailSubject')?.value || '';
  const editor = document.getElementById('newEmailEditor');
  const html = editor?.innerHTML || '';
  
  if (!EmailAddonState.selectedAccountId) {
    showNotification(emailT('email.no_account_selected', 'Please select an email account'), 'error');
    return;
  }
  
  if (!to || !html.trim()) {
    showNotification(emailT('email.reply_body_required', 'Message body is required'), 'error');
    return;
  }
  
  if (!to.includes('@')) {
    showNotification(emailT('email.invalid_email', 'Invalid email address'), 'error');
    return;
  }
  
  const formData = new FormData();
  formData.append('account_id', EmailAddonState.selectedAccountId);
  formData.append('to', to);
  formData.append('subject', subject || '(No subject)');
  formData.append('html', html);
  
  EmailAddonState.replyAttachments.forEach(item => {
    formData.append('attachments', item.file, item.file.name);
  });
  
  try {
    await EmailAddonAPI.postForm('/messages/reply', formData);
    showNotification(emailT('email.reply_sent', 'Reply sent'), 'success');
    closeNewEmailModal();
    loadSents();
  } catch (error) {
    console.error('Error sending email:', error);
    showNotification(error.message || 'Error sending email', 'error');
  }
}

async function loadSents(page = EmailAddonState.sentPage, force = false, silent = false) {
  const list = document.getElementById('emailSentsList');
  const pagination = document.getElementById('emailSentsPagination');
  const messageContainer = document.getElementById('emailSentsMessage');
  if (!list || !pagination) return;
  messageContainer.innerHTML = '';
  if (!EmailAddonState.selectedAccountId) {
    list.innerHTML = `<p data-i18n="email.no_accounts">No accounts connected.</p>`;
    return;
  }
  const cacheKey = `${EmailAddonState.selectedAccountId}:${page}`;
  const cached = getCachedValue(EmailAddonState.sentsCache, cacheKey, EmailAddonCacheTTL.sents);
  if (cached && !force) {
    EmailAddonState.sentPage = page;
    renderSentsList(cached.items || [], cached.total || 0, page, list, pagination);
    loadSents(page, true, true);
    return;
  }
  if (!silent) {
    list.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  }
  try {
    if (EmailAddonState.sentsAbort) {
      EmailAddonState.sentsAbort.abort();
    }
    EmailAddonState.sentsAbort = new AbortController();
    const response = await EmailAddonAPI.get('/messages/sent', {
      account_id: EmailAddonState.selectedAccountId,
      page
    }, { signal: EmailAddonState.sentsAbort.signal });
    const items = response.data.items || [];
    EmailAddonState.sentPage = page;
    setCachedValue(EmailAddonState.sentsCache, cacheKey, {
      items,
      total: response.data.total || 0
    });
    renderSentsList(items, response.data.total || 0, page, list, pagination);
  } catch (error) {
    if (error.name !== 'AbortError') {
      list.innerHTML = `<p>${error.message}</p>`;
    }
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function renderSentsList(items, total, page, list, pagination) {
  if (!list || !pagination) return;
  list.innerHTML = `
      <table class="email-addon-table">
        <thead>
          <tr>
            <th data-i18n="email.to">To</th>
            <th data-i18n="email.subject">Subject</th>
            <th data-i18n="email.date">Date</th>
          </tr>
        </thead>
        <tbody>
          ${items.map(item => `
            <tr class="email-row" data-id="${item.id}">
              <td>${item.to_email || '-'}</td>
              <td>${item.subject || '-'}</td>
              <td>${item.sent_at ? new Date(item.sent_at).toLocaleString() : new Date(item.created_at).toLocaleString()}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;
  list.querySelectorAll('.email-row').forEach(row => {
    row.addEventListener('click', () => loadSentMessage(row.dataset.id));
  });
  renderPagination(pagination, total || 0, page, newPage => loadSents(newPage));
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadSentMessage(id) {
  const messageContainer = document.getElementById('emailSentsMessage');
  if (!messageContainer) return;
  messageContainer.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  try {
    const response = await EmailAddonAPI.get(`/messages/${id}`, {
      account_id: EmailAddonState.selectedAccountId,
      folder: 'sent'
    });
    const message = response.data;
    messageContainer.innerHTML = `
      <div class="email-addon-message">
        <div><strong data-i18n="email.from">From</strong>: ${message.from_email || '-'}</div>
        <div><strong data-i18n="email.to">To</strong>: ${message.to_email || '-'}</div>
        <div><strong data-i18n="email.subject">Subject</strong>: ${message.subject || '-'}</div>
        <div class="email-body">${message.html_content || message.text_content || ''}</div>
      </div>
    `;
  } catch (error) {
    messageContainer.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function renderPagination(container, total, currentPage, onChange) {
  const pageSize = 35;
  const totalPages = Math.max(Math.ceil(total / pageSize), 1);
  if (!container) return;
  if (totalPages <= 1) {
    container.innerHTML = '';
    return;
  }
  const pages = [];
  for (let i = 1; i <= totalPages; i += 1) {
    pages.push(`<button class="${i === currentPage ? 'active' : ''}" data-page="${i}">${i}</button>`);
  }
  container.innerHTML = pages.join('');
  container.querySelectorAll('button').forEach(btn => {
    btn.addEventListener('click', () => onChange(parseInt(btn.dataset.page, 10)));
  });
}

function initTemplateEditor() {
  if (!window.grapesjs) return;
}

async function loadTemplates() {
  try {
    const response = await EmailAddonAPI.get('/templates');
    EmailAddonState.templates = response.data || [];
    renderTemplateList();
    renderTemplateSelect();
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

function renderTemplateList() {
  const list = document.getElementById('emailTemplateList');
  if (!list) return;
  if (!EmailAddonState.templates.length) {
    list.innerHTML = `
      <div class="email-template-empty">
        <i class="fas fa-layer-group" style="font-size: 48px; color: #cbd5e0; margin-bottom: 12px;"></i>
        <p data-i18n="email.no_templates">No templates yet</p>
        <p class="email-small" data-i18n="email.create_first_template">Click "New Template" to create your first template</p>
      </div>
    `;
    return;
  }
  list.innerHTML = `
    <div class="email-template-grid">
      ${EmailAddonState.templates.map(template => `
        <div class="email-template-card ${EmailAddonState.selectedTemplateId === template.id ? 'active' : ''}" data-id="${template.id}">
          <div class="email-template-preview">
            <iframe srcdoc="${escapeHtmlAttribute(template.html_content || '')}" style="width:100%;height:160px;border:none;pointer-events:none;border-radius:8px;"></iframe>
          </div>
          <div class="email-template-info">
            <div class="email-template-title">${escapeHtml(template.name)}</div>
            <div class="email-small">${escapeHtml(template.subject || emailT('email.no_subject', 'No subject'))}</div>
          </div>
          <div class="email-template-actions">
            <button class="btn btn-sm btn-secondary email-template-edit" data-id="${template.id}" title="Edit">
              <i class="fas fa-edit"></i>
            </button>
            <button class="btn btn-sm btn-danger email-template-delete" data-id="${template.id}" title="Delete">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      `).join('')}
    </div>
  `;
  list.querySelectorAll('.email-template-edit').forEach(btn => {
    btn.addEventListener('click', event => {
      event.stopPropagation();
      selectTemplate(btn.dataset.id);
    });
  });
  list.querySelectorAll('.email-template-delete').forEach(btn => {
    btn.addEventListener('click', async event => {
      event.stopPropagation();
      const confirmed = await showCustomConfirm(
        emailT('email.template_delete_confirm', 'Are you sure you want to delete this template?')
      );
      if (confirmed) {
        await deleteTemplate(btn.dataset.id);
      }
    });
  });
}

async function selectTemplate(templateId) {
  EmailAddonState.selectedTemplateId = parseInt(templateId, 10);
  renderTemplateList();
  const response = await EmailAddonAPI.get(`/templates/${templateId}`);
  const template = response.data;
  const nameInput = document.getElementById('emailTemplateName');
  if (nameInput) nameInput.value = template.name || '';
  openTemplateModal(() => {
    mountTemplateEditor();
    if (EmailAddonState.templateEditor && EmailAddonState.templateEditor.setHTML) {
      if (template.design_json) {
        try {
          const components = JSON.parse(template.design_json);
          EmailAddonState.templateEditor.components = components;
          EmailAddonState.templateEditor.render();
        } catch (e) {
          EmailAddonState.templateEditor.setHTML(template.html_content || '');
        }
      } else {
        EmailAddonState.templateEditor.setHTML(template.html_content || '');
      }
    }
  });
}

function createNewTemplate() {
  EmailAddonState.selectedTemplateId = null;
  const nameInput = document.getElementById('emailTemplateName');
  if (nameInput) nameInput.value = '';
  openTemplateModal(() => {
    mountTemplateEditor();
    if (EmailAddonState.templateEditor && EmailAddonState.templateEditor.clear) {
      EmailAddonState.templateEditor.clear();
    }
    renderTemplateList();
  });
}

function getTemplateHtml() {
  if (!EmailAddonState.templateEditor) return '';
  if (EmailAddonState.templateEditor.getHTML) {
    return EmailAddonState.templateEditor.getHTML();
  }
  return '';
}

function getTemplateDesign() {
  if (!EmailAddonState.templateEditor) return '';
  if (EmailAddonState.templateEditor.components) {
    return JSON.stringify(EmailAddonState.templateEditor.components);
  }
  return '';
}

async function saveTemplate() {
  const nameInput = document.getElementById('emailTemplateName');
  const name = nameInput?.value?.trim();
  if (!name) {
    showNotification(emailT('email.template_name_required', 'Template name is required'), 'error');
    return;
  }
  const payload = {
    name,
    html_content: getTemplateHtml(),
    design_json: getTemplateDesign()
  };
  try {
    if (EmailAddonState.selectedTemplateId) {
      await EmailAddonAPI.put(`/templates/${EmailAddonState.selectedTemplateId}`, payload);
    } else {
      const response = await EmailAddonAPI.post('/templates', payload);
      EmailAddonState.selectedTemplateId = response.data.id;
    }
    await loadTemplates();
    showNotification(emailT('email.template_saved', 'Template saved'), 'success');
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

async function deleteTemplate(templateId) {
  try {
    await EmailAddonAPI.delete(`/templates/${templateId}`);
    if (EmailAddonState.selectedTemplateId === parseInt(templateId, 10)) {
      EmailAddonState.selectedTemplateId = null;
    }
    await loadTemplates();
    showNotification(emailT('email.template_deleted', 'Template deleted'), 'success');
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

function openHtmlEditor() {
  const modal = document.getElementById('email-html-modal');
  const textarea = document.getElementById('emailHtmlTextarea');
  if (!modal || !textarea) return;
  textarea.value = getTemplateHtml();
  modal.style.display = 'block';
  const applyBtn = document.getElementById('emailHtmlApply');
  if (applyBtn) {
    applyBtn.onclick = () => {
      if (EmailAddonState.templateEditor) {
        EmailAddonState.templateEditor.setComponents(textarea.value || '');
      }
      modal.style.display = 'none';
    };
  }
}

function openTemplateModal(onOpen) {
  const modal = document.getElementById('email-template-modal');
  if (!modal) return;
  modal.style.display = 'flex';
  modal.querySelectorAll('.modal-close').forEach(btn => {
    btn.onclick = () => closeTemplateModal();
  });
  const saveBtn = document.getElementById('emailTemplateModalSave');
  if (saveBtn) saveBtn.onclick = () => saveTemplate();
  const exportBtn = document.getElementById('emailTemplateExport');
  if (exportBtn) exportBtn.onclick = () => {
    const html = getTemplateHtml();
    const blob = new Blob([html], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${document.getElementById('emailTemplateName')?.value || 'template'}.html`;
    a.click();
    URL.revokeObjectURL(url);
  };
  if (!EmailAddonState.templateEditor) {
    mountTemplateEditor();
  }
  if (typeof onOpen === 'function') onOpen();
}

function closeTemplateModal() {
  const modal = document.getElementById('email-template-modal');
  if (!modal) return;
  modal.style.display = 'none';
}

function mountTemplateEditor() {
  // Use our simple editor instead of GrapesJS
  const canvasContainer = document.getElementById('emailTemplateEditorCanvas');
  if (!canvasContainer) return;
  
  // Clear and setup canvas
  canvasContainer.innerHTML = '';
  
  // Add canvas header
  const header = document.createElement('div');
  header.className = 'canvas-header';
  const canvasTitle = emailT('email.editor.canvas_title', 'Content Canvas');
  const desktopTitle = emailT('email.editor.device_desktop', 'Desktop View');
  const mobileTitle = emailT('email.editor.device_mobile', 'Mobile View');
  header.innerHTML = `
    <div class="canvas-title">
      <strong>${canvasTitle}</strong>
    </div>
    <div class="canvas-actions">
      <button class="canvas-device-btn active" data-device="desktop" title="${desktopTitle}">
        <i class="fas fa-desktop"></i>
      </button>
      <button class="canvas-device-btn" data-device="mobile" title="${mobileTitle}">
        <i class="fas fa-mobile-alt"></i>
      </button>
    </div>
  `;
  
  // Add canvas content area
  const canvasContent = document.createElement('div');
  canvasContent.className = 'canvas-content-area';
  canvasContent.id = 'simpleEmailCanvas';
  
  canvasContainer.appendChild(header);
  canvasContainer.appendChild(canvasContent);
  
  // Add floating button to reopen blocks panel
  const modal = document.querySelector('.template-modal-new');
  if (modal && !modal.querySelector('.reopen-blocks-btn')) {
    const reopenBtn = document.createElement('button');
    reopenBtn.className = 'reopen-blocks-btn';
    reopenBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
    reopenBtn.title = emailT('email.editor.show_blocks', 'Show blocks');
    reopenBtn.style.display = 'none';
    reopenBtn.addEventListener('click', () => {
      modal.classList.remove('blocks-collapsed');
      reopenBtn.style.display = 'none';
    });
    modal.appendChild(reopenBtn);
  }
  
  // Initialize simple editor
  if (window.SimpleEmailEditor) {
    SimpleEmailEditor.init('simpleEmailCanvas');
    EmailAddonState.templateEditor = SimpleEmailEditor;
  }
  const propertiesPanel = document.getElementById('emailTemplateProperties');
  if (propertiesPanel && EmailAddonState.templateEditor?.setPropertiesPanel) {
    EmailAddonState.templateEditor.setPropertiesPanel(propertiesPanel);
  }
  
  // Device switcher
  header.querySelectorAll('.canvas-device-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      header.querySelectorAll('.canvas-device-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      const device = btn.dataset.device;
      const canvas = document.querySelector('.simple-email-canvas');
      if (canvas) {
        if (device === 'mobile') {
          canvas.style.maxWidth = '375px';
        } else {
          canvas.style.maxWidth = '960px';
        }
      }
    });
  });
  
  // Setup blocks
  setupSimpleBlocks();
}

function setupSimpleBlocks() {
  const blocksContainer = document.getElementById('emailTemplateBlocks');
  if (!blocksContainer) return;
  
  const blocksTitle = emailT('email.editor.add_blocks', 'Add Blocks');
  const blocksHint = emailT('email.editor.drag_hint', 'Drag or click to add to canvas');
  const categoryContent = emailT('email.editor.category_content', 'CONTENT');
  const categoryMedia = emailT('email.editor.category_media', 'MEDIA');
  const categoryLayout = emailT('email.editor.category_layout', 'LAYOUT');
  const headingLabel = emailT('email.editor.block_heading', 'Heading');
  const headingHint = emailT('email.editor.block_heading_hint', 'Title text');
  const paragraphLabel = emailT('email.editor.block_paragraph', 'Paragraph');
  const paragraphHint = emailT('email.editor.block_paragraph_hint', 'Body text');
  const textLabel = emailT('email.editor.block_text', 'Text Block');
  const textHint = emailT('email.editor.block_text_hint', 'Simple text');
  const buttonLabel = emailT('email.editor.block_button', 'Button');
  const buttonHint = emailT('email.editor.block_button_hint', 'CTA button');
  const linkLabel = emailT('email.editor.block_link', 'Link');
  const linkHint = emailT('email.editor.block_link_hint', 'Hyperlink');
  const imageLabel = emailT('email.editor.block_image', 'Image');
  const imageHint = emailT('email.editor.block_image_hint', 'Add image URL');
  const dividerLabel = emailT('email.editor.block_divider', 'Divider');
  const dividerHint = emailT('email.editor.block_divider_hint', 'Separator');
  const spacerLabel = emailT('email.editor.block_spacer', 'Spacer');
  const spacerHint = emailT('email.editor.block_spacer_hint', 'Vertical space');
  const cols2Label = emailT('email.editor.block_cols_2', '2 Columns');
  const cols2Hint = emailT('email.editor.block_cols_2_hint', 'Split layout');
  const cols3Label = emailT('email.editor.block_cols_3', '3 Columns');
  const cols3Hint = emailT('email.editor.block_cols_3_hint', 'Triple layout');

  blocksContainer.innerHTML = `
    <div class="email-blocks-header">
      <div class="email-blocks-title">
        <button class="email-blocks-collapse" id="emailBlocksCollapse">
          <i class="fas fa-chevron-left"></i>
        </button>
        <div>
          <strong>${blocksTitle}</strong>
          <p>${blocksHint}</p>
        </div>
      </div>
    </div>
    
    <div class="blocks-category">${categoryContent}</div>
    
    <div class="block-item" data-type="heading" draggable="true">
      <div class="block-icon"><i class="fas fa-heading"></i></div>
      <div class="block-text">
        <strong>${headingLabel}</strong>
        <span>${headingHint}</span>
      </div>
    </div>
    
    <div class="block-item" data-type="paragraph" draggable="true">
      <div class="block-icon"><i class="fas fa-align-left"></i></div>
      <div class="block-text">
        <strong>${paragraphLabel}</strong>
        <span>${paragraphHint}</span>
      </div>
    </div>
    
    <div class="block-item" data-type="text" draggable="true">
      <div class="block-icon"><i class="fas fa-font"></i></div>
      <div class="block-text">
        <strong>${textLabel}</strong>
        <span>${textHint}</span>
      </div>
    </div>
    
    <div class="block-item" data-type="button" draggable="true">
      <div class="block-icon"><i class="fas fa-square"></i></div>
      <div class="block-text">
        <strong>${buttonLabel}</strong>
        <span>${buttonHint}</span>
      </div>
    </div>
    
    <div class="block-item" data-type="link" draggable="true">
      <div class="block-icon"><i class="fas fa-link"></i></div>
      <div class="block-text">
        <strong>${linkLabel}</strong>
        <span>${linkHint}</span>
      </div>
    </div>
    
    <div class="blocks-category">${categoryMedia}</div>
    
    <div class="block-item" data-type="image" draggable="true">
      <div class="block-icon"><i class="fas fa-image"></i></div>
      <div class="block-text">
        <strong>${imageLabel}</strong>
        <span>${imageHint}</span>
      </div>
    </div>
    
    <div class="blocks-category">${categoryLayout}</div>
    
    <div class="block-item" data-type="divider" draggable="true">
      <div class="block-icon"><i class="fas fa-minus"></i></div>
      <div class="block-text">
        <strong>${dividerLabel}</strong>
        <span>${dividerHint}</span>
      </div>
    </div>
    
    <div class="block-item" data-type="spacer" draggable="true">
      <div class="block-icon"><i class="fas fa-arrows-alt-v"></i></div>
      <div class="block-text">
        <strong>${spacerLabel}</strong>
        <span>${spacerHint}</span>
      </div>
    </div>
    
    <div class="block-item" data-type="2cols" draggable="true">
      <div class="block-icon"><i class="fas fa-columns"></i></div>
      <div class="block-text">
        <strong>${cols2Label}</strong>
        <span>${cols2Hint}</span>
      </div>
    </div>
    
    <div class="block-item" data-type="3cols" draggable="true">
      <div class="block-icon"><i class="fas fa-th"></i></div>
      <div class="block-text">
        <strong>${cols3Label}</strong>
        <span>${cols3Hint}</span>
      </div>
    </div>
  `;
  
  // Add drag and click handlers
  blocksContainer.querySelectorAll('.block-item').forEach(block => {
    // Click handler
    block.addEventListener('click', () => {
      const type = block.dataset.type;
      if (EmailAddonState.templateEditor && EmailAddonState.templateEditor.addComponent) {
        EmailAddonState.templateEditor.addComponent(type);
      }
    });
    
    // Drag start
    block.addEventListener('dragstart', (e) => {
      if (EmailAddonState.templateEditor) {
        EmailAddonState.templateEditor.draggedElement = block;
      }
      block.classList.add('dragging');
      e.dataTransfer.effectAllowed = 'copy';
      e.dataTransfer.setData('text/plain', block.dataset.type);
    });
    
    // Drag end
    block.addEventListener('dragend', () => {
      block.classList.remove('dragging');
    });
  });
  
  // Collapse/Expand button
  const collapseBtn = document.getElementById('emailBlocksCollapse');
  if (collapseBtn) {
    collapseBtn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      const modal = document.querySelector('.template-modal-new');
      const reopenBtn = modal ? modal.querySelector('.reopen-blocks-btn') : null;
      
      if (modal) {
        const isCollapsed = modal.classList.contains('blocks-collapsed');
        
        if (isCollapsed) {
          // Expandir
          modal.classList.remove('blocks-collapsed');
          collapseBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
          collapseBtn.title = emailT('email.editor.hide_blocks', 'Hide blocks');
          if (reopenBtn) reopenBtn.style.display = 'none';
        } else {
          // Colapsar
          modal.classList.add('blocks-collapsed');
          collapseBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
          collapseBtn.title = emailT('email.editor.show_blocks', 'Show blocks');
          if (reopenBtn) reopenBtn.style.display = 'flex';
        }
      }
    });
  }
}

function updateCanvasPlaceholder() {
  if (!EmailAddonState.templateEditor) return;
  const wrapper = EmailAddonState.templateEditor.getWrapper();
  const components = wrapper.components();
  
  if (components.length === 0) {
    const placeholder = document.createElement('div');
    placeholder.className = 'canvas-empty-placeholder';
    placeholder.innerHTML = 'Drop here to add at end';
    
    const frame = document.querySelector('.gjs-frame');
    if (frame) {
      const existingPlaceholder = frame.querySelector('.canvas-empty-placeholder');
      if (existingPlaceholder) {
        existingPlaceholder.remove();
      }
      const frameDoc = frame.contentDocument || frame.contentWindow.document;
      if (frameDoc && frameDoc.body) {
        const placeholderInFrame = frameDoc.createElement('div');
        placeholderInFrame.className = 'canvas-empty-placeholder';
        placeholderInFrame.style.cssText = 'text-align: center; padding: 80px 20px; color: #a0aec0; font-size: 14px;';
        placeholderInFrame.textContent = 'Drop here to add at end';
        frameDoc.body.appendChild(placeholderInFrame);
      }
    }
  } else {
    const frame = document.querySelector('.gjs-frame');
    if (frame) {
      const frameDoc = frame.contentDocument || frame.contentWindow.document;
      if (frameDoc) {
        const placeholder = frameDoc.querySelector('.canvas-empty-placeholder');
        if (placeholder) {
          placeholder.remove();
        }
      }
    }
  }
}

function setupCanvasInteractions(editor) {
  if (!editor) return;
  
  editor.on('component:selected', component => {
    if (!component || component.get('type') === 'wrapper') return;
    
    const toolbar = component.get('toolbar');
    const customToolbar = [
      {
        attributes: { class: 'fa fa-arrow-up', title: 'Move Up' },
        command: (editor, sender) => {
          const parent = component.parent();
          const index = parent.components().indexOf(component);
          if (index > 0) {
            parent.components().remove(component);
            parent.components().add(component, { at: index - 1 });
            editor.select(component);
          }
        }
      },
      {
        attributes: { class: 'fa fa-arrow-down', title: 'Move Down' },
        command: (editor, sender) => {
          const parent = component.parent();
          const components = parent.components();
          const index = components.indexOf(component);
          if (index < components.length - 1) {
            parent.components().remove(component);
            parent.components().add(component, { at: index + 1 });
            editor.select(component);
          }
        }
      },
      {
        attributes: { class: 'fa fa-clone', title: 'Duplicate' },
        command: 'tlb-clone'
      },
      {
        attributes: { class: 'fa fa-trash', title: 'Delete' },
        command: 'tlb-delete'
      }
    ];
    
    component.set('toolbar', customToolbar);
  });
}

function configureTemplateBlocks(editor) {
  if (!editor) return;
  const bm = editor.BlockManager;
  bm.getAll().reset();
  
  const blocksHeader = document.createElement('div');
  blocksHeader.className = 'email-blocks-header';
  blocksHeader.innerHTML = `
    <div class="email-blocks-title">
      <button class="email-blocks-collapse" id="emailBlocksCollapse">
        <i class="fas fa-chevron-left"></i>
      </button>
      <div>
        <strong>${emailT('email.editor.add_blocks', 'Add Blocks')}</strong>
        <p>${emailT('email.editor.drag_hint', 'Drag or click to add to canvas')}</p>
      </div>
    </div>
  `;
  
  const blocksContainer = document.getElementById('emailTemplateBlocks');
  if (blocksContainer && !blocksContainer.querySelector('.email-blocks-header')) {
    blocksContainer.insertBefore(blocksHeader, blocksContainer.firstChild);
    
    const collapseBtn = document.getElementById('emailBlocksCollapse');
    if (collapseBtn) {
      collapseBtn.addEventListener('click', () => {
        const modal = document.querySelector('.template-modal-new');
        if (modal) {
          modal.classList.toggle('blocks-collapsed');
        }
      });
    }
  }
  
  bm.add('content-heading', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-heading"></i></div>
        <div class="email-block-text">
          <strong>Heading</strong>
          <span>Title text</span>
        </div>
      </div>
    `,
    category: { id: 'content', label: 'CONTENT', open: true },
    content: {
      type: 'text',
      content: 'Your Heading Here',
      style: {
        'font-size': '32px',
        'font-weight': 'bold',
        'margin': '0 0 16px 0',
        'color': '#1a202c',
        'line-height': '1.2'
      },
      editable: true
    }
  });
  
  bm.add('content-paragraph', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-align-left"></i></div>
        <div class="email-block-text">
          <strong>Paragraph</strong>
          <span>Body text</span>
        </div>
      </div>
    `,
    category: 'content',
    content: {
      type: 'text',
      content: 'Add your paragraph text here. Use {{first_name}} for personalization.',
      style: {
        'font-size': '16px',
        'line-height': '1.6',
        'color': '#4a5568',
        'margin': '0 0 16px 0'
      },
      editable: true
    }
  });
  
  bm.add('content-text', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-font"></i></div>
        <div class="email-block-text">
          <strong>Text Block</strong>
          <span>Simple text</span>
        </div>
      </div>
    `,
    category: 'content',
    content: {
      type: 'text',
      content: 'Simple text block',
      style: {
        'font-size': '15px',
        'line-height': '1.5',
        'color': '#2d3748',
        'margin': '0 0 12px 0'
      },
      editable: true
    }
  });
  
  bm.add('content-button', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-square"></i></div>
        <div class="email-block-text">
          <strong>Button</strong>
          <span>CTA button</span>
        </div>
      </div>
    `,
    category: 'content',
    content: `
      <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin: 16px 0;">
        <tr>
          <td style="background: #3182ce; padding: 14px 28px; border-radius: 8px; text-align: center;">
            <a href="https://example.com" style="color: #ffffff; text-decoration: none; font-weight: 600; font-size: 16px; display: inline-block;">Call to Action</a>
          </td>
        </tr>
      </table>
    `
  });
  
  bm.add('content-link', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-link"></i></div>
        <div class="email-block-text">
          <strong>Link</strong>
          <span>Hyperlink</span>
        </div>
      </div>
    `,
    category: 'content',
    content: {
      type: 'link',
      content: 'Click here',
      attributes: { href: 'https://example.com' },
      style: {
        'color': '#3182ce',
        'text-decoration': 'underline',
        'font-size': '15px'
      }
    }
  });
  
  bm.add('media-image', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-image"></i></div>
        <div class="email-block-text">
          <strong>Image</strong>
          <span>Add image URL</span>
        </div>
      </div>
    `,
    category: { id: 'media', label: 'MEDIA', open: false },
    content: {
      type: 'image',
      style: {
        'width': '100%',
        'max-width': '600px',
        'height': 'auto',
        'border-radius': '8px',
        'margin': '16px 0',
        'border': '2px dashed #cbd5e0',
        'padding': '60px 20px',
        'background': '#f7fafc',
        'display': 'block'
      },
      attributes: {
        src: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="100" height="100"%3E%3Crect fill="%23f0f0f0" width="100" height="100"/%3E%3Ctext fill="%23999" x="50%25" y="50%25" text-anchor="middle" dy=".3em"%3EImage%3C/text%3E%3C/svg%3E',
        alt: 'Add image URL'
      }
    }
  });
  
  bm.add('layout-divider', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-minus"></i></div>
        <div class="email-block-text">
          <strong>Divider</strong>
          <span>Separator</span>
        </div>
      </div>
    `,
    category: { id: 'layout', label: 'LAYOUT', open: false },
    content: `
      <hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 24px 0;">
    `
  });
  
  bm.add('layout-spacer', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-arrows-alt-v"></i></div>
        <div class="email-block-text">
          <strong>Spacer</strong>
          <span>Vertical space</span>
        </div>
      </div>
    `,
    category: 'layout',
    content: `
      <div style="height: 32px; line-height: 32px; font-size: 0;">&nbsp;</div>
    `
  });
  
  bm.add('layout-2cols', {
    label: `
      <div class="email-block-item">
        <div class="email-block-icon"><i class="fas fa-columns"></i></div>
        <div class="email-block-text">
          <strong>2 Columns</strong>
          <span>Split layout</span>
        </div>
      </div>
    `,
    category: 'layout',
    content: `
      <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="width: 100%; margin: 16px 0;">
        <tr>
          <td style="width: 50%; padding: 12px; vertical-align: top; border: 1px dashed #cbd5e0;">
            <p style="margin: 0; color: #718096;">Left column</p>
          </td>
          <td style="width: 50%; padding: 12px; vertical-align: top; border: 1px dashed #cbd5e0;">
            <p style="margin: 0; color: #718096;">Right column</p>
          </td>
        </tr>
      </table>
    `
  });
}

function renderTemplateSelect() {
  const select = document.getElementById('emailMarketingTemplate');
  if (!select) return;
  select.innerHTML = EmailAddonState.templates
    .map(template => `<option value="${template.id}">${template.name}</option>`)
    .join('');
}

async function submitCampaign() {
  const accountId = EmailAddonState.selectedAccountId;
  const templateId = document.getElementById('emailMarketingTemplate')?.value || null;
  const name = document.getElementById('emailCampaignName')?.value || '';
  const subject = document.getElementById('emailCampaignSubject')?.value || '';
  const recipients = document.getElementById('emailCampaignRecipients')?.value || '';
  const mode = document.getElementById('emailCampaignMode')?.value || 'now';
  const schedule = document.getElementById('emailCampaignSchedule')?.value || null;
  
  console.log('Submitting email campaign', {
    accountId,
    templateId,
    name,
    subject,
    recipients: recipients.substring(0, 100),
    mode,
    schedule
  });
  
  if (!accountId) {
    showNotification(emailT('email.account_required', 'Please select an email account'), 'error');
    return;
  }
  
  if (!name) {
    showNotification(emailT('email.name_required', 'Campaign name is required'), 'error');
    return;
  }
  
  if (!subject) {
    showNotification(emailT('email.subject_required', 'Subject is required'), 'error');
    return;
  }
  
  if (!recipients.trim()) {
    showNotification(emailT('email.recipients_required', 'Recipients are required'), 'error');
    return;
  }
  
  try {
    console.log('Sending campaign request...');
    const response = await EmailAddonAPI.post('/campaigns', {
      account_id: accountId,
      template_id: templateId,
      name,
      subject,
      recipients,
      send_mode: mode,
      schedule_at: mode === 'schedule' ? schedule : null
    });
    
    console.log('Campaign response:', response);
    
    showNotification(emailT('email.campaign_created', 'Campaign created successfully'), 'success');
    document.getElementById('emailCampaignName').value = '';
    document.getElementById('emailCampaignSubject').value = '';
    document.getElementById('emailCampaignRecipients').value = '';
    document.getElementById('emailCampaignSchedule').value = '';
    loadCampaigns();
  } catch (error) {
    console.error('Error creating campaign:', error);
    showNotification(error.message || 'Failed to create campaign', 'error');
  }
}

async function openMarketingCampaignModal() {
  EmailAddonState.campaignStep = 1;
  EmailAddonState.campaignData = {
    details: {},
    recipients: [],
    recipientsText: '',
    template: null,
    schedule: null,
    account: null
  };
  
  // Ensure modal exists in DOM
  let modal = document.getElementById('emailMarketingCampaignModal');
  if (!modal) {
    createMarketingCampaignModal();
    modal = document.getElementById('emailMarketingCampaignModal');
  }
  
  if (modal) {
    modal.style.display = 'block';
    updateMarketingCampaignStepUI();
    loadMarketingCampaignAccounts();
    // Don't load templates here - they will be loaded when user reaches step 4
  }
}

function createMarketingCampaignModal() {
  const modalHTML = `
    <div id="emailMarketingCampaignModal" class="modal email-campaign-modal" style="display:none;">
      <div class="modal-content email-campaign-modal-content">
        <div class="email-campaign-modal-header">
          <h3 data-i18n="email.create_campaign">Create Campaign</h3>
          <button class="btn btn-danger btn-sm marketing-modal-close">×</button>
        </div>
        
        <div class="email-campaign-steps">
          <div class="email-campaign-step active" data-step="1">
            <div class="step-number">1</div>
            <div class="step-label" data-i18n="email.step_account">Account</div>
          </div>
          <div class="email-campaign-step-line"></div>
          <div class="email-campaign-step" data-step="2">
            <div class="step-number">2</div>
            <div class="step-label" data-i18n="email.step_details">Details</div>
          </div>
          <div class="email-campaign-step-line"></div>
          <div class="email-campaign-step" data-step="3">
            <div class="step-number">3</div>
            <div class="step-label" data-i18n="email.step_recipients">Recipients</div>
          </div>
          <div class="email-campaign-step-line"></div>
          <div class="email-campaign-step" data-step="4">
            <div class="step-number">4</div>
            <div class="step-label" data-i18n="email.step_template">Template</div>
          </div>
          <div class="email-campaign-step-line"></div>
          <div class="email-campaign-step" data-step="5">
            <div class="step-number">5</div>
            <div class="step-label" data-i18n="email.step_schedule">Schedule</div>
          </div>
          <div class="email-campaign-step-line"></div>
          <div class="email-campaign-step" data-step="6">
            <div class="step-number">6</div>
            <div class="step-label" data-i18n="email.step_review">Review</div>
          </div>
        </div>
        
        <div class="email-campaign-modal-body">
          <!-- Step 1: Account Selection -->
          <div class="email-campaign-step-content active" data-step-content="1">
            <h4 data-i18n="email.select_account">Select Email Account</h4>
            <div class="form-group">
              <label data-i18n="email.account">Account</label>
              <select id="marketingCampaignAccount" class="form-control" required></select>
            </div>
          </div>
          
          <!-- Step 2: Details -->
          <div class="email-campaign-step-content" data-step-content="2">
            <h4 data-i18n="email.campaign_details">Campaign Details</h4>
            <div class="form-group">
              <label data-i18n="email.campaign_name">Campaign Name</label>
              <input type="text" id="marketingCampaignName" class="form-control" required>
            </div>
            <div class="form-group">
              <label data-i18n="email.campaign_subject">Subject Line</label>
              <input type="text" id="marketingCampaignSubject" class="form-control" required>
            </div>
            <div class="form-group">
              <label data-i18n="email.from_name">From Name</label>
              <input type="text" id="marketingCampaignFromName" class="form-control">
            </div>
          </div>
          
          <!-- Step 3: Recipients -->
          <div class="email-campaign-step-content" data-step-content="3">
            <h4 data-i18n="email.add_recipients">Add Recipients</h4>
            
            <div class="email-recipients-tabs">
              <button class="email-recipients-tab active" data-tab="manual" data-i18n="email.manual_entry">Manual Entry</button>
              <button class="email-recipients-tab" data-tab="contacts" data-i18n="email.select_contacts">Select Contacts</button>
              <button class="email-recipients-tab" data-tab="groups" data-i18n="email.select_groups">Select Groups</button>
            </div>
            
            <!-- Manual Entry Tab -->
            <div class="email-recipients-tab-content active" data-tab-content="manual">
              <p class="email-small" data-i18n="email.recipients_hint">Enter email addresses (one per line or comma-separated)</p>
              <div class="form-group">
                <textarea id="marketingCampaignRecipients" class="form-control" rows="10" placeholder="email1@example.com&#10;email2@example.com&#10;email3@example.com" data-i18n-placeholder="email.recipients_placeholder"></textarea>
              </div>
            </div>
            
            <!-- Select Contacts Tab -->
            <div class="email-recipients-tab-content" data-tab-content="contacts">
              <div class="email-contacts-search-box">
                <input type="text" id="marketingContactsSearch" class="form-control" placeholder="Search contacts..." data-i18n-placeholder="email.search_contacts">
              </div>
              <div class="email-contacts-selection-list" id="marketingContactsList">
                <p class="email-small" data-i18n="common.loading">Loading...</p>
              </div>
            </div>
            
            <!-- Select Groups Tab -->
            <div class="email-recipients-tab-content" data-tab-content="groups">
              <div class="email-groups-selection-list" id="marketingGroupsList">
                <p class="email-small" data-i18n="common.loading">Loading...</p>
              </div>
            </div>
            
            <div class="email-recipient-summary">
              <strong data-i18n="email.total_recipients">Total Recipients:</strong>
              <span id="marketingRecipientCount">0</span>
            </div>
          </div>
          
          <!-- Step 4: Template -->
          <div class="email-campaign-step-content" data-step-content="4">
            <h4 data-i18n="email.select_template">Select Template</h4>
            <div class="email-template-selector" id="marketingTemplateSelector"></div>
          </div>
          
          <!-- Step 5: Schedule -->
          <div class="email-campaign-step-content" data-step-content="5">
            <h4 data-i18n="email.schedule_campaign">Schedule Campaign</h4>
            <div class="form-group">
              <label>
                <input type="radio" name="marketingScheduleType" value="now" checked>
                <span data-i18n="email.send_now">Send Now</span>
              </label>
            </div>
            <div class="form-group">
              <label>
                <input type="radio" name="marketingScheduleType" value="schedule">
                <span data-i18n="email.schedule_later">Schedule for Later</span>
              </label>
            </div>
            <div class="form-group" id="marketingScheduleDateGroup" style="display:none;">
              <label data-i18n="email.schedule_date">Schedule Date & Time</label>
              <input type="datetime-local" id="marketingScheduleDate" class="form-control">
            </div>
          </div>
          
          <!-- Step 6: Review -->
          <div class="email-campaign-step-content" data-step-content="6">
            <h4 data-i18n="email.review_campaign">Review Campaign</h4>
            <div class="email-campaign-review">
              <div class="review-item">
                <strong data-i18n="email.account">Account:</strong>
                <span id="marketingReviewAccount"></span>
              </div>
              <div class="review-item">
                <strong data-i18n="email.campaign_name">Campaign Name:</strong>
                <span id="marketingReviewCampaignName"></span>
              </div>
              <div class="review-item">
                <strong data-i18n="email.subject">Subject:</strong>
                <span id="marketingReviewSubject"></span>
              </div>
              <div class="review-item">
                <strong data-i18n="email.recipients">Recipients:</strong>
                <span id="marketingReviewRecipients"></span>
              </div>
              <div class="review-item">
                <strong data-i18n="email.template">Template:</strong>
                <span id="marketingReviewTemplate"></span>
              </div>
              <div class="review-item">
                <strong data-i18n="email.schedule">Schedule:</strong>
                <span id="marketingReviewSchedule"></span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="email-campaign-modal-footer">
          <button class="btn btn-secondary" id="marketingCampaignPrevBtn" style="display:none;" data-i18n="common.previous">Previous</button>
          <button class="btn btn-primary" id="marketingCampaignNextBtn" data-i18n="common.next">Next</button>
          <button class="btn btn-success" id="marketingCampaignSubmitBtn" style="display:none;" data-i18n="email.send_campaign">Send Campaign</button>
        </div>
      </div>
    </div>
  `;
  
  document.body.insertAdjacentHTML('beforeend', modalHTML);
  
  // Event listeners
  document.getElementById('marketingCampaignNextBtn')?.addEventListener('click', nextMarketingCampaignStep);
  document.getElementById('marketingCampaignPrevBtn')?.addEventListener('click', prevMarketingCampaignStep);
  document.getElementById('marketingCampaignSubmitBtn')?.addEventListener('click', submitMarketingCampaign);
  
  // Schedule type change
  document.querySelectorAll('input[name="marketingScheduleType"]').forEach(radio => {
    radio.addEventListener('change', (e) => {
      const dateGroup = document.getElementById('marketingScheduleDateGroup');
      if (e.target.value === 'schedule') {
        dateGroup.style.display = 'block';
      } else {
        dateGroup.style.display = 'none';
      }
    });
  });
  
  // Recipients count
  document.getElementById('marketingCampaignRecipients')?.addEventListener('input', updateMarketingRecipientCount);
  
  // Recipients tabs
  document.querySelectorAll('.email-recipients-tab').forEach(tab => {
    tab.addEventListener('click', () => {
      const tabName = tab.dataset.tab;
      
      // Update tab buttons
      document.querySelectorAll('.email-recipients-tab').forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      
      // Update tab content
      document.querySelectorAll('.email-recipients-tab-content').forEach(content => {
        content.classList.remove('active');
      });
      document.querySelector(`[data-tab-content="${tabName}"]`)?.classList.add('active');
      
      // Load data for the selected tab
      if (tabName === 'contacts') {
        loadMarketingContacts();
      } else if (tabName === 'groups') {
        loadMarketingGroups();
      }
    });
  });
  
  // Contact search
  document.getElementById('marketingContactsSearch')?.addEventListener('input', (e) => {
    filterMarketingContacts(e.target.value);
  });
  
  // Modal close handlers
  document.querySelectorAll('.marketing-modal-close').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('emailMarketingCampaignModal').style.display = 'none';
    });
  });
  
  window.addEventListener('click', (event) => {
    const modal = document.getElementById('emailMarketingCampaignModal');
    if (event.target === modal) {
      modal.style.display = 'none';
    }
  });
}

function updateMarketingCampaignStepUI() {
  const step = EmailAddonState.campaignStep;
  
  // Update step indicators
  document.querySelectorAll('#emailMarketingCampaignModal .email-campaign-step').forEach((el, index) => {
    const stepNum = index + 1;
    if (stepNum < step) {
      el.classList.add('completed');
      el.classList.remove('active');
    } else if (stepNum === step) {
      el.classList.add('active');
      el.classList.remove('completed');
    } else {
      el.classList.remove('active', 'completed');
    }
  });
  
  // Update content visibility
  document.querySelectorAll('#emailMarketingCampaignModal .email-campaign-step-content').forEach(el => {
    el.classList.remove('active');
  });
  document.querySelector(`#emailMarketingCampaignModal [data-step-content="${step}"]`)?.classList.add('active');
  
  // Update buttons
  const prevBtn = document.getElementById('marketingCampaignPrevBtn');
  const nextBtn = document.getElementById('marketingCampaignNextBtn');
  const submitBtn = document.getElementById('marketingCampaignSubmitBtn');
  
  if (prevBtn) prevBtn.style.display = step > 1 ? 'inline-block' : 'none';
  if (nextBtn) nextBtn.style.display = step < 6 ? 'inline-block' : 'none';
  if (submitBtn) submitBtn.style.display = step === 6 ? 'inline-block' : 'none';
  
  // Apply translations
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function nextMarketingCampaignStep() {
  if (!validateMarketingCampaignStep(EmailAddonState.campaignStep)) {
    return;
  }
  
  saveMarketingCampaignStepData(EmailAddonState.campaignStep);
  
  if (EmailAddonState.campaignStep < 6) {
    EmailAddonState.campaignStep++;
    updateMarketingCampaignStepUI();
    
    // Load data for specific steps
    if (EmailAddonState.campaignStep === 3) {
      // Load contacts and groups when reaching recipients step
      // They will be loaded on-demand when user clicks the tabs
    } else if (EmailAddonState.campaignStep === 4) {
      // Load templates when reaching template step
      await loadMarketingCampaignTemplates();
    } else if (EmailAddonState.campaignStep === 6) {
      // Populate review when reaching review step
      populateMarketingReviewStep();
    }
  }
}

function prevMarketingCampaignStep() {
  if (EmailAddonState.campaignStep > 1) {
    EmailAddonState.campaignStep--;
    updateMarketingCampaignStepUI();
  }
}

function validateMarketingCampaignStep(step) {
  switch (step) {
    case 1:
      const account = document.getElementById('marketingCampaignAccount')?.value;
      if (!account) {
        showNotification(emailT('email.account_required', 'Please select an email account'), 'error');
        return false;
      }
      return true;
    case 2:
      const name = document.getElementById('marketingCampaignName')?.value?.trim();
      const subject = document.getElementById('marketingCampaignSubject')?.value?.trim();
      if (!name || !subject) {
        showNotification(emailT('email.fill_required_fields', 'Please fill in all required fields'), 'error');
        return false;
      }
      return true;
    case 3:
      // Check all three sources for recipients
      let hasRecipients = false;
      
      // Check manual textarea
      const manualText = document.getElementById('marketingCampaignRecipients')?.value?.trim();
      if (manualText) {
        hasRecipients = true;
      }
      
      // Check selected contacts
      const selectedContacts = document.querySelectorAll('#marketingContactsList input[type="checkbox"]:checked');
      if (selectedContacts.length > 0) {
        hasRecipients = true;
      }
      
      // Check selected groups
      const selectedGroups = document.querySelectorAll('#marketingGroupsList input[type="checkbox"]:checked');
      if (selectedGroups.length > 0) {
        hasRecipients = true;
      }
      
      if (!hasRecipients) {
        showNotification(emailT('email.recipients_required', 'Please add at least one recipient'), 'error');
        return false;
      }
      return true;
    case 4:
      if (!EmailAddonState.campaignData.template) {
        showNotification(emailT('email.template_required', 'Please select a template'), 'error');
        return false;
      }
      return true;
    case 5:
      const scheduleType = document.querySelector('input[name="marketingScheduleType"]:checked')?.value;
      if (scheduleType === 'schedule') {
        const scheduleDate = document.getElementById('marketingScheduleDate')?.value;
        if (!scheduleDate) {
          showNotification(emailT('email.schedule_date_required', 'Please select a schedule date'), 'error');
          return false;
        }
      }
      return true;
    default:
      return true;
  }
}

function saveMarketingCampaignStepData(step) {
  switch (step) {
    case 1:
      const accountId = document.getElementById('marketingCampaignAccount')?.value;
      const accountSelect = document.getElementById('marketingCampaignAccount');
      const accountText = accountSelect?.options[accountSelect.selectedIndex]?.text || '';
      EmailAddonState.campaignData.account = { id: accountId, text: accountText };
      break;
    case 2:
      EmailAddonState.campaignData.details = {
        name: document.getElementById('marketingCampaignName')?.value?.trim() || '',
        subject: document.getElementById('marketingCampaignSubject')?.value?.trim() || '',
        fromName: document.getElementById('marketingCampaignFromName')?.value?.trim() || ''
      };
      break;
    case 3:
      // Collect all recipients from different sources
      const manualEmails = [];
      const selectedContactEmails = [];
      const selectedGroupIds = [];
      
      // Manual textarea
      const textarea = document.getElementById('marketingCampaignRecipients');
      if (textarea) {
        const text = textarea.value.trim();
        if (text) {
          const emails = text.split(/[\n,;]/).map(e => e.trim()).filter(e => e.length > 0);
          manualEmails.push(...emails);
        }
      }
      
      // Selected contacts
      const selectedContacts = document.querySelectorAll('#marketingContactsList input[type="checkbox"]:checked');
      selectedContacts.forEach(checkbox => {
        selectedContactEmails.push(checkbox.value);
      });
      
      // Selected groups
      const selectedGroups = document.querySelectorAll('#marketingGroupsList input[type="checkbox"]:checked');
      selectedGroups.forEach(checkbox => {
        selectedGroupIds.push(checkbox.value);
      });
      
      EmailAddonState.campaignData.recipients = {
        manual: manualEmails,
        contacts: selectedContactEmails,
        groups: selectedGroupIds
      };
      break;
    case 5:
      const scheduleType = document.querySelector('input[name="marketingScheduleType"]:checked')?.value;
      EmailAddonState.campaignData.schedule = {
        type: scheduleType,
        date: scheduleType === 'schedule' ? document.getElementById('marketingScheduleDate')?.value : null
      };
      break;
  }
}

function loadMarketingCampaignAccounts() {
  const select = document.getElementById('marketingCampaignAccount');
  if (!select) return;
  
  select.innerHTML = EmailAddonState.accounts
    .map(account => `<option value="${account.id}">${escapeHtml(account.email_address)}</option>`)
    .join('');
    
  if (EmailAddonState.selectedAccountId) {
    select.value = EmailAddonState.selectedAccountId;
  }
}

async function loadMarketingCampaignTemplates() {
  const container = document.getElementById('marketingTemplateSelector');
  if (!container) return;
  
  // Load templates if not already loaded
  if (!EmailAddonState.templates || EmailAddonState.templates.length === 0) {
    try {
      container.innerHTML = '<p class="email-small" data-i18n="common.loading">Loading templates...</p>';
      const response = await EmailAddonAPI.get('/templates');
      EmailAddonState.templates = response.data || [];
    } catch (error) {
      console.error('Error loading templates:', error);
      container.innerHTML = `<p class="email-small" style="color: #e53e3e;">Error loading templates: ${error.message}</p>`;
      return;
    }
  }
  
  const templates = EmailAddonState.templates;
  if (templates.length === 0) {
    container.innerHTML = '<p data-i18n="email.no_templates">No templates available</p>';
    return;
  }
  
  container.innerHTML = templates.map(template => `
    <div class="email-template-card ${EmailAddonState.campaignData.template?.id == template.id ? 'selected' : ''}" data-template-id="${template.id}">
      <div class="template-card-preview">
        <iframe srcdoc="${escapeHtmlAttribute(template.html_content || '')}" style="width:100%;height:140px;border:none;pointer-events:none;border-radius:8px;"></iframe>
      </div>
      <div class="template-card-info">
        <h5>${escapeHtml(template.name)}</h5>
        <button class="btn btn-sm btn-primary select-marketing-template-btn" data-template-id="${template.id}" data-i18n="common.select">Select</button>
      </div>
    </div>
  `).join('');
  
  // Add click event to cards
  container.querySelectorAll('.email-template-card').forEach(card => {
    card.addEventListener('click', (e) => {
      // Don't trigger if clicking the button directly
      if (e.target.classList.contains('select-marketing-template-btn')) {
        return;
      }
      const templateId = card.dataset.templateId;
      selectMarketingTemplate(templateId);
    });
  });
  
  // Add click event to buttons
  container.querySelectorAll('.select-marketing-template-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation(); // Prevent card click
      const templateId = btn.dataset.templateId;
      selectMarketingTemplate(templateId);
    });
  });
  
  // Apply translations
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function selectMarketingTemplate(templateId) {
  const template = EmailAddonState.templates.find(t => t.id == templateId);
  if (!template) return;
  
  EmailAddonState.campaignData.template = template;
  
  // Update UI
  document.querySelectorAll('#marketingTemplateSelector .email-template-card').forEach(card => {
    card.classList.remove('selected');
  });
  document.querySelector(`#marketingTemplateSelector [data-template-id="${templateId}"]`)?.classList.add('selected');
}

function updateMarketingRecipientCount() {
  const countSpan = document.getElementById('marketingRecipientCount');
  if (!countSpan) return;
  
  let totalCount = 0;
  
  // Count from manual textarea
  const textarea = document.getElementById('marketingCampaignRecipients');
  if (textarea) {
    const text = textarea.value.trim();
    if (text) {
      const emails = text.split(/[\n,;]/).map(e => e.trim()).filter(e => e.length > 0);
      totalCount += emails.length;
    }
  }
  
  // Count from selected contacts
  const selectedContacts = document.querySelectorAll('#marketingContactsList input[type="checkbox"]:checked');
  totalCount += selectedContacts.length;
  
  // Count from selected groups
  const selectedGroups = document.querySelectorAll('#marketingGroupsList input[type="checkbox"]:checked');
  selectedGroups.forEach(checkbox => {
    totalCount += parseInt(checkbox.dataset.count || 0);
  });
  
  countSpan.textContent = totalCount;
}

async function loadMarketingContacts() {
  const container = document.getElementById('marketingContactsList');
  if (!container) return;
  
  try {
    container.innerHTML = '<p class="email-small" data-i18n="common.loading">Loading...</p>';
    
    const response = await EmailAddonAPI.get('/contacts');
    const contacts = response.data || [];
    
    if (contacts.length === 0) {
      container.innerHTML = '<p class="email-small" data-i18n="email.no_contacts">No contacts found</p>';
      return;
    }
    
    // Store contacts for filtering
    EmailAddonState.marketingContacts = contacts;
    
    renderMarketingContacts(contacts);
  } catch (error) {
    console.error('Error loading contacts:', error);
    container.innerHTML = `<p class="email-small" style="color: #e53e3e;">${error.message}</p>`;
  }
}

function renderMarketingContacts(contacts) {
  const container = document.getElementById('marketingContactsList');
  if (!container) return;
  
  container.innerHTML = `
    <div class="email-contacts-checkboxes">
      ${contacts.map(contact => `
        <label class="email-contact-checkbox-item">
          <input type="checkbox" value="${escapeHtmlAttribute(contact.email)}" data-contact-id="${contact.id}">
          <div class="contact-info">
            <span class="contact-name">${escapeHtml(contact.name)}</span>
            <span class="contact-email">${escapeHtml(contact.email)}</span>
          </div>
        </label>
      `).join('')}
    </div>
  `;
  
  // Add change listeners
  container.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
    checkbox.addEventListener('change', updateMarketingRecipientCount);
  });
  
  // Apply translations
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function filterMarketingContacts(searchTerm) {
  if (!EmailAddonState.marketingContacts) return;
  
  const term = searchTerm.toLowerCase().trim();
  
  if (!term) {
    renderMarketingContacts(EmailAddonState.marketingContacts);
    return;
  }
  
  const filtered = EmailAddonState.marketingContacts.filter(contact => {
    return contact.name.toLowerCase().includes(term) || 
           contact.email.toLowerCase().includes(term);
  });
  
  renderMarketingContacts(filtered);
}

async function loadMarketingGroups() {
  const container = document.getElementById('marketingGroupsList');
  if (!container) return;
  
  try {
    container.innerHTML = '<p class="email-small" data-i18n="common.loading">Loading...</p>';
    
    const response = await EmailAddonAPI.get('/contact-groups');
    const groups = response.data || [];
    
    if (groups.length === 0) {
      container.innerHTML = '<p class="email-small" data-i18n="email.no_groups">No groups found</p>';
      return;
    }
    
    container.innerHTML = `
      <div class="email-groups-checkboxes">
        ${groups.map(group => `
          <label class="email-group-checkbox-item">
            <input type="checkbox" value="${group.id}" data-count="${group.contact_count || 0}">
            <div class="group-info">
              <span class="group-name">
                <i class="fas fa-folder"></i>
                ${escapeHtml(group.name)}
              </span>
              <span class="group-count">${group.contact_count || 0} contacts</span>
            </div>
          </label>
        `).join('')}
      </div>
    `;
    
    // Add change listeners
    container.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
      checkbox.addEventListener('change', updateMarketingRecipientCount);
    });
    
    // Apply translations
    if (window.applyLanguage) {
      window.applyLanguage(localStorage.getItem('language') || 'en');
    }
  } catch (error) {
    console.error('Error loading groups:', error);
    container.innerHTML = `<p class="email-small" style="color: #e53e3e;">${error.message}</p>`;
  }
}

function populateMarketingReviewStep() {
  const data = EmailAddonState.campaignData;
  
  document.getElementById('marketingReviewAccount').textContent = data.account?.text || '-';
  document.getElementById('marketingReviewCampaignName').textContent = data.details?.name || '-';
  document.getElementById('marketingReviewSubject').textContent = data.details?.subject || '-';
  
  // Calculate total recipients
  let totalCount = 0;
  let recipientDetails = [];
  
  if (data.recipients) {
    if (data.recipients.manual && data.recipients.manual.length > 0) {
      totalCount += data.recipients.manual.length;
      recipientDetails.push(`${data.recipients.manual.length} manual`);
    }
    if (data.recipients.contacts && data.recipients.contacts.length > 0) {
      totalCount += data.recipients.contacts.length;
      recipientDetails.push(`${data.recipients.contacts.length} contacts`);
    }
    if (data.recipients.groups && data.recipients.groups.length > 0) {
      // Count contacts in groups
      const selectedGroups = document.querySelectorAll('#marketingGroupsList input[type="checkbox"]:checked');
      let groupContactCount = 0;
      selectedGroups.forEach(checkbox => {
        groupContactCount += parseInt(checkbox.dataset.count || 0);
      });
      totalCount += groupContactCount;
      recipientDetails.push(`${data.recipients.groups.length} groups (${groupContactCount} contacts)`);
    }
  }
  
  const recipientText = totalCount > 0 
    ? `${totalCount} recipients (${recipientDetails.join(', ')})`
    : '0 recipients';
  document.getElementById('marketingReviewRecipients').textContent = recipientText;
  
  document.getElementById('marketingReviewTemplate').textContent = data.template?.name || '-';
  
  const scheduleText = data.schedule?.type === 'now' 
    ? emailT('email.send_immediately', 'Send immediately')
    : emailT('email.scheduled_for', 'Scheduled for') + ' ' + new Date(data.schedule?.date).toLocaleString();
  document.getElementById('marketingReviewSchedule').textContent = scheduleText;
}

async function submitMarketingCampaign() {
  try {
    const data = EmailAddonState.campaignData;
    
    // Combine all recipients into a single list
    let allRecipients = [];
    
    if (data.recipients) {
      // Add manual emails
      if (data.recipients.manual && data.recipients.manual.length > 0) {
        allRecipients.push(...data.recipients.manual);
      }
      
      // Add selected contact emails
      if (data.recipients.contacts && data.recipients.contacts.length > 0) {
        allRecipients.push(...data.recipients.contacts);
      }
      
      // Fetch emails from selected groups
      if (data.recipients.groups && data.recipients.groups.length > 0) {
        try {
          for (const groupId of data.recipients.groups) {
            const response = await EmailAddonAPI.get('/contacts', { group_id: groupId });
            const groupContacts = response.data || [];
            groupContacts.forEach(contact => {
              if (contact.email && !allRecipients.includes(contact.email)) {
                allRecipients.push(contact.email);
              }
            });
          }
        } catch (error) {
          console.error('Error fetching group contacts:', error);
          showNotification('Error loading contacts from groups', 'error');
          return;
        }
      }
    }
    
    // Check if we have any recipients
    if (allRecipients.length === 0) {
      showNotification(emailT('email.recipients_required', 'Please add at least one recipient'), 'error');
      return;
    }
    
    // Convert to newline-separated string for backend
    const recipientsText = allRecipients.join('\n');
    
    const payload = {
      account_id: data.account?.id,
      name: data.details?.name,
      subject: data.details?.subject,
      from_name: data.details?.fromName,
      template_id: data.template?.id,
      recipients: recipientsText,
      send_mode: data.schedule?.type === 'now' ? 'now' : 'schedule',
      schedule_at: data.schedule?.type === 'schedule' ? data.schedule?.date : null
    };
    
    console.log('Submitting marketing campaign:', payload);
    
    await EmailAddonAPI.post('/campaigns', payload);
    showNotification(emailT('email.campaign_created', 'Campaign created successfully'), 'success');
    
    document.getElementById('emailMarketingCampaignModal').style.display = 'none';
    
    // Reload campaigns
    loadCampaigns();
  } catch (error) {
    console.error('Error creating campaign:', error);
    showNotification(error.message || 'Error creating campaign', 'error');
  }
}

async function loadCampaigns() {
  const container = document.getElementById('emailCampaignHistory');
  if (!container) return;
  try {
    const response = await EmailAddonAPI.get('/campaigns');
    const campaigns = response.data || [];
    if (!campaigns.length) {
      container.innerHTML = `<p data-i18n="email.no_campaigns">No campaigns yet.</p>`;
      return;
    }
    
    // Check if there are any campaigns in "sending" status
    const hasSendingCampaigns = campaigns.some(c => c.status === 'sending');
    
    container.innerHTML = `
      <table class="email-addon-table email-campaigns-table">
        <thead>
          <tr>
            <th data-i18n="email.campaign_name">Campaign Name</th>
            <th data-i18n="email.subject">Subject</th>
            <th data-i18n="email.status">Status</th>
            <th data-i18n="email.progress">Progress</th>
            <th data-i18n="email.schedule">Schedule</th>
          </tr>
        </thead>
        <tbody>
          ${campaigns.map(campaign => {
            const total = campaign.total_recipients || 0;
            const sent = campaign.sent_count || 0;
            const failed = campaign.failed_count || 0;
            const progress = total > 0 ? Math.round((sent + failed) / total * 100) : 0;
            
            return `
              <tr class="email-campaign-row" data-campaign-id="${campaign.id}" style="cursor: pointer;">
                <td>${escapeHtml(campaign.name)}</td>
                <td>${escapeHtml(campaign.subject || '-')}</td>
                <td>
                  <span class="status-badge status-${campaign.status}">
                    ${campaign.status}
                  </span>
                </td>
                <td>
                  ${sent}/${total} sent
                  ${failed > 0 ? `, ${failed} failed` : ''}
                  ${campaign.status === 'sending' ? ` (${progress}%)` : ''}
                </td>
                <td>${campaign.schedule_at ? new Date(campaign.schedule_at).toLocaleString() : '-'}</td>
              </tr>
            `;
          }).join('')}
        </tbody>
      </table>
    `;
    
    // Add click handlers to campaign rows
    container.querySelectorAll('.email-campaign-row').forEach(row => {
      row.addEventListener('click', () => {
        const campaignId = row.dataset.campaignId;
        openCampaignDetailsModal(campaignId);
      });
    });
    
    // Auto-refresh if there are campaigns in "sending" status
    if (hasSendingCampaigns) {
      console.log('Campaigns still sending, will refresh in 3 seconds...');
      setTimeout(() => {
        if (EmailAddonState.activeTab === 'marketing') {
          loadCampaigns();
        }
      }, 3000);
    }
  } catch (error) {
    container.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadAccessOptions() {
  try {
    const [stores, departments, users] = await Promise.all([
      api.getStores(),
      api.getDepartments(),
      api.getUsers()
    ]);
    const storeSelect = document.getElementById('emailAccessStores');
    const departmentSelect = document.getElementById('emailAccessDepartments');
    const userSelect = document.getElementById('emailAccessUsers');
    if (storeSelect) {
      storeSelect.innerHTML = (stores.data || stores.stores || []).map(store => `<option value="${store.id}">${store.name}</option>`).join('');
    }
    if (departmentSelect) {
      departmentSelect.innerHTML = (departments.data || departments.departments || []).map(dept => `<option value="${dept.id}">${dept.name}</option>`).join('');
    }
    if (userSelect) {
      userSelect.innerHTML = (users.data || users.users || []).map(user => `<option value="${user.id}">${user.name || user.full_name || user.email}</option>`).join('');
    }
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

function renderAccountsList() {
  const container = document.getElementById('emailAccountsList');
  if (!container) return;
  if (!EmailAddonState.accounts.length) {
    container.innerHTML = `<p data-i18n="email.no_accounts">No accounts connected.</p>`;
    return;
  }
  container.innerHTML = EmailAddonState.accounts.map(account => `
    <div class="email-account-card">
      <div>
        <strong>${account.name || account.email_address}</strong>
        <div class="email-small">${account.email_address}</div>
      </div>
      <div style="display: flex; gap: 6px;">
        <button class="btn btn-secondary btn-sm email-account-edit" data-id="${account.id}"><i class="fas fa-edit"></i></button>
        <button class="btn btn-danger btn-sm email-account-delete" data-id="${account.id}"><i class="fas fa-trash"></i></button>
      </div>
    </div>
  `).join('');
  container.querySelectorAll('.email-account-edit').forEach(btn => {
    btn.addEventListener('click', () => editAccount(btn.dataset.id));
  });
  container.querySelectorAll('.email-account-delete').forEach(btn => {
    btn.addEventListener('click', () => deleteAccount(btn.dataset.id));
  });
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function getSelectedOptions(selectId) {
  const select = document.getElementById(selectId);
  if (!select) return [];
  return Array.from(select.selectedOptions).map(option => option.value);
}

async function saveAccount() {
  const accountId = document.getElementById('emailAccountId')?.value;
  const payload = {
    name: document.getElementById('emailAccountName')?.value || '',
    email_address: document.getElementById('emailAccountAddress')?.value,
    imap_host: document.getElementById('emailImapHost')?.value,
    imap_port: document.getElementById('emailImapPort')?.value,
    imap_user: document.getElementById('emailImapUser')?.value,
    imap_password: document.getElementById('emailImapPassword')?.value,
    imap_secure: document.getElementById('emailImapSecure')?.value === '1',
    imap_allow_self_signed: document.getElementById('emailImapAllowSelfSigned')?.checked || false,
    imap_sent_folder: document.getElementById('emailImapSentFolder')?.value,
    smtp_host: document.getElementById('emailSmtpHost')?.value,
    smtp_port: document.getElementById('emailSmtpPort')?.value,
    smtp_user: document.getElementById('emailSmtpUser')?.value,
    smtp_password: document.getElementById('emailSmtpPassword')?.value,
    smtp_secure: document.getElementById('emailSmtpSecure')?.value === '1',
    access: {
      store_ids: getSelectedOptions('emailAccessStores'),
      department_ids: getSelectedOptions('emailAccessDepartments'),
      user_ids: getSelectedOptions('emailAccessUsers')
    }
  };
  try {
    if (accountId) {
      await EmailAddonAPI.put(`/accounts/${accountId}`, payload);
    } else {
      await EmailAddonAPI.post('/accounts', payload);
    }
    await loadAccounts();
    renderAccountsList();
    resetAccountForm();
    showNotification(emailT('email.account_saved', 'Account saved'), 'success');
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

async function editAccount(accountId) {
  const account = EmailAddonState.accounts.find(item => String(item.id) === String(accountId));
  if (!account) return;
  document.getElementById('emailAccountId').value = account.id;
  document.getElementById('emailAccountName').value = account.name || '';
  document.getElementById('emailAccountAddress').value = account.email_address || '';
  document.getElementById('emailImapHost').value = account.imap_host || '';
  document.getElementById('emailImapPort').value = account.imap_port || '';
  document.getElementById('emailImapUser').value = account.imap_user || '';
  document.getElementById('emailImapSecure').value = account.imap_secure ? '1' : '0';
  document.getElementById('emailImapAllowSelfSigned').checked = account.imap_allow_self_signed ? true : false;
  document.getElementById('emailImapSentFolder').value = account.imap_sent_folder || 'Sent';
  document.getElementById('emailSmtpHost').value = account.smtp_host || '';
  document.getElementById('emailSmtpPort').value = account.smtp_port || '';
  document.getElementById('emailSmtpUser').value = account.smtp_user || '';
  document.getElementById('emailSmtpSecure').value = account.smtp_secure ? '1' : '0';
  document.getElementById('emailImapPassword').value = '';
  document.getElementById('emailSmtpPassword').value = '';
  try {
    const response = await EmailAddonAPI.get(`/accounts/${accountId}/access`);
    setSelectValues('emailAccessStores', response.data.store_ids || []);
    setSelectValues('emailAccessDepartments', response.data.department_ids || []);
    setSelectValues('emailAccessUsers', response.data.user_ids || []);
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

async function deleteAccount(accountId) {
  try {
    await EmailAddonAPI.delete(`/accounts/${accountId}`);
    await loadAccounts();
    renderAccountsList();
    showNotification(emailT('email.account_deleted', 'Account deleted'), 'success');
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

function resetAccountForm() {
  document.getElementById('emailAccountId').value = '';
  document.getElementById('emailAccountName').value = '';
  document.getElementById('emailAccountAddress').value = '';
  document.getElementById('emailImapHost').value = '';
  document.getElementById('emailImapPort').value = '993';
  document.getElementById('emailImapUser').value = '';
  document.getElementById('emailImapPassword').value = '';
  document.getElementById('emailImapSecure').value = '1';
  document.getElementById('emailImapAllowSelfSigned').checked = false;
  document.getElementById('emailImapSentFolder').value = 'Sent';
  document.getElementById('emailSmtpHost').value = '';
  document.getElementById('emailSmtpPort').value = '465';
  document.getElementById('emailSmtpUser').value = '';
  document.getElementById('emailSmtpPassword').value = '';
  document.getElementById('emailSmtpSecure').value = '1';
  setSelectValues('emailAccessStores', []);
  setSelectValues('emailAccessDepartments', []);
  setSelectValues('emailAccessUsers', []);
}

function setSelectValues(selectId, values) {
  const select = document.getElementById(selectId);
  if (!select) return;
  const valueSet = new Set(values.map(String));
  Array.from(select.options).forEach(option => {
    option.selected = valueSet.has(String(option.value));
  });
}


/**
 * Open campaign details modal
 */
async function openCampaignDetailsModal(campaignId) {
  try {
    const response = await EmailAddonAPI.get(`/campaigns/${campaignId}`);
    const { campaign, recipients } = response.data;
    
    const isScheduled = campaign.status === 'scheduled';
    const canEdit = isScheduled;
    const canDelete = ['scheduled', 'failed'].includes(campaign.status);
    
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.id = 'campaignDetailsModal';
    modal.style.display = 'block';
    
    modal.innerHTML = `
      <div class="modal-content" style="max-width: 900px;">
        <div class="modal-header">
          <h3 data-i18n="email.campaign_details">Campaign Details</h3>
          <span class="close" onclick="closeCampaignDetailsModal()">&times;</span>
        </div>
        <div class="modal-body">
          <div class="email-campaign-details">
            <div class="email-campaign-info">
              <div class="email-campaign-info-row">
                <label data-i18n="email.campaign_name">Campaign Name:</label>
                <span>${escapeHtml(campaign.name)}</span>
              </div>
              <div class="email-campaign-info-row">
                <label data-i18n="email.subject">Subject:</label>
                <span>${escapeHtml(campaign.subject || '-')}</span>
              </div>
              <div class="email-campaign-info-row">
                <label data-i18n="email.account">Account:</label>
                <span>${escapeHtml(campaign.account_email || '-')}</span>
              </div>
              <div class="email-campaign-info-row">
                <label data-i18n="email.template">Template:</label>
                <span>${escapeHtml(campaign.template_name || 'None')}</span>
              </div>
              <div class="email-campaign-info-row">
                <label data-i18n="email.status">Status:</label>
                <span class="status-badge status-${campaign.status}">${campaign.status}</span>
              </div>
              <div class="email-campaign-info-row">
                <label data-i18n="email.schedule_time">Schedule Time:</label>
                <span>${campaign.schedule_at ? new Date(campaign.schedule_at).toLocaleString() : 'Send Now'}</span>
              </div>
              <div class="email-campaign-info-row">
                <label data-i18n="email.created_at">Created At:</label>
                <span>${new Date(campaign.created_at).toLocaleString()}</span>
              </div>
              <div class="email-campaign-info-row">
                <label data-i18n="email.created_by">Created By:</label>
                <span>${escapeHtml(campaign.created_by_name || 'System')}</span>
              </div>
              ${campaign.error_message ? `
                <div class="email-campaign-info-row">
                  <label data-i18n="email.error_message">Error:</label>
                  <span style="color: #dc3545;">${escapeHtml(campaign.error_message)}</span>
                </div>
              ` : ''}
            </div>
            
            <div class="email-campaign-recipients">
              <h4 data-i18n="email.recipients_list">Recipients List (${recipients.length})</h4>
              <div class="email-recipients-table-container">
                <table class="email-addon-table">
                  <thead>
                    <tr>
                      <th data-i18n="email.email_address">Email Address</th>
                      <th data-i18n="email.status">Status</th>
                      <th data-i18n="email.sent_at">Sent At</th>
                    </tr>
                  </thead>
                  <tbody>
                    ${recipients.map(recipient => `
                      <tr>
                        <td>${escapeHtml(recipient.email_address)}</td>
                        <td>
                          <span class="status-badge status-${recipient.status}">
                            ${recipient.status}
                          </span>
                        </td>
                        <td>
                          ${recipient.sent_at ? new Date(recipient.sent_at).toLocaleString() : '-'}
                          ${recipient.error_message ? `<br><small style="color: #dc3545;">${escapeHtml(recipient.error_message)}</small>` : ''}
                        </td>
                      </tr>
                    `).join('')}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer" style="display: flex; justify-content: space-between; gap: 8px;">
          <div>
            ${canDelete ? `
              <button class="btn btn-danger" onclick="deleteCampaign(${campaign.id})" data-i18n="common.delete">Delete</button>
            ` : ''}
          </div>
          <div style="display: flex; gap: 8px;">
            ${canEdit ? `
              <button class="btn btn-primary" onclick="editCampaign(${campaign.id})" data-i18n="common.edit">Edit</button>
            ` : ''}
            <button class="btn btn-secondary" onclick="closeCampaignDetailsModal()" data-i18n="common.close">Close</button>
          </div>
        </div>
      </div>
    `;
    
    document.body.appendChild(modal);
    
    // Apply translations
    if (window.applyLanguage) {
      window.applyLanguage(localStorage.getItem('language') || 'en');
    }
    
    // Close on outside click
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        closeCampaignDetailsModal();
      }
    });
  } catch (error) {
    showNotification(error.message || 'Error loading campaign details', 'error');
  }
}

/**
 * Close campaign details modal
 */
function closeCampaignDetailsModal() {
  const modal = document.getElementById('campaignDetailsModal');
  if (modal) {
    modal.remove();
  }
}

/**
 * Edit campaign
 */
async function editCampaign(campaignId) {
  try {
    const response = await EmailAddonAPI.get(`/campaigns/${campaignId}`);
    const { campaign, recipients } = response.data;
    
    closeCampaignDetailsModal();
    
    // Open edit modal
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.id = 'editCampaignModal';
    modal.style.display = 'block';
    
    const recipientEmails = recipients.map(r => r.email_address).join('\n');
    const scheduleValue = campaign.schedule_at ? new Date(campaign.schedule_at).toISOString().slice(0, 16) : '';
    
    modal.innerHTML = `
      <div class="modal-content" style="max-width: 720px;">
        <div class="modal-header">
          <h3 data-i18n="email.edit_campaign">Edit Campaign</h3>
          <span class="close" onclick="closeEditCampaignModal()">&times;</span>
        </div>
        <div class="modal-body">
          <div class="email-marketing-form">
            <div>
              <label data-i18n="email.campaign_name">Campaign Name</label>
              <input type="text" id="editCampaignName" class="form-control" value="${escapeHtmlAttribute(campaign.name)}">
            </div>
            <div>
              <label data-i18n="email.subject">Subject</label>
              <input type="text" id="editCampaignSubject" class="form-control" value="${escapeHtmlAttribute(campaign.subject || '')}">
            </div>
            <div>
              <label data-i18n="email.recipients">Recipients</label>
              <textarea id="editCampaignRecipients" class="form-control" rows="8">${escapeHtml(recipientEmails)}</textarea>
            </div>
            <div>
              <label data-i18n="email.schedule_time">Schedule Time</label>
              <input type="datetime-local" id="editCampaignSchedule" class="form-control" value="${scheduleValue}">
            </div>
          </div>
        </div>
        <div class="modal-footer" style="display: flex; justify-content: flex-end; gap: 8px;">
          <button class="btn btn-secondary" onclick="closeEditCampaignModal()" data-i18n="common.cancel">Cancel</button>
          <button class="btn btn-primary" onclick="saveCampaignEdit(${campaign.id})" data-i18n="common.save">Save</button>
        </div>
      </div>
    `;
    
    document.body.appendChild(modal);
    
    // Apply translations
    if (window.applyLanguage) {
      window.applyLanguage(localStorage.getItem('language') || 'en');
    }
    
    // Close on outside click
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        closeEditCampaignModal();
      }
    });
  } catch (error) {
    showNotification(error.message || 'Error loading campaign', 'error');
  }
}

/**
 * Close edit campaign modal
 */
function closeEditCampaignModal() {
  const modal = document.getElementById('editCampaignModal');
  if (modal) {
    modal.remove();
  }
}

/**
 * Save campaign edit
 */
async function saveCampaignEdit(campaignId) {
  try {
    const name = document.getElementById('editCampaignName')?.value;
    const subject = document.getElementById('editCampaignSubject')?.value;
    const recipients = document.getElementById('editCampaignRecipients')?.value;
    const schedule_at = document.getElementById('editCampaignSchedule')?.value;
    
    if (!name) {
      showNotification(emailT('email.name_required', 'Campaign name is required'), 'error');
      return;
    }
    
    if (!subject) {
      showNotification(emailT('email.subject_required', 'Subject is required'), 'error');
      return;
    }
    
    if (!recipients.trim()) {
      showNotification(emailT('email.recipients_required', 'Recipients are required'), 'error');
      return;
    }
    
    await EmailAddonAPI.put(`/campaigns/${campaignId}`, {
      name,
      subject,
      recipients,
      schedule_at: schedule_at || null
    });
    
    showNotification(emailT('email.campaign_updated', 'Campaign updated successfully'), 'success');
    closeEditCampaignModal();
    loadCampaigns();
  } catch (error) {
    showNotification(error.message || 'Error updating campaign', 'error');
  }
}

/**
 * Delete campaign
 */
async function deleteCampaign(campaignId) {
  if (!confirm(emailT('email.confirm_delete_campaign', 'Are you sure you want to delete this campaign?'))) {
    return;
  }
  
  try {
    await EmailAddonAPI.delete(`/campaigns/${campaignId}`);
    showNotification(emailT('email.campaign_deleted', 'Campaign deleted successfully'), 'success');
    closeCampaignDetailsModal();
    loadCampaigns();
  } catch (error) {
    showNotification(error.message || 'Error deleting campaign', 'error');
  }
}
