<?php
/**
 * Clients List View - Card & List Layout with Toggle
 *
 * @package Freelance_Studio
 */

if (!defined('ABSPATH')) {
    exit;
}

$messages = array(
    'created' => __('Client created successfully.', 'freelance-studio'),
    'updated' => __('Client updated successfully.', 'freelance-studio'),
    'deleted' => __('Client deleted successfully.', 'freelance-studio'),
    'merged' => __('Client merged successfully. All records have been reassigned.', 'freelance-studio'),
    'archived' => __('Client archived successfully.', 'freelance-studio'),
    'unarchived' => __('Client restored successfully.', 'freelance-studio'),
    'not_found' => __('Client not found.', 'freelance-studio'),
    'error' => __('An error occurred. Please try again.', 'freelance-studio'),
);

// Calculate total income for percentage calculations (used in list view)
$total_income = 0;
foreach ($clients as $c) {
    $stats = FS_Client::get_client_stats($c->id);
    $total_income += $stats['total_paid'];
}

/**
 * Generate a consistent color based on string
 */
function fs_get_avatar_color($string) {
    $colors = array(
        '#3ECFB2', // Teal (primary)
        '#81A5DF', // Purple/Blue (secondary)
        '#FFA26E', // Coral (accent)
        '#D2E767', // Lime (highlight)
        '#7B68A6', // Deep purple (info)
        '#F2B6F6', // Pink
        '#5D9CEC', // Blue
        '#48CFAD', // Mint
        '#FC6E51', // Orange
        '#A0D468', // Green
    );
    
    $hash = crc32($string);
    $index = abs($hash) % count($colors);
    
    return $colors[$index];
}

/**
 * Get initials from company name or contact name
 */
function fs_get_initials($company_name, $contact_name = '') {
    $name = !empty($company_name) ? $company_name : $contact_name;
    
    if (empty($name)) {
        return '?';
    }
    
    $words = explode(' ', trim($name));
    $initials = '';
    
    foreach ($words as $i => $word) {
        if ($i < 2 && !empty($word)) {
            $initials .= strtoupper(substr($word, 0, 1));
        }
    }
    
    return $initials ?: '?';
}
?>

<div class="wrap fs-wrap">
    <div class="fs-page-header">
        <h1 class="fs-page-title"><?php esc_html_e('Clients', 'freelance-studio'); ?></h1>
        <?php if (!empty($clients)): ?>
        <div class="fs-view-toggle" id="fs-clients-view-toggle">
            <button type="button" class="fs-btn fs-btn-secondary" data-view="grid" title="<?php esc_attr_e('Card View', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-grid-view"></span>
            </button>
            <button type="button" class="fs-btn fs-btn-secondary" data-view="list" title="<?php esc_attr_e('List View', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-list-view"></span>
            </button>
        </div>
        <?php endif; ?>
        <div style="flex:1;"></div>
        <?php if ( function_exists( 'fs_studio_limit_reached' ) && fs_studio_limit_reached( 'clients' ) ): ?>
            <span class="fs-btn fs-btn-primary fs-btn-pro-gate" onclick="alert('<?php echo esc_js( __( 'You\'ve reached the 3-client limit on the free plan. Upgrade to Pro for unlimited clients.', 'freelance-studio' ) ); ?>')">
                <?php esc_html_e('New client', 'freelance-studio'); ?>
            </span>
        <?php else: ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=add') ); ?>" class="fs-btn fs-btn-primary">
                <?php esc_html_e('New client', 'freelance-studio'); ?>
            </a>
        <?php endif; ?>
    </div>
    
    <?php
    // Show usage counter and upgrade notices for free plan
    if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ):
        $client_count = fs_studio_get_usage_count( 'clients' );
        $limits = fs_studio_free_limits();
        if ( $client_count >= $limits['clients'] ):
            fs_studio_upgrade_notice( 'clients', 'banner' );
        else:
    ?>
        <div class="fs-usage-counter">
            <span class="fs-usage-counter-text">
                <?php /* translators: 1. count/number, 2. count/number */ ?>
                <?php echo esc_html( sprintf( __(  'Using %1$d of %2$d free client profiles', 'freelance-studio' ), $client_count, $limits['clients'] ) ); ?>
            </span>
            <div class="fs-usage-bar">
                <div class="fs-usage-bar-fill" style="width: <?php echo  esc_attr( min( 100, ( $client_count / $limits['clients'] ) * 100 ) ); ?>%"></div>
            </div>
            <a href="<?php echo  esc_url( freelance_studio_fs()->get_upgrade_url() ); ?>" class="fs-usage-upgrade-link"><?php esc_html_e( 'Upgrade for unlimited', 'freelance-studio' ); ?> &rarr;</a>
        </div>
    <?php
        endif;
    endif;
    ?>
    
    <?php if ($message && isset($messages[$message])): ?>
        <div class="fs-notice <?php echo in_array($message, array('error', 'not_found')) ? 'error' : 'success'; ?>">
            <?php echo esc_html($messages[$message]); ?>
        </div>
    <?php endif; ?>
    
    <?php if (!empty($clients) || $current_tab === 'archived'): ?>
        <!-- Tab Navigation -->
        <div class="fs-tab-nav">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'active' ? 'active' : '' ); ?>">
                <?php esc_html_e('Active', 'freelance-studio'); ?>
                <span class="fs-tab-count"><?php echo  intval( $active_count ); ?></span>
            </a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&tab=archived') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'archived' ? 'active' : '' ); ?>">
                <?php esc_html_e('Archived', 'freelance-studio'); ?>
                <span class="fs-tab-count"><?php echo  intval( $archived_count ); ?></span>
            </a>
        </div>
    <?php endif; ?>
    
    <?php if (empty($clients)): ?>
        <div class="fs-empty-state">
            <div class="fs-empty-state-icon">👥</div>
            <h3><?php esc_html_e('No clients yet', 'freelance-studio'); ?></h3>
            <p><?php esc_html_e('Get started by adding your first client.', 'freelance-studio'); ?></p>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=add') ); ?>" class="button button-primary">
                <?php esc_html_e('Add client', 'freelance-studio'); ?>
            </a>
        </div>
    <?php else: ?>
        
        <!-- Card/Grid View -->
        <div class="fs-clients-grid" id="fs-clients-grid-view">
            <?php foreach ($clients as $client): 
                $stats = FS_Client::get_client_stats($client->id);
                $display_name = $client->company_name ?: $client->name;
                $contact_name = $client->company_name ? $client->name : '';
                $initials = fs_get_initials($client->company_name, $client->name);
                $avatar_color = fs_get_avatar_color($display_name);
                
                // Check for logo - prefer uploaded (logo_id), fallback to linked URL (logo_url)
                $logo_url = '';
                if (!empty($client->logo_id)) {
                    $logo_url = wp_get_attachment_image_url($client->logo_id, 'thumbnail');
                } elseif (!empty($client->logo_url)) {
                    $logo_url = $client->logo_url;
                }
            ?>
                <div class="fs-client-card">
                    <div class="fs-client-card-header">
                        <?php if ($logo_url): ?>
                            <div class="fs-client-avatar fs-client-avatar-logo">
                                <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr($display_name); ?>">
                            </div>
                        <?php else: ?>
                            <div class="fs-client-avatar" style="background-color: <?php echo esc_attr($avatar_color); ?>;">
                                <?php echo esc_html($initials); ?>
                            </div>
                        <?php endif; ?>
                        <div class="fs-client-info">
                            <h3 class="fs-client-name">
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id) ); ?>">
                                    <?php echo esc_html($display_name); ?>
                                </a>
                                <?php if (!empty($client->is_internal)): ?>
                                    <span class="fs-badge fs-badge-internal" title="<?php esc_attr_e('Internal', 'freelance-studio'); ?>">INT</span>
                                <?php endif; ?>
                            </h3>
                            <?php if ($contact_name): ?>
                                <p class="fs-client-contact"><?php echo esc_html($contact_name); ?></p>
                            <?php endif; ?>
                        </div>
                        <div class="fs-card-actions-menu">
                            <button type="button" class="fs-card-menu-trigger" aria-label="<?php esc_attr_e('Actions', 'freelance-studio'); ?>">
                                <span class="dashicons dashicons-ellipsis"></span>
                            </button>
                            <div class="fs-card-dropdown">
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id) ); ?>">
                                    <span class="dashicons dashicons-visibility"></span> <?php esc_html_e('View', 'freelance-studio'); ?>
                                </a>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=edit&id=' . $client->id) ); ?>">
                                    <span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?>
                                </a>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=add&client_id=' . $client->id) ); ?>">
                                    <span class="dashicons dashicons-portfolio"></span> <?php esc_html_e('New Project', 'freelance-studio'); ?>
                                </a>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add&client_id=' . $client->id) ); ?>">
                                    <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('New Invoice', 'freelance-studio'); ?>
                                </a>
                                <a href="#" class="fs-merge-client-btn" data-id="<?php echo intval($client->id); ?>" data-name="<?php echo esc_attr(FS_Client::get_display_name($client)); ?>">
                                    <span class="dashicons dashicons-randomize"></span> <?php esc_html_e('Merge Into...', 'freelance-studio'); ?>
                                </a>
                                <?php if (isset($client->status) && $client->status === 'inactive'): ?>
                                <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=fs-clients&action=unarchive&id=' . $client->id), 'fs_unarchive_client_' . $client->id)); ?>">
                                    <span class="dashicons dashicons-upload"></span> <?php esc_html_e('Restore', 'freelance-studio'); ?>
                                </a>
                                <?php else: ?>
                                <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=fs-clients&action=archive&id=' . $client->id), 'fs_archive_client_' . $client->id)); ?>">
                                    <span class="dashicons dashicons-archive"></span> <?php esc_html_e('Archive', 'freelance-studio'); ?>
                                </a>
                                <?php endif; ?>
                                <hr>
                                <a href="#" class="fs-delete-btn fs-text-danger" data-type="client" data-id="<?php echo  intval( $client->id ); ?>">
                                    <span class="dashicons dashicons-trash"></span> <?php esc_html_e('Delete', 'freelance-studio'); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="fs-client-card-stats">
                        <div class="fs-client-stat">
                            <span class="fs-stat-label"><?php esc_html_e('PROJECTS', 'freelance-studio'); ?></span>
                            <span class="fs-stat-value"><?php echo intval($stats['total_projects']); ?></span>
                        </div>
                        <div class="fs-client-stat">
                            <span class="fs-stat-label"><?php esc_html_e('TOTAL BILLED', 'freelance-studio'); ?></span>
                            <span class="fs-stat-value"><?php echo  esc_html( FS_View_Context::format_currency($stats['total_invoiced']) ); ?></span>
                        </div>
                    </div>
                    
                    <div class="fs-client-card-actions">
                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id) ); ?>" class="fs-btn fs-btn-card">
                            <?php esc_html_e('View', 'freelance-studio'); ?>
                        </a>
                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=add&client_id=' . $client->id) ); ?>" class="fs-btn fs-btn-card">
                            <?php esc_html_e('New Project', 'freelance-studio'); ?>
                        </a>
                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add&client_id=' . $client->id) ); ?>" class="fs-btn fs-btn-card">
                            <?php esc_html_e('Invoice', 'freelance-studio'); ?>
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Table/List View -->
        <div class="fs-table-responsive" id="fs-clients-list-view" style="display: none;">
            <table class="fs-table fs-client-table widefat">
                <thead>
                    <tr>
                        <th class="column-name"><?php esc_html_e('Name', 'freelance-studio'); ?></th>
                        <th class="column-city"><?php esc_html_e('City', 'freelance-studio'); ?></th>
                        <th class="column-projects"><?php esc_html_e('Total projects', 'freelance-studio'); ?></th>
                        <th class="column-income"><?php esc_html_e('Income received', 'freelance-studio'); ?></th>
                        <th class="column-actions"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($clients as $client): 
                        $stats = FS_Client::get_client_stats($client->id);
                        $income_percent = $total_income > 0 ? round(($stats['total_paid'] / $total_income) * 100, 1) : 0;
                        $display_name = $client->company_name ?: $client->name;
                        $initials = fs_get_initials($client->company_name, $client->name);
                        $avatar_color = fs_get_avatar_color($display_name);
                        
                        // Check for logo - prefer uploaded (logo_id), fallback to linked URL (logo_url)
                        $logo_url = '';
                        if (!empty($client->logo_id)) {
                            $logo_url = wp_get_attachment_image_url($client->logo_id, 'thumbnail');
                        } elseif (!empty($client->logo_url)) {
                            $logo_url = $client->logo_url;
                        }
                    ?>
                        <tr>
                            <td class="column-name">
                                <div class="fs-client-name-cell">
                                    <?php if ($logo_url): ?>
                                        <img src="<?php echo esc_url($logo_url); ?>" alt="" class="fs-client-logo-thumb">
                                    <?php else: ?>
                                        <div class="fs-client-avatar-small" style="background-color: <?php echo esc_attr($avatar_color); ?>;">
                                            <?php echo esc_html($initials); ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="fs-client-name-text">
                                        <span class="fs-status-dot <?php echo  esc_attr( $client->status ); ?>"></span>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id) ); ?>">
                                            <strong><?php echo esc_html($display_name); ?></strong>
                                        </a>
                                        <?php if (!empty($client->is_internal)): ?>
                                            <span class="fs-badge fs-badge-internal" title="<?php esc_attr_e('Internal client - excluded from client metrics', 'freelance-studio'); ?>"><?php esc_html_e('Internal', 'freelance-studio'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td class="column-city">
                                <?php echo $client->city ? esc_html($client->city) : '-'; ?>
                            </td>
                            <td class="column-projects">
                                <?php echo  esc_html( $stats['total_projects'] ); ?>
                            </td>
                            <td class="column-income">
                                <div class="fs-income-cell">
                                    <span class="fs-income-amount"><?php echo  esc_html( FS_View_Context::format_currency($stats['total_paid']) ); ?></span>
                                    <span class="fs-income-percent"><?php echo  esc_html( $income_percent ); ?>% of income</span>
                                </div>
                            </td>
                            <td class="column-actions">
                                <div class="fs-row-menu">
                                    <button type="button" class="fs-row-menu-trigger">⋯</button>
                                    <div class="fs-row-menu-dropdown">
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id) ); ?>"><?php esc_html_e('View', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=edit&id=' . $client->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add&client_id=' . $client->id) ); ?>"><?php esc_html_e('Invoice client', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=add&client_id=' . $client->id) ); ?>"><?php esc_html_e('New project', 'freelance-studio'); ?></a>
                                        <a href="#" class="fs-merge-client-btn" data-id="<?php echo intval($client->id); ?>" data-name="<?php echo esc_attr(FS_Client::get_display_name($client)); ?>"><?php esc_html_e('Merge Into...', 'freelance-studio'); ?></a>
                                        <?php if (isset($client->status) && $client->status === 'inactive'): ?>
                                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=fs-clients&action=unarchive&id=' . $client->id), 'fs_unarchive_client_' . $client->id)); ?>"><?php esc_html_e('Restore', 'freelance-studio'); ?></a>
                                        <?php else: ?>
                                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=fs-clients&action=archive&id=' . $client->id), 'fs_archive_client_' . $client->id)); ?>"><?php esc_html_e('Archive', 'freelance-studio'); ?></a>
                                        <?php endif; ?>
                                        <hr>
                                        <a href="#" class="fs-delete-btn text-danger" data-type="client" data-id="<?php echo  intval( $client->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
    <?php endif; ?>
    
    <?php
    // Pagination
    $base_url = admin_url('admin.php?page=fs-clients');
    if ($current_tab !== 'active') $base_url = add_query_arg('tab', $current_tab, $base_url);
    if ($per_page !== 25) $base_url = add_query_arg('per_page', $per_page, $base_url);
    $item_label = __('clients', 'freelance-studio');
    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/pagination.php';
    ?>
</div>

<script>
(function() {
    const STORAGE_KEY = 'fs_clients_view';
    const gridView = document.getElementById('fs-clients-grid-view');
    const listView = document.getElementById('fs-clients-list-view');
    const toggleContainer = document.getElementById('fs-clients-view-toggle');
    
    if (!gridView || !listView || !toggleContainer) return;
    
    const buttons = toggleContainer.querySelectorAll('.fs-btn');
    
    function setView(viewType) {
        // Update visibility
        if (viewType === 'list') {
            gridView.style.display = 'none';
            listView.style.display = 'block';
        } else {
            gridView.style.display = 'grid';
            listView.style.display = 'none';
        }
        
        // Update button states
        buttons.forEach(btn => {
            if (btn.dataset.view === viewType) {
                btn.classList.remove('fs-btn-secondary');
                btn.classList.add('fs-btn-primary');
            } else {
                btn.classList.remove('fs-btn-primary');
                btn.classList.add('fs-btn-secondary');
            }
        });
        
        // Save preference
        localStorage.setItem(STORAGE_KEY, viewType);
    }
    
    // Initialize from saved preference
    const savedView = localStorage.getItem(STORAGE_KEY) || 'grid';
    setView(savedView);
    
    // Handle button clicks
    buttons.forEach(btn => {
        btn.addEventListener('click', function() {
            setView(this.dataset.view);
        });
    });
})();
</script>

<!-- Merge Client Modal -->
<div class="fs-modal" id="fs-merge-client-modal">
    <div class="fs-modal-content" style="max-width: 520px;">
        <div class="fs-modal-header">
            <h3><?php esc_html_e('Merge Client', 'freelance-studio'); ?></h3>
            <button type="button" class="fs-modal-close" id="fs-merge-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <div class="fs-merge-description">
                <p><?php esc_html_e('All projects, invoices, proposals, contracts, expenses, bookings, and tasks belonging to this client will be reassigned to the target client. The original client will then be deleted.', 'freelance-studio'); ?></p>
            </div>

            <div class="fs-merge-visual">
                <div class="fs-merge-source">
                    <span class="fs-merge-label"><?php esc_html_e('Merge this client:', 'freelance-studio'); ?></span>
                    <strong id="fs-merge-source-name"></strong>
                </div>
                <span class="dashicons dashicons-arrow-right-alt fs-merge-arrow"></span>
                <div class="fs-merge-target">
                    <span class="fs-merge-label"><?php esc_html_e('Into this client:', 'freelance-studio'); ?></span>
                    <select id="fs-merge-target-select">
                        <option value=""><?php esc_html_e('Select target client...', 'freelance-studio'); ?></option>
                        <?php
                        $all_clients = FS_Client::get_all(array('orderby' => 'display_name', 'order' => 'ASC'));
                        if (!empty($all_clients)) {
                            foreach ($all_clients as $c) {
                                $display = FS_Client::get_display_name($c);
                                printf(
                                    '<option value="%d">%s</option>',
                                    intval($c->id),
                                    esc_html($display)
                                );
                            }
                        }
                        ?>
                    </select>
                </div>
            </div>

            <div class="fs-merge-summary" id="fs-merge-summary" style="display:none;">
                <p id="fs-merge-summary-text"></p>
            </div>

            <div class="fs-merge-warning">
                <span class="dashicons dashicons-warning"></span>
                <span><?php esc_html_e('This action cannot be undone. The source client record will be permanently deleted after all records are reassigned.', 'freelance-studio'); ?></span>
            </div>
        </div>
        <div class="fs-modal-footer">
            <button type="button" class="fs-btn fs-btn-secondary" id="fs-merge-cancel-btn"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
            <button type="button" class="fs-btn fs-btn-primary" id="fs-merge-confirm-btn" disabled><?php esc_html_e('Merge & Delete', 'freelance-studio'); ?></button>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    var mergeSourceId = null;
    var $mergeModal = $('#fs-merge-client-modal');

    // Open merge modal
    $(document).on('click', '.fs-merge-client-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        mergeSourceId = $(this).data('id');
        var sourceName = $(this).data('name');

        $('#fs-merge-source-name').text(sourceName);
        $('#fs-merge-target-select').val('');
        $('#fs-merge-confirm-btn').prop('disabled', true);
        $('#fs-merge-summary').hide();

        // Hide the source client from the target dropdown
        $('#fs-merge-target-select option').show();
        $('#fs-merge-target-select option[value="' + mergeSourceId + '"]').hide();

        // Close any open card menus
        document.querySelectorAll('.fs-card-actions-menu.open').forEach(function(m) {
            m.classList.remove('open');
            var parentCard = m.closest('.fs-project-card, .fs-client-card');
            if (parentCard) parentCard.style.zIndex = '';
        });

        $mergeModal.addClass('active');
    });

    // Target selection — fetch counts
    $('#fs-merge-target-select').on('change', function() {
        var targetId = $(this).val();
        if (!targetId) {
            $('#fs-merge-confirm-btn').prop('disabled', true);
            $('#fs-merge-summary').hide();
            return;
        }

        $.post(fs_ajax.ajax_url, {
            action: 'fs_merge_client_preview',
            nonce: fs_ajax.nonce,
            source_id: mergeSourceId
        }, function(response) {
            if (response.success) {
                var d = response.data;
                var parts = [];
                if (d.projects > 0) parts.push(d.projects + ' <?php esc_html_e('projects', 'freelance-studio'); ?>');
                if (d.invoices > 0) parts.push(d.invoices + ' <?php esc_html_e('invoices', 'freelance-studio'); ?>');
                if (d.proposals > 0) parts.push(d.proposals + ' <?php esc_html_e('proposals', 'freelance-studio'); ?>');
                if (d.contracts > 0) parts.push(d.contracts + ' <?php esc_html_e('contracts', 'freelance-studio'); ?>');
                if (d.expenses > 0) parts.push(d.expenses + ' <?php esc_html_e('expenses', 'freelance-studio'); ?>');
                if (d.tasks > 0) parts.push(d.tasks + ' <?php esc_html_e('tasks', 'freelance-studio'); ?>');
                if (d.bookings > 0) parts.push(d.bookings + ' <?php esc_html_e('bookings', 'freelance-studio'); ?>');
                if (d.contacts > 0) parts.push(d.contacts + ' <?php esc_html_e('contacts', 'freelance-studio'); ?>');

                if (parts.length > 0) {
                    $('#fs-merge-summary-text').html(
                        '<?php esc_html_e('Will reassign:', 'freelance-studio'); ?> <strong>' + parts.join(', ') + '</strong>'
                    );
                } else {
                    $('#fs-merge-summary-text').text('<?php esc_html_e('No associated records found. The client will be deleted.', 'freelance-studio'); ?>');
                }
                $('#fs-merge-summary').show();
                $('#fs-merge-confirm-btn').prop('disabled', false);
            }
        });
    });

    // Close modal
    function closeMergeModal() {
        $mergeModal.removeClass('active');
        mergeSourceId = null;
    }
    $('#fs-merge-modal-close, #fs-merge-cancel-btn').on('click', closeMergeModal);
    $mergeModal.on('click', function(e) {
        if ($(e.target).hasClass('fs-modal')) closeMergeModal();
    });

    // Confirm merge
    $('#fs-merge-confirm-btn').on('click', function() {
        var targetId = $('#fs-merge-target-select').val();
        if (!mergeSourceId || !targetId) return;

        var $btn = $(this);
        $btn.prop('disabled', true).text('<?php esc_html_e('Merging...', 'freelance-studio'); ?>');

        $.post(fs_ajax.ajax_url, {
            action: 'fs_merge_client',
            nonce: fs_ajax.nonce,
            source_id: mergeSourceId,
            target_id: targetId
        }, function(response) {
            if (response.success) {
                window.location.href = '<?php echo esc_url(admin_url('admin.php?page=fs-clients&message=merged')); ?>';
            } else {
                alert(response.data && response.data.message ? response.data.message : '<?php esc_html_e('Merge failed.', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).text('<?php esc_html_e('Merge & Delete', 'freelance-studio'); ?>');
            }
        }).fail(function() {
            alert('<?php esc_html_e('Network error. Please try again.', 'freelance-studio'); ?>');
            $btn.prop('disabled', false).text('<?php esc_html_e('Merge & Delete', 'freelance-studio'); ?>');
        });
    });
});
</script>