# All files whatsapp-cloud.js

0% Statements 0/175
0% Branches 0/111
0% Functions 0/37
0% Lines 0/149

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298

     let wcState = {
      accounts: [],
      activeAccountId: null,
      activeTab: 'conversations',
      search: ''
    };

    function wcTranslate(key, fallback) {
      if (window.i18n && typeof window.i18n.t === 'function') {
        return window.i18n.t(key) || fallback || key;
      }
      return fallback || key;
    }

    function wcNotify(type, message) {
      if (typeof showNotification === 'function') {
        showNotification(type, message);
      }
    }

    function wcLoadAccounts() {
      try {
        const raw = localStorage.getItem('whatsappCloudAccounts');
        const parsed = raw ? JSON.parse(raw) : [];
        wcState.accounts = Array.isArray(parsed) ? parsed : [];
        const savedActive = localStorage.getItem('whatsappCloudActiveAccount');
        wcState.activeAccountId = savedActive || (wcState.accounts.find(acc => acc.isDefault)?.id || wcState.accounts[0]?.id || null);
      } catch (error) {
        wcState.accounts = [];
        wcState.activeAccountId = null;
      }
    }

    function wcSaveAccounts() {
      localStorage.setItem('whatsappCloudAccounts', JSON.stringify(wcState.accounts));
      localStorage.setItem('whatsappCloudActiveAccount', wcState.activeAccountId || '');
    }

    function wcSetActiveAccount(accountId) {
      wcState.activeAccountId = accountId;
      wcSaveAccounts();
      wcRenderAccounts();
      wcRenderAccountSelectors();
    }

    function wcRenderAccounts() {
      const list = document.getElementById('wcAccountList');
      const empty = document.getElementById('wcAccountEmpty');
      if (!list || !empty) return;

      const searchTerm = wcState.search.toLowerCase();
      const filtered = wcState.accounts.filter(acc => acc.name.toLowerCase().includes(searchTerm));

      if (filtered.length === 0) {
        list.innerHTML = '';
        empty.style.display = 'block';
        return;
      }

      empty.style.display = 'none';
      list.innerHTML = filtered.map(account => {
        const statusKey = `whatsapp_cloud.status_${account.status || 'pending'}`;
        const statusLabel = wcTranslate(statusKey, account.status || 'pending');
        const isActive = wcState.activeAccountId === account.id;
        const defaultLabel = account.isDefault ? `<span class="wc-account-status">${wcTranslate('whatsapp_cloud.account_default', 'Default')}</span>` : '';
        const phoneLabel = wcTranslate('whatsapp_cloud.phone_id_label', 'Phone ID');
        return `
          <div class="wc-account-item ${isActive ? 'active' : ''}" data-account-id="${account.id}">
            <div class="wc-account-main">
              <div>
                <div class="wc-account-name">${account.name}</div>
                <div class="wc-account-meta">${phoneLabel}: ${account.phoneNumberId || '-'}</div>
              </div>
              <span class="wc-account-status">${statusLabel}</span>
            </div>
            ${defaultLabel}
            <div class="wc-account-actions">
              <button class="icon-btn" data-action="set-default">
                <i class="fas fa-star"></i>
              </button>
              <button class="icon-btn" data-action="remove">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
        `;
      }).join('');
    }

    function wcRenderAccountSelectors() {
      const selects = document.querySelectorAll('.wc-account-select');
      const active = wcState.accounts.find(acc => acc.id === wcState.activeAccountId);
      const label = document.getElementById('wcActiveAccountLabel');
      if (label) {
        label.textContent = active ? active.name : wcTranslate('whatsapp_cloud.no_active_account', 'No account selected');
      }

      selects.forEach(select => {
        const options = wcState.accounts.map(acc => `<option value="${acc.id}">${acc.name}</option>`).join('');
        const placeholder = `<option value="">${wcTranslate('whatsapp_cloud.account_select_placeholder', 'Select account')}</option>`;
        select.innerHTML = placeholder + options;
        select.value = wcState.activeAccountId || '';
      });

      const statusLabel = document.getElementById('wcAccountStatus');
      if (statusLabel) {
        const statusKey = active ? `whatsapp_cloud.status_${active.status || 'pending'}` : 'whatsapp_cloud.status_pending';
        statusLabel.textContent = wcTranslate(statusKey, 'Pending');
      }
    }

    function wcHandleAccountListClick(event) {
      const item = event.target.closest('.wc-account-item');
      if (!item) return;

      const accountId = item.dataset.accountId;
      const action = event.target.closest('[data-action]')?.dataset?.action;

      if (!action) {
        wcSetActiveAccount(accountId);
        return;
      }

      if (action === 'set-default') {
        wcState.accounts = wcState.accounts.map(acc => ({
          ...acc,
          isDefault: acc.id === accountId
        }));
        wcSaveAccounts();
        wcRenderAccounts();
        return;
      }

      if (action === 'remove') {
        wcState.accounts = wcState.accounts.filter(acc => acc.id !== accountId);
        if (wcState.activeAccountId === accountId) {
          wcState.activeAccountId = wcState.accounts[0]?.id || null;
        }
        wcSaveAccounts();
        wcRenderAccounts();
        wcRenderAccountSelectors();
      }
    }

    function wcOpenAddAccountModal() {
      if (!window.Modal || typeof Modal.form !== 'function') return;
      const modal = Modal.form({
        title: wcTranslate('whatsapp_cloud.modal_add_account_title', 'Add WhatsApp Cloud Account'),
        fields: [
          { name: 'name', label: wcTranslate('whatsapp_cloud.modal_add_account_name', 'Account name'), type: 'text', required: true },
          { name: 'phoneNumberId', label: wcTranslate('whatsapp_cloud.modal_add_account_phone_id', 'Phone Number ID'), type: 'text' },
          { name: 'wabaId', label: wcTranslate('whatsapp_cloud.modal_add_account_waba_id', 'WABA ID'), type: 'text' },
          { name: 'status', label: wcTranslate('whatsapp_cloud.modal_add_account_status', 'Status'), type: 'select', options: [
            { value: 'connected', label: wcTranslate('whatsapp_cloud.status_connected', 'Connected') },
            { value: 'pending', label: wcTranslate('whatsapp_cloud.status_pending', 'Pending') },
            { value: 'disconnected', label: wcTranslate('whatsapp_cloud.status_disconnected', 'Disconnected') }
          ]}
        ],
        submitText: wcTranslate('whatsapp_cloud.modal_add_account_save', 'Add account')
      });

      modal.submit = data => {
        const account = {
          id: String(Date.now()),
          name: data.name.trim(),
          phoneNumberId: data.phoneNumberId?.trim() || '',
          wabaId: data.wabaId?.trim() || '',
          status: data.status || 'pending',
          isDefault: wcState.accounts.length === 0
        };
        wcState.accounts = [...wcState.accounts, account];
        if (!wcState.activeAccountId) {
          wcState.activeAccountId = account.id;
        }
        wcSaveAccounts();
        wcRenderAccounts();
        wcRenderAccountSelectors();
        wcNotify('success', wcTranslate('whatsapp_cloud.notification_account_added', 'Account added successfully'));
      };
    }

    function wcOpenTemplateModal() {
      if (!window.Modal || typeof Modal.form !== 'function') return;
      const modal = Modal.form({
        title: wcTranslate('whatsapp_cloud.template_modal_title', 'Create Template'),
        fields: [
          { name: 'name', label: wcTranslate('whatsapp_cloud.template_modal_name', 'Template name'), type: 'text', required: true },
          { name: 'language', label: wcTranslate('whatsapp_cloud.template_modal_language', 'Language'), type: 'text', required: true },
          { name: 'category', label: wcTranslate('whatsapp_cloud.template_modal_category', 'Category'), type: 'text', required: true },
          { name: 'body', label: wcTranslate('whatsapp_cloud.template_modal_body', 'Message body'), type: 'textarea', required: true }
        ],
        submitText: wcTranslate('whatsapp_cloud.template_modal_create', 'Create template')
      });

      modal.submit = () => {
        wcNotify('success', wcTranslate('whatsapp_cloud.notification_template_created', 'Template submitted for approval'));
      };
    }

    function wcInitTabs() {
      const tabs = document.querySelectorAll('#wcTabs .wc-tab');
      const panels = document.querySelectorAll('.wc-panel');
      tabs.forEach(tab => {
        tab.addEventListener('click', () => {
          const target = tab.dataset.wcTab;
          wcState.activeTab = target;
          tabs.forEach(t => t.classList.toggle('active', t.dataset.wcTab === target));
          panels.forEach(panel => panel.classList.toggle('active', panel.dataset.wcPanel === target));
        });
      });
    }

    function wcInitEvents() {
      const list = document.getElementById('wcAccountList');
      if (list) {
        list.addEventListener('click', wcHandleAccountListClick);
      }

      const search = document.getElementById('wcAccountSearch');
      if (search) {
        search.addEventListener('input', event => {
          wcState.search = event.target.value;
          wcRenderAccounts();
        });
      }

      const addBtn = document.getElementById('wcAddAccountBtn');
      if (addBtn) addBtn.addEventListener('click', wcOpenAddAccountModal);

      const emptyConnectBtn = document.getElementById('wcEmptyConnectBtn');
      if (emptyConnectBtn) emptyConnectBtn.addEventListener('click', wcOpenAddAccountModal);

      const connectShortcut = document.getElementById('wcConnectAccountShortcut');
      if (connectShortcut) connectShortcut.addEventListener('click', wcOpenAddAccountModal);

      const templateBtn = document.getElementById('wcCreateTemplateBtn');
      if (templateBtn) templateBtn.addEventListener('click', wcOpenTemplateModal);

      const templateSync = document.getElementById('wcTemplateSyncBtn');
      if (templateSync) templateSync.addEventListener('click', () => wcNotify('success', wcTranslate('whatsapp_cloud.notification_templates_synced', 'Templates synced')));

      const openInbox = document.getElementById('wcOpenInboxBtn');
      if (openInbox) openInbox.addEventListener('click', () => {
        if (typeof navigateTo === 'function') {
          navigateTo('conversations');
        }
      });

      document.querySelectorAll('.wc-account-select').forEach(select => {
        select.addEventListener('change', event => {
          if (event.target.value) {
            wcSetActiveAccount(event.target.value);
            wcNotify('success', wcTranslate('whatsapp_cloud.notification_account_selected', 'Account selected'));
          }
        });
      });

      const connectionForm = document.getElementById('wcConnectionForm');
      if (connectionForm) {
        connectionForm.addEventListener('submit', event => {
          event.preventDefault();
          const active = wcState.accounts.find(acc => acc.id === wcState.activeAccountId);
          if (active) {
            active.status = 'connected';
            wcSaveAccounts();
            wcRenderAccounts();
            wcRenderAccountSelectors();
          }
          wcNotify('success', wcTranslate('whatsapp_cloud.notification_connection_saved', 'Connection saved'));
        });
      }

      const testBtn = document.getElementById('wcTestConnectionBtn');
      if (testBtn) testBtn.addEventListener('click', () => wcNotify('success', wcTranslate('whatsapp_cloud.notification_connection_tested', 'Connection test queued')));

      const rotateBtn = document.getElementById('wcRotateTokenBtn');
      if (rotateBtn) rotateBtn.addEventListener('click', () => wcNotify('success', wcTranslate('whatsapp_cloud.notification_token_rotated', 'Token rotation requested')));

      const refreshBtn = document.getElementById('wcRefreshAccounts');
      if (refreshBtn) refreshBtn.addEventListener('click', () => {
        wcLoadAccounts();
        wcRenderAccounts();
        wcRenderAccountSelectors();
        wcNotify('success', wcTranslate('whatsapp_cloud.notification_accounts_refreshed', 'Accounts refreshed'));
      });
    }

    function initWhatsAppCloudPage() {
      const page = document.getElementById('whatsapp-cloud-page');
      if (!page || page.dataset.initialized === 'true') return;
      page.dataset.initialized = 'true';
      wcLoadAccounts();
      wcRenderAccounts();
      wcRenderAccountSelectors();
      wcInitTabs();
      wcInitEvents();
    }