const OmnichannelAPI = {
  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) });
  },
  delete(path) {
    return this.request(path, { method: 'DELETE' });
  }
};

const OmnichannelState = {
  settings: null,
  activeChannel: 'instagram',
  accounts: {
    instagram: [],
    messenger: [],
    telegram: []
  }
};

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

function loadOmnichannelPage() {
  const page = document.getElementById('chats-channel-page');
  if (!page) return;
  if (typeof isAddonActive === 'function' && !isAddonActive('omnichannel')) {
    page.innerHTML = `
      <div class="feature-disabled-message">
        <h3 data-i18n="omnichannel.addon_required">Omnichannel addon required</h3>
        <p data-i18n="omnichannel.addon_required_desc">Contact your superadmin to enable Omnichannel Channels.</p>
      </div>
    `;
    if (window.applyLanguage) {
      window.applyLanguage(localStorage.getItem('language') || 'en');
    } else if (window.i18n && window.i18n.translatePage) {
      window.i18n.translatePage();
    }
    return;
  }

  page.innerHTML = `
    <div class="page-header">
      <h1 data-i18n="omnichannel.title">Chats Channel</h1>
    </div>
    <div class="card" style="margin-bottom: 20px;">
      <div class="card-body">
        <div class="tabs">
          <button class="tab-btn active" data-channel="instagram">
            <i class="fab fa-instagram"></i> <span data-i18n="omnichannel.instagram">Instagram</span>
          </button>
          <button class="tab-btn" data-channel="messenger">
            <i class="fab fa-facebook-messenger"></i> <span data-i18n="omnichannel.messenger">Messenger</span>
          </button>
          <button class="tab-btn" data-channel="telegram">
            <i class="fab fa-telegram-plane"></i> <span data-i18n="omnichannel.telegram">Telegram</span>
          </button>
        </div>
      </div>
    </div>
    <div id="omnichannel-channel-content"></div>
    <div id="omnichannel-modal-container"></div>
  `;

  setupOmnichannelTabs();
  loadOmnichannelSettings().then(() => {
    renderOmnichannelChannel(OmnichannelState.activeChannel);
    checkOmnichannelFacebookCallback();
  });
}

function setupOmnichannelTabs() {
  document.querySelectorAll('#chats-channel-page .tab-btn').forEach(button => {
    button.addEventListener('click', () => {
      document.querySelectorAll('#chats-channel-page .tab-btn').forEach(btn => btn.classList.remove('active'));
      button.classList.add('active');
      OmnichannelState.activeChannel = button.dataset.channel;
      renderOmnichannelChannel(OmnichannelState.activeChannel);
    });
  });
}

async function loadOmnichannelSettings() {
  try {
    const response = await OmnichannelAPI.get('/settings');
    OmnichannelState.settings = response.data || null;
  } catch (error) {
    OmnichannelState.settings = null;
  }
}

async function renderOmnichannelChannel(channel) {
  const container = document.getElementById('omnichannel-channel-content');
  if (!container) return;
  container.innerHTML = `
    <div class="card">
      <div class="card-header" style="display:flex; justify-content: space-between; align-items: center;">
        <h3 style="margin:0;">
          <span data-i18n="omnichannel.channel_settings">Channel Settings</span>
        </h3>
        <button class="btn btn-primary" onclick="openOmnichannelConnectModal('${channel}')">
          <i class="fas fa-plug"></i> <span data-i18n="omnichannel.connect_button_${channel}">Connect</span>
        </button>
      </div>
      <div class="card-body">
        <div id="omnichannel-embedded-status"></div>
        <div id="omnichannel-accounts-list"></div>
      </div>
    </div>
  `;

  renderEmbeddedStatus(channel);
  await loadOmnichannelAccounts(channel);
}

function renderEmbeddedStatus(channel) {
  const statusEl = document.getElementById('omnichannel-embedded-status');
  if (!statusEl) return;
  const settings = OmnichannelState.settings || {};
  const channelSettings = settings[channel] || {};
  const configured = channelSettings.is_configured;
  let statusText = '';
  if (channel === 'telegram') {
    statusText = configured ? omniT('omnichannel.telegram_ready', 'Telegram settings configured.') : omniT('omnichannel.telegram_not_ready', 'Telegram settings are not configured.');
  } else {
    statusText = configured ? omniT('omnichannel.embedded_ready', 'Embedded signup is configured.') : omniT('omnichannel.embedded_not_ready', 'Embedded signup is not configured.');
  }
  statusEl.innerHTML = `
    <div class="alert ${configured ? 'alert-success' : 'alert-warning'}" style="margin-bottom: 16px;">
      ${statusText}
    </div>
  `;
  if (window.i18n && window.i18n.translatePage) {
    window.i18n.translatePage();
  }
}

async function loadOmnichannelAccounts(channel) {
  const listEl = document.getElementById('omnichannel-accounts-list');
  if (!listEl) return;
  listEl.innerHTML = `<p data-i18n="common.loading">Loading...</p>`;
  try {
    const response = await OmnichannelAPI.get('/accounts', { channel });
    OmnichannelState.accounts[channel] = response.data || [];
    renderOmnichannelAccounts(channel);
  } catch (error) {
    listEl.innerHTML = `<div class="alert alert-danger">${error.message}</div>`;
  }
  if (window.i18n && window.i18n.translatePage) {
    window.i18n.translatePage();
  }
}

function renderOmnichannelAccounts(channel) {
  const listEl = document.getElementById('omnichannel-accounts-list');
  if (!listEl) return;
  const accounts = OmnichannelState.accounts[channel] || [];
  if (!accounts.length) {
    listEl.innerHTML = `<p data-i18n="omnichannel.no_accounts">No accounts connected yet.</p>`;
    return;
  }
  listEl.innerHTML = `
    <div class="table-container">
      <table>
        <thead>
          <tr>
            <th data-i18n="omnichannel.account_name">Account</th>
            <th data-i18n="omnichannel.account_id">External ID</th>
            <th data-i18n="omnichannel.status">Status</th>
            <th data-i18n="omnichannel.actions">Actions</th>
          </tr>
        </thead>
        <tbody>
          ${accounts.map(account => `
            <tr>
              <td>${account.display_name || '-'}</td>
              <td>${account.external_id || '-'}</td>
              <td>${account.status || 'active'}</td>
              <td>
                <button class="btn btn-sm btn-danger" onclick="disconnectOmnichannelAccount(${account.id}, '${channel}')">
                  <i class="fas fa-unlink"></i> <span data-i18n="omnichannel.disconnect">Disconnect</span>
                </button>
              </td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
  `;
  if (window.i18n && window.i18n.translatePage) {
    window.i18n.translatePage();
  }
}

function openOmnichannelConnectModal(channel) {
  if (channel === 'telegram') {
    openOmnichannelTelegramModal(channel);
    return;
  }
  openOmnichannelEmbeddedModal(channel);
}

function openOmnichannelEmbeddedModal(channel) {
  const container = document.getElementById('omnichannel-modal-container');
  if (!container) return;
  const settings = OmnichannelState.settings || {};
  const channelSettings = settings[channel] || {};
  const configured = channelSettings.is_configured;
  const title = omniT('omnichannel.connect_with_facebook', 'Connect with Facebook');
  const description = omniT('omnichannel.connect_with_facebook_desc', 'Use embedded signup to connect this channel securely in one click.');
  const notConfiguredDesc = omniT('omnichannel.facebook_login_not_configured_desc', 'Ask your superadmin to configure the embedded signup settings for this channel.');
  container.innerHTML = `
    <div class="modal active" id="omnichannelConnectModal">
      <div class="modal-content" style="max-width: 520px;">
        <div class="modal-header">
          <h3>${title}</h3>
          <button class="modal-close" onclick="closeOmnichannelConnectModal()">&times;</button>
        </div>
        <div class="modal-body">
          <div class="alert ${configured ? 'alert-info' : 'alert-warning'}" style="margin-bottom: 16px;">
            ${configured ? description : notConfiguredDesc}
          </div>
          <div style="display:flex; justify-content: flex-end; gap: 10px;">
            <button type="button" class="btn btn-secondary" onclick="closeOmnichannelConnectModal()" data-i18n="common.cancel">Cancel</button>
            <button type="button" class="btn btn-primary" onclick="startOmnichannelFacebookLogin('${channel}')" ${configured ? '' : 'disabled'}>
              <i class="fab fa-facebook"></i> <span data-i18n="omnichannel.connect_with_facebook_button">Connect with Facebook</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  `;
  if (window.i18n && window.i18n.translatePage) {
    window.i18n.translatePage();
  }
}

function openOmnichannelTelegramModal(channel) {
  const container = document.getElementById('omnichannel-modal-container');
  if (!container) return;
  const labels = getOmnichannelChannelLabels(channel);
  container.innerHTML = `
    <div class="modal active" id="omnichannelConnectModal">
      <div class="modal-content" style="max-width: 520px;">
        <div class="modal-header">
          <h3>${labels.title}</h3>
          <button class="modal-close" onclick="closeOmnichannelConnectModal()">&times;</button>
        </div>
        <div class="modal-body">
          <form id="omnichannelConnectForm">
            <div class="form-group">
              <label>${labels.nameLabel}</label>
              <input type="text" class="form-control" id="omniDisplayName" placeholder="${labels.namePlaceholder}">
            </div>
            <div class="form-group">
              <label>${labels.tokenLabel}</label>
              <input type="password" class="form-control" id="omniAccessToken" placeholder="${labels.tokenPlaceholder}">
            </div>
            <div class="form-group">
              <label>${labels.metadataLabel}</label>
              <textarea class="form-control" id="omniMetadata" rows="3" placeholder="${labels.metadataPlaceholder}"></textarea>
            </div>
            <div style="display:flex; justify-content: flex-end; gap: 10px;">
              <button type="button" class="btn btn-secondary" onclick="closeOmnichannelConnectModal()" data-i18n="common.cancel">Cancel</button>
              <button type="submit" class="btn btn-primary" data-i18n="omnichannel.connect_submit">Connect</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  `;

  const form = document.getElementById('omnichannelConnectForm');
  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    await submitOmnichannelConnect(channel);
  });

  if (window.i18n && window.i18n.translatePage) {
    window.i18n.translatePage();
  }
}

function closeOmnichannelConnectModal() {
  const container = document.getElementById('omnichannel-modal-container');
  if (container) container.innerHTML = '';
}

function getOmnichannelChannelLabels(channel) {
  const labels = {
    instagram: {
      title: omniT('omnichannel.connect_instagram', 'Connect Instagram'),
      nameLabel: omniT('omnichannel.instagram_name', 'Instagram Account Name'),
      namePlaceholder: omniT('omnichannel.instagram_name_placeholder', 'Business name'),
      tokenLabel: omniT('omnichannel.instagram_token', 'Access Token'),
      tokenPlaceholder: omniT('omnichannel.instagram_token_placeholder', 'Paste a valid access token'),
      metadataLabel: omniT('omnichannel.instagram_metadata', 'Metadata (JSON)'),
      metadataPlaceholder: omniT('omnichannel.instagram_metadata_placeholder', '{"page_id":"123"}')
    },
    messenger: {
      title: omniT('omnichannel.connect_messenger', 'Connect Messenger'),
      nameLabel: omniT('omnichannel.messenger_name', 'Page Name'),
      namePlaceholder: omniT('omnichannel.messenger_name_placeholder', 'Page name'),
      tokenLabel: omniT('omnichannel.messenger_token', 'Page Access Token'),
      tokenPlaceholder: omniT('omnichannel.messenger_token_placeholder', 'Paste the page token'),
      metadataLabel: omniT('omnichannel.messenger_metadata', 'Metadata (JSON)'),
      metadataPlaceholder: omniT('omnichannel.messenger_metadata_placeholder', '{"app_scoped_user_id":"..."}')
    },
    telegram: {
      title: omniT('omnichannel.connect_telegram', 'Connect Telegram'),
      nameLabel: omniT('omnichannel.telegram_name', 'Bot Display Name'),
      namePlaceholder: omniT('omnichannel.telegram_name_placeholder', 'Bot name'),
      tokenLabel: omniT('omnichannel.telegram_token', 'Bot Token'),
      tokenPlaceholder: omniT('omnichannel.telegram_token_placeholder', 'Paste the bot token'),
      metadataLabel: omniT('omnichannel.telegram_metadata', 'Metadata (JSON)'),
      metadataPlaceholder: omniT('omnichannel.telegram_metadata_placeholder', '{"webhook":"https://..."}')
    }
  };
  return labels[channel] || labels.instagram;
}

async function submitOmnichannelConnect(channel) {
  if (channel !== 'telegram') return;
  const displayName = document.getElementById('omniDisplayName')?.value || '';
  const accessToken = document.getElementById('omniAccessToken')?.value || '';
  const metadataRaw = document.getElementById('omniMetadata')?.value || '';
  let metadata;
  if (metadataRaw) {
    try {
      metadata = JSON.parse(metadataRaw);
    } catch (error) {
      showNotification(omniT('omnichannel.invalid_metadata', 'Invalid JSON metadata'), 'error');
      return;
    }
  }
  if (!accessToken) {
    showNotification(omniT('omnichannel.telegram_token_required', 'Telegram bot token is required'), 'error');
    return;
  }
  try {
    await OmnichannelAPI.post('/accounts/connect', {
      channel,
      display_name: displayName,
      access_token: accessToken,
      metadata
    });
    closeOmnichannelConnectModal();
    showNotification(omniT('omnichannel.connected_success', 'Channel connected successfully'), 'success');
    await loadOmnichannelAccounts(channel);
  } catch (error) {
    showNotification(error.message, 'error');
  }
}

function disconnectOmnichannelAccount(accountId, channel) {
  const confirmAction = async () => {
    try {
      await OmnichannelAPI.delete(`/accounts/${accountId}`);
      showNotification(omniT('omnichannel.disconnected_success', 'Channel disconnected'), 'success');
      await loadOmnichannelAccounts(channel);
    } catch (error) {
      showNotification(error.message, 'error');
    }
  };
  if (window.showCustomConfirm) {
    window.showCustomConfirm(
      omniT('omnichannel.disconnect_confirm', 'Disconnect this channel?'),
      omniT('omnichannel.disconnect_desc', 'This will remove the connection for this account.'),
      confirmAction
    );
  } else if (window.confirm(omniT('omnichannel.disconnect_confirm', 'Disconnect this channel?'))) {
    confirmAction();
  }
}

function getOmnichannelFacebookScope(channel) {
  if (channel === 'instagram') {
    return 'instagram_basic,instagram_manage_messages,pages_show_list,pages_read_engagement';
  }
  return 'pages_messaging,pages_show_list,pages_read_engagement';
}

function startOmnichannelFacebookLogin(channel) {
  const settings = OmnichannelState.settings || {};
  const channelSettings = settings[channel] || {};
  if (!channelSettings || !channelSettings.is_configured) {
    showNotification(omniT('omnichannel.facebook_login_not_configured', 'Facebook Login Not Configured'), 'error');
    return;
  }
  const appId = (channelSettings.app_id || '').toString().replace(/\D/g, '');
  if (!appId) {
    showNotification(omniT('omnichannel.facebook_login_invalid_app_id', 'Invalid App ID'), 'error');
    return;
  }
  const configId = channelSettings.config_id;
  localStorage.setItem('omnichannel_facebook_channel', channel);
  localStorage.setItem('omnichannel_facebook_timestamp', Date.now().toString());

  if (typeof FB === 'undefined') {
    loadOmnichannelFacebookSDK(appId, () => {
      launchOmnichannelFacebookLogin(appId, configId, channel);
    });
  } else {
    launchOmnichannelFacebookLogin(appId, configId, channel);
  }
}

function loadOmnichannelFacebookSDK(appId, callback) {
  window.fbAsyncInit = function() {
    FB.init({
      appId: appId,
      cookie: true,
      xfbml: true,
      version: 'v18.0'
    });
    if (callback) callback();
  };
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = 'https://connect.facebook.net/en_US/sdk.js';
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
}

function launchOmnichannelFacebookLogin(appId, configId, channel) {
  const redirectUri = `${window.location.origin}/admin/facebook-callback.html`;
  const width = 600;
  const height = 700;
  const left = (screen.width - width) / 2;
  const top = (screen.height - height) / 2;
  const scope = getOmnichannelFacebookScope(channel);
  const fbLoginUrl = `https://www.facebook.com/v18.0/dialog/oauth?` +
    `client_id=${appId}` +
    `&redirect_uri=${encodeURIComponent(redirectUri)}` +
    `&config_id=${configId}` +
    `&response_type=code` +
    `&scope=${encodeURIComponent(scope)}` +
    `&state=${Date.now()}`;

  const popup = window.open(
    fbLoginUrl,
    'facebook-login',
    `width=${width},height=${height},left=${left},top=${top},scrollbars=yes`
  );

  const messageHandler = (event) => {
    if (event.origin !== window.location.origin) {
      return;
    }
    if (event.data && event.data.type === 'facebook-callback') {
      window.removeEventListener('message', messageHandler);
      if (event.data.code) {
        handleOmnichannelFacebookLoginSuccess(channel, { code: event.data.code });
      } else if (event.data.error) {
        showNotification(omniT('omnichannel.facebook_login_failed', 'Facebook login failed'), 'error');
      }
      if (popup && !popup.closed) {
        popup.close();
      }
    }
  };

  window.addEventListener('message', messageHandler);

  if (!popup || popup.closed || typeof popup.closed === 'undefined') {
    showNotification(omniT('omnichannel.popup_blocked', 'Popup was blocked. Please allow popups for this site.'), 'error');
    window.removeEventListener('message', messageHandler);
  }
}

function checkOmnichannelFacebookCallback() {
  const channel = localStorage.getItem('omnichannel_facebook_channel');
  const timestampRaw = localStorage.getItem('omnichannel_facebook_timestamp');
  if (!channel || !timestampRaw) return;
  const timestamp = parseInt(timestampRaw, 10);
  if (Number.isNaN(timestamp) || Date.now() - timestamp > 10 * 60 * 1000) {
    localStorage.removeItem('omnichannel_facebook_channel');
    localStorage.removeItem('omnichannel_facebook_timestamp');
    return;
  }
  const code = localStorage.getItem('facebook_callback_code');
  const error = localStorage.getItem('facebook_callback_error');
  if (error) {
    localStorage.removeItem('facebook_callback_error');
    showNotification(omniT('omnichannel.facebook_login_failed', 'Facebook login failed'), 'error');
    return;
  }
  if (!code) return;
  localStorage.removeItem('facebook_callback_code');
  localStorage.removeItem('facebook_callback_timestamp');
  localStorage.removeItem('omnichannel_facebook_channel');
  localStorage.removeItem('omnichannel_facebook_timestamp');
  handleOmnichannelFacebookLoginSuccess(channel, { code });
}

function handleOmnichannelFacebookLoginSuccess(channel, authResponse) {
  showNotification(omniT('omnichannel.facebook_processing', 'Processing Facebook login...'), 'info');
  const token = localStorage.getItem('token');
  if (!token) {
    showNotification(omniT('omnichannel.auth_required', 'Authentication required'), 'error');
    return;
  }
  fetch('/api/addons/omnichannel/embedded-callback', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      code: authResponse.code || authResponse.accessToken,
      channel
    })
  })
  .then(response => response.json())
  .then(result => {
    if (result.success) {
      const count = result.data?.connected_count || 0;
      const skipped = result.data?.skipped_count || 0;
      if (count > 0) {
        showNotification(omniT('omnichannel.embedded_connect_success', 'Channel connected successfully'), 'success');
      } else {
        showNotification(omniT('omnichannel.embedded_connect_none', 'No new accounts were connected'), 'warning');
      }
      if (skipped > 0) {
        showNotification(omniT('omnichannel.embedded_connect_limit', 'Some accounts were skipped due to plan limits'), 'warning');
      }
      closeOmnichannelConnectModal();
      loadOmnichannelAccounts(channel);
    } else {
      showNotification(result.message || omniT('omnichannel.facebook_login_failed', 'Facebook login failed'), 'error');
    }
  })
  .catch(() => {
    showNotification(omniT('omnichannel.facebook_login_failed', 'Facebook login failed'), 'error');
  });
}
