/**
 * Invoices & Quotes Management
 * Multi-tenant admin interface with tabs support
 */

let currentInvoices = [];
let searchTimeout = null;
let currentInvoiceItems = [];
let currentTab = 'active';
let tabCounts = { active: 0, archived: 0, disabled: 0 };

/**
 * Show custom alert modal
 */
function showAlert(message, type = 'info') {
  const modal = document.createElement('div');
  modal.className = 'modal active';
  modal.style.zIndex = '10001';
  const bgColor = type === 'error' ? '#dc3545' : type === 'success' ? '#28a745' : '#00a149';
  const icon = type === 'error' ? '⚠️' : type === 'success' ? '✅' : 'ℹ️';
  const title = type === 'error' ? 'Error' : type === 'success' ? 'Success' : 'Information';
  
  modal.innerHTML = `
    <div class="modal-content" style="max-width: 400px;">
      <div class="modal-header" style="background: ${bgColor};">
        <h3 style="color: white; margin: 0;">${icon} <span data-i18n="common.${type}">${title}</span></h3>
      </div>
      <div class="modal-body">
        <p style="margin: 20px 0; font-size: 15px;">${message}</p>
      </div>
      <div class="modal-footer" style="text-align: right; padding: 15px; border-top: 1px solid #ddd;">
        <button class="btn btn-primary" onclick="this.closest('.modal').remove()" data-i18n="common.ok">OK</button>
      </div>
    </div>
  `;
  document.body.appendChild(modal);
}

/**
 * Show notification (alias for showAlert)
 */
function showNotification(message, type = 'info') {
  showAlert(message, type);
}

/**
 * Show custom confirm modal
 */
function showConfirm(message, onConfirm, onCancel = null) {
  const modal = document.createElement('div');
  modal.className = 'modal active';
  modal.style.zIndex = '10001';
  modal.innerHTML = `
    <div class="modal-content" style="max-width: 450px;">
      <div class="modal-header" style="background: #00a149;">
        <h3 style="color: white; margin: 0;">🤔 <span data-i18n="common.confirm">Confirm Action</span></h3>
      </div>
      <div class="modal-body">
        <p style="margin: 20px 0; font-size: 15px;">${message}</p>
      </div>
      <div class="modal-footer" style="text-align: right; padding: 15px; border-top: 1px solid #ddd; display: flex; gap: 10px; justify-content: flex-end;">
        <button class="btn btn-secondary" onclick="this.closest('.modal').remove(); ${onCancel ? 'window.invoiceConfirmCancel()' : ''}" data-i18n="common.cancel">Cancel</button>
        <button class="btn btn-primary" onclick="this.closest('.modal').remove(); window.invoiceConfirmCallback()" data-i18n="common.ok">OK</button>
      </div>
    </div>
  `;
  document.body.appendChild(modal);
  window.invoiceConfirmCallback = onConfirm;
  if (onCancel) window.invoiceConfirmCancel = onCancel;
}

/**
 * Initialize invoices page
 */
function initInvoicesPage() {
  renderTabs();
  loadInvoices();
}

/**
 * Render tabs
 */
function renderTabs() {
  const tabsContainer = document.getElementById('invoicesTabs');
  if (!tabsContainer) return;
  
  tabsContainer.innerHTML = `
    <div class="tabs-container" style="display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid #e0e0e0; padding-bottom: 10px;">
      <button class="tab-btn ${currentTab === 'active' ? 'active' : ''}" onclick="switchTab('active')" data-i18n="invoices.tab_active">
        📋 Active <span class="tab-count">(${tabCounts.active})</span>
      </button>
      <button class="tab-btn ${currentTab === 'archived' ? 'active' : ''}" onclick="switchTab('archived')" data-i18n="invoices.tab_archived">
        📦 Archived <span class="tab-count">(${tabCounts.archived})</span>
      </button>
      <button class="tab-btn ${currentTab === 'disabled' ? 'active' : ''}" onclick="switchTab('disabled')" data-i18n="invoices.tab_disabled">
        🚫 Disabled <span class="tab-count">(${tabCounts.disabled})</span>
      </button>
    </div>
  `;
}

/**
 * Switch tab
 */
function switchTab(tab) {
  currentTab = tab;
  renderTabs();
  loadInvoices();
}

/**
 * Load invoices list
 */
async function loadInvoices() {
  const type = document.getElementById('invoiceTypeFilter')?.value || '';
  const status = document.getElementById('invoiceStatusFilter')?.value || '';
  const search = document.getElementById('invoiceSearchInput')?.value || '';

  try {
    const params = new URLSearchParams();
    params.append('tab', currentTab);
    if (type) params.append('type', type);
    if (status && currentTab === 'active') params.append('status', status);
    if (search) params.append('search', search);

    const response = await fetch(`/api/invoices/admin?${params.toString()}`, {
      headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
    });

    const data = await response.json();

    if (data.success) {
      currentInvoices = data.invoices;
      if (data.tabCounts) {
        tabCounts = data.tabCounts;
        renderTabs();
      }
      renderInvoicesList(data.invoices);
    } else {
      showNotification(data.error || 'Failed to load invoices', 'error');
    }
  } catch (error) {
    console.error('Error loading invoices:', error);
    showNotification('Failed to load invoices', 'error');
  }
}

/**
 * Render invoices list
 */
function renderInvoicesList(invoices) {
  const container = document.getElementById('invoicesContainer');
  
  if (!invoices || invoices.length === 0) {
    const emptyMessages = {
      active: 'No active invoices found',
      archived: 'No archived invoices',
      disabled: 'No disabled invoices'
    };
    container.innerHTML = `<p style="text-align: center; padding: 40px; color: #999;" data-i18n="invoices.empty_${currentTab}">${emptyMessages[currentTab]}</p>`;
    return;
  }

  const table = `
    <table class="data-table">
      <thead>
        <tr>
          <th data-i18n="invoices.number">Number</th>
          <th data-i18n="invoices.type">Type</th>
          <th data-i18n="invoices.client">Client</th>
          <th data-i18n="invoices.title">Title</th>
          <th data-i18n="invoices.amount">Amount</th>
          <th data-i18n="invoices.status">Status</th>
          <th data-i18n="invoices.date">Date</th>
          <th data-i18n="invoices.actions">Actions</th>
        </tr>
      </thead>
      <tbody>
        ${invoices.map(inv => renderInvoiceRow(inv)).join('')}
      </tbody>
    </table>
  `;

  container.innerHTML = table;
}

/**
 * Render single invoice row
 */
function renderInvoiceRow(inv) {
  const isRejected = inv.status === 'rejected';
  const isArchived = inv.status === 'archived';
  const isDisabled = inv.is_active === 0 || inv.is_active === false;
  
  let actions = `
    <button class="btn-icon" onclick="viewInvoice(${inv.id})" title="View">👁️</button>
    <button class="btn-icon" onclick="copyInvoiceLink('${inv.invoice_number}')" title="Copy Link">🔗</button>
  `;
  
  if (currentTab === 'active') {
    actions += `
      <button class="btn-icon" onclick="sendInvoice(${inv.id})" title="Send via WhatsApp">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="#25D366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/></svg>
      </button>
    `;
    
    if (inv.type === 'quote' && inv.status === 'accepted') {
      actions += `<button class="btn-icon" onclick="convertToInvoice(${inv.id})" title="Convert to Invoice">🔄</button>`;
    }
    
    if (isRejected) {
      actions += `<button class="btn-icon" onclick="handleRejection(${inv.id})" title="Handle Rejection">⚠️</button>`;
    }
    
    actions += `
      <button class="btn-icon" onclick="archiveInvoice(${inv.id})" title="Archive">📦</button>
      <button class="btn-icon" onclick="toggleInvoiceActive(${inv.id}, false)" title="Disable">🚫</button>
      <button class="btn-icon btn-delete" onclick="deleteInvoice(${inv.id})" title="Delete">🗑️</button>
    `;
  } else if (currentTab === 'archived') {
    actions += `
      <button class="btn-icon" onclick="reactivateInvoice(${inv.id})" title="Reactivate">♻️</button>
      <button class="btn-icon" onclick="deleteInvoice(${inv.id})" title="Delete Permanently">🗑️</button>
    `;
  } else if (currentTab === 'disabled') {
    actions += `
      <button class="btn-icon" onclick="toggleInvoiceActive(${inv.id}, true)" title="Enable">✅</button>
      <button class="btn-icon" onclick="deleteInvoice(${inv.id})" title="Delete Permanently">🗑️</button>
    `;
  }
  
  return `
    <tr class="${isRejected ? 'row-rejected' : ''} ${isDisabled ? 'row-disabled' : ''}">
      <td><strong>${inv.invoice_number}</strong></td>
      <td>${inv.type === 'quote' ? '📋 Quote' : '📄 Invoice'}</td>
      <td>${inv.client_name}<br><small>${inv.client_email}</small></td>
      <td>${inv.title}</td>
      <td><strong>${formatCurrency(inv.total_amount, inv.currency)}</strong></td>
      <td><span class="status-badge status-${inv.status}">${inv.status}</span></td>
      <td>${new Date(inv.created_at).toLocaleDateString()}</td>
      <td>${actions}</td>
    </tr>
  `;
}


/**
 * Show create invoice modal
 */
async function showCreateInvoiceModal() {
  let defaultCurrency = 'USD';
  try {
    const response = await fetch('/api/public/default-currency');
    const data = await response.json();
    defaultCurrency = data?.data?.code || defaultCurrency;
  } catch (e) {}
  try {
    const res = await api.get('/plan/current');
    defaultCurrency = res.data?.currency || res.data?.data?.currency || defaultCurrency;
  } catch (e) {}
  const modal = document.createElement('div');
  modal.className = 'modal active';
  modal.id = 'createInvoiceModal';
  modal.innerHTML = `
    <div class="modal-content" style="max-width: 900px; max-height: 90vh; overflow-y: auto;">
      <div class="modal-header">
        <h2 data-i18n="invoices.create_title">Create New Invoice/Quote</h2>
        <button class="close-btn" onclick="closeModal('createInvoiceModal')">&times;</button>
      </div>
      <div class="modal-body">
        <form id="createInvoiceForm" onsubmit="submitInvoice(event)">
          <div class="form-row">
            <div class="form-group">
              <label data-i18n="invoices.currency">Currency *</label>
              <select id="invoiceCurrency" required>
                <option value="USD" ${defaultCurrency==='USD'?'selected':''}>USD ($)</option>
                <option value="BRL" ${defaultCurrency==='BRL'?'selected':''}>BRL (R$)</option>
                <option value="EUR" ${defaultCurrency==='EUR'?'selected':''}>EUR (€)</option>
                <option value="GBP" ${defaultCurrency==='GBP'?'selected':''}>GBP (£)</option>
              </select>
            </div>
            <div class="form-group">
              <label data-i18n="invoices.type">Type *</label>
              <select id="invoiceType" required>
                <option value="invoice" data-i18n="invoices.type_invoice">Invoice</option>
                <option value="quote" data-i18n="invoices.type_quote">Quote</option>
              </select>
            </div>
          </div>

          <h3 style="margin-top: 20px; margin-bottom: 15px;" data-i18n="invoices.client_info">Client Information</h3>
          <div class="form-row">
            <div class="form-group">
              <label data-i18n="invoices.client_name">Client Name *</label>
              <input type="text" id="clientName" required>
            </div>
            <div class="form-group">
              <label data-i18n="invoices.client_email">Email * (used as password)</label>
              <input type="email" id="clientEmail" required>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label data-i18n="invoices.client_phone">Phone (with country code) *</label>
              <input type="text" id="clientPhone" required>
            </div>
            <div class="form-group">
              <label data-i18n="invoices.client_company">Company Name</label>
              <input type="text" id="clientCompany">
            </div>
          </div>

          <h3 style="margin-top: 20px; margin-bottom: 15px;" data-i18n="invoices.details">Invoice Details</h3>
          <div class="form-group">
            <label data-i18n="invoices.title_field">Title *</label>
            <input type="text" id="invoiceTitle" required>
          </div>
          <div class="form-group">
            <label data-i18n="invoices.description">Description</label>
            <textarea id="invoiceDescription" rows="3"></textarea>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label data-i18n="invoices.due_date">Due Date</label>
              <input type="date" id="invoiceDueDate">
            </div>
          </div>

          <div class="form-group" style="margin-top: 15px;">
            <label data-i18n="invoices.payment_methods_allowed">Allowed Payment Methods</label>
            <p style="font-size: 12px; color: #666; margin-bottom: 10px;" data-i18n="invoices.payment_methods_help">Select which payment methods the client can use to pay this invoice.</p>
            <div class="payment-methods-toggles" style="display: flex; flex-wrap: wrap; gap: 20px;">
              <div style="display: flex; align-items: center; gap: 8px;">
                <label class="toggle-switch">
                  <input type="checkbox" class="payment-method-toggle" value="stripe" checked>
                  <span class="toggle-slider"></span>
                </label>
                <span>💳 Stripe</span>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <label class="toggle-switch">
                  <input type="checkbox" class="payment-method-toggle" value="paypal">
                  <span class="toggle-slider"></span>
                </label>
                <span>🅿️ PayPal</span>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <label class="toggle-switch">
                  <input type="checkbox" class="payment-method-toggle" value="bank_transfer">
                  <span class="toggle-slider"></span>
                </label>
                <span data-i18n="invoices.bank_transfer">🏦 Bank Transfer</span>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <label class="toggle-switch">
                  <input type="checkbox" class="payment-method-toggle" value="cash">
                  <span class="toggle-slider"></span>
                </label>
                <span data-i18n="invoices.cash">💵 Cash</span>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <label class="toggle-switch">
                  <input type="checkbox" class="payment-method-toggle" value="pix">
                  <span class="toggle-slider"></span>
                </label>
                <span>📱 PIX</span>
              </div>
            </div>
          </div>

          <div class="invoice-items-section">
            <h4 data-i18n="invoices.items">Items</h4>
            <div id="itemsList"></div>
            <button type="button" class="btn-add-item" onclick="addInvoiceItem()" data-i18n="invoices.add_item">+ Add Item</button>
          </div>

          <div class="form-row" style="margin-top: 20px;">
            <div class="form-group invoice-tax-section">
              <label data-i18n="invoices.tax_rate">Tax Rate (%)</label>
              <input type="number" id="invoiceTaxRate" value="0" min="0" max="100" step="0.01" onchange="calculateInvoiceTotal()">
            </div>
            <div class="form-group">
              <label data-i18n="invoices.discount_type">Discount Type</label>
              <select id="invoiceDiscountType" onchange="calculateInvoiceTotal()">
                <option value="fixed" data-i18n="invoices.fixed">Fixed Amount</option>
                <option value="percentage" data-i18n="invoices.percentage">Percentage</option>
              </select>
            </div>
            <div class="form-group">
              <label data-i18n="invoices.discount_value">Discount Value</label>
              <input type="number" id="invoiceDiscountValue" value="0" min="0" step="0.01" onchange="calculateInvoiceTotal()">
            </div>
          </div>

          <div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
              <span data-i18n="invoices.subtotal">Subtotal:</span>
              <strong id="displaySubtotal">$0.00</strong>
            </div>
            <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
              <span data-i18n="invoices.tax">Tax:</span>
              <strong id="displayTax">$0.00</strong>
            </div>
            <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
              <span data-i18n="invoices.discount">Discount:</span>
              <strong id="displayDiscount">$0.00</strong>
            </div>
            <div style="display: flex; justify-content: space-between; font-size: 18px; padding-top: 10px; border-top: 2px solid #ddd;">
              <span data-i18n="invoices.total">Total:</span>
              <strong id="displayTotal" style="color: #00a149;">$0.00</strong>
            </div>
          </div>

          <div class="form-actions" style="margin-top: 30px;">
            <button type="button" class="btn btn-secondary" onclick="closeModal('createInvoiceModal')" data-i18n="common.cancel">Cancel</button>
            <button type="submit" class="btn btn-primary" data-i18n="common.create">Create</button>
          </div>
        </form>
      </div>
    </div>
  `;

  document.body.appendChild(modal);
  currentInvoiceItems = [];
  addInvoiceItem();
}

/**
 * Add invoice item
 */
function addInvoiceItem() {
  const itemId = Date.now();
  currentInvoiceItems.push({ id: itemId, description: '', quantity: 1, unit_price: 0 });
  
  const itemsList = document.getElementById('itemsList');
  const itemDiv = document.createElement('div');
  itemDiv.className = 'invoice-items-grid';
  itemDiv.id = `item-${itemId}`;
  itemDiv.innerHTML = `
    <div>
      <label data-i18n="invoices.item_description">Description</label>
      <input type="text" data-item-id="${itemId}" data-field="description" onchange="updateInvoiceItem(${itemId})" required>
    </div>
    <div>
      <label data-i18n="invoices.item_quantity">Quantity</label>
      <input type="number" data-item-id="${itemId}" data-field="quantity" value="1" min="1" onchange="updateInvoiceItem(${itemId})" required>
    </div>
    <div>
      <label data-i18n="invoices.item_price">Unit Price</label>
      <input type="number" data-item-id="${itemId}" data-field="unit_price" value="0" min="0" step="0.01" onchange="updateInvoiceItem(${itemId})" required>
    </div>
    <div>
      <label data-i18n="invoices.item_total">Total</label>
      <input type="text" id="item-total-${itemId}" value="$0.00" readonly>
    </div>
    <button type="button" class="btn-remove-item" onclick="removeInvoiceItem(${itemId})">×</button>
  `;
  
  itemsList.appendChild(itemDiv);
}

/**
 * Update invoice item
 */
function updateInvoiceItem(itemId) {
  const item = currentInvoiceItems.find(i => i.id === itemId);
  if (!item) return;

  const inputs = document.querySelectorAll(`[data-item-id="${itemId}"]`);
  inputs.forEach(input => {
    const field = input.getAttribute('data-field');
    item[field] = input.value;
  });

  const total = parseFloat(item.quantity || 0) * parseFloat(item.unit_price || 0);
  const currency = document.getElementById('invoiceCurrency').value;
  document.getElementById(`item-total-${itemId}`).value = formatCurrency(total, currency);
  calculateInvoiceTotal();
}

/**
 * Remove invoice item
 */
function removeInvoiceItem(itemId) {
  if (currentInvoiceItems.length <= 1) {
    showAlert('At least one item is required', 'error');
    return;
  }
  currentInvoiceItems = currentInvoiceItems.filter(i => i.id !== itemId);
  document.getElementById(`item-${itemId}`).remove();
  calculateInvoiceTotal();
}

/**
 * Calculate invoice total
 */
function calculateInvoiceTotal() {
  const currency = document.getElementById('invoiceCurrency').value;
  const taxRate = parseFloat(document.getElementById('invoiceTaxRate').value || 0);
  const discountType = document.getElementById('invoiceDiscountType').value;
  const discountValue = parseFloat(document.getElementById('invoiceDiscountValue').value || 0);

  const subtotal = currentInvoiceItems.reduce((sum, item) => {
    return sum + (parseFloat(item.quantity || 0) * parseFloat(item.unit_price || 0));
  }, 0);

  const taxAmount = (subtotal * taxRate) / 100;
  const discountAmount = discountType === 'percentage' ? (subtotal * discountValue) / 100 : discountValue;
  const total = subtotal + taxAmount - discountAmount;

  document.getElementById('displaySubtotal').textContent = formatCurrency(subtotal, currency);
  document.getElementById('displayTax').textContent = formatCurrency(taxAmount, currency);
  document.getElementById('displayDiscount').textContent = formatCurrency(discountAmount, currency);
  document.getElementById('displayTotal').textContent = formatCurrency(total, currency);
}

/**
 * Submit invoice
 */
async function submitInvoice(event) {
  event.preventDefault();

  if (currentInvoiceItems.length === 0) {
    showAlert('Please add at least one item', 'error');
    return;
  }

  // Get selected payment methods
  const selectedPaymentMethods = [];
  document.querySelectorAll('.payment-method-toggle:checked').forEach(checkbox => {
    selectedPaymentMethods.push(checkbox.value);
  });

  if (selectedPaymentMethods.length === 0) {
    showAlert('Please select at least one payment method', 'error');
    return;
  }

  const invoiceData = {
    type: document.getElementById('invoiceType').value,
    title: document.getElementById('invoiceTitle').value,
    description: document.getElementById('invoiceDescription').value,
    currency: document.getElementById('invoiceCurrency').value,
    tax_rate: parseFloat(document.getElementById('invoiceTaxRate').value || 0),
    discount_type: document.getElementById('invoiceDiscountType').value,
    discount_value: parseFloat(document.getElementById('invoiceDiscountValue').value || 0),
    allowed_payment_methods: selectedPaymentMethods,
    due_date: document.getElementById('invoiceDueDate').value || null,
    client: {
      name: document.getElementById('clientName').value,
      email: document.getElementById('clientEmail').value,
      phone: document.getElementById('clientPhone').value,
      company_name: document.getElementById('clientCompany').value || null
    },
    items: currentInvoiceItems.map(item => ({
      description: item.description,
      quantity: parseFloat(item.quantity),
      unit_price: parseFloat(item.unit_price)
    }))
  };

  try {
    const response = await fetch('/api/invoices/admin', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(invoiceData)
    });

    const data = await response.json();

    if (data.success) {
      showNotification(`${invoiceData.type === 'quote' ? 'Quote' : 'Invoice'} created successfully!`, 'success');
      closeModal('createInvoiceModal');
      loadInvoices();
    } else {
      showNotification(data.error || 'Failed to create invoice', 'error');
    }
  } catch (error) {
    console.error('Error creating invoice:', error);
    showNotification('Failed to create invoice', 'error');
  }
}

/**
 * View invoice details
 */
async function viewInvoice(id) {
  try {
    const response = await fetch(`/api/invoices/admin/${id}`, {
      headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
    });
    const data = await response.json();

    if (data.success) {
      showInvoiceDetailsModal(data.invoice);
    } else {
      showNotification(data.error || 'Failed to load invoice', 'error');
    }
  } catch (error) {
    console.error('Error loading invoice:', error);
    showNotification('Failed to load invoice', 'error');
  }
}

/**
 * Show invoice details modal
 */
function showInvoiceDetailsModal(invoice) {
  const isRejected = invoice.status === 'rejected';
  
  const modal = document.createElement('div');
  modal.className = 'modal active';
  modal.id = 'invoiceDetailsModal';
  modal.innerHTML = `
    <div class="modal-content" style="max-width: 800px; max-height: 90vh; overflow-y: auto;">
      <div class="modal-header">
        <h2>${invoice.invoice_number} - ${invoice.title}</h2>
        <button class="close-btn" onclick="closeModal('invoiceDetailsModal')">&times;</button>
      </div>
      <div class="modal-body">
        <div style="margin-bottom: 20px;">
          <span class="status-badge status-${invoice.status}">${invoice.status}</span>
          <span style="margin-left: 10px;">${invoice.type === 'quote' ? '📋 Quote' : '📄 Invoice'}</span>
        </div>

        ${isRejected && invoice.rejection_reason ? `
          <div style="background: #f8d7da; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
            <h4 style="color: #721c24; margin-bottom: 10px;">⚠️ <span data-i18n="invoices.rejection_reason">Rejection Reason</span>:</h4>
            <p style="color: #721c24;">"${invoice.rejection_reason}"</p>
          </div>
        ` : ''}

        <h3 data-i18n="invoices.client">Client</h3>
        <p><strong>${invoice.client_name}</strong><br>
        ${invoice.client_email}<br>
        ${invoice.client_phone}</p>

        <h3 style="margin-top: 20px;" data-i18n="invoices.items">Items</h3>
        <table class="data-table">
          <thead>
            <tr>
              <th data-i18n="invoices.item_description">Description</th>
              <th data-i18n="invoices.item_quantity">Qty</th>
              <th data-i18n="invoices.item_price">Price</th>
              <th data-i18n="invoices.item_total">Total</th>
            </tr>
          </thead>
          <tbody>
            ${invoice.items.map(item => `
              <tr>
                <td>${item.description}</td>
                <td>${item.quantity}</td>
                <td>${formatCurrency(item.unit_price, invoice.currency)}</td>
                <td>${formatCurrency(item.total_price, invoice.currency)}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>

        <div style="margin-top: 20px; text-align: right;">
          <p><span data-i18n="invoices.subtotal">Subtotal</span>: ${formatCurrency(invoice.subtotal, invoice.currency)}</p>
          <p><span data-i18n="invoices.tax">Tax</span>: ${formatCurrency(invoice.tax_amount, invoice.currency)}</p>
          <p><span data-i18n="invoices.discount">Discount</span>: ${formatCurrency(invoice.discount_amount, invoice.currency)}</p>
          <p style="font-size: 20px;"><strong><span data-i18n="invoices.total">Total</span>: ${formatCurrency(invoice.total_amount, invoice.currency)}</strong></p>
        </div>

        <div class="form-actions" style="margin-top: 30px;">
          <button class="btn btn-secondary" onclick="closeModal('invoiceDetailsModal')" data-i18n="common.close">Close</button>
          ${invoice.status === 'draft' ? `<button class="btn btn-primary" onclick="sendInvoice(${invoice.id})" data-i18n="invoices.send">Send</button>` : ''}
          ${isRejected ? `<button class="btn btn-primary" onclick="showRespondModal(${invoice.id})" data-i18n="invoices.respond">Respond</button>` : ''}
        </div>
      </div>
    </div>
  `;

  document.body.appendChild(modal);
}


/**
 * Show respond to rejection modal
 */
function showRespondModal(invoiceId) {
  closeModal('invoiceDetailsModal');
  
  const modal = document.createElement('div');
  modal.className = 'modal active';
  modal.id = 'respondModal';
  modal.innerHTML = `
    <div class="modal-content" style="max-width: 500px;">
      <div class="modal-header">
        <h2 data-i18n="invoices.respond_title">Respond to Rejection</h2>
        <button class="close-btn" onclick="closeModal('respondModal')">&times;</button>
      </div>
      <div class="modal-body">
        <p data-i18n="invoices.respond_prompt">Write your response to the client. The invoice will be sent back for their review.</p>
        <textarea id="adminResponse" rows="5" style="width: 100%; margin-top: 15px; padding: 12px; border: 1px solid #ddd; border-radius: 8px;" placeholder="Your response..."></textarea>
        <div class="form-actions" style="margin-top: 20px;">
          <button class="btn btn-secondary" onclick="closeModal('respondModal')" data-i18n="common.cancel">Cancel</button>
          <button class="btn btn-primary" onclick="submitResponse(${invoiceId})" data-i18n="invoices.send_response">Send Response</button>
        </div>
      </div>
    </div>
  `;
  document.body.appendChild(modal);
}

/**
 * Submit response to rejection
 */
async function submitResponse(invoiceId) {
  const response = document.getElementById('adminResponse').value.trim();
  if (response.length < 10) {
    showAlert('Response must be at least 10 characters', 'error');
    return;
  }

  try {
    const res = await fetch(`/api/invoices/admin/${invoiceId}/respond`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({ response })
    });

    const data = await res.json();

    if (data.success) {
      showNotification('Response sent successfully!', 'success');
      closeModal('respondModal');
      loadInvoices();
    } else {
      showNotification(data.error || 'Failed to send response', 'error');
    }
  } catch (error) {
    console.error('Error sending response:', error);
    showNotification('Failed to send response', 'error');
  }
}

/**
 * Send invoice via WhatsApp
 */
async function sendInvoice(id) {
  const invoice = currentInvoices.find(inv => inv.id === id);
  if (!invoice) {
    showNotification('Invoice not found', 'error');
    return;
  }
  showSendWhatsAppModal(invoice);
}

/**
 * Show send via WhatsApp modal
 */
function showSendWhatsAppModal(invoice) {
  // Get base URL for link placeholder
  const baseUrl = window.location.origin;
  const invoiceLink = `${baseUrl}/invoice/${invoice.invoice_number}`;
  
  // Mask email for password hint
  const email = invoice.client_email || '';
  const maskedEmail = maskEmail(email);
  
  // Use built-in template immediately
  const invoiceType = invoice.type === 'quote' ? 'Quote' : 'Invoice';
  const defaultMessage = `Hello ${invoice.client_name}! 👋

Your ${invoiceType} *${invoice.invoice_number}* is ready.

📋 *${invoice.title}*
💰 Total: ${formatCurrency(invoice.total_amount, invoice.currency)}

🔗 Click here to view: {{LINK}}
🔐 Your password is the email: {{PASSWORD}}

Thank you for your business! 🙏`;

  const modal = document.createElement('div');
  modal.className = 'modal active';
  modal.id = 'sendWhatsAppModal';
  modal.innerHTML = `
    <div class="modal-content" style="max-width: 700px;">
      <div class="modal-header">
        <h2 data-i18n="invoices.send_whatsapp">Send via WhatsApp</h2>
        <button class="close-btn" onclick="closeModal('sendWhatsAppModal')">&times;</button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label data-i18n="invoices.select_instance">Select WhatsApp Instance *</label>
          <select id="invoiceWhatsAppInstance" class="form-control" required>
            <option value="" data-i18n="invoices.loading_instances">Loading instances...</option>
          </select>
          <small style="color: #666; display: block; margin-top: 5px;" data-i18n="invoices.instance_required">Please select a connected WhatsApp instance to send the invoice</small>
        </div>

        <div class="form-group" style="margin-top: 20px;">
          <label>
            <input type="radio" name="phoneOption" value="client" checked onchange="togglePhoneSelection()">
            <span data-i18n="invoices.use_client_phone">Use Client Phone</span>
          </label>
          <div style="margin-left: 25px; margin-top: 8px; color: #666;">
            <strong>${invoice.client_name}</strong><br>
            📱 ${invoice.client_phone}
          </div>
        </div>

        <div style="margin: 20px 0; text-align: center; color: #999;">— OR —</div>

        <div class="form-group">
          <label>
            <input type="radio" name="phoneOption" value="manual" onchange="togglePhoneSelection()">
            <span data-i18n="invoices.custom_phone">Custom Phone</span>
          </label>
          <div id="manualPhoneSection" style="margin-left: 25px; margin-top: 10px; display: none;">
            <input type="text" id="customPhone" class="form-control" placeholder="+1234567890">
          </div>
        </div>

        <div class="form-group" style="margin-top: 25px;">
          <label style="display: flex; justify-content: space-between; align-items: center;">
            <span data-i18n="invoices.message_template">Message Template</span>
            <button type="button" class="btn btn-sm" style="padding: 4px 12px; font-size: 12px;" onclick="resetMessageTemplate()" data-i18n="invoices.reset_template">Reset to Default</button>
          </label>
          
          <!-- Formatting Toolbar -->
          <div class="message-editor-toolbar" style="display: flex; gap: 5px; margin-bottom: 8px; padding: 8px; background: #f8f9fa; border-radius: 6px 6px 0 0; border: 1px solid #ddd; border-bottom: none;">
            <button type="button" class="editor-btn" onclick="formatText('bold')" title="Bold (*text*)" data-i18n-title="invoices.format_bold">
              <strong>B</strong>
            </button>
            <button type="button" class="editor-btn" onclick="formatText('italic')" title="Italic (_text_)" data-i18n-title="invoices.format_italic">
              <em>I</em>
            </button>
            <button type="button" class="editor-btn" onclick="formatText('strikethrough')" title="Strikethrough (~text~)" data-i18n-title="invoices.format_strike">
              <s>S</s>
            </button>
            <button type="button" class="editor-btn" onclick="formatText('monospace')" title="Monospace (\`\`\`text\`\`\`)" data-i18n-title="invoices.format_mono">
              <code>M</code>
            </button>
            <div style="width: 1px; background: #ddd; margin: 0 5px;"></div>
            <button type="button" class="editor-btn" onclick="insertPlaceholder('{{LINK}}')" title="Insert Link" data-i18n-title="invoices.insert_link">
              🔗
            </button>
            <button type="button" class="editor-btn" onclick="insertPlaceholder('{{PASSWORD}}')" title="Insert Password Hint" data-i18n-title="invoices.insert_password">
              🔐
            </button>
            <button type="button" class="editor-btn" onclick="insertPlaceholder('{{CLIENT_NAME}}')" title="Insert Client Name" data-i18n-title="invoices.insert_client_name">
              👤
            </button>
            <button type="button" class="editor-btn" onclick="insertPlaceholder('{{INVOICE_NUMBER}}')" title="Insert Invoice Number" data-i18n-title="invoices.insert_invoice_number">
              #️⃣
            </button>
            <button type="button" class="editor-btn" onclick="insertPlaceholder('{{TOTAL}}')" title="Insert Total Amount" data-i18n-title="invoices.insert_total">
              💰
            </button>
          </div>
          
          <textarea id="whatsappMessageEditor" class="form-control" rows="8" style="font-family: monospace; border-radius: 0 0 6px 6px; resize: vertical;">${defaultMessage}</textarea>
          
          <div style="margin-top: 8px; padding: 10px; background: #e3f2fd; border-radius: 6px; font-size: 12px;">
            <strong data-i18n="invoices.placeholders_title">📌 Available Placeholders:</strong>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; margin-top: 8px;">
              <div><code>{{LINK}}</code> - <span data-i18n="invoices.placeholder_link">Invoice link</span></div>
              <div><code>{{PASSWORD}}</code> - <span data-i18n="invoices.placeholder_password">Masked email</span></div>
              <div><code>{{CLIENT_NAME}}</code> - <span data-i18n="invoices.placeholder_client_name">Client name</span></div>
              <div><code>{{INVOICE_NUMBER}}</code> - <span data-i18n="invoices.placeholder_invoice_number">Invoice number</span></div>
              <div><code>{{TOTAL}}</code> - <span data-i18n="invoices.placeholder_total">Total amount</span></div>
            </div>
            <div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid #90caf9;">
              <strong data-i18n="invoices.formatting_title">✨ Formatting:</strong>
              <span data-i18n="invoices.formatting_help">*bold* _italic_ ~strike~ \`\`\`mono\`\`\`</span>
            </div>
          </div>

          <!-- WhatsApp Preview -->
          <div style="margin-top: 15px;">
            <label style="font-weight: 600; margin-bottom: 8px; display: block;" data-i18n="invoices.whatsapp_preview">WhatsApp Preview</label>
            <div class="whatsapp-phone-mockup" style="max-width: 320px; margin: 0 auto; background: linear-gradient(145deg, #1a1a1a, #2d2d2d); border-radius: 25px; padding: 8px; box-shadow: 0 8px 32px rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.1);">
              <!-- Phone Screen -->
              <div style="background: #111b21; border-radius: 18px; overflow: hidden; position: relative; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.05);">
                <!-- WhatsApp Header -->
                <div style="background: linear-gradient(180deg, #202c33 0%, #1e2a31 100%); padding: 12px 16px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid #2a3942;">
                  <div style="width: 32px; height: 32px; border-radius: 50%; background: linear-gradient(135deg, #25d366, #128c7e); display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 14px; box-shadow: 0 2px 8px rgba(37, 211, 102, 0.3);">B</div>
                  <div style="flex: 1;">
                    <div style="color: #e9edef; font-size: 16px; font-weight: 500;" data-i18n="invoices.preview_contact_name">Business</div>
                    <div style="color: #8696a0; font-size: 13px;" data-i18n="invoices.preview_time_now">online</div>
                  </div>
                  <div style="color: #8696a0; cursor: pointer; padding: 4px; border-radius: 50%; transition: background-color 0.2s;">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M12 7a2 2 0 1 0-.001-4.001A2 2 0 0 0 12 7zm0 2a2 2 0 1 0-.001 3.999A2 2 0 0 0 12 9zm0 6a2 2 0 1 0-.001 3.999A2 2 0 0 0 12 15z"/>
                    </svg>
                  </div>
                </div>
                
                <!-- Chat Area -->
                <div style="background: linear-gradient(180deg, #0b141a 0%, #0a1014 100%); min-height: 400px; padding: 16px; position: relative; background-image: url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"40\" viewBox=\"0 0 40 40\"><defs><pattern id=\"a\" width=\"40\" height=\"40\" patternUnits=\"userSpaceOnUse\"><circle cx=\"20\" cy=\"20\" r=\"0.5\" fill=\"%23ffffff\" fill-opacity=\"0.02\"/></pattern></defs><rect width=\"100%25\" height=\"100%25\" fill=\"url(%23a)\"/></svg>');">
                  <!-- Message Bubble -->
                  <div style="display: flex; justify-content: flex-end; margin-bottom: 8px;">
                    <div style="background: linear-gradient(135deg, #005c4b, #004a3d); border-radius: 8px 8px 2px 8px; padding: 10px 14px; max-width: 85%; position: relative; box-shadow: 0 2px 8px rgba(0,0,0,0.3), 0 1px 0 rgba(255,255,255,0.05) inset;">
                      <div id="whatsappMessagePreview" style="color: #e9edef; font-size: 14px; line-height: 1.4; white-space: pre-wrap; word-wrap: break-word; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;"></div>
                      <div style="display: flex; align-items: center; justify-content: flex-end; gap: 4px; margin-top: 6px;">
                        <span style="color: #8696a0; font-size: 11px; font-weight: 400;" data-i18n="invoices.preview_time_now">now</span>
                        <svg width="16" height="11" viewBox="0 0 16 11" fill="none" style="margin-left: 2px;">
                          <path d="M11.071 0.929L5.657 6.343L4.243 4.929L3.172 6L5.657 8.485L12.142 2L11.071 0.929Z" fill="#53bdeb"/>
                          <path d="M15.071 0.929L9.657 6.343L8.243 4.929L7.172 6L9.657 8.485L16.142 2L15.071 0.929Z" fill="#53bdeb"/>
                        </svg>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- Input Area -->
                <div style="background: linear-gradient(180deg, #202c33 0%, #1e2a31 100%); padding: 8px 16px; display: flex; align-items: center; gap: 8px; border-top: 1px solid #2a3942;">
                  <div style="flex: 1; background: #2a3942; border-radius: 20px; padding: 10px 16px; color: #8696a0; font-size: 14px; border: 1px solid #3b4a54;">Type a message</div>
                  <div style="width: 36px; height: 36px; border-radius: 50%; background: linear-gradient(135deg, #00a884, #008f6f); display: flex; align-items: center; justify-content: center; cursor: pointer; transition: transform 0.2s; box-shadow: 0 2px 8px rgba(0, 168, 132, 0.3);">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
                      <path d="M1.101 21.757L23.8 12.028L1.101 2.3l.011 7.912 13.623 1.816-13.623 1.817-.011 7.912z"/>
                    </svg>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="form-actions" style="margin-top: 30px;">
          <button class="btn btn-secondary" onclick="closeModal('sendWhatsAppModal')" data-i18n="common.cancel">Cancel</button>
          <button class="btn btn-primary" id="sendWhatsAppBtn" onclick="confirmSendWhatsApp(${invoice.id})" data-i18n="invoices.send_now">Send Now</button>
        </div>
      </div>
    </div>
  `;
  document.body.appendChild(modal);
  
  // Store invoice data for later use
  window.currentInvoiceData = {
    id: invoice.id,
    client_name: invoice.client_name,
    client_email: invoice.client_email,
    invoice_number: invoice.invoice_number,
    total_amount: invoice.total_amount,
    currency: invoice.currency,
    type: invoice.type,
    title: invoice.title,
    link: invoiceLink,
    masked_email: maskedEmail
  };
  
  // Setup message editor immediately
  setTimeout(() => {
    setupMessageEditor();
  }, 100);
  
  // Load WhatsApp instances in background
  loadWhatsAppInstancesForInvoice();
  
  // Load custom default message in background (if exists)
  loadCustomDefaultMessage(invoice, invoiceType);
}

/**
 * Mask email for password hint
 */
function maskEmail(email) {
  if (!email || !email.includes('@')) return email;
  
  const [localPart, domain] = email.split('@');
  
  if (localPart.length <= 4) {
    // For very short emails, show first 2 chars
    return `${localPart.substring(0, 2)}***@${domain}`;
  }
  
  // Show first 2 and last 2 characters
  const firstTwo = localPart.substring(0, 2);
  const lastTwo = localPart.substring(localPart.length - 2);
  const maskedMiddle = '*'.repeat(Math.min(localPart.length - 4, 5));
  
  return `${firstTwo}${maskedMiddle}${lastTwo}@${domain}`;
}

/**
 * Setup message editor with live preview
 */
function setupMessageEditor() {
  const editor = document.getElementById('whatsappMessageEditor');
  const preview = document.getElementById('whatsappMessagePreview');
  
  if (!editor || !preview) return;
  
  // Update preview on input
  editor.addEventListener('input', updateMessagePreview);
  
  // Initial preview
  updateMessagePreview();
}

/**
 * Update message preview with placeholder replacement
 */
function updateMessagePreview() {
  const editor = document.getElementById('whatsappMessageEditor');
  const preview = document.getElementById('whatsappMessagePreview');
  
  if (!editor || !preview || !window.currentInvoiceData) {
    console.log('Preview update failed:', { 
      editor: !!editor, 
      preview: !!preview, 
      data: !!window.currentInvoiceData 
    });
    return;
  }
  
  let message = editor.value;
  const data = window.currentInvoiceData;
  
  // Replace placeholders
  message = message
    .replace(/\{\{LINK\}\}/g, data.link)
    .replace(/\{\{PASSWORD\}\}/g, data.masked_email)
    .replace(/\{\{CLIENT_NAME\}\}/g, data.client_name)
    .replace(/\{\{INVOICE_NUMBER\}\}/g, data.invoice_number)
    .replace(/\{\{TOTAL\}\}/g, formatCurrency(data.total_amount, data.currency));
  
  // Apply WhatsApp formatting for preview
  message = message
    .replace(/\*([^*]+)\*/g, '<strong>$1</strong>')  // Bold
    .replace(/_([^_]+)_/g, '<em>$1</em>')            // Italic
    .replace(/~([^~]+)~/g, '<s>$1</s>')              // Strikethrough
    .replace(/```([^`]+)```/g, '<code style="background: rgba(255,255,255,0.1); padding: 2px 4px; border-radius: 3px; font-family: monospace;">$1</code>'); // Monospace
  
  preview.innerHTML = message;
  console.log('Preview updated successfully');
}

/**
 * Format selected text
 */
function formatText(format) {
  const editor = document.getElementById('whatsappMessageEditor');
  if (!editor) return;
  
  const start = editor.selectionStart;
  const end = editor.selectionEnd;
  const selectedText = editor.value.substring(start, end);
  
  if (!selectedText) {
    alert('Please select text to format');
    return;
  }
  
  let formattedText = '';
  
  switch(format) {
    case 'bold':
      formattedText = `*${selectedText}*`;
      break;
    case 'italic':
      formattedText = `_${selectedText}_`;
      break;
    case 'strikethrough':
      formattedText = `~${selectedText}~`;
      break;
    case 'monospace':
      formattedText = `\`\`\`${selectedText}\`\`\``;
      break;
  }
  
  // Replace selected text
  editor.value = editor.value.substring(0, start) + formattedText + editor.value.substring(end);
  
  // Update cursor position
  const newPos = start + formattedText.length;
  editor.setSelectionRange(newPos, newPos);
  editor.focus();
  
  updateMessagePreview();
}

/**
 * Insert placeholder at cursor position
 */
function insertPlaceholder(placeholder) {
  const editor = document.getElementById('whatsappMessageEditor');
  if (!editor) return;
  
  const start = editor.selectionStart;
  const end = editor.selectionEnd;
  
  // Insert placeholder
  editor.value = editor.value.substring(0, start) + placeholder + editor.value.substring(end);
  
  // Update cursor position
  const newPos = start + placeholder.length;
  editor.setSelectionRange(newPos, newPos);
  editor.focus();
  
  updateMessagePreview();
}

/**
 * Reset message template to default
 */
function resetMessageTemplate() {
  if (!window.currentInvoiceData) return;
  
  const data = window.currentInvoiceData;
  const invoiceType = data.type === 'quote' ? 'Quote' : 'Invoice';
  
  const defaultMessage = `Hello ${data.client_name}! 👋

Your ${invoiceType} *${data.invoice_number}* is ready.

📋 *${data.title}*
💰 Total: {{TOTAL}}

🔗 Click here to view: {{LINK}}
🔐 Your password is the email: {{PASSWORD}}

Thank you for your business! 🙏`;
  
  const editor = document.getElementById('whatsappMessageEditor');
  if (editor) {
    editor.value = defaultMessage;
    updateMessagePreview();
  }
}

/**
 * Toggle phone selection mode
 */
function togglePhoneSelection() {
  const manualSection = document.getElementById('manualPhoneSection');
  const isManual = document.querySelector('input[name="phoneOption"]:checked').value === 'manual';
  manualSection.style.display = isManual ? 'block' : 'none';
}

/**
 * Load WhatsApp instances for invoice sending
 */
async function loadWhatsAppInstancesForInvoice() {
  try {
    const response = await fetch('/api/tenant/whatsapp/instances', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.ok) {
      const data = await response.json();
      const select = document.getElementById('invoiceWhatsAppInstance');
      if (select && data.success && data.data && data.data.instances) {
        const connectedInstances = data.data.instances.filter(inst => inst.status === 'connected');
        
        if (connectedInstances.length === 0) {
          select.innerHTML = `<option value="" data-i18n="invoices.no_connected_instances">No connected instances available</option>`;
          select.disabled = true;
          showNotification('No connected WhatsApp instances found. Please connect an instance first.', 'warning');
        } else {
          select.innerHTML = `<option value="" data-i18n="invoices.select_instance_option">Select an instance...</option>` +
            connectedInstances.map(instance => 
              `<option value="${instance.id}">${instance.instance_name}${instance.phone_number ? ' (' + instance.phone_number + ')' : ''}</option>`
            ).join('');
          select.disabled = false;
        }
      }
    }
  } catch (error) {
    console.error('Error loading WhatsApp instances:', error);
    const select = document.getElementById('invoiceWhatsAppInstance');
    if (select) {
      select.innerHTML = `<option value="">Error loading instances</option>`;
      select.disabled = true;
    }
  }
}

/**
 * Load custom default message in background
 */
async function loadCustomDefaultMessage(invoice, invoiceType) {
  try {
    const response = await fetch('/api/invoices/admin/default-message', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.ok) {
      const data = await response.json();
      const customMessage = data.default_message;
      
      if (customMessage) {
        // Replace placeholders in custom message
        const processedMessage = customMessage
          .replace(/\\n/g, '\n')  // Convert literal \n to actual line breaks
          .replace(/\{\{CLIENT_NAME\}\}/g, invoice.client_name)
          .replace(/\{\{INVOICE_NUMBER\}\}/g, invoice.invoice_number)
          .replace(/\{\{TITLE\}\}/g, invoice.title)
          .replace(/\{\{TYPE\}\}/g, invoiceType)
          .replace(/\{\{TOTAL\}\}/g, formatCurrency(invoice.total_amount, invoice.currency))
          .replace(/\{\{LINK\}\}/g, '{{LINK}}')
          .replace(/\{\{PASSWORD\}\}/g, '{{PASSWORD}}');
        
        // Update editor with custom message
        const editor = document.getElementById('whatsappMessageEditor');
        if (editor) {
          editor.value = processedMessage;
          updateMessagePreview();
        }
      }
    }
  } catch (error) {
    console.error('Error loading custom default message:', error);
    // Silently fail - default message is already loaded
  }
}

/**
 * Confirm and send invoice via WhatsApp
 */
async function confirmSendWhatsApp(invoiceId) {
  const instanceId = document.getElementById('invoiceWhatsAppInstance')?.value;
  const phoneOption = document.querySelector('input[name="phoneOption"]:checked').value;
  const sendBtn = document.getElementById('sendWhatsAppBtn');
  const customMessage = document.getElementById('whatsappMessageEditor')?.value;
  
  // Validate instance selection
  if (!instanceId) {
    showNotification('Please select a WhatsApp instance', 'error');
    return;
  }
  
  // Validate custom message
  if (!customMessage || customMessage.trim().length === 0) {
    showNotification('Please enter a message', 'error');
    return;
  }
  
  let requestBody = {
    instance_id: parseInt(instanceId),
    use_client_phone: phoneOption === 'client',
    custom_message: customMessage
  };

  if (phoneOption !== 'client') {
    const customPhone = document.getElementById('customPhone')?.value;
    if (!customPhone) {
      showNotification('Please enter a phone number', 'error');
      return;
    }
    requestBody.phone = customPhone;
  }

  sendBtn.disabled = true;
  sendBtn.textContent = 'Sending...';

  try {
    const response = await fetch(`/api/invoices/admin/${invoiceId}/send-whatsapp`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(requestBody)
    });

    const data = await response.json();

    if (data.success) {
      showNotification('Invoice sent successfully via WhatsApp!', 'success');
      closeModal('sendWhatsAppModal');
      loadInvoices();
    } else {
      showNotification(data.error || 'Failed to send invoice', 'error');
      sendBtn.disabled = false;
      sendBtn.textContent = 'Send Now';
    }
  } catch (error) {
    console.error('Error sending invoice:', error);
    showNotification('Failed to send invoice', 'error');
    sendBtn.disabled = false;
    sendBtn.textContent = 'Send Now';
  }
}

/**
 * Convert quote to invoice
 */
async function convertToInvoice(id) {
  showConfirm('Convert this quote to an invoice?', async () => {
    try {
      const response = await fetch(`/api/invoices/admin/${id}/convert-to-invoice`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
      });
      const data = await response.json();

      if (data.success) {
        showNotification('Quote converted to invoice!', 'success');
        loadInvoices();
      } else {
        showNotification(data.error || 'Failed to convert quote', 'error');
      }
    } catch (error) {
      console.error('Error converting quote:', error);
      showNotification('Failed to convert quote', 'error');
    }
  });
}

/**
 * Handle rejection
 */
function handleRejection(id) {
  const invoice = currentInvoices.find(inv => inv.id === id);
  if (!invoice) return;

  showConfirm(
    `<strong data-i18n="invoices.rejection_reason">Rejection reason</strong>: "${invoice.rejection_reason || 'No reason provided'}"<br><br>
     <span data-i18n="invoices.rejection_options">Click OK to archive, or Cancel to respond to the client.</span>`,
    () => finalizeRejection(id),
    () => showRespondModal(id)
  );
}

/**
 * Finalize rejection (archive)
 */
async function finalizeRejection(id) {
  try {
    const response = await fetch(`/api/invoices/admin/${id}/finalize-rejection`, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
    });
    const data = await response.json();

    if (data.success) {
      showNotification('Invoice archived', 'success');
      loadInvoices();
    } else {
      showNotification(data.error || 'Failed to archive', 'error');
    }
  } catch (error) {
    console.error('Error archiving:', error);
    showNotification('Failed to archive', 'error');
  }
}

/**
 * Archive invoice
 */
async function archiveInvoice(id) {
  showConfirm('Archive this invoice?', async () => {
    try {
      const response = await fetch(`/api/invoices/admin/${id}/archive`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
      });
      const data = await response.json();

      if (data.success) {
        showNotification('Invoice archived', 'success');
        loadInvoices();
      } else {
        showNotification(data.error || 'Failed to archive', 'error');
      }
    } catch (error) {
      console.error('Error archiving:', error);
      showNotification('Failed to archive', 'error');
    }
  });
}

/**
 * Toggle invoice active status
 */
async function toggleInvoiceActive(id, isActive) {
  const action = isActive ? 'enable' : 'disable';
  showConfirm(`${isActive ? 'Enable' : 'Disable'} this invoice?`, async () => {
    try {
      const response = await fetch(`/api/invoices/admin/${id}/toggle-active`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ is_active: isActive })
      });
      const data = await response.json();

      if (data.success) {
        showNotification(`Invoice ${isActive ? 'enabled' : 'disabled'}`, 'success');
        loadInvoices();
      } else {
        showNotification(data.error || `Failed to ${action}`, 'error');
      }
    } catch (error) {
      console.error(`Error ${action}ing:`, error);
      showNotification(`Failed to ${action}`, 'error');
    }
  });
}

/**
 * Reactivate invoice
 */
async function reactivateInvoice(id) {
  showConfirm('Reactivate this invoice?', async () => {
    try {
      const response = await fetch(`/api/invoices/admin/${id}/reactivate`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
      });
      const data = await response.json();

      if (data.success) {
        showNotification('Invoice reactivated', 'success');
        loadInvoices();
      } else {
        showNotification(data.error || 'Failed to reactivate', 'error');
      }
    } catch (error) {
      console.error('Error reactivating:', error);
      showNotification('Failed to reactivate', 'error');
    }
  });
}

/**
 * Delete invoice permanently
 */
async function deleteInvoice(id) {
  showConfirm('⚠️ Delete this invoice permanently? This action cannot be undone.', async () => {
    try {
      const response = await fetch(`/api/invoices/admin/${id}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
      });
      const data = await response.json();

      if (data.success) {
        showNotification('Invoice deleted', 'success');
        loadInvoices();
      } else {
        showNotification(data.error || 'Failed to delete', 'error');
      }
    } catch (error) {
      console.error('Error deleting:', error);
      showNotification('Failed to delete', 'error');
    }
  });
}

/**
 * Copy invoice public link
 */
function copyInvoiceLink(invoiceNumber) {
  const baseUrl = window.location.origin;
  const publicLink = `${baseUrl}/invoice/${invoiceNumber}`;
  
  navigator.clipboard.writeText(publicLink).then(() => {
    showNotification('Link copied to clipboard!', 'success');
  }).catch(() => {
    const textArea = document.createElement('textarea');
    textArea.value = publicLink;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    showNotification('Link copied to clipboard!', 'success');
  });
}

/**
 * Format currency
 */
function formatCurrency(amount, currency) {
  const symbols = { USD: '$', BRL: 'R$', EUR: '€', GBP: '£' };
  return `${symbols[currency] || currency} ${parseFloat(amount).toFixed(2)}`;
}

/**
 * Debounce search
 */
function debounceSearch() {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => loadInvoices(), 500);
}

/**
 * Close modal
 */
function closeModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) modal.remove();
}

// Initialize when page loads
if (typeof window !== 'undefined') {
  // Register page handler
  if (!window.pageHandlers) window.pageHandlers = {};
  window.pageHandlers.invoices = function() {
    console.log('Invoices handler called');
    // Check if feature is enabled before loading
    if (typeof checkFeatureEnabled === 'function') {
      checkFeatureEnabled('invoices').then(enabled => {
        if (enabled) {
          initInvoicesPage();
        }
      });
    } else {
      initInvoicesPage();
    }
  };

  window.initInvoicesPage = initInvoicesPage;
  window.loadInvoices = loadInvoices;
  window.switchTab = switchTab;
  window.showCreateInvoiceModal = showCreateInvoiceModal;
  window.addInvoiceItem = addInvoiceItem;
  window.updateInvoiceItem = updateInvoiceItem;
  window.removeInvoiceItem = removeInvoiceItem;
  window.calculateInvoiceTotal = calculateInvoiceTotal;
  window.submitInvoice = submitInvoice;
  window.viewInvoice = viewInvoice;
  window.sendInvoice = sendInvoice;
  window.convertToInvoice = convertToInvoice;
  window.handleRejection = handleRejection;
  window.archiveInvoice = archiveInvoice;
  window.toggleInvoiceActive = toggleInvoiceActive;
  window.reactivateInvoice = reactivateInvoice;
  window.deleteInvoice = deleteInvoice;
  window.showRespondModal = showRespondModal;
  window.submitResponse = submitResponse;
  window.debounceSearch = debounceSearch;
  window.closeModal = closeModal;
  window.togglePhoneSelection = togglePhoneSelection;
  window.confirmSendWhatsApp = confirmSendWhatsApp;
  window.copyInvoiceLink = copyInvoiceLink;
}


/**
 * Show default message template configuration modal
 */
function showDefaultMessageConfig() {
  console.log('showDefaultMessageConfig called');
  
  // Default template to show immediately
  const defaultTemplate = `Hello {{CLIENT_NAME}}! 👋\\n\\n` +
    `Your {{TYPE}} *{{INVOICE_NUMBER}}* is ready.\\n\\n` +
    `📋 *{{TITLE}}*\\n` +
    `💰 Total: {{TOTAL}}\\n\\n` +
    `🔗 Click here to view: {{LINK}}\\n` +
    `🔐 Your password is the email: {{PASSWORD}}\\n\\n` +
    `Thank you for your business! 🙏`;
  
  console.log('Creating modal...');
  
  const modal = document.createElement('div');
  modal.className = 'modal active';
  modal.id = 'defaultMessageConfigModal';
  modal.innerHTML = `
    <div class="modal-content" style="max-width: 700px;">
      <div class="modal-header">
        <h2 data-i18n="invoices.default_message_config">⚙️ Default WhatsApp Message Template</h2>
        <button class="close-btn" onclick="closeModal('defaultMessageConfigModal')">&times;</button>
      </div>
      <div class="modal-body">
        <p style="margin-bottom: 20px; color: #666;" data-i18n="invoices.default_message_help">
          Configure the default message template that will be used when sending invoices via WhatsApp. 
          This template will be pre-filled for all invoice sends.
        </p>
        
        <div class="form-group">
          <label style="display: flex; justify-content: space-between; align-items: center;">
            <span data-i18n="invoices.message_template">Message Template</span>
            <small id="loadingTemplateIndicator" style="color: #999;">Loading...</small>
          </label>
          
          <!-- Formatting Toolbar -->
          <div class="message-editor-toolbar" style="display: flex; gap: 5px; margin-bottom: 8px; padding: 8px; background: #f8f9fa; border-radius: 6px 6px 0 0; border: 1px solid #ddd; border-bottom: none;">
            <button type="button" class="editor-btn" onclick="formatDefaultText('bold')" title="Bold (*text*)" data-i18n-title="invoices.format_bold">
              <strong>B</strong>
            </button>
            <button type="button" class="editor-btn" onclick="formatDefaultText('italic')" title="Italic (_text_)" data-i18n-title="invoices.format_italic">
              <em>I</em>
            </button>
            <button type="button" class="editor-btn" onclick="formatDefaultText('strikethrough')" title="Strikethrough (~text~)" data-i18n-title="invoices.format_strike">
              <s>S</s>
            </button>
            <button type="button" class="editor-btn" onclick="formatDefaultText('monospace')" title="Monospace (\`\`\`text\`\`\`)" data-i18n-title="invoices.format_mono">
              <code>M</code>
            </button>
            <div style="width: 1px; background: #ddd; margin: 0 5px;"></div>
            <button type="button" class="editor-btn" onclick="insertDefaultPlaceholder('{{LINK}}')" title="Insert Link" data-i18n-title="invoices.insert_link">
              🔗
            </button>
            <button type="button" class="editor-btn" onclick="insertDefaultPlaceholder('{{PASSWORD}}')" title="Insert Password Hint" data-i18n-title="invoices.insert_password">
              🔐
            </button>
            <button type="button" class="editor-btn" onclick="insertDefaultPlaceholder('{{CLIENT_NAME}}')" title="Insert Client Name" data-i18n-title="invoices.insert_client_name">
              👤
            </button>
            <button type="button" class="editor-btn" onclick="insertDefaultPlaceholder('{{INVOICE_NUMBER}}')" title="Insert Invoice Number" data-i18n-title="invoices.insert_invoice_number">
              #️⃣
            </button>
            <button type="button" class="editor-btn" onclick="insertDefaultPlaceholder('{{TOTAL}}')" title="Insert Total Amount" data-i18n-title="invoices.insert_total">
              💰
            </button>
            <button type="button" class="editor-btn" onclick="insertDefaultPlaceholder('{{TYPE}}')" title="Insert Type (Invoice/Quote)" data-i18n-title="invoices.insert_type">
              📄
            </button>
            <button type="button" class="editor-btn" onclick="insertDefaultPlaceholder('{{TITLE}}')" title="Insert Title" data-i18n-title="invoices.insert_title">
              📝
            </button>
          </div>
          
          <textarea id="defaultMessageEditor" class="form-control" rows="10" style="font-family: monospace; border-radius: 0 0 6px 6px; resize: vertical;">${defaultTemplate}</textarea>
          
          <div style="margin-top: 8px; padding: 10px; background: #e3f2fd; border-radius: 6px; font-size: 12px;">
            <strong data-i18n="invoices.placeholders_title">📌 Available Placeholders:</strong>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; margin-top: 8px;">
              <div><code>{{LINK}}</code> - <span data-i18n="invoices.placeholder_link">Invoice link</span></div>
              <div><code>{{PASSWORD}}</code> - <span data-i18n="invoices.placeholder_password">Masked email</span></div>
              <div><code>{{CLIENT_NAME}}</code> - <span data-i18n="invoices.placeholder_client_name">Client name</span></div>
              <div><code>{{INVOICE_NUMBER}}</code> - <span data-i18n="invoices.placeholder_invoice_number">Invoice number</span></div>
              <div><code>{{TOTAL}}</code> - <span data-i18n="invoices.placeholder_total">Total amount</span></div>
              <div><code>{{TYPE}}</code> - <span data-i18n="invoices.placeholder_type">Invoice or Quote</span></div>
              <div><code>{{TITLE}}</code> - <span data-i18n="invoices.placeholder_title">Invoice title</span></div>
            </div>
            <div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid #90caf9;">
              <strong data-i18n="invoices.formatting_title">✨ Formatting:</strong>
              <span data-i18n="invoices.formatting_help">*bold* _italic_ ~strike~ \`\`\`mono\`\`\`</span>
            </div>
          </div>
        </div>

        <div class="form-actions" style="margin-top: 30px;">
          <button class="btn btn-secondary" onclick="closeModal('defaultMessageConfigModal')" data-i18n="common.cancel">Cancel</button>
          <button class="btn btn-primary" id="saveDefaultMessageBtn" onclick="saveDefaultMessage()" data-i18n="common.save">Save Template</button>
        </div>
      </div>
    </div>
  `;
  document.body.appendChild(modal);
  
  // Load saved template in background (non-blocking)
  setTimeout(async () => {
    try {
      const response = await fetch('/api/invoices/admin/default-message', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      if (response.ok) {
        const data = await response.json();
        const savedMessage = data.default_message;
        
        if (savedMessage) {
          const editor = document.getElementById('defaultMessageEditor');
          if (editor) {
            editor.value = savedMessage;
            console.log('Loaded saved template');
          }
        }
      }
      
      // Hide loading indicator
      const indicator = document.getElementById('loadingTemplateIndicator');
      if (indicator) indicator.style.display = 'none';
      
    } catch (error) {
      console.error('Error loading default message:', error);
      const indicator = document.getElementById('loadingTemplateIndicator');
      if (indicator) indicator.style.display = 'none';
    }
  }, 100);
}

/**
 * Format selected text in default message editor
 */
function formatDefaultText(format) {
  const editor = document.getElementById('defaultMessageEditor');
  if (!editor) return;
  
  const start = editor.selectionStart;
  const end = editor.selectionEnd;
  const selectedText = editor.value.substring(start, end);
  
  if (!selectedText) {
    alert('Please select text to format');
    return;
  }
  
  let formattedText = '';
  
  switch(format) {
    case 'bold':
      formattedText = `*${selectedText}*`;
      break;
    case 'italic':
      formattedText = `_${selectedText}_`;
      break;
    case 'strikethrough':
      formattedText = `~${selectedText}~`;
      break;
    case 'monospace':
      formattedText = `\`\`\`${selectedText}\`\`\``;
      break;
  }
  
  // Replace selected text
  editor.value = editor.value.substring(0, start) + formattedText + editor.value.substring(end);
  
  // Update cursor position
  const newPos = start + formattedText.length;
  editor.setSelectionRange(newPos, newPos);
  editor.focus();
}

/**
 * Insert placeholder at cursor position in default message editor
 */
function insertDefaultPlaceholder(placeholder) {
  const editor = document.getElementById('defaultMessageEditor');
  if (!editor) return;
  
  const start = editor.selectionStart;
  const end = editor.selectionEnd;
  
  // Insert placeholder
  editor.value = editor.value.substring(0, start) + placeholder + editor.value.substring(end);
  
  // Update cursor position
  const newPos = start + placeholder.length;
  editor.setSelectionRange(newPos, newPos);
  editor.focus();
}

/**
 * Save default message template
 */
async function saveDefaultMessage() {
  const editor = document.getElementById('defaultMessageEditor');
  const saveBtn = document.getElementById('saveDefaultMessageBtn');
  
  if (!editor) return;
  
  const message = editor.value.trim();
  
  if (!message) {
    showAlert('Please enter a message template', 'error');
    return;
  }
  
  saveBtn.disabled = true;
  saveBtn.textContent = 'Saving...';
  
  try {
    const response = await fetch('/api/invoices/admin/default-message', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({ default_message: message })
    });
    
    const data = await response.json();
    
    if (data.success) {
      showNotification('Default message template saved successfully!', 'success');
      closeModal('defaultMessageConfigModal');
    } else {
      showNotification(data.error || 'Failed to save template', 'error');
      saveBtn.disabled = false;
      saveBtn.textContent = 'Save Template';
    }
  } catch (error) {
    console.error('Error saving default message:', error);
    showNotification('Failed to save template', 'error');
    saveBtn.disabled = false;
    saveBtn.textContent = 'Save Template';
  }
}
