const UserEmailAPI = {
  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 = {}) {
    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);
  }
};

const UserEmailState = {
  accounts: [],
  selectedAccountId: null,
  activeTab: 'inbox',
  inboxPage: 1,
  sentsPage: 1
};

document.addEventListener('DOMContentLoaded', () => {
  checkEmailAddonAvailability();
  setupUserEmailNavigation();
});

async function checkEmailAddonAvailability() {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/tenant/active-addons', {
      headers: token ? { Authorization: `Bearer ${token}` } : {}
    });
    const data = await response.json();
    const addons = data?.data?.addons || [];
    const isActive = addons.some(addon => addon.slug === 'email-marketing');
    if (!isActive) {
      document.querySelectorAll('.user-tab-btn[data-tab="email"]').forEach(btn => {
        btn.style.display = 'none';
      });
      const emailPage = document.getElementById('user-email-page');
      if (emailPage) emailPage.style.display = 'none';
    }
  } catch (error) {
  }
}

function setupUserEmailNavigation() {
  document.querySelectorAll('.user-tab-btn').forEach(button => {
    button.addEventListener('click', () => {
      const target = button.dataset.tab;
      if (target === 'email') {
        showUserEmailPage();
      } else if (target === 'channels' && typeof showUserChannelsPage === 'function') {
        showUserChannelsPage();
      } else {
        showUserConversationsPage();
      }
    });
  });

  const userEmailRefresh = document.getElementById('userEmailRefresh');
  if (userEmailRefresh) {
    userEmailRefresh.addEventListener('click', () => {
      if (UserEmailState.activeTab === 'inbox') {
        loadUserInbox();
      } else {
        loadUserSents();
      }
    });
  }

  document.querySelectorAll('.user-email-tab').forEach(button => {
    button.addEventListener('click', () => {
      document.querySelectorAll('.user-email-tab').forEach(btn => btn.classList.remove('active'));
      button.classList.add('active');
      UserEmailState.activeTab = button.dataset.tab;
      toggleUserEmailTab();
    });
  });
}

async function showUserEmailPage() {
  document.getElementById('user-conversations-page').style.display = 'none';
  document.getElementById('user-email-page').style.display = 'block';
  document.querySelectorAll('.user-tab-btn').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.tab === 'email');
  });
  await loadUserEmailAccounts();
  toggleUserEmailTab();
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function showUserConversationsPage() {
  document.getElementById('user-email-page').style.display = 'none';
  document.getElementById('user-conversations-page').style.display = 'block';
  document.querySelectorAll('.user-tab-btn').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.tab === 'conversations');
  });
}

async function loadUserEmailAccounts() {
  try {
    const response = await UserEmailAPI.get('/accounts');
    UserEmailState.accounts = response.data || [];
    if (!UserEmailState.accounts.length) {
      const inbox = document.getElementById('userEmailInbox');
      if (inbox) inbox.innerHTML = `<p data-i18n="email.no_accounts">No accounts connected.</p>`;
      return;
    }
    if (!UserEmailState.selectedAccountId) {
      UserEmailState.selectedAccountId = UserEmailState.accounts[0].id;
    }
    const select = document.getElementById('userEmailAccountSelect');
    if (select) {
      select.innerHTML = UserEmailState.accounts.map(account => `<option value="${account.id}">${account.email_address}</option>`).join('');
      select.value = UserEmailState.selectedAccountId;
      select.onchange = () => {
        UserEmailState.selectedAccountId = select.value;
        toggleUserEmailTab();
      };
    }
  } catch (error) {
    const inbox = document.getElementById('userEmailInbox');
    if (inbox) inbox.innerHTML = `<p>${error.message}</p>`;
  }
}

function toggleUserEmailTab() {
  const inbox = document.getElementById('userEmailInbox');
  const sents = document.getElementById('userEmailSents');
  if (!inbox || !sents) return;
  if (UserEmailState.activeTab === 'inbox') {
    inbox.style.display = 'block';
    sents.style.display = 'none';
    loadUserInbox();
  } else {
    inbox.style.display = 'none';
    sents.style.display = 'block';
    loadUserSents();
  }
}

async function loadUserInbox(page = UserEmailState.inboxPage) {
  const inbox = document.getElementById('userEmailInbox');
  const message = document.getElementById('userEmailMessage');
  if (!inbox) return;
  message.innerHTML = '';
  if (!UserEmailState.selectedAccountId) {
    inbox.innerHTML = `<p data-i18n="email.no_accounts">No accounts connected.</p>`;
    return;
  }
  inbox.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  try {
    const response = await UserEmailAPI.get('/messages/inbox', {
      account_id: UserEmailState.selectedAccountId,
      page
    });
    const items = response.data.items || [];
    UserEmailState.inboxPage = page;
    inbox.innerHTML = `
      <table class="user-email-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="user-email-row" data-uid="${item.uid}">
              <td>${item.from || '-'}</td>
              <td>${item.subject || '-'}</td>
              <td>${item.date ? new Date(item.date).toLocaleString() : '-'}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;
    inbox.querySelectorAll('.user-email-row').forEach(row => {
      row.addEventListener('click', () => loadUserInboxMessage(row.dataset.uid));
    });
  } catch (error) {
    inbox.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadUserInboxMessage(uid) {
  const message = document.getElementById('userEmailMessage');
  if (!message) return;
  message.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  try {
    const response = await UserEmailAPI.get(`/messages/${uid}`, {
      account_id: UserEmailState.selectedAccountId,
      folder: 'inbox'
    });
    const detail = response.data;
    message.innerHTML = `
      <div class="user-email-message">
        <div><strong data-i18n="email.from">From</strong>: ${detail.from || '-'}</div>
        <div><strong data-i18n="email.subject">Subject</strong>: ${detail.subject || '-'}</div>
        <div><strong data-i18n="email.date">Date</strong>: ${detail.date ? new Date(detail.date).toLocaleString() : '-'}</div>
        <div style="margin-top: 8px;">${detail.html || detail.text || ''}</div>
      </div>
    `;
  } catch (error) {
    message.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadUserSents(page = UserEmailState.sentsPage) {
  const sents = document.getElementById('userEmailSents');
  const message = document.getElementById('userEmailMessage');
  if (!sents) return;
  message.innerHTML = '';
  if (!UserEmailState.selectedAccountId) {
    sents.innerHTML = `<p data-i18n="email.no_accounts">No accounts connected.</p>`;
    return;
  }
  sents.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  try {
    const response = await UserEmailAPI.get('/messages/sent', {
      account_id: UserEmailState.selectedAccountId,
      page
    });
    const items = response.data.items || [];
    UserEmailState.sentsPage = page;
    sents.innerHTML = `
      <table class="user-email-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="user-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>
    `;
    sents.querySelectorAll('.user-email-row').forEach(row => {
      row.addEventListener('click', () => loadUserSentMessage(row.dataset.id));
    });
  } catch (error) {
    sents.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadUserSentMessage(id) {
  const message = document.getElementById('userEmailMessage');
  if (!message) return;
  message.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  try {
    const response = await UserEmailAPI.get(`/messages/${id}`, {
      account_id: UserEmailState.selectedAccountId,
      folder: 'sent'
    });
    const detail = response.data;
    message.innerHTML = `
      <div class="user-email-message">
        <div><strong data-i18n="email.to">To</strong>: ${detail.to_email || '-'}</div>
        <div><strong data-i18n="email.subject">Subject</strong>: ${detail.subject || '-'}</div>
        <div style="margin-top: 8px;">${detail.html_content || detail.text_content || ''}</div>
      </div>
    `;
  } catch (error) {
    message.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}
