// ==================== COMPANIES (CLEARING AGENTS) MANAGEMENT ====================
// Global variables (assume userObj and serverURL are defined elsewhere)
// serverURL = "https://demo2.bsl.co.ke/api/v1/"

// Main function to load companies – filter can be 'all' or 'active'
function allCompanies(filter = 'active') {
    $(".crud_section").html("");

    // Modern loading skeleton
    var loadingHTML = `
        <div class="companies-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
            <div class="loading-skeleton">
                <div style="height: 60px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 12px; margin-bottom: 20px;"></div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(4).fill().map(() => '<div style="height: 100px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>').join('')}
                </div>
                <div style="height: 400px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
            </div>
        </div>
        <style>
            @keyframes loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        </style>
    `;
    $(".crud_section").html(loadingHTML);

    // Build URL based on filter
    let url = filter === 'all' ? serverURL + 'companies/all' : serverURL + 'companies/active';

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        success: function(companies) {
            // companies is an array (as seen in response)
            renderCompaniesTable(companies, filter);
        },
        error: function(xhr, status, error) {
            console.error("Error loading companies:", error);
            $(".crud_section").html(`
                <div style="padding: 40px; text-align: center; background: white; border-radius: 16px; margin: 24px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626;"></i>
                    <h3 style="color: #1a1f36;">Failed to load companies</h3>
                    <p style="color: #5b677c;">${error}</p>
                    <button onclick="allCompanies('${filter}')" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Render the companies table
function renderCompaniesTable(companies, currentFilter) {
    const total = companies.length;

    var html = `
    <div class="companies-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
        
        <!-- Header Section -->
        <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2;">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-building" style="color: #000;"></i>
                        Clearing Agents / Companies
                    </h1>
                    <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                        ${total} Total
                    </span>
                </div>
                <div style="display: flex; gap: 12px;">
                    <button onclick="addCompany()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #000; color: white; border: none; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                        <i class="fas fa-plus"></i> Add Company
                    </button>
                    <button onclick="exportCompanies()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #ffffff; color: #1a1f36; border: 1px solid #d0d5dd; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                        <i class="fas fa-download"></i> Export
                    </button>
                </div>
            </div>
            <!-- Filter toggle -->
            <div style="margin-top: 16px; display: flex; gap: 10px;">
                <button onclick="allCompanies('active')" style="padding: 8px 20px; border: 1px solid #eaeef2; border-radius: 40px; background: ${currentFilter === 'active' ? '#000' : 'white'}; color: ${currentFilter === 'active' ? 'white' : '#1a1f36'}; cursor: pointer; font-weight: 500;">
                    Active Only
                </button>
                <button onclick="allCompanies('all')" style="padding: 8px 20px; border: 1px solid #eaeef2; border-radius: 40px; background: ${currentFilter === 'all' ? '#000' : 'white'}; color: ${currentFilter === 'all' ? 'white' : '#1a1f36'}; cursor: pointer; font-weight: 500;">
                    All Companies
                </button>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px;">
            <!-- Total Card -->
            <div style="background: #ffffff; border-radius: 16px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                <div style="width: 48px; height: 48px; background: #f0f2f5; border-radius: 12px; display: flex; align-items: center; justify-content: center; margin: 0 auto 12px;">
                    <i class="fas fa-building" style="font-size: 24px; color: #000;"></i>
                </div>
                <div style="font-size: 28px; font-weight: 700; color: #1a1f36;">${total}</div>
                <div style="font-size: 14px; color: #5b677c;">Total Companies</div>
            </div>
        </div>

        <!-- Search and Controls -->
        <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
            <div style="position: relative; flex: 1; max-width: 400px;">
                <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                <input type="text" id="companySearch" placeholder="Search by code, name, email, TIN..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none;">
            </div>
            <div style="display: flex; gap: 12px;">
                <select id="pageSize" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px;">
                    <option value="10">10 per page</option>
                    <option value="25">25 per page</option>
                    <option value="50">50 per page</option>
                    <option value="100">100 per page</option>
                </select>
                <button onclick="allCompanies('${currentFilter}')" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer;">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        </div>

        <!-- Companies Table -->
        <div style="background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: inherit; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
            <table class="companies-table" id="companytableview" style="width: 100%; border-collapse: collapse; min-width: 1200px;">
                <thead>
                    <tr style="background: #f8fafc; border-bottom: 2px solid #eaeef2;">
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36; width: 60px;">#</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Code</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Name</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Email</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">TIN</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Reg No</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Entity Type</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Address (City)</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                    </tr>
                </thead>
                <tbody id="companyTableBody">
    `;

    companies.forEach((company, i) => {
        // Get first address if available
        const addr = company.addresses && company.addresses[0];
        const cityCountry = addr ? `${addr.city || ''}${addr.country ? ', ' + addr.country.name : ''}` : 'N/A';

        html += `
        <tr data-company-id="${company.id}" style="border-bottom: 1px solid #eaeef2;">
            <td style="padding: 16px; color: #5b677c;">${i + 1}</td>
            <td style="padding: 16px; font-weight: 600; color: #1a1f36;">${company.code || 'N/A'}</td>
            <td style="padding: 16px;">${company.name || 'N/A'}</td>
            <td style="padding: 16px;">${company.email || 'N/A'}</td>
            <td style="padding: 16px;">${company.tin || 'N/A'}</td>
            <td style="padding: 16px;">${company.companyRegistrationNo || 'N/A'}</td>
            <td style="padding: 16px;">${company.entityTypeCode || 'N/A'}</td>
            <td style="padding: 16px;">${cityCountry}</td>
            <td style="padding: 16px; text-align: center;">
                <div class="action-dropdown" style="position: relative; display: inline-block;">
                    <button onclick="toggleCompanyActionMenu(${company.id})" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 8px; background: white; cursor: pointer;">
                        <i class="fas fa-ellipsis-v" style="color: #5b677c;"></i>
                    </button>
                    <div id="company_menu_${company.id}" style="display: none; position: absolute; right: 0; top: 45px; width: 180px; background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border: 1px solid #eaeef2; z-index: 1000;">
                        <div style="padding: 12px; border-bottom: 1px solid #eaeef2;">
                            <span style="font-weight: 600; color: #1a1f36;">Actions</span>
                        </div>
                        <div style="padding: 8px;">
                            <button onclick='viewCompanyDetails(${company.id})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                <i class="fas fa-eye"></i> View
                            </button>
                            <button onclick='editCompany(${company.id})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button onclick='deleteCompany(${company.id}, "${company.name}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #dc2626;">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
        `;
    });

    html += `
                </tbody>
            </table>
        </div>

        <!-- Table Footer -->
        <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-top: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
            <div style="color: #5b677c;">
                <span id="selectedCount">0</span> items selected
            </div>
            <div class="table-pagination" id="tablePagination"></div>
        </div>

        <style>
            .companies-table tbody tr:hover { background: #f8fafc; cursor: pointer; }
            .action-dropdown button:hover { background: #f0f2f5; }
        </style>
    </div>
    `;

    $(".crud_section").html(html);

    // Initialize DataTable
    const table = $('#companytableview').DataTable({
        dom: 'rtip',
        pageLength: 10,
        lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
        order: [[0, 'asc']],
        columnDefs: [
            { orderable: false, targets: [8] }
        ]
    });

    // Search
    $('#companySearch').off('keyup').on('keyup', function() {
        table.search(this.value).draw();
    });

    // Page size
    $('#pageSize').off('change').on('change', function() {
        table.page.len(this.value).draw();
    });

    function updateSelectedCount() {
        $("#selectedCount").text($(".row-checkbox:checked").length);
    }
}

// Toggle action menu
function toggleCompanyActionMenu(companyId) {
    $('[id^="company_menu_"]').hide();
    $(`#company_menu_${companyId}`).toggle();
}

// ---------- Add Company ----------
function addCompany() {
    // Load countries and entity types
    Promise.all([
        $.ajax({ url: serverURL_V + 'countries?page=0&size=1000&sort=createdAt,desc', headers: { Authorization: 'Bearer ' + userObj.accessToken } }),
        $.ajax({ url: serverURL + 'entity-types/active', headers: { Authorization: 'Bearer ' + userObj.accessToken } })
    ]).then(([countriesResponse, entityTypes]) => {
        let countries = [];
        if (countriesResponse.content) countries = countriesResponse.content;
        else if (Array.isArray(countriesResponse)) countries = countriesResponse;

        // entityTypes is an array directly (as per response)
        showCompanyModal('add', null, countries, entityTypes);
    }).catch(() => {
        Swal.fire({
            title: 'Error',
            text: 'Could not load countries or entity types',
            icon: 'error',
            confirmButtonColor: '#000'
        });
    });
}

// Show Add/Edit modal
function showCompanyModal(mode, companyData, countries, entityTypes) {
    const isEdit = mode === 'edit';
    const title = isEdit ? 'Edit Company' : 'Add New Company';

    // Build dropdown options
    let countryOptions = '<option value="">Select a country</option>';
    countries.forEach(c => {
        const selected = (isEdit && companyData.addresses && companyData.addresses[0] && companyData.addresses[0].countryId == c.id) ? 'selected' : '';
        countryOptions += `<option value="${c.id}" ${selected}>${c.name}</option>`;
    });

    let entityOptions = '<option value="">Select entity type</option>';
    entityTypes.forEach(e => {
        const selected = (isEdit && companyData.entityTypeId == e.id) ? 'selected' : '';
        entityOptions += `<option value="${e.id}" ${selected}>${e.name} (${e.code})</option>`;
    });

    // Prefill address fields if editing
    const addr = (isEdit && companyData.addresses && companyData.addresses[0]) ? companyData.addresses[0] : {};

    Swal.fire({
        title: title,
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <!-- Company Code -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Code <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-barcode" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="companyCode" placeholder="e.g., BSL" value="${isEdit ? companyData.code || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Name -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Name <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-building" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="companyName" placeholder="e.g., BSL Agent" value="${isEdit ? companyData.name || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Email -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Email</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-envelope" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="email" id="companyEmail" placeholder="contact@company.com" value="${isEdit ? companyData.email || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- TIN -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">TIN</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-id-card" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="companyTin" placeholder="Tax Identification Number" value="${isEdit ? companyData.tin || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Registration No -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Company Registration No</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="companyRegNo" placeholder="e.g., REG-BSL-001" value="${isEdit ? companyData.companyRegistrationNo || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Entity Type Dropdown -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Entity Type <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-tag" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <select id="entityTypeId" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box; background: white; appearance: none;">
                            ${entityOptions}
                        </select>
                        <i class="fas fa-chevron-down" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></i>
                    </div>
                </div>

                <!-- Address Section -->
                <div style="margin-top: 20px; border-top: 1px solid #eaeef2; padding-top: 15px;">
                    <h4 style="margin: 0 0 10px 0; color: #1a1f36;">Primary Address</h4>

                     <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Postal Address</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="postalAddress" placeholder="Address" value="${addr.postalAddress || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                  </div>

                   <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Postal Code</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="postalCode" placeholder="Postal Code" value="${addr.postalCode || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                  </div>


                   <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Building Name</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="buildingName" placeholder="Building Name" value="${addr.buildingName || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                  </div>


                   <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Building Name</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="buildingName" placeholder="Building Name" value="${addr.buildingName || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                  </div>
                    
                  
                 
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Street Name</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input type="text" id="streetName" placeholder="Street Name" value="${addr.streetName || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">City</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-file-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input type="text" id="city" placeholder="City" value="${addr.city || ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing： border-box;">
                        </div>
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Country</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-globe" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <select id="countryId" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box; background: white; appearance: none;">
                                ${countryOptions}
                            </select>
                            <i class="fas fa-chevron-down" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></i>
                        </div>
                    </div>
                </div>
            </div>

            <style>
                input:focus, select:focus {
                    border-color: #85b7d9 !important;
                    outline: 0 !important;
                    box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                }
                select { cursor: pointer; }
            </style>
        `,
        showCancelButton: true,
        confirmButtonText: isEdit ? 'Update Company' : 'Create Company',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '700px',
        preConfirm: () => {
            const code = $('#companyCode').val();
            const name = $('#companyName').val();
            const entityTypeId = $('#entityTypeId').val();

            if (!code) {
                Swal.showValidationMessage('Code is required');
                return false;
            }
            if (!name) {
                Swal.showValidationMessage('Name is required');
                return false;
            }
            if (!entityTypeId) {
                Swal.showValidationMessage('Entity type is required');
                return false;
            }

            // Build address object only if any field filled
            const address = {
                postalAddress: $('#postalAddress').val() || null,
                postalCode: $('#postalCode').val() || null,
                buildingName: $('#buildingName').val() || null,
                streetName: $('#streetName').val() || null,
                city: $('#city').val() || null,
                countryId: $('#countryId').val() ? parseInt($('#countryId').val()) : null
            };
            const addresses = Object.values(address).some(v => v !== null && v !== '') ? [address] : [];

            return {
                code: code.trim(),
                name: name.trim(),
                email: $('#companyEmail').val()?.trim() || null,
                tin: $('#companyTin').val()?.trim() || null,
                companyRegistrationNo: $('#companyRegNo').val()?.trim() || null,
                entityTypeId: parseInt(entityTypeId),
                addresses: addresses
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            if (isEdit) {
                updateCompany(companyData.id, result.value);
            } else {
                createCompany(result.value);
            }
        }
    });
}

// Create company
function createCompany(data) {
    Swal.fire({
        title: 'Creating...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'companies',
        type: 'POST',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: function() {
            Swal.fire({
                title: 'Success!',
                text: 'Company created successfully',
                icon: 'success',
                confirmButtonColor: '#000'
            }).then(() => allCompanies('all')); // after add, show all
        },
        error: function(xhr) {
            let msg = 'Creation failed';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({
                title: 'Error',
                text: msg,
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Edit company – fetch details then show modal
function editCompany(companyId) {
    Swal.fire({
        title: 'Loading...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'companies/' + companyId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(company) {
            // Now load countries and entity types
            Promise.all([
                $.ajax({ url: serverURL_V + 'countries?page=0&size=1000&sort=createdAt,desc', headers: { Authorization: 'Bearer ' + userObj.accessToken } }),
                $.ajax({ url: serverURL + 'entity-types/active', headers: { Authorization: 'Bearer ' + userObj.accessToken } })
            ]).then(([countriesResponse, entityTypes]) => {
                let countries = [];
                if (countriesResponse.content) countries = countriesResponse.content;
                else if (Array.isArray(countriesResponse)) countries = countriesResponse;

                Swal.close();
                showCompanyModal('edit', company, countries, entityTypes);
            }).catch(() => {
                Swal.fire({ title: 'Error', text: 'Could not load countries/entity types', icon: 'error' });
            });
        },
        error: function() {
            Swal.fire({ title: 'Error', text: 'Could not fetch company details', icon: 'error' });
        }
    });
}

// Update company
function updateCompany(companyId, data) {
    Swal.fire({
        title: 'Updating...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'companies/' + companyId,
        type: 'PUT',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: function() {
            Swal.fire({
                title: 'Success!',
                text: 'Company updated successfully',
                icon: 'success',
                confirmButtonColor: '#000'
            }).then(() => allCompanies('all'));
        },
        error: function(xhr) {
            let msg = 'Update failed';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({
                title: 'Error',
                text: msg,
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Delete company
function deleteCompany(companyId, companyName) {
    Swal.fire({
        title: 'Delete Company?',
        html: `Are you sure you want to delete <strong>${companyName || 'this company'}</strong>?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        confirmButtonText: 'Yes, delete',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Deleting...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            $.ajax({
                url: serverURL + 'companies/' + companyId,
                type: 'DELETE',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                success: function() {
                    Swal.fire({
                        title: 'Deleted!',
                        text: 'Company has been removed.',
                        icon: 'success',
                        confirmButtonColor: '#000'
                    }).then(() => allCompanies('all'));
                },
                error: function(xhr) {
                    let msg = 'Deletion failed';
                    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
                    Swal.fire({
                        title: 'Error',
                        text: msg,
                        icon: 'error',
                        confirmButtonColor: '#000'
                    });
                }
            });
        }
    });
}

// View details (simple)
function viewCompanyDetails(companyId) {
    $.ajax({
        url: serverURL + 'companies/' + companyId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(company) {
            Swal.fire({
                title: 'Company Details',
                html: `<pre style="text-align: left; background: #f8fafc; padding: 16px; border-radius: 8px;">${JSON.stringify(company, null, 2)}</pre>`,
                confirmButtonColor: '#000',
                width: '700px'
            });
        },
        error: function() {
            Swal.fire({ title: 'Error', text: 'Could not fetch details', icon: 'error' });
        }
    });
}

// Export companies (JSON)
function exportCompanies() {
    const table = $('#companytableview').DataTable();
    const data = table.data().toArray();
    const jsonStr = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonStr], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `companies_export_${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
}

// Initialize on document ready
$(document).ready(function() {
    allCompanies('active'); // default to active

    $(document).on('click', function(e) {
        if (!$(e.target).closest('.action-dropdown').length) {
            $('[id^="company_menu_"]').hide();
        }
    });
});