const UserChannelsAPI = {
  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/omnichannel${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);
  },
  post(path, body = {}) {
    return this.request(path, { method: 'POST', body: JSON.stringify(body) });
  }
};

const UserChannelsState = {
  accounts: [],
  selectedAccountId: null,
  conversations: [],
  selectedConversationId: null,
  messages: []
};

document.addEventListener('DOMContentLoaded', () => {
  checkChannelsAddonAvailability();
  setupUserChannelsNavigation();
});

async function checkChannelsAddonAvailability() {
  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 === 'omnichannel');
    if (!isActive) {
      document.querySelectorAll('.user-tab-btn[data-tab="channels"]').forEach(btn => {
        btn.style.display = 'none';
      });
      const channelsPage = document.getElementById('user-channels-page');
      if (channelsPage) channelsPage.style.display = 'none';
    }
  } catch (error) {
  }
}

function setupUserChannelsNavigation() {
  const form = document.getElementById('userChannelsSendForm');
  if (form) {
    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      await sendUserChannelMessage();
    });
  }

  const select = document.getElementById('userChannelsSelect');
  if (select) {
    select.addEventListener('change', async () => {
      UserChannelsState.selectedAccountId = select.value;
      await loadUserChannelConversations();
    });
  }
}

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

async function loadUserChannelAccounts() {
  const select = document.getElementById('userChannelsSelect');
  if (select) {
    select.innerHTML = '';
  }
  const list = document.getElementById('userChannelsConversations');
  if (list) {
    list.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  }
  try {
    const response = await UserChannelsAPI.get('/accounts');
    UserChannelsState.accounts = response.data || [];
    if (!UserChannelsState.accounts.length) {
      if (select) {
        select.innerHTML = '';
      }
      if (list) {
        list.innerHTML = `<p data-i18n="user.channels_no_accounts">No channels connected yet.</p>`;
      }
      return;
    }
    if (!UserChannelsState.selectedAccountId) {
      UserChannelsState.selectedAccountId = UserChannelsState.accounts[0].id;
    }
    if (select) {
      select.innerHTML = UserChannelsState.accounts.map(account => {
        const label = `${formatChannelLabel(account.channel)}${account.display_name ? ` · ${account.display_name}` : ''}`;
        return `<option value="${account.id}">${label}</option>`;
      }).join('');
      select.value = UserChannelsState.selectedAccountId;
    }
    await loadUserChannelConversations();
  } catch (error) {
    if (list) list.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

async function loadUserChannelConversations() {
  const list = document.getElementById('userChannelsConversations');
  if (!list) return;
  if (!UserChannelsState.selectedAccountId) {
    list.innerHTML = `<p data-i18n="user.channels_no_accounts">No channels connected yet.</p>`;
    return;
  }
  list.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  try {
    const response = await UserChannelsAPI.get(`/accounts/${UserChannelsState.selectedAccountId}/conversations`);
    UserChannelsState.conversations = response.data || [];
    UserChannelsState.selectedConversationId = UserChannelsState.conversations[0]?.id || null;
    renderUserChannelConversations();
    if (UserChannelsState.selectedConversationId) {
      await loadUserChannelMessages(UserChannelsState.selectedConversationId);
    } else {
      renderUserChannelMessages([]);
    }
  } catch (error) {
    list.innerHTML = `<p>${error.message}</p>`;
  }
  if (window.applyLanguage) {
    window.applyLanguage(localStorage.getItem('language') || 'en');
  }
}

function renderUserChannelConversations() {
  const list = document.getElementById('userChannelsConversations');
  if (!list) return;
  if (!UserChannelsState.conversations.length) {
    list.innerHTML = `<p data-i18n="user.channels_no_conversations">No conversations available.</p>`;
    return;
  }
  list.innerHTML = UserChannelsState.conversations.map(conversation => {
    const active = conversation.id === UserChannelsState.selectedConversationId;
    const label = conversation.contact_name || conversation.contact_handle || omniFallbackConversationLabel(conversation);
    const time = conversation.last_message_at ? new Date(conversation.last_message_at).toLocaleString() : '';
    return `
      <div class="user-channel-item ${active ? 'active' : ''}" data-id="${conversation.id}">
        <strong>${label}</strong>
        <div style="font-size: 12px; color: #6b7280;">${time}</div>
      </div>
    `;
  }).join('');

  list.querySelectorAll('.user-channel-item').forEach(item => {
    item.addEventListener('click', async () => {
      const id = item.dataset.id;
      UserChannelsState.selectedConversationId = id;
      renderUserChannelConversations();
      await loadUserChannelMessages(id);
    });
  });
}

async function loadUserChannelMessages(conversationId) {
  try {
    const response = await UserChannelsAPI.get(`/conversations/${conversationId}/messages`);
    UserChannelsState.messages = response.data || [];
    renderUserChannelMessages(UserChannelsState.messages);
  } catch (error) {
    renderUserChannelMessages([], error.message);
  }
}

function renderUserChannelMessages(messages = [], errorMessage = null) {
  const container = document.getElementById('userChannelsMessages');
  const title = document.getElementById('userChannelsConversationTitle');
  const meta = document.getElementById('userChannelsConversationMeta');
  if (!container) return;

  const selected = UserChannelsState.conversations.find(conv => String(conv.id) === String(UserChannelsState.selectedConversationId));
  if (title) {
    title.textContent = selected?.contact_name || selected?.contact_handle || omniFallbackConversationLabel(selected);
  }
  if (meta) {
    meta.textContent = selected?.channel ? formatChannelLabel(selected.channel) : '';
  }

  if (errorMessage) {
    container.innerHTML = `<p>${errorMessage}</p>`;
    return;
  }
  if (!messages.length) {
    container.innerHTML = `<p data-i18n="user.channels_no_messages">No messages yet.</p>`;
    return;
  }
  container.innerHTML = messages.map(message => `
    <div class="user-channels-message ${message.direction === 'out' ? 'out' : 'in'}">
      <div class="user-channels-message-bubble">
        <div>${message.body || ''}</div>
        <div style="font-size: 11px; margin-top: 6px; opacity: 0.7;">${message.created_at ? new Date(message.created_at).toLocaleString() : ''}</div>
      </div>
    </div>
  `).join('');
}

async function sendUserChannelMessage() {
  const input = document.getElementById('userChannelsMessageInput');
  if (!input) return;
  const body = input.value.trim();
  if (!body || !UserChannelsState.selectedConversationId) return;
  try {
    await UserChannelsAPI.post(`/conversations/${UserChannelsState.selectedConversationId}/messages`, { body });
    input.value = '';
    await loadUserChannelMessages(UserChannelsState.selectedConversationId);
  } catch (error) {
    console.error('Error sending message:', error);
  }
}

function formatChannelLabel(channel) {
  if (channel === 'instagram') return 'Instagram';
  if (channel === 'messenger') return 'Messenger';
  if (channel === 'telegram') return 'Telegram';
  return channel || '';
}

function omniFallbackConversationLabel(conversation) {
  return conversation?.external_thread_id || 'Conversation';
}
