<?php
/**
 * Project Detail View - Tabbed Interface
 *
 * @package Freelance_Studio
 */

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

// Get related data
$client = $project->client_id ? FS_Client::get($project->client_id) : null;
$invoices = FS_Invoice::get_by_project($project->id);
$expenses = FS_Expense::get_all(array('project_id' => $project->id));
$time_entries = FS_Time_Entry::get_all(array('project_id' => $project->id, 'running' => false));
$time_summary = FS_Time_Entry::get_summary(array('project_id' => $project->id));
$milestones = FS_Milestone::get_by_project($project->id);
$tasks = FS_Task::get_all(array('project_id' => $project->id, 'smart_recurring' => true));
$templates = FS_Project_Template::get_all();

// Calculate tracked hours from time summary (convert seconds to hours)
$tracked_hours = floatval(($time_summary->total_seconds ?? 0) / 3600);

// Calculate totals
$total_invoiced = 0;
$total_paid = 0;
foreach ($invoices as $inv) {
    $total_invoiced += $inv->total;
    $total_paid += $inv->amount_paid;
}

$total_expenses = 0;
foreach ($expenses as $exp) {
    $total_expenses += $exp->amount;
}

// Get current tab
$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'terms';
$base_url = admin_url('admin.php?page=fs-projects&action=view&id=' . $project->id);

// Define tabs
$tabs = array(
    'terms' => __('Terms', 'freelance-studio'),
    'milestones' => __('Milestones', 'freelance-studio'),
    'tasks' => __('Tasks', 'freelance-studio'),
    'timer' => __('Timer', 'freelance-studio'),
    'invoices' => __('Invoices', 'freelance-studio'),
    'expenses' => __('Expenses', 'freelance-studio'),
    'files' => __('Files', 'freelance-studio'),
    'notes' => __('Notes', 'freelance-studio'),
);

// Billing frequency labels
$billing_frequencies = array(
    'once' => __('Once', 'freelance-studio'),
    'weekly' => __('Weekly', 'freelance-studio'),
    'biweekly' => __('Bi-weekly', 'freelance-studio'),
    'monthly' => __('Monthly', 'freelance-studio'),
    'quarterly' => __('Quarterly', 'freelance-studio'),
    'milestone' => __('Per Milestone', 'freelance-studio'),
);

$milestone_progress = FS_Milestone::get_project_progress($project->id);
?>

<div class="wrap fs-wrap fs-project-detail">
    <?php
    // Display messages from redirects (e.g., expense created from project context)
    $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
    if ($message):
        $notice_class = 'success';
        $notice_text = __('Done!', 'freelance-studio');
        switch ($message) {
            case 'expense_created':
                $notice_text = __('Expense added successfully.', 'freelance-studio');
                break;
            case 'updated':
                $notice_text = __('Updated successfully.', 'freelance-studio');
                break;
            case 'error':
                $notice_class = 'error';
                $notice_text = __('Something went wrong. Please try again.', 'freelance-studio');
                break;
        }
    ?>
        <div class="fs-notice <?php echo  esc_attr( $notice_class ); ?>"><?php echo  esc_attr( $notice_text ); ?></div>
    <?php endif; ?>
    
    <!-- Breadcrumb -->
    <div class="fs-breadcrumb">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects') ); ?>"><?php esc_html_e('Projects', 'freelance-studio'); ?></a>
        <span>/</span>
        <span><?php echo esc_html($project->name); ?></span>
        <?php if (!empty($project->archived)): ?>
            <span class="fs-status-badge status-on-hold fs-ml-sm"><?php esc_html_e('Archived', 'freelance-studio'); ?></span>
        <?php endif; ?>
    </div>
    
    <!-- Header Actions -->
    <div class="fs-list-header">
        <div class="fs-header-actions">
            <button type="button" class="fs-btn fs-open-invoice-wizard" data-project-id="<?php echo  intval( $project->id ); ?>" data-client-id="<?php echo  intval( $project->client_id ); ?>">
                <?php esc_html_e('Invoice Project', 'freelance-studio'); ?>
            </button>
            <?php 
            // Show Invoice Deposit button if deposit required but not yet paid
            $has_deposit = ($project->deposit_amount > 0 || $project->deposit_percentage > 0);
            if ($has_deposit && !$project->deposit_paid): 
            ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=invoice_deposit&id=' . $project->id . '&_wpnonce=' . wp_create_nonce('fs_invoice_deposit_' . $project->id)) ); ?>" class="fs-btn fs-btn-deposit">
                <?php esc_html_e('Invoice Deposit', 'freelance-studio'); ?>
            </a>
            <?php endif; ?>
            <div class="fs-dropdown">
                <button type="button" class="fs-btn fs-btn-secondary fs-dropdown-trigger"><?php esc_html_e('More', 'freelance-studio'); ?> ▾</button>
                <div class="fs-dropdown-menu">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=edit&id=' . $project->id) ); ?>"><?php esc_html_e('Edit Project', 'freelance-studio'); ?></a>
                    <a href="#" class="fs-duplicate-project" data-project-id="<?php echo  intval( $project->id ); ?>"><?php esc_html_e('Duplicate Project', 'freelance-studio'); ?></a>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=add&project_id=' . $project->id) ); ?>"><?php esc_html_e('Add Expense', 'freelance-studio'); ?></a>
                    <hr>
                    <?php if (!empty($project->archived)): ?>
                    <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-projects&do_unarchive=1&id=' . $project->id) ), 'fs_unarchive_project'); ?>"><?php esc_html_e('Restore from Archive', 'freelance-studio'); ?></a>
                    <?php else: ?>
                    <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-projects&do_archive=1&id=' . $project->id) ), 'fs_archive_project'); ?>"><?php esc_html_e('Archive Project', 'freelance-studio'); ?></a>
                    <?php endif; ?>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects') ); ?>"><?php esc_html_e('Back to Projects', 'freelance-studio'); ?></a>
                </div>
            </div>
            <?php if ($client): ?>
                <span class="fs-header-client">
                    📋 <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id) ); ?>"><?php echo esc_html($client->company_name ?: $client->name); ?></a>
                </span>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Tab Navigation -->
    <nav class="fs-tab-nav">
        <?php foreach ($tabs as $tab_id => $tab_label): ?>
            <a href="<?php echo esc_url(add_query_arg('tab', $tab_id, $base_url)); ?>" 
               class="fs-tab-link <?php echo $current_tab === $tab_id ? 'active' : ''; ?>">
                <?php if ($tab_id === 'invoices' && count($invoices) > 0): ?>
                    <span class="fs-tab-indicator"></span>
                <?php endif; ?>
                <?php echo esc_html($tab_label); ?>
            </a>
        <?php endforeach; ?>
    </nav>
    
    <!-- Tab Content -->
    <div class="fs-tab-content">
        
        <?php if ($current_tab === 'terms'): 
            // Get services from project
            $services = !empty($project->services) ? json_decode($project->services, true) : array();
            if (!is_array($services)) $services = array();
            
            // Get billing frequencies and activity types
            $billing_frequencies_list = FS_Project::get_billing_frequencies();
            $current_frequency = isset($project->billing_frequency) ? $project->billing_frequency : 'once';
            $activity_types = FS_Time_Entry::get_activity_types();
            
            // Pre-calculate hours per activity for this project
            $hours_by_activity = array();
            foreach ($activity_types as $activity_key => $activity_label) {
                $activity_summary = FS_Time_Entry::get_summary(array(
                    'project_id' => $project->id,
                    'activity' => $activity_key
                ));
                $hours_by_activity[$activity_key] = floatval(($activity_summary->total_seconds ?? 0) / 3600);
            }
            
            // Calculate project total (considering tracked hours for hourly services)
            $project_total = 0;
            if (!empty($services)) {
                foreach ($services as $svc) {
                    $pricing_type = $svc['pricing_type'] ?? 'fixed';
                    $hourly_source = $svc['hourly_source'] ?? 'estimated';
                    
                    if ($pricing_type === 'hourly' && $hourly_source === 'tracked') {
                        // Get hours for the specific activity
                        $service_activity = $svc['activity'] ?? '';
                        $service_hours = !empty($service_activity) ? ($hours_by_activity[$service_activity] ?? 0) : $tracked_hours;
                        $rate = floatval($svc['rate'] ?? 0);
                        $project_total += $rate * $service_hours;
                    } else {
                        $project_total += floatval($svc['amount'] ?? 0);
                    }
                }
            } elseif ($project->billing_type === 'fixed') {
                $project_total = floatval($project->fixed_price);
            } elseif ($project->billing_type === 'retainer') {
                $project_total = floatval($project->retainer_amount);
            }
        ?>
            <!-- Terms Tab - Two Column Layout -->
            <div class="fs-tab-pane fs-terms-two-col">
                <!-- Left Column: Main Content -->
                <div class="fs-terms-main">
                    <!-- Project Info Card -->
                    <div class="fs-project-card">
                        <div class="fs-card-header">
                            <h2 class="fs-card-title"><?php echo esc_html($project->name); ?></h2>
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=edit&id=' . $project->id) ); ?>" class="fs-btn fs-btn-secondary fs-btn-small fs-edit-link"><span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                        </div>
                        
                        <?php 
                        // Show retainer summary for projects with retainer service (v3.9.0)
                        $retainer_service = FS_Project::get_retainer_service($project);
                        $capped_service = null;
                        if ($retainer_service):
                            $project_id = $project->id;
                            unset($tracked_hours); // Let widget scope hours to current period
                            include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/retainer-widget.php';
                            $tracked_hours = floatval(($time_summary->total_seconds ?? 0) / 3600); // Restore
                        endif;
                        
                        // Show hours budget for capped hourly projects (v7.9.0)
                        if (!$retainer_service):
                            $capped_service = FS_Project::get_capped_hourly_service($project);
                            if ($capped_service):
                                $project_id = $project->id;
                                $retainer_service = null;
                                unset($tracked_hours); // Let widget calculate its own total
                                include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/retainer-widget.php';
                                $tracked_hours = floatval(($time_summary->total_seconds ?? 0) / 3600); // Restore
                            endif;
                        endif;
                        ?>
                        
                        <!-- Billing Schedule Section -->
                        <div class="fs-card-section" id="billing-schedule-section">
                            <div class="fs-card-section-header">
                                <h3><?php esc_html_e('Billing schedule', 'freelance-studio'); ?></h3>
                                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-edit-link fs-inline-edit-trigger" data-section="billing-schedule"><span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?></button>
                            </div>
                            <p class="fs-section-description"><?php esc_html_e('Set dates to get invoice reminders.', 'freelance-studio'); ?></p>
                            
                            <!-- Display Mode -->
                            <div class="fs-billing-details fs-display-mode">
                                <div class="fs-detail-row">
                                    <span class="fs-detail-label"><?php esc_html_e('Start date', 'freelance-studio'); ?></span>
                                    <span class="fs-detail-value" id="display-start-date">
                                        <?php if ($project->start_date): ?>
                                            <?php echo  esc_html( FS_View_Context::format_date($project->start_date) ); ?>
                                        <?php else: ?>
                                            <a href="#" class="fs-set-date-link fs-inline-edit-trigger" data-section="billing-schedule"><?php esc_html_e('Set date', 'freelance-studio'); ?></a>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <div class="fs-detail-row">
                                    <span class="fs-detail-label"><?php esc_html_e('End date', 'freelance-studio'); ?></span>
                                    <span class="fs-detail-value" id="display-end-date">
                                        <?php if ($project->due_date): ?>
                                            <?php echo  esc_html( FS_View_Context::format_date($project->due_date) ); ?>
                                        <?php else: ?>
                                            <a href="#" class="fs-set-date-link fs-inline-edit-trigger" data-section="billing-schedule"><?php esc_html_e('Set date', 'freelance-studio'); ?></a>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <div class="fs-detail-row">
                                    <span class="fs-detail-label"><?php esc_html_e('Date of 1st invoice', 'freelance-studio'); ?></span>
                                    <span class="fs-detail-value" id="display-first-invoice">
                                        <?php if (!empty($project->first_invoice_date)): ?>
                                            <?php echo  esc_html( FS_View_Context::format_date($project->first_invoice_date) ); ?>
                                        <?php else: ?>
                                            <a href="#" class="fs-set-date-link fs-inline-edit-trigger" data-section="billing-schedule"><?php esc_html_e('Set date', 'freelance-studio'); ?></a>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <div class="fs-detail-row">
                                    <span class="fs-detail-label"><?php esc_html_e('I will bill', 'freelance-studio'); ?></span>
                                    <span class="fs-detail-value" id="display-billing-frequency">
                                        <?php echo  esc_html( isset($billing_frequencies_list[$current_frequency]) ? $billing_frequencies_list[$current_frequency] : __('Once', 'freelance-studio') ); ?>
                                    </span>
                                </div>
                            </div>
                            
                            <!-- Edit Mode -->
                            <div class="fs-billing-edit fs-edit-mode" style="display: none;">
                                <div class="fs-form-row">
                                    <div class="fs-form-group">
                                        <label><?php esc_html_e('Start date', 'freelance-studio'); ?></label>
                                        <input type="date" name="start_date" value="<?php echo esc_attr($project->start_date); ?>">
                                    </div>
                                    <div class="fs-form-group">
                                        <label><?php esc_html_e('End date', 'freelance-studio'); ?></label>
                                        <input type="date" name="due_date" value="<?php echo esc_attr($project->due_date); ?>">
                                    </div>
                                </div>
                                <div class="fs-form-row">
                                    <div class="fs-form-group">
                                        <label><?php esc_html_e('Date of 1st invoice', 'freelance-studio'); ?></label>
                                        <input type="date" name="first_invoice_date" value="<?php echo esc_attr($project->first_invoice_date ?? ''); ?>">
                                    </div>
                                    <div class="fs-form-group">
                                        <label><?php esc_html_e('I will bill', 'freelance-studio'); ?></label>
                                        <select name="billing_frequency">
                                            <?php foreach ($billing_frequencies_list as $key => $label): ?>
                                                <option value="<?php echo esc_attr($key); ?>" <?php selected($current_frequency, $key); ?>>
                                                    <?php echo esc_html($label); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="fs-edit-actions">
                                    <button type="button" class="button button-primary fs-save-billing-schedule"><?php esc_html_e('Save', 'freelance-studio'); ?></button>
                                    <button type="button" class="button fs-cancel-edit"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Project Services Card -->
                    <div class="fs-project-card" id="services-section">
                        <div class="fs-card-header">
                            <h3 class="fs-card-title"><?php esc_html_e('Project services', 'freelance-studio'); ?></h3>
                            <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-edit-link fs-inline-edit-trigger" data-section="services"><span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?></button>
                        </div>
                    
                        <!-- Display Mode -->
                        <div class="fs-services-display fs-display-mode">
                            <?php if (!empty($services)): ?>
                                <div class="fs-services-list-modern">
                                    <?php foreach ($services as $svc): 
                                        $pricing_type = $svc['pricing_type'] ?? 'fixed';
                                        $hourly_source = $svc['hourly_source'] ?? 'estimated';
                                        $service_activity = $svc['activity'] ?? '';
                                        $rate = floatval($svc['rate'] ?? 0);
                                        
                                        // Calculate quantity and amount based on source
                                        if ($pricing_type === 'hourly' && $hourly_source === 'tracked') {
                                            $qty = !empty($service_activity) ? ($hours_by_activity[$service_activity] ?? 0) : $tracked_hours;
                                            $amount = $rate * $qty;
                                        } else {
                                            $qty = floatval($svc['quantity'] ?? 1);
                                            $amount = floatval($svc['amount'] ?? 0);
                                        }
                                        
                                        // Format quantity label
                                        if ($pricing_type === 'hourly' && $hourly_source === 'tracked') {
                                            $qty_label = '<span class="fs-tracked-indicator"><span class="dashicons dashicons-clock"></span> ' . number_format($qty, 2) . ' tracked hrs × ' . FS_View_Context::format_currency($rate) . '</span>';
                                        } elseif ($pricing_type === 'hourly') {
                                            $qty_label = $qty . ' hr(s) × ' . FS_View_Context::format_currency($rate);
                                        } elseif ($pricing_type === 'retainer') {
                                            $qty_label = __('Monthly Retainer', 'freelance-studio');
                                        } else {
                                            $qty_label = $qty . ' item(s) (flat fee)';
                                        }

                                        // Hour cap badge info
                                        $has_cap = $pricing_type === 'hourly' && $hourly_source === 'tracked'
                                                   && !empty($svc['hour_cap']) && floatval($svc['hour_cap']) > 0;
                                        $cap_hours = $has_cap ? floatval($svc['hour_cap']) : 0;
                                        $cap_activity = $svc['activity'] ?? '';
                                        $cap_tracked  = $has_cap ? (!empty($cap_activity) ? ($hours_by_activity[$cap_activity] ?? 0) : $tracked_hours) : 0;
                                    ?>
                                        <div class="fs-service-row-modern">
                                            <div class="fs-service-info">
                                                <span class="fs-service-name-modern"><?php echo esc_html($svc['name']); ?></span>
                                                <?php if (!empty($svc['description'])): ?>
                                                    <span class="fs-service-desc-modern"><?php echo esc_html($svc['description']); ?></span>
                                                <?php endif; ?>
                                                <?php if ($has_cap): ?>
                                                    <span class="fs-service-cap-badge <?php echo $cap_tracked >= $cap_hours ? 'fs-cap-reached' : ''; ?>">
                                                        <span class="dashicons dashicons-clock"></span>
                                                        <?php echo number_format($cap_tracked, 1); ?> / <?php echo number_format($cap_hours, 1); ?> <?php esc_html_e('hrs cap', 'freelance-studio'); ?>
                                                        <?php if ($cap_tracked >= $cap_hours): ?>
                                                            &mdash; <strong><?php esc_html_e('Cap reached', 'freelance-studio'); ?></strong>
                                                        <?php endif; ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                            <div class="fs-service-pricing-modern">
                                                <span class="fs-service-rate-qty"><small><?php echo  esc_html( $qty_label ); ?></small></span>
                                                <span class="fs-service-amount-modern"><?php echo  esc_html( FS_View_Context::format_currency($amount) ); ?></span>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>

                            <?php else: ?>
                                <p class="text-muted"><?php esc_html_e('No services added yet.', 'freelance-studio'); ?></p>
                            <?php endif; ?>
                            
                            <div class="fs-currency-label"><?php esc_html_e('Currency:', 'freelance-studio'); ?> USD</div>
                            
                            <div class="fs-project-total-row">
                                <span class="fs-project-total-label"><?php esc_html_e('Project Total', 'freelance-studio'); ?></span>
                                <span class="fs-project-total-amount" id="display-project-total"><?php echo  esc_html( FS_View_Context::format_currency($project_total) ); ?></span>
                            </div>
                            
                            <div class="fs-add-service-link">
                                <button type="button" class="fs-quick-add-btn fs-inline-edit-trigger" data-section="services">⊕ <?php esc_html_e('Add service', 'freelance-studio'); ?></button>
                            </div>
                        </div>
                    
                    <!-- Edit Mode -->
                    <div class="fs-services-edit fs-edit-mode" style="display: none;">
                        <div id="fs-services-container">
                            <?php if (!empty($services)): ?>
                                <?php foreach ($services as $index => $svc): 
                                    $pricing_type = $svc['pricing_type'] ?? 'fixed';
                                    $hourly_source = $svc['hourly_source'] ?? 'estimated';
                                    $service_activity = $svc['activity'] ?? '';
                                    $service_hours = !empty($service_activity) ? ($hours_by_activity[$service_activity] ?? 0) : $tracked_hours;
                                ?>
                                    <div class="fs-service-item" data-index="<?php echo  esc_attr( $index ); ?>" data-hours-by-activity='<?php echo  esc_attr( json_encode($hours_by_activity) ); ?>'>
                                        <div class="fs-service-header">
                                            <span class="fs-service-drag">☰</span>
                                            <input type="text" name="services[<?php echo  esc_attr( $index ); ?>][name]" 
                                                   class="fs-service-name-input" placeholder="<?php esc_attr_e('Service name', 'freelance-studio'); ?>"
                                                   value="<?php echo esc_attr($svc['name'] ?? ''); ?>">
                                            <button type="button" class="fs-remove-service" title="<?php esc_attr_e('Remove', 'freelance-studio'); ?>">×</button>
                                        </div>
                                        <div class="fs-service-body">
                                            <textarea name="services[<?php echo  esc_attr( $index ); ?>][description]" 
                                                      class="fs-service-description" rows="2"
                                                      placeholder="<?php esc_attr_e('Description (optional)', 'freelance-studio'); ?>"><?php echo esc_textarea($svc['description'] ?? ''); ?></textarea>
                                            <div class="fs-service-pricing">
                                                <select name="services[<?php echo  esc_attr( $index ); ?>][pricing_type]" class="fs-service-pricing-type">
                                                    <option value="fixed" <?php selected($pricing_type, 'fixed'); ?>><?php esc_html_e('Flat fee', 'freelance-studio'); ?></option>
                                                    <option value="hourly" <?php selected($pricing_type, 'hourly'); ?>><?php esc_html_e('Hourly', 'freelance-studio'); ?></option>
                                                    <option value="retainer" <?php selected($pricing_type, 'retainer'); ?>><?php esc_html_e('Monthly Retainer', 'freelance-studio'); ?></option>
                                                </select>
                                                <div class="fs-hourly-options" style="<?php echo $pricing_type !== 'hourly' ? 'display:none;' : ''; ?>">
                                                    <select name="services[<?php echo  esc_attr( $index ); ?>][hourly_source]" class="fs-hourly-source">
                                                        <option value="estimated" <?php selected($hourly_source, 'estimated'); ?>><?php esc_html_e('Estimated hours', 'freelance-studio'); ?></option>
                                                        <option value="tracked" <?php selected($hourly_source, 'tracked'); ?>><?php esc_html_e('From tracked time', 'freelance-studio'); ?></option>
                                                    </select>
                                                    <select name="services[<?php echo  esc_attr( $index ); ?>][activity]" class="fs-service-activity" style="<?php echo  esc_attr( $hourly_source !== 'tracked' ? 'display:none;' : '' ); ?>">
                                                        <option value=""><?php esc_html_e('All activities', 'freelance-studio'); ?></option>
                                                        <?php foreach ($activity_types as $act_key => $act_label): ?>
                                                            <option value="<?php echo esc_attr($act_key); ?>" <?php selected($service_activity, $act_key); ?> data-hours="<?php echo esc_attr($hours_by_activity[$act_key] ?? 0); ?>">
                                                                <?php echo esc_html($act_label); ?> (<?php echo number_format($hours_by_activity[$act_key] ?? 0, 2); ?> hrs)
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="fs-pricing-fields">
                                                    <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][rate]" 
                                                           class="fs-service-rate" step="0.01" min="0"
                                                           placeholder="<?php esc_attr_e('Rate', 'freelance-studio'); ?>"
                                                           value="<?php echo esc_attr($svc['rate'] ?? ''); ?>">
                                                    <span class="fs-pricing-separator fs-qty-separator" style="<?php echo ($pricing_type === 'hourly' && $hourly_source === 'tracked') ? 'display:none;' : ''; ?>">×</span>
                                                    <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][quantity]" 
                                                           class="fs-service-quantity" step="0.01" min="0"
                                                           placeholder="<?php esc_attr_e('Qty', 'freelance-studio'); ?>"
                                                           value="<?php echo esc_attr($svc['quantity'] ?? 1); ?>"
                                                           style="<?php echo ($pricing_type === 'hourly' && $hourly_source === 'tracked') ? 'display:none;' : ''; ?>">
                                                    <span class="fs-tracked-hours-display" style="<?php echo ($pricing_type === 'hourly' && $hourly_source === 'tracked') ? '' : 'display:none;'; ?>">
                                                        × <strong class="fs-activity-hours"><?php echo number_format($service_hours, 2); ?></strong> <?php esc_html_e('tracked hrs', 'freelance-studio'); ?>
                                                    </span>
                                                    <span class="fs-pricing-separator">=</span>
                                                    <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][amount]" 
                                                           class="fs-service-amount" step="0.01" min="0" readonly
                                                           value="<?php echo esc_attr($svc['amount'] ?? ''); ?>">
                                                </div>
                                                
                                                <?php 
                                                // v7.9.0: Hour cap fields for inline editor
                                                $hour_cap = $svc['hour_cap'] ?? '';
                                                $hour_cap_overage_rate = $svc['hour_cap_overage_rate'] ?? '';
                                                $hour_cap_notify_client = !empty($svc['hour_cap_notify_client']);
                                                $hour_cap_notify_freelancer = !empty($svc['hour_cap_notify_freelancer']);
                                                $hour_cap_warn_threshold = $svc['hour_cap_warn_threshold'] ?? '';
                                                $has_hour_cap = !empty($hour_cap) && floatval($hour_cap) > 0;
                                                ?>
                                                <div class="fs-hour-cap-fields" style="<?php echo ($pricing_type === 'hourly' && $hourly_source === 'tracked') ? '' : 'display:none;'; ?>">
                                                    <label class="fs-checkbox-label fs-hour-cap-toggle">
                                                        <input type="checkbox" name="services[<?php echo  esc_attr( $index ); ?>][hour_cap_enabled]" 
                                                               class="fs-hour-cap-checkbox" value="1" <?php checked($has_hour_cap); ?>>
                                                        <?php esc_html_e('Cap my hours', 'freelance-studio'); ?>
                                                    </label>
                                                    <div class="fs-hour-cap-options" style="<?php echo $has_hour_cap ? '' : 'display:none;'; ?>">
                                                        <div class="fs-hour-cap-row">
                                                            <div class="fs-hour-cap-field">
                                                                <label><?php esc_html_e('Hour Limit', 'freelance-studio'); ?></label>
                                                                <div class="fs-hours-input">
                                                                    <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][hour_cap]" 
                                                                           class="fs-hour-cap-input" step="0.5" min="0"
                                                                           placeholder="10"
                                                                           value="<?php echo esc_attr($hour_cap); ?>">
                                                                    <span class="fs-hours-suffix"><?php esc_html_e('hrs', 'freelance-studio'); ?></span>
                                                                </div>
                                                            </div>
                                                            <div class="fs-hour-cap-field">
                                                                <label><?php esc_html_e('Overage Rate', 'freelance-studio'); ?></label>
                                                                <div class="fs-currency-input">
                                                                    <span class="fs-currency-symbol">$</span>
                                                                    <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][hour_cap_overage_rate]" 
                                                                           class="fs-hour-cap-overage-rate" step="0.01" min="0"
                                                                           placeholder="<?php echo esc_attr($svc['rate'] ?? ''); ?>"
                                                                           value="<?php echo esc_attr($hour_cap_overage_rate); ?>">
                                                                    <span class="fs-rate-suffix">/hr</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="fs-hour-cap-notify-row">
                                                            <label class="fs-checkbox-label">
                                                                <input type="checkbox" name="services[<?php echo  esc_attr( $index ); ?>][hour_cap_notify_freelancer]" 
                                                                       class="fs-hour-cap-notify-freelancer-checkbox" value="1" <?php checked($hour_cap_notify_freelancer); ?>>
                                                                <?php esc_html_e('Notify me when cap is reached', 'freelance-studio'); ?>
                                                            </label>
                                                        </div>
                                                        <div class="fs-hour-cap-notify-row">
                                                            <label class="fs-checkbox-label">
                                                                <input type="checkbox" name="services[<?php echo  esc_attr( $index ); ?>][hour_cap_notify_client]" 
                                                                       class="fs-hour-cap-notify-checkbox" value="1" <?php checked($hour_cap_notify_client); ?>>
                                                                <?php esc_html_e('Notify client when cap is reached', 'freelance-studio'); ?>
                                                            </label>
                                                            <?php 
                                                            $notify_contact_id = $svc['hour_cap_notify_contact_id'] ?? 'primary';
                                                            if ($project->client_id):
                                                                $cap_contacts = FS_Client_Contact::get_by_client($project->client_id);
                                                                $cap_client = FS_Client::get($project->client_id);
                                                            ?>
                                                            <select name="services[<?php echo  esc_attr( $index ); ?>][hour_cap_notify_contact_id]" 
                                                                    class="fs-hour-cap-contact-select"
                                                                    style="<?php echo $hour_cap_notify_client ? '' : 'display:none;'; ?>">
                                                                <?php if ($cap_client && $cap_client->email): ?>
                                                                    <option value="primary" <?php selected($notify_contact_id, 'primary'); ?>>
                                                                        <?php echo esc_html(($cap_client->name ?: $cap_client->company_name) . ' — ' . $cap_client->email); ?>
                                                                    </option>
                                                                <?php endif; ?>
                                                                <?php foreach ($cap_contacts as $cc): if (!empty($cc->email)): ?>
                                                                    <option value="<?php echo esc_attr($cc->id); ?>" <?php selected($notify_contact_id, $cc->id); ?>>
                                                                        <?php echo esc_html($cc->name . ' — ' . $cc->email); ?>
                                                                    </option>
                                                                <?php endif; endforeach; ?>
                                                            </select>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="fs-hour-cap-warn-row">
                                                            <label class="fs-checkbox-label">
                                                                <input type="checkbox" class="fs-hour-cap-warn-checkbox" value="1" <?php checked(!empty($hour_cap_warn_threshold)); ?>>
                                                                <?php esc_html_e('Send early warning at', 'freelance-studio'); ?>
                                                            </label>
                                                            <div class="fs-hour-cap-warn-fields" style="<?php echo !empty($hour_cap_warn_threshold) ? '' : 'display:none;'; ?>">
                                                                <div class="fs-hours-input fs-warn-threshold-input">
                                                                    <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][hour_cap_warn_threshold]"
                                                                           class="fs-hour-cap-warn-threshold" step="1" min="1" max="99"
                                                                           placeholder="80"
                                                                           value="<?php echo esc_attr($hour_cap_warn_threshold); ?>">
                                                                    <span class="fs-hours-suffix">%</span>
                                                                </div>
                                                                <span class="fs-warn-label"><?php esc_html_e('of hours used', 'freelance-studio'); ?></span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <?php
                                            // Retainer-specific fields (Issue 2 fix: match form.php)
                                            $retainer_amount     = $svc['retainer_amount'] ?? '';
                                            $retainer_hours      = $svc['retainer_hours'] ?? '';
                                            $retainer_overage    = $svc['retainer_overage_rate'] ?? '';
                                            $retainer_rollover   = isset($svc['retainer_rollover']) ? (bool)$svc['retainer_rollover'] : true;
                                            $saved_reset_day     = intval($project->retainer_reset_day ?? 0);
                                            ?>
                                            <div class="fs-retainer-service-fields" style="<?php echo $pricing_type !== 'retainer' ? 'display:none;' : ''; ?>">
                                                <div class="fs-retainer-service-row">
                                                    <div class="fs-retainer-field">
                                                        <label><?php esc_html_e('Monthly Amount', 'freelance-studio'); ?></label>
                                                        <div class="fs-currency-input">
                                                            <span class="fs-currency-symbol">$</span>
                                                            <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][retainer_amount]"
                                                                   class="fs-retainer-amount" step="0.01" min="0"
                                                                   placeholder="1500.00"
                                                                   value="<?php echo esc_attr($retainer_amount); ?>">
                                                        </div>
                                                    </div>
                                                    <div class="fs-retainer-field">
                                                        <label><?php esc_html_e('Hours Included', 'freelance-studio'); ?></label>
                                                        <div class="fs-hours-input">
                                                            <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][retainer_hours]"
                                                                   class="fs-retainer-hours" step="0.5" min="0"
                                                                   placeholder="10"
                                                                   value="<?php echo esc_attr($retainer_hours); ?>">
                                                            <span class="fs-hours-suffix"><?php esc_html_e('hrs/mo', 'freelance-studio'); ?></span>
                                                        </div>
                                                    </div>
                                                    <div class="fs-retainer-field">
                                                        <label><?php esc_html_e('Overage Rate', 'freelance-studio'); ?></label>
                                                        <div class="fs-currency-input">
                                                            <span class="fs-currency-symbol">$</span>
                                                            <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][retainer_overage_rate]"
                                                                   class="fs-retainer-overage" step="0.01" min="0"
                                                                   placeholder="150.00"
                                                                   value="<?php echo esc_attr($retainer_overage); ?>">
                                                            <span class="fs-rate-suffix">/hr</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="fs-retainer-options">
                                                    <label class="fs-checkbox-label">
                                                        <input type="checkbox" name="services[<?php echo  esc_attr( $index ); ?>][retainer_rollover]"
                                                               class="fs-retainer-rollover" value="1" <?php checked($retainer_rollover); ?>>
                                                        <?php esc_html_e('Allow unused hours to roll over to next month', 'freelance-studio'); ?>
                                                    </label>
                                                    <div class="fs-retainer-reset-day-row">
                                                        <label><?php esc_html_e('Hours reset on the', 'freelance-studio'); ?></label>
                                                        <select name="retainer_reset_day" class="fs-retainer-reset-day-select">
                                                            <option value=""><?php esc_html_e('— same day as project start —', 'freelance-studio'); ?></option>
                                                            <?php for ($d = 1; $d <= 28; $d++): ?>
                                                            <option value="<?php echo  esc_attr( $d ); ?>" <?php selected($saved_reset_day, $d); ?>><?php echo  esc_attr( $d . __('th of each month', 'freelance-studio') ); ?></option>
                                                            <?php endfor; ?>
                                                        </select>
                                                        <span class="fs-reset-day-hint"><?php esc_html_e('(max 28 to handle all months)', 'freelance-studio'); ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        
                        <button type="button" class="button fs-add-service-btn">➕ <?php esc_html_e('Add Service', 'freelance-studio'); ?></button>
                        
                        <div class="fs-services-total">
                            <span><?php esc_html_e('Total:', 'freelance-studio'); ?></span>
                            <span id="fs-services-edit-total"><?php echo  esc_html( FS_View_Context::format_currency($project_total) ); ?></span>
                        </div>
                        
                        <div class="fs-edit-actions">
                            <button type="button" class="button button-primary fs-save-services"><?php esc_html_e('Save', 'freelance-studio'); ?></button>
                            <button type="button" class="button fs-cancel-edit"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                        </div>
                    </div>
                    </div>
                </div><!-- End fs-terms-main -->
                
                <!-- Right Column: Sidebar -->
                <div class="fs-terms-sidebar">
                    <!-- Deposit Card -->
                    <div class="fs-project-card" id="deposit-section">
                        <div class="fs-card-header">
                            <h3 class="fs-card-title"><?php esc_html_e('Deposit', 'freelance-studio'); ?></h3>
                            <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-edit-link fs-inline-edit-trigger" data-section="deposit"><span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?></button>
                        </div>
                        
                        <!-- Display Mode -->
                        <div class="fs-deposit-display fs-display-mode">
                            <?php 
                            $has_deposit = ($project->deposit_amount > 0 || $project->deposit_percentage > 0);
                            $deposit_type = isset($project->deposit_type) ? $project->deposit_type : 'percentage';
                            ?>
                            <?php if ($has_deposit): ?>
                                <div class="fs-deposit-summary">
                                    <div class="fs-deposit-row">
                                        <span class="fs-deposit-label">
                                            <?php 
                                            if ($deposit_type === 'percentage' && $project->deposit_percentage > 0) {
                                                echo  esc_html( $project->deposit_percentage . '% ' . __('deposit', 'freelance-studio') );                                            } else {
                                                echo  esc_html( __('Fixed deposit', 'freelance-studio') );                                            }
                                            ?>
                                        </span>
                                        <span class="fs-deposit-amount"><?php echo  esc_html( FS_View_Context::format_currency($project->deposit_amount) ); ?></span>
                                    </div>
                                    <div class="fs-deposit-row">
                                        <span class="fs-deposit-label"><?php esc_html_e('Status', 'freelance-studio'); ?></span>
                                        <span class="fs-deposit-status">
                                            <?php if ($project->deposit_paid): ?>
                                                <span class="fs-status-badge status-paid"><?php esc_html_e('PAID', 'freelance-studio'); ?></span>
                                            <?php else: ?>
                                                <span class="fs-status-badge status-pending"><?php esc_html_e('UNPAID', 'freelance-studio'); ?></span>
                                            <?php endif; ?>
                                        </span>
                                    </div>
                                </div>
                            <?php else: ?>
                                <p class="text-muted"><?php esc_html_e('Deposit not required.', 'freelance-studio'); ?></p>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Edit Mode -->
                        <div class="fs-deposit-edit fs-edit-mode" style="display: none;">
                            <div class="fs-form-group">
                                <label><?php esc_html_e('Deposit type', 'freelance-studio'); ?></label>
                                <select name="deposit_type" id="deposit-type-select">
                                    <option value="none" <?php selected(!$has_deposit, true); ?>><?php esc_html_e('No deposit required', 'freelance-studio'); ?></option>
                                    <option value="percentage" <?php selected($deposit_type, 'percentage'); selected($has_deposit && $deposit_type === 'percentage', true); ?>><?php esc_html_e('Percentage of total', 'freelance-studio'); ?></option>
                                    <option value="fixed" <?php selected($deposit_type, 'fixed'); ?>><?php esc_html_e('Fixed amount', 'freelance-studio'); ?></option>
                                </select>
                            </div>
                            <div class="fs-deposit-fields" style="<?php echo !$has_deposit ? 'display:none;' : ''; ?>">
                                <div class="fs-form-group fs-deposit-percentage-field" style="<?php echo $deposit_type !== 'percentage' ? 'display:none;' : ''; ?>">
                                    <label><?php esc_html_e('Percentage', 'freelance-studio'); ?></label>
                                    <input type="number" name="deposit_percentage" step="1" min="0" max="100" 
                                           value="<?php echo esc_attr($project->deposit_percentage); ?>">
                                </div>
                                <div class="fs-form-group fs-deposit-amount-field" style="<?php echo $deposit_type !== 'fixed' ? 'display:none;' : ''; ?>">
                                    <label><?php esc_html_e('Amount', 'freelance-studio'); ?></label>
                                    <input type="number" name="deposit_amount" step="0.01" min="0" 
                                           value="<?php echo esc_attr($project->deposit_amount); ?>">
                                </div>
                            </div>
                            <?php if ($project->deposit_paid): ?>
                            <p class="fs-deposit-paid-note">
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php esc_html_e('Deposit has been paid.', 'freelance-studio'); ?>
                            </p>
                            <?php endif; ?>
                            <div class="fs-edit-actions">
                                <button type="button" class="button button-primary fs-save-deposit"><?php esc_html_e('Save', 'freelance-studio'); ?></button>
                                <button type="button" class="button fs-cancel-edit"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Milestones Preview Card -->
                    <div class="fs-project-card">
                        <div class="fs-card-header">
                            <h3 class="fs-card-title"><?php esc_html_e('Milestones', 'freelance-studio'); ?></h3>
                        </div>
                        
                        <?php if (!empty($milestones)): ?>
                            <div class="fs-milestones-preview">
                                <?php foreach ($milestones as $ms): 
                                    $is_completed = $ms->status === 'completed';
                                    $is_current = $ms->status === 'in_progress';
                                ?>
                                    <div class="fs-milestone-preview-item <?php echo $is_completed ? 'completed' : ($is_current ? 'current' : ''); ?>" data-milestone-id="<?php echo esc_attr($ms->id); ?>">
                                        <div class="fs-milestone-indicator <?php echo $is_completed ? 'completed' : ($is_current ? 'current' : ''); ?>" title="<?php echo $is_completed ? esc_attr__('Completed', 'freelance-studio') : esc_attr__('Click to mark complete', 'freelance-studio'); ?>">
                                            <?php if ($is_completed): ?>
                                                <span class="dashicons dashicons-yes"></span>
                                            <?php elseif ($is_current): ?>
                                                <span class="dashicons dashicons-marker"></span>
                                            <?php else: ?>
                                                <span class="dashicons dashicons-marker fs-icon-muted"></span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="fs-milestone-preview-info">
                                            <span class="fs-milestone-preview-name"><?php echo esc_html($ms->name); ?></span>
                                            <?php if ($ms->due_date): ?>
                                                <span class="fs-milestone-preview-date"><?php echo  esc_html( gmdate('M j, Y', strtotime($ms->due_date)) ); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-muted"><?php esc_html_e('No milestones added yet.', 'freelance-studio'); ?></p>
                            <a href="<?php echo  esc_url( add_query_arg('tab', 'milestones', $base_url) ); ?>" class="fs-btn fs-btn-secondary fs-btn-small">+ <?php esc_html_e('Add Milestone', 'freelance-studio'); ?></a>
                        <?php endif; ?>
                    </div>
                </div><!-- End fs-terms-sidebar -->
            </div><!-- End fs-terms-two-col -->
            
            <!-- Service Item Template -->
            <script type="text/template" id="fs-service-template">
                <div class="fs-service-item" data-index="{{index}}" data-hours-by-activity='<?php echo json_encode($hours_by_activity); ?>'>
                    <div class="fs-service-header">
                        <span class="fs-service-drag">☰</span>
                        <input type="text" name="services[{{index}}][name]" 
                               class="fs-service-name-input" placeholder="<?php esc_attr_e('Service name', 'freelance-studio'); ?>">
                        <button type="button" class="fs-remove-service" title="<?php esc_attr_e('Remove', 'freelance-studio'); ?>">×</button>
                    </div>
                    <div class="fs-service-body">
                        <textarea name="services[{{index}}][description]" 
                                  class="fs-service-description" rows="2"
                                  placeholder="<?php esc_attr_e('Description (optional)', 'freelance-studio'); ?>"></textarea>
                        <div class="fs-service-pricing">
                            <select name="services[{{index}}][pricing_type]" class="fs-service-pricing-type">
                                <option value="fixed"><?php esc_html_e('Flat fee', 'freelance-studio'); ?></option>
                                <option value="hourly"><?php esc_html_e('Hourly', 'freelance-studio'); ?></option>
                                <option value="retainer"><?php esc_html_e('Monthly Retainer', 'freelance-studio'); ?></option>
                            </select>
                            <div class="fs-hourly-options" style="display:none;">
                                <select name="services[{{index}}][hourly_source]" class="fs-hourly-source">
                                    <option value="estimated"><?php esc_html_e('Estimated hours', 'freelance-studio'); ?></option>
                                    <option value="tracked"><?php esc_html_e('From tracked time', 'freelance-studio'); ?></option>
                                </select>
                                <select name="services[{{index}}][activity]" class="fs-service-activity" style="display:none;">
                                    <option value=""><?php esc_html_e('All activities', 'freelance-studio'); ?></option>
                                    <?php foreach ($activity_types as $act_key => $act_label): ?>
                                        <option value="<?php echo esc_attr($act_key); ?>" data-hours="<?php echo esc_attr($hours_by_activity[$act_key] ?? 0); ?>">
                                            <?php echo esc_html($act_label); ?> (<?php echo number_format($hours_by_activity[$act_key] ?? 0, 2); ?> hrs)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="fs-pricing-fields">
                                <input type="number" name="services[{{index}}][rate]" 
                                       class="fs-service-rate" step="0.01" min="0"
                                       placeholder="<?php esc_attr_e('Rate', 'freelance-studio'); ?>">
                                <span class="fs-pricing-separator fs-qty-separator">×</span>
                                <input type="number" name="services[{{index}}][quantity]" 
                                       class="fs-service-quantity" step="0.01" min="0" value="1"
                                       placeholder="<?php esc_attr_e('Qty', 'freelance-studio'); ?>">
                                <span class="fs-tracked-hours-display" style="display:none;">
                                    × <strong class="fs-activity-hours"><?php echo number_format($tracked_hours, 2); ?></strong> <?php esc_html_e('tracked hrs', 'freelance-studio'); ?>
                                </span>
                                <span class="fs-pricing-separator">=</span>
                                <input type="number" name="services[{{index}}][amount]" 
                                       class="fs-service-amount" step="0.01" min="0" readonly value="0">
                            </div>

                            <!-- Hour Cap fields -->
                            <div class="fs-hour-cap-fields" style="display:none;">
                                <label class="fs-checkbox-label fs-hour-cap-toggle">
                                    <input type="checkbox" name="services[{{index}}][hour_cap_enabled]" 
                                           class="fs-hour-cap-checkbox" value="1">
                                    <?php esc_html_e('Cap my hours', 'freelance-studio'); ?>
                                </label>
                                <div class="fs-hour-cap-options" style="display:none;">
                                    <div class="fs-hour-cap-row">
                                        <div class="fs-hour-cap-field">
                                            <label><?php esc_html_e('Hour Limit', 'freelance-studio'); ?></label>
                                            <div class="fs-hours-input">
                                                <input type="number" name="services[{{index}}][hour_cap]" 
                                                       class="fs-hour-cap-input" step="0.5" min="0" placeholder="10">
                                                <span class="fs-hours-suffix"><?php esc_html_e('hrs', 'freelance-studio'); ?></span>
                                            </div>
                                        </div>
                                        <div class="fs-hour-cap-field">
                                            <label><?php esc_html_e('Overage Rate', 'freelance-studio'); ?></label>
                                            <div class="fs-currency-input">
                                                <span class="fs-currency-symbol">$</span>
                                                <input type="number" name="services[{{index}}][hour_cap_overage_rate]" 
                                                       class="fs-hour-cap-overage-rate" step="0.01" min="0" placeholder="">
                                                <span class="fs-rate-suffix">/hr</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="fs-hour-cap-notify-row">
                                        <label class="fs-checkbox-label">
                                            <input type="checkbox" name="services[{{index}}][hour_cap_notify_freelancer]" 
                                                   class="fs-hour-cap-notify-freelancer-checkbox" value="1">
                                            <?php esc_html_e('Notify me when cap is reached', 'freelance-studio'); ?>
                                        </label>
                                    </div>
                                    <div class="fs-hour-cap-notify-row">
                                        <label class="fs-checkbox-label">
                                            <input type="checkbox" name="services[{{index}}][hour_cap_notify_client]" 
                                                   class="fs-hour-cap-notify-checkbox" value="1">
                                            <?php esc_html_e('Notify client when cap is reached', 'freelance-studio'); ?>
                                        </label>
                                        <select name="services[{{index}}][hour_cap_notify_contact_id]" 
                                                class="fs-hour-cap-contact-select" style="display:none;">
                                            <option value="primary"><?php esc_html_e('— Select contact —', 'freelance-studio'); ?></option>
                                        </select>
                                    </div>
                                    <div class="fs-hour-cap-warn-row">
                                        <label class="fs-checkbox-label">
                                            <input type="checkbox" class="fs-hour-cap-warn-checkbox" value="1">
                                            <?php esc_html_e('Send early warning at', 'freelance-studio'); ?>
                                        </label>
                                        <div class="fs-hour-cap-warn-fields" style="display:none;">
                                            <div class="fs-hours-input fs-warn-threshold-input">
                                                <input type="number" name="services[{{index}}][hour_cap_warn_threshold]"
                                                       class="fs-hour-cap-warn-threshold" step="1" min="1" max="99" placeholder="80">
                                                <span class="fs-hours-suffix">%</span>
                                            </div>
                                            <span class="fs-warn-label"><?php esc_html_e('of hours used', 'freelance-studio'); ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Retainer-specific fields -->
                            <div class="fs-retainer-service-fields" style="display:none;">
                                <div class="fs-retainer-service-row">
                                    <div class="fs-retainer-field">
                                        <label><?php esc_html_e('Monthly Amount', 'freelance-studio'); ?></label>
                                        <div class="fs-currency-input">
                                            <span class="fs-currency-symbol">$</span>
                                            <input type="number" name="services[{{index}}][retainer_amount]" 
                                                   class="fs-retainer-amount" step="0.01" min="0" placeholder="1500.00">
                                        </div>
                                    </div>
                                    <div class="fs-retainer-field">
                                        <label><?php esc_html_e('Hours Included', 'freelance-studio'); ?></label>
                                        <div class="fs-hours-input">
                                            <input type="number" name="services[{{index}}][retainer_hours]" 
                                                   class="fs-retainer-hours" step="0.5" min="0" placeholder="10">
                                            <span class="fs-hours-suffix"><?php esc_html_e('hrs/mo', 'freelance-studio'); ?></span>
                                        </div>
                                    </div>
                                    <div class="fs-retainer-field">
                                        <label><?php esc_html_e('Overage Rate', 'freelance-studio'); ?></label>
                                        <div class="fs-currency-input">
                                            <span class="fs-currency-symbol">$</span>
                                            <input type="number" name="services[{{index}}][retainer_overage_rate]" 
                                                   class="fs-retainer-overage" step="0.01" min="0" placeholder="150.00">
                                            <span class="fs-rate-suffix">/hr</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="fs-retainer-options">
                                    <label class="fs-checkbox-label">
                                        <input type="checkbox" name="services[{{index}}][retainer_rollover]" 
                                               class="fs-retainer-rollover" value="1" checked>
                                        <?php esc_html_e('Allow unused hours to roll over to next month', 'freelance-studio'); ?>
                                    </label>
                                    <div class="fs-retainer-reset-day-row">
                                        <label><?php esc_html_e('Hours reset on the', 'freelance-studio'); ?></label>
                                        <select name="retainer_reset_day" class="fs-retainer-reset-day-select">
                                            <option value=""><?php esc_html_e('— same day as project start —', 'freelance-studio'); ?></option>
                                            <?php for ($d = 1; $d <= 28; $d++): ?>
                                            <option value="<?php echo  esc_attr( $d ); ?>"><?php echo  esc_attr( $d . __('th of each month', 'freelance-studio') ); ?></option>
                                            <?php endfor; ?>
                                        </select>
                                        <span class="fs-reset-day-hint"><?php esc_html_e('(max 28 to handle all months)', 'freelance-studio'); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </script>
        
        <?php elseif ($current_tab === 'milestones'): ?>
            <!-- Milestones Tab - Modern Card Design -->
            <div class="fs-tab-pane fs-milestones-tab">
                <div class="fs-tab-header">
                    <button type="button" class="fs-btn fs-btn-primary" id="add-milestone-btn">
                        <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Milestone', 'freelance-studio'); ?>
                    </button>
                    <?php if (!empty($templates)): ?>
                        <div class="fs-dropdown">
                            <button type="button" class="fs-btn fs-btn-secondary fs-dropdown-trigger">
                                <span class="dashicons dashicons-layout"></span> <?php esc_html_e('Apply Template', 'freelance-studio'); ?> ▾
                            </button>
                            <div class="fs-dropdown-menu">
                                <?php foreach ($templates as $tpl): ?>
                                    <a href="#" class="apply-template-link" data-template-id="<?php echo esc_attr($tpl->id); ?>">
                                        <?php echo esc_html($tpl->name); ?>
                                        <small>(<?php echo count($tpl->default_milestones); ?> milestones, <?php echo count($tpl->default_tasks); ?> tasks)</small>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($milestones)): 
                    $total_milestones = count($milestones);
                    $completed_milestones = count(array_filter($milestones, function($m) { return $m->status === 'completed'; }));
                ?>
                    <!-- Progress Overview Card -->
                    <div class="fs-milestone-overview-card">
                        <div class="fs-milestone-overview-stats">
                            <div class="fs-milestone-stat">
                                <span class="fs-stat-number"><?php echo  esc_html( $completed_milestones ); ?></span>
                                <span class="fs-stat-label"><?php esc_html_e('Completed', 'freelance-studio'); ?></span>
                            </div>
                            <div class="fs-milestone-stat">
                                <span class="fs-stat-number"><?php echo  esc_html( $total_milestones - $completed_milestones ); ?></span>
                                <span class="fs-stat-label"><?php esc_html_e('Remaining', 'freelance-studio'); ?></span>
                            </div>
                            <div class="fs-milestone-stat">
                                <span class="fs-stat-number"><?php echo  intval( $total_milestones ); ?></span>
                                <span class="fs-stat-label"><?php esc_html_e('Total', 'freelance-studio'); ?></span>
                            </div>
                        </div>
                        <div class="fs-milestone-progress-wrapper">
                            <div class="fs-milestone-progress-header">
                                <span><?php esc_html_e('Overall Progress', 'freelance-studio'); ?></span>
                                <span class="fs-milestone-progress-percent"><?php echo  esc_html( $milestone_progress ); ?>%</span>
                            </div>
                            <div class="fs-milestone-progress-bar-modern">
                                <div class="fs-milestone-progress-fill-modern" style="width: <?php echo  esc_attr( $milestone_progress ); ?>%;"></div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                
                <div id="milestones-list" class="fs-milestones-grid">
                    <?php if (empty($milestones)): ?>
                        <div class="fs-empty-state-card">
                            <div class="fs-empty-state-icon">
                                <span class="dashicons dashicons-flag"></span>
                            </div>
                            <h3><?php esc_html_e('No milestones yet', 'freelance-studio'); ?></h3>
                            <p><?php esc_html_e('Break your project into milestones to track progress and optionally trigger invoices when each phase is completed.', 'freelance-studio'); ?></p>
                            <button type="button" class="button button-primary" id="add-first-milestone-btn">
                                <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add First Milestone', 'freelance-studio'); ?>
                            </button>
                        </div>
                    <?php else: ?>
                        <?php 
                        $milestone_index = 0;
                        foreach ($milestones as $milestone): 
                            $milestone_index++;
                            $is_completed = $milestone->status === 'completed';
                            $is_overdue = $milestone->due_date && strtotime($milestone->due_date) < time() && !$is_completed;
                            $is_upcoming = $milestone->due_date && strtotime($milestone->due_date) <= strtotime('+7 days') && strtotime($milestone->due_date) >= time();
                            
                            // Determine card status class
                            $card_class = 'fs-milestone-card';
                            if ($is_completed) {
                                $card_class .= ' completed';
                            } elseif ($is_overdue) {
                                $card_class .= ' overdue';
                            } elseif ($is_upcoming) {
                                $card_class .= ' upcoming';
                            }
                        ?>
                            <div class="<?php echo  esc_attr( $card_class ); ?>" data-id="<?php echo esc_attr($milestone->id); ?>">
                                <div class="fs-milestone-card-header">
                                    <div class="fs-milestone-number"><?php echo  esc_html( $milestone_index ); ?></div>
                                    <div class="fs-milestone-status-indicator">
                                        <?php if ($is_completed): ?>
                                            <span class="fs-status-dot completed"></span>
                                        <?php elseif ($is_overdue): ?>
                                            <span class="fs-status-dot overdue"></span>
                                        <?php elseif ($is_upcoming): ?>
                                            <span class="fs-status-dot upcoming"></span>
                                        <?php else: ?>
                                            <span class="fs-status-dot pending"></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fs-milestone-card-actions">
                                        <button type="button" class="fs-icon-btn edit-milestone-btn" data-id="<?php echo esc_attr($milestone->id); ?>" title="<?php esc_attr_e('Edit', 'freelance-studio'); ?>">
                                            <span class="dashicons dashicons-edit"></span>
                                        </button>
                                        <button type="button" class="fs-icon-btn delete-milestone-btn" data-id="<?php echo esc_attr($milestone->id); ?>" title="<?php esc_attr_e('Delete', 'freelance-studio'); ?>">
                                            <span class="dashicons dashicons-trash"></span>
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="fs-milestone-card-body">
                                    <h3 class="fs-milestone-title <?php echo $is_completed ? 'completed' : ''; ?>">
                                        <?php echo esc_html($milestone->name); ?>
                                    </h3>
                                    
                                    <?php if ($milestone->description): ?>
                                        <p class="fs-milestone-description"><?php echo esc_html($milestone->description); ?></p>
                                    <?php endif; ?>
                                    
                                    <?php if ($milestone->due_date): ?>
                                        <div class="fs-milestone-due <?php echo $is_overdue ? 'overdue' : ($is_upcoming ? 'upcoming' : ''); ?>">
                                            <span class="dashicons dashicons-calendar-alt"></span>
                                            <?php if ($is_completed && $milestone->completed_date): ?>
                                                <?php /* translators: 1. completed value */ ?>
                                                <?php echo esc_html( sprintf( __( 'Completed %s', 'freelance-studio'), FS_View_Context::format_date($milestone->completed_date)) ); ?>
                                            <?php elseif ($is_overdue): ?>
                                                <?php /* translators: 1. overdue value */ ?>
                                                <?php echo esc_html( sprintf( __( 'Overdue: %s', 'freelance-studio'), FS_View_Context::format_date($milestone->due_date)) ); ?>
                                            <?php else: ?>
                                                <?php /* translators: 1. due value */ ?>
                                                <?php echo esc_html( sprintf( __( 'Due %s', 'freelance-studio'), FS_View_Context::format_date($milestone->due_date)) ); ?>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($milestone->invoice_on_completion && !$milestone->invoice_id): ?>
                                        <div class="fs-milestone-invoice-badge">
                                            <span class="dashicons dashicons-money-alt"></span>
                                            <?php if ($milestone->invoice_percentage): ?>
                                                <?php /* translators: 1. %% invoice value */ ?>
                                                <?php echo esc_html( sprintf( __( '%s%% invoice on completion', 'freelance-studio'), $milestone->invoice_percentage) ); ?>
                                            <?php elseif ($milestone->invoice_amount): ?>
                                                <?php echo  esc_html( FS_View_Context::format_currency($milestone->invoice_amount) ); ?> <?php esc_html_e('on completion', 'freelance-studio'); ?>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($milestone->invoice_id): ?>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $milestone->invoice_id) ); ?>" class="fs-milestone-invoice-link">
                                            <span class="dashicons dashicons-media-text"></span>
                                            <?php esc_html_e('View Invoice', 'freelance-studio'); ?>
                                        </a>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="fs-milestone-card-footer">
                                    <?php if (!$is_completed): ?>
                                        <button type="button" class="fs-complete-milestone-btn" data-id="<?php echo esc_attr($milestone->id); ?>">
                                            <span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Mark Complete', 'freelance-studio'); ?>
                                        </button>
                                    <?php else: ?>
                                        <span class="fs-completed-badge">
                                            <span class="dashicons dashicons-yes"></span> <?php esc_html_e('Completed', 'freelance-studio'); ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        
        <?php elseif ($current_tab === 'tasks'): ?>
            <!-- Tasks Tab - Modern Card Design -->
            <div class="fs-tab-pane">
                <div class="fs-tab-header">
                    <button type="button" class="fs-btn fs-btn-primary" id="add-task-btn">
                        <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Task', 'freelance-studio'); ?>
                    </button>
                    <div class="fs-task-filters">
                        <select id="task-filter-assignee" class="fs-filter-select">
                            <option value=""><?php esc_html_e('All Assignees', 'freelance-studio'); ?></option>
                            <option value="freelancer"><?php esc_html_e('My Tasks', 'freelance-studio'); ?></option>
                            <option value="client"><?php esc_html_e('Client Tasks', 'freelance-studio'); ?></option>
                        </select>
                        <select id="task-filter-status" class="fs-filter-select">
                            <option value=""><?php esc_html_e('All Statuses', 'freelance-studio'); ?></option>
                            <option value="pending"><?php echo esc_html(FS_View_Context::get_task_status_labels('pending')); ?></option>
                            <option value="in_progress"><?php echo esc_html(FS_View_Context::get_task_status_labels('in_progress')); ?></option>
                            <option value="needs_info"><?php echo esc_html(FS_View_Context::get_task_status_labels('needs_info')); ?></option>
                            <option value="with_client"><?php echo esc_html(FS_View_Context::get_task_status_labels('with_client')); ?></option>
                            <option value="completed"><?php echo esc_html(FS_View_Context::get_task_status_labels('completed')); ?></option>
                        </select>
                    </div>
                </div>
                
                <?php if (!empty($tasks)): 
                    $total_tasks = count($tasks);
                    $completed_tasks = count(array_filter($tasks, function($t) { return $t->status === 'completed' || $t->status === 'archived'; }));
                    $my_tasks = count(array_filter($tasks, function($t) { return ($t->assigned_to ?? 'freelancer') === 'freelancer'; }));
                    $client_tasks = count(array_filter($tasks, function($t) { return ($t->assigned_to ?? 'freelancer') === 'client'; }));
                    $task_progress = $total_tasks > 0 ? round(($completed_tasks / $total_tasks) * 100) : 0;
                ?>
                    <!-- Task Overview Card -->
                    <div class="fs-task-overview-card">
                        <div class="fs-task-overview-stats">
                            <div class="fs-task-stat">
                                <span class="fs-stat-icon completed"><span class="dashicons dashicons-yes-alt"></span></span>
                                <div class="fs-stat-content">
                                    <span class="fs-stat-number"><?php echo  esc_html( $completed_tasks ); ?></span>
                                    <span class="fs-stat-label"><?php esc_html_e('Completed', 'freelance-studio'); ?></span>
                                </div>
                            </div>
                            <div class="fs-task-stat">
                                <span class="fs-stat-icon pending"><span class="dashicons dashicons-clock"></span></span>
                                <div class="fs-stat-content">
                                    <span class="fs-stat-number"><?php echo  esc_html( $total_tasks - $completed_tasks ); ?></span>
                                    <span class="fs-stat-label"><?php esc_html_e('Remaining', 'freelance-studio'); ?></span>
                                </div>
                            </div>
                            <div class="fs-task-stat">
                                <span class="fs-stat-icon designer"><span class="dashicons dashicons-admin-users"></span></span>
                                <div class="fs-stat-content">
                                    <span class="fs-stat-number"><?php echo  esc_html( $my_tasks ); ?></span>
                                    <span class="fs-stat-label"><?php esc_html_e('My Tasks', 'freelance-studio'); ?></span>
                                </div>
                            </div>
                            <div class="fs-task-stat">
                                <span class="fs-stat-icon client"><span class="dashicons dashicons-businessperson"></span></span>
                                <div class="fs-stat-content">
                                    <span class="fs-stat-number"><?php echo  esc_html( $client_tasks ); ?></span>
                                    <span class="fs-stat-label"><?php esc_html_e('Client Tasks', 'freelance-studio'); ?></span>
                                </div>
                            </div>
                        </div>
                        <div class="fs-task-progress-wrapper">
                            <div class="fs-task-progress-header">
                                <span><?php esc_html_e('Overall Progress', 'freelance-studio'); ?></span>
                                <span class="fs-task-progress-percent"><?php echo  esc_html( $task_progress ); ?>%</span>
                            </div>
                            <div class="fs-task-progress-bar-modern">
                                <div class="fs-task-progress-fill-modern" style="width: <?php echo  esc_attr( $task_progress ); ?>%;"></div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                
                <div id="tasks-list">
                    <?php if (empty($tasks)): ?>
                        <div class="fs-empty-state-card">
                            <div class="fs-empty-state-icon blue">
                                <span class="dashicons dashicons-yes-alt"></span>
                            </div>
                            <h3><?php esc_html_e('No tasks yet', 'freelance-studio'); ?></h3>
                            <p><?php esc_html_e('Break your project into tasks to stay organized. Assign tasks to yourself or your client.', 'freelance-studio'); ?></p>
                            <button type="button" class="button button-primary" id="add-first-task-btn">
                                <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add First Task', 'freelance-studio'); ?>
                            </button>
                        </div>
                    <?php else: ?>
                        <?php 
                        $priorities = FS_Task::get_priorities();
                        $priority_colors = array(
                            'low' => '#6b7280',
                            'medium' => '#f59e0b',
                            'high' => '#f97316',
                            'urgent' => '#ef4444',
                        );
                        $kanban_status_labels = FS_View_Context::get_task_status_labels();
                        ?>
                        <table class="wp-list-table widefat fixed striped fs-table" style="table-layout: auto;">
                            <thead>
                                <tr>
                                    <th style="width: 40px;"></th>
                                    <th><?php esc_html_e('Task', 'freelance-studio'); ?></th>
                                    <?php if (!empty($milestones)): ?>
                                    <th style="width: 15%;"><?php esc_html_e('Milestone', 'freelance-studio'); ?></th>
                                    <?php endif; ?>
                                    <th style="width: 90px;"><?php esc_html_e('Assigned To', 'freelance-studio'); ?></th>
                                    <th style="width: 80px;"><?php esc_html_e('Priority', 'freelance-studio'); ?></th>
                                    <th style="width: 130px;"><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                                    <th style="width: 110px;"><?php esc_html_e('Due Date', 'freelance-studio'); ?></th>
                                    <th style="width: 50px;"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($tasks as $task): 
                                    $is_completed = ($task->status === 'completed' || $task->status === 'archived');
                                    $is_overdue = $task->due_date && strtotime($task->due_date) < time() && !$is_completed;
                                    $is_client_task = ($task->assigned_to ?? 'freelancer') === 'client';
                                    $priority_color = $priority_colors[$task->priority] ?? '#6b7280';
                                ?>
                                <tr class="<?php echo $is_completed ? 'task-completed' : ''; ?> <?php echo $is_overdue ? 'task-overdue' : ''; ?>"
                                    data-assignee="<?php echo esc_attr($task->assigned_to ?? 'freelancer'); ?>"
                                    data-status="<?php echo esc_attr($task->status); ?>">
                                    <td>
                                        <label class="fs-task-checkbox-wrapper">
                                            <input type="checkbox" class="fs-task-toggle" data-id="<?php echo esc_attr($task->id); ?>" <?php checked($is_completed); ?>>
                                            <span class="fs-task-checkbox-custom"></span>
                                        </label>
                                    </td>
                                    <td>
                                        <div class="fs-task-title-cell">
                                            <a href="#" class="fs-task-title-link <?php echo  esc_attr( $is_completed ? 'completed' : '' ); ?>" data-id="<?php echo  intval( $task->id ); ?>">
                                                <?php if (!empty($task->is_recurring)): ?>
                                                    <span class="fs-task-recurring-icon" title="<?php esc_attr_e('Recurring task', 'freelance-studio'); ?>">↻</span>
                                                <?php endif; ?>
                                                <?php echo esc_html($task->title); ?>
                                            </a>
                                            <?php if (!empty($task->is_non_billable)): ?>
                                                <span class="fs-non-billable-badge"><?php esc_html_e('Non-billable', 'freelance-studio'); ?></span>
                                            <?php endif; ?>
                                            <?php if ($task->description): ?>
                                                <span class="fs-task-description"><?php echo esc_html(wp_trim_words($task->description, 10)); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <?php if (!empty($milestones)): ?>
                                    <td>
                                        <?php if ($task->milestone_name): ?>
                                            <span class="fs-task-milestone-tag">
                                                <span class="dashicons dashicons-flag"></span>
                                                <?php echo esc_html($task->milestone_name); ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="fs-no-date">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <?php endif; ?>
                                    <td>
                                        <span class="fs-assignee-badge <?php echo $is_client_task ? 'client' : 'designer'; ?>">
                                            <span class="dashicons <?php echo $is_client_task ? 'dashicons-businessperson' : 'dashicons-admin-users'; ?>"></span>
                                            <?php echo  esc_html( $is_client_task ? __('Client', 'freelance-studio') : __('Me', 'freelance-studio') ); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="fs-priority-badge" style="background-color: <?php echo  esc_attr( $priority_color ); ?>15; color: <?php echo  esc_attr( $priority_color ); ?>;">
                                            <?php echo esc_html($priorities[$task->priority] ?? $task->priority); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <select class="fs-inline-status-select fs-task-status-select fs-dashboard-task-status task-status-<?php echo esc_attr($task->status); ?>"
                                                data-task-id="<?php echo esc_attr($task->id); ?>"
                                                data-original="<?php echo esc_attr($task->status); ?>">
                                            <?php 
                                            $inline_statuses = array_diff_key($kanban_status_labels, array('archived' => 1, 'cancelled' => 1));
                                            foreach ($inline_statuses as $skey => $slabel): ?>
                                                <option value="<?php echo esc_attr($skey); ?>" <?php selected($task->status, $skey); ?>>
                                                    <?php echo esc_html($slabel); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td>
                                        <?php if ($task->due_date): ?>
                                            <span class="fs-due-date <?php echo $is_overdue ? 'overdue' : ''; ?>">
                                                <?php if ($is_overdue): ?>
                                                    <span class="dashicons dashicons-warning"></span>
                                                <?php endif; ?>
                                                <?php echo esc_html(gmdate('M j, Y', strtotime($task->due_date))); ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="fs-no-date">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="column-actions">
                                        <?php if ($task->status === 'requested'): ?>
                                            <button type="button" class="fs-btn fs-btn-primary fs-btn-small accept-task-request"
                                                    data-id="<?php echo esc_attr($task->id); ?>"
                                                    title="<?php esc_attr_e('Accept Request', 'freelance-studio'); ?>">
                                                <?php esc_html_e('Accept', 'freelance-studio'); ?>
                                            </button>
                                        <?php elseif (!$is_completed): ?>
                                            <?php if ( ! function_exists( 'fs_studio_is_free_plan' ) || ! fs_studio_is_free_plan() ): ?>
                                            <button type="button" class="fs-task-start-timer"
                                                    data-task-id="<?php echo esc_attr($task->id); ?>"
                                                    data-project-id="<?php echo esc_attr($project->id); ?>"
                                                    data-task-name="<?php echo esc_attr($task->title); ?>"
                                                    title="<?php esc_attr_e('Start Timer', 'freelance-studio'); ?>">
                                                <span class="dashicons dashicons-clock"></span>
                                            </button>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        <div class="fs-row-menu">
                                            <button type="button" class="fs-row-menu-trigger">⋯</button>
                                            <div class="fs-row-menu-dropdown">
                                                <a href="#" class="edit-task-btn" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                                <a href="#" class="archive-task-btn" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Archive', 'freelance-studio'); ?></a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        
        <?php elseif ($current_tab === 'timer'): ?>
            <!-- Timer Tab -->
            <?php FS_View_Context::render_custom_activity_css(); ?>
            <div class="fs-tab-pane">
                <!-- Timer and Quick Add Section -->
                <div class="fs-timer-quickadd-container">
                    <?php 
                    // Timer Widget - pre-select this project
                    $timer_context = 'project';
                    $selected_project_id = $project->id;
                    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/timer-widget.php';
                    
                    // Quick Add Widget - pre-select this project, hide project dropdown
                    $quickadd_context = 'project';
                    $quickadd_project_id = $project->id;
                    $show_project_field = false;
                    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/quickadd-time-entry.php';
                    ?>
                </div>
                
                <div class="fs-tab-header" style="margin-top: 15px;">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking&action=add&project_id=' . $project->id) ); ?>" class="fs-btn fs-btn-primary">
                        <?php esc_html_e('New Activity', 'freelance-studio'); ?>
                    </a>
                    <?php if (!empty($time_entries) && $time_summary->uninvoiced_billable_seconds > 0): ?>
                        <button type="button" class="fs-btn fs-btn-secondary fs-invoice-from-time" data-project-id="<?php echo esc_attr($project->id); ?>">
                            <?php esc_html_e('Invoice Time', 'freelance-studio'); ?> (<?php echo  esc_html( FS_View_Context::format_currency($time_summary->uninvoiced_amount ?: 0) ); ?>)
                        </button>
                    <?php endif; ?>
                </div>
                
                <!-- Time Stats -->
                <div class="fs-invoice-stats">
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Total Time', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value"><?php echo esc_html(FS_Time_Entry::format_duration($time_summary->total_seconds ?: 0)); ?></span>
                    </div>
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Billable', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value"><?php echo esc_html(FS_Time_Entry::format_duration($time_summary->billable_seconds ?: 0)); ?></span>
                        <?php 
                        $pv_rounding = intval(get_option('fs_time_rounding', 0));
                        if ($pv_rounding > 0 && ($time_summary->rounded_billable_hours ?? 0) > 0): ?>
                            <?php /* translators: 1. hours value, 2. rounding interval in minutes */ ?>
                            <span class="fs-stat-sub"><?php echo wp_kses_post( sprintf( __('%1$s hrs rounded (%2$d-min)', 'freelance-studio'), number_format($time_summary->rounded_billable_hours, 2), $pv_rounding)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Billable Amount', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value"><?php echo  esc_html( FS_View_Context::format_currency($time_summary->total_billable_amount ?: 0) ); ?></span>
                    </div>
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Uninvoiced', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value <?php echo ($time_summary->uninvoiced_amount ?? 0) > 0 ? 'warning' : ''; ?>">
                            <?php echo  esc_html( FS_View_Context::format_currency($time_summary->uninvoiced_amount ?: 0) ); ?>
                        </span>
                    </div>
                </div>
                
                <?php 
                // v3.9.0 - Show retainer status widget on timer tab for projects with retainer service
                // v7.9.0 - Also show for capped hourly projects
                $retainer_service = FS_Project::get_retainer_service($project);
                $capped_service = null;
                if ($retainer_service):
                    $project_id = $project->id;
                    unset($tracked_hours);
                    echo '<div class="fs-retainer-timer-wrapper">';
                    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/retainer-widget.php';
                    echo '</div>';
                    $tracked_hours = floatval(($time_summary->total_seconds ?? 0) / 3600);
                elseif ($capped_service = FS_Project::get_capped_hourly_service($project)):
                    $project_id = $project->id;
                    $retainer_service = null;
                    unset($tracked_hours);
                    echo '<div class="fs-retainer-timer-wrapper">';
                    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/retainer-widget.php';
                    echo '</div>';
                    $tracked_hours = floatval(($time_summary->total_seconds ?? 0) / 3600);
                endif;
                ?>
                
                <?php if (empty($time_entries)): ?>
                    <div class="fs-empty-state small">
                        <p><?php esc_html_e('No time tracked for this project yet.', 'freelance-studio'); ?></p>
                    </div>
                <?php else: ?>
                    <?php $local_activity_types = FS_Time_Entry::get_activity_types(); ?>
                    
                    <!-- Mobile Time Entry Cards -->
                    <div class="fs-invoice-mobile-list fs-mobile-only">
                        <?php foreach ($time_entries as $entry): 
                            $te_local_time = FS_Time_Entry::utc_to_local($entry->start_time, 'g:ia');
                            $te_local_date = FS_Time_Entry::utc_to_local($entry->start_time, 'n/j');
                            $te_activity_label = $local_activity_types[$entry->activity] ?? $entry->activity;
                        ?>
                        <a href="#" class="fs-invoice-mobile-row fs-edit-time-entry" data-id="<?php echo esc_attr($entry->id); ?>">
                            <div class="fs-invoice-mobile-left">
                                <span class="fs-invoice-mobile-client"><?php echo esc_html(FS_Time_Entry::format_duration($entry->duration)); ?><?php
                                    if ($entry->billable) {
                                        $pv_rounding_min = intval(get_option('fs_time_rounding', 0));
                                        if ($pv_rounding_min > 0) {
                                            $pv_rounded_sec = FS_Time_Entry::round_duration($entry->duration);
                                            if ($pv_rounded_sec !== intval($entry->duration)) {
                                                echo '<span class="fs-rounded-duration">→ ' . esc_html(FS_Time_Entry::format_duration($pv_rounded_sec)) . '</span>';
                                            }
                                        }
                                    }
                                ?> · <?php echo esc_html($te_activity_label); ?></span>
                                <span class="fs-invoice-mobile-number"><?php echo esc_html($te_local_time); ?> · <?php echo esc_html($te_local_date); ?><?php if (!empty($entry->description)): ?> · <?php echo esc_html(wp_trim_words($entry->description, 6)); ?><?php endif; ?></span>
                                <?php if ($entry->invoiced): ?>
                                    <span class="fs-status-dot-inline fs-dot-invoiced"></span>
                                <?php elseif ($entry->billable): ?>
                                    <span class="fs-status-dot-inline fs-dot-billable"></span>
                                <?php endif; ?>
                            </div>
                            <div class="fs-invoice-mobile-right">
                                <?php if ($entry->billable): 
                                    $te_rate = get_option('fs_default_hourly_rate', 75);
                                    $te_svcs = $project->services;
                                    if (is_string($te_svcs)) $te_svcs = json_decode($te_svcs, true);
                                    if (!empty($te_svcs) && is_array($te_svcs)) {
                                        foreach ($te_svcs as $svc) {
                                            if (isset($svc['pricing_type']) && $svc['pricing_type'] === 'hourly' && !empty($svc['rate'])) {
                                                $te_rate = floatval($svc['rate']);
                                                break;
                                            }
                                        }
                                    }
                                    if ($te_rate == get_option('fs_default_hourly_rate', 75) && !empty($entry->hourly_rate) && $entry->hourly_rate > 0) {
                                        $te_rate = $entry->hourly_rate;
                                    }
                                    $te_amount = FS_Time_Entry::get_rounded_hours($entry->duration) * $te_rate;
                                ?>
                                <span class="fs-invoice-mobile-amount"><?php echo  esc_html( FS_View_Context::format_currency($te_amount) ); ?></span>
                                <?php endif; ?>
                            </div>
                        </a>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Desktop Table -->
                    <table class="fs-table widefat fs-desktop-only">
                        <thead>
                            <tr>
                                <th class="col-duration"><?php esc_html_e('Duration', 'freelance-studio'); ?></th>
                                <th class="col-time"><?php esc_html_e('Time', 'freelance-studio'); ?></th>
                                <th class="col-activity"><?php esc_html_e('Activity', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Description', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Task', 'freelance-studio'); ?></th>
                                <th class="col-amount"><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                <th class="col-status"><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                                <th class="column-actions col-actions"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($time_entries as $entry): ?>
                                <tr data-entry-id="<?php echo  intval( $entry->id ); ?>">
                                    <td>
                                        <strong><?php echo esc_html(FS_Time_Entry::format_duration($entry->duration)); ?></strong>
                                        <?php 
                                        if ($entry->billable) {
                                            $pv_rnd_min = intval(get_option('fs_time_rounding', 0));
                                            if ($pv_rnd_min > 0) {
                                                $pv_rnd_sec = FS_Time_Entry::round_duration($entry->duration);
                                                if ($pv_rnd_sec !== intval($entry->duration)) {
                                                    /* translators: 1. count/number */
                                                    echo '<span class="fs-rounded-duration" title="' . esc_attr(sprintf(__('Rounded to %d-min increments for billing', 'freelance-studio'), $pv_rnd_min)) . '">';
                                                    echo '→ ' . esc_html(FS_Time_Entry::format_duration($pv_rnd_sec));
                                                    echo '</span>';
                                                }
                                            }
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $local_time = FS_Time_Entry::utc_to_local($entry->start_time, 'g:ia');
                                        $local_date = FS_Time_Entry::utc_to_local($entry->start_time, 'n/j');
                                        echo esc_html($local_time);
                                        echo ' <span class="fs-date">' . esc_html($local_date) . '</span>';
                                        ?>
                                    </td>
                                    <td>
                                        <span class="fs-activity-badge fs-activity-<?php echo esc_attr($entry->activity); ?>">
                                            <?php echo esc_html($local_activity_types[$entry->activity] ?? $entry->activity); ?>
                                        </span>
                                    </td>
                                    <td><?php echo esc_html($entry->description ?: '—'); ?></td>
                                    <td>
                                        <?php if (!empty($entry->task_name)): ?>
                                            <span class="dashicons dashicons-yes-alt fs-icon-success"></span>
                                            <?php echo esc_html($entry->task_name); ?>
                                        <?php else: ?>
                                            <span class="fs-no-task">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        if ($entry->billable) {
                                            $default_rate = get_option('fs_default_hourly_rate', 75);
                                            $rate = $default_rate;
                                            
                                            $proj_services = $project->services;
                                            if (is_string($proj_services)) {
                                                $proj_services = json_decode($proj_services, true);
                                            }
                                            if (!empty($proj_services) && is_array($proj_services)) {
                                                foreach ($proj_services as $svc) {
                                                    if (isset($svc['pricing_type']) && $svc['pricing_type'] === 'hourly' && !empty($svc['rate'])) {
                                                        $rate = floatval($svc['rate']);
                                                        break;
                                                    }
                                                }
                                            }
                                            
                                            if ($rate == $default_rate && !empty($entry->hourly_rate) && $entry->hourly_rate > 0) {
                                                $rate = $entry->hourly_rate;
                                            }
                                            
                                            $amount = FS_Time_Entry::get_rounded_hours($entry->duration) * $rate;
                                            echo  esc_html( FS_View_Context::format_currency($amount) );                                        } else {
                                            echo wp_kses_post( '<span class="fs-muted">' . __('Non-billable', 'freelance-studio') . '</span>' );                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php if ($entry->invoiced): ?>
                                            <span class="fs-status-badge fs-status-invoiced" title="<?php esc_attr_e('Invoiced', 'freelance-studio'); ?>">
                                                <span class="fs-status-dot"></span>
                                                <span class="fs-status-text"><?php esc_html_e('Invoiced', 'freelance-studio'); ?></span>
                                            </span>
                                        <?php elseif ($entry->billable): ?>
                                            <span class="fs-status-badge fs-status-billable" title="<?php esc_attr_e('Billable', 'freelance-studio'); ?>">
                                                <span class="fs-status-dot"></span>
                                                <span class="fs-status-text"><?php esc_html_e('Billable', 'freelance-studio'); ?></span>
                                            </span>
                                        <?php else: ?>
                                            <span class="fs-status-badge fs-status-non-billable" title="<?php esc_attr_e('Non-billable', 'freelance-studio'); ?>">
                                                <span class="fs-status-dot"></span>
                                                <span class="fs-status-text"><?php esc_html_e('Non-billable', 'freelance-studio'); ?></span>
                                            </span>
                                        <?php endif; ?>
                                    </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="#" class="fs-edit-time-entry" data-id="<?php echo esc_attr($entry->id); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                                <?php if ($entry->billable && !$entry->invoiced): ?>
                                                    <a href="#" class="fs-toggle-billable" data-id="<?php echo esc_attr($entry->id); ?>" data-billable="0"><?php esc_html_e('Mark Non-billable', 'freelance-studio'); ?></a>
                                                <?php elseif (!$entry->billable): ?>
                                                    <a href="#" class="fs-toggle-billable" data-id="<?php echo esc_attr($entry->id); ?>" data-billable="1"><?php esc_html_e('Mark Billable', 'freelance-studio'); ?></a>
                                                <?php endif; ?>
                                                <hr>
                                                <a href="#" class="fs-delete-entry text-danger" data-id="<?php echo esc_attr($entry->id); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
                
                <?php
                // Include time entry modal for inline editing
                $modal_id = 'fs-project-time-entry';
                include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/time-entry-modal-form.php';
                ?>
                
                <script>
                jQuery(document).ready(function($) {
                    // Edit time entry via modal
                    $(document).on('click', '.fs-edit-time-entry', function(e) {
                        e.preventDefault();
                        var entryId = $(this).data('id');
                        var nonce = '<?php echo esc_attr( wp_create_nonce("fs_ajax_nonce") ); ?>';
                        
                        // Fetch entry data
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: { action: 'fs_get_time_entry', nonce: nonce, id: entryId },
                            success: function(response) {
                                if (response.success && response.data) {
                                    var entry = response.data;
                                    var prefix = 'fs-project-time-entry';
                                    var $modal = $('#' + prefix + '-modal');
                                    
                                    // Populate form
                                    $('#' + prefix + '-entry-id').val(entry.id);
                                    $('#' + prefix + '-project').val(entry.project_id || '').trigger('change');
                                    $('#' + prefix + '-activity').val(entry.activity || 'other');
                                    $('#' + prefix + '-description').val(entry.description || '');
                                    $('#' + prefix + '-rate').val(entry.hourly_rate || '');
                                    $('#' + prefix + '-billable').prop('checked', entry.billable == 1);
                                    
                                    // Set duration
                                    var dur = parseInt(entry.duration) || 0;
                                    $('#' + prefix + '-hours').val(Math.floor(dur / 3600));
                                    $('#' + prefix + '-minutes').val(Math.floor((dur % 3600) / 60));
                                    $('#' + prefix + '-seconds').val(dur % 60);
                                    
                                    // Set date and times
                                    if (entry.start_time) {
                                        var startDt = new Date(entry.start_time);
                                        $('#' + prefix + '-date').val(entry.start_time.substring(0, 10));
                                        var sh = String(startDt.getHours()).padStart(2, '0');
                                        var sm = String(startDt.getMinutes()).padStart(2, '0');
                                        $('#' + prefix + '-start-time').val(sh + ':' + sm);
                                    }
                                    if (entry.end_time) {
                                        var endDt = new Date(entry.end_time);
                                        var eh = String(endDt.getHours()).padStart(2, '0');
                                        var em = String(endDt.getMinutes()).padStart(2, '0');
                                        $('#' + prefix + '-end-time').val(eh + ':' + em);
                                    }
                                    
                                    // Set task after project change triggers task load
                                    if (entry.task_id) {
                                        setTimeout(function() {
                                            $('#' + prefix + '-task').val(entry.task_id);
                                        }, 500);
                                    }
                                    
                                    // Update modal title and button
                                    $('#' + prefix + '-modal-title').text('<?php echo esc_js(__("Edit Time Entry", "freelance-studio")); ?>');
                                    $modal.find('.fs-modal-save').text('<?php echo esc_js(__("Update Entry", "freelance-studio")); ?>');
                                    
                                    $modal.addClass('active');
                                } else {
                                    alert(response.data || '<?php echo esc_js(__("Error loading time entry", "freelance-studio")); ?>');
                                }
                            },
                            error: function() {
                                alert('<?php echo esc_js(__("Error loading time entry", "freelance-studio")); ?>');
                            }
                        });
                    });
                });
                </script>
            </div>
            
        <?php elseif ($current_tab === 'invoices'): ?>
            <!-- Invoices Tab -->
            <div class="fs-tab-pane">
                <div class="fs-tab-header">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add&project_id=' . $project->id . '&client_id=' . $project->client_id) ); ?>" class="fs-btn fs-btn-primary">
                        <?php esc_html_e('New Invoice', 'freelance-studio'); ?>
                    </a>
                </div>
                
                <!-- Invoice Stats -->
                <div class="fs-invoice-stats">
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Total Invoiced', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value"><?php echo  esc_html( FS_View_Context::format_currency($total_invoiced) ); ?></span>
                    </div>
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Total Paid', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value success"><?php echo  esc_html( FS_View_Context::format_currency($total_paid) ); ?></span>
                    </div>
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Outstanding', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value <?php echo  esc_attr( ($total_invoiced - $total_paid) > 0 ? 'warning' : '' ); ?>"><?php echo  esc_html( FS_View_Context::format_currency($total_invoiced - $total_paid) ); ?></span>
                    </div>
                </div>
                
                <?php if (empty($invoices)): ?>
                    <div class="fs-empty-state small">
                        <p><?php esc_html_e('No invoices for this project yet.', 'freelance-studio'); ?></p>
                    </div>
                <?php else: ?>
                    <table class="fs-table widefat">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Invoice #', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Due Date', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                                <th class="column-actions"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($invoices as $invoice): ?>
                                <tr>
                                    <td>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $invoice->id) ); ?>">
                                            <strong><?php echo esc_html($invoice->invoice_number); ?></strong>
                                        </a>
                                    </td>
                                    <td><?php echo  esc_html( FS_View_Context::format_date($invoice->invoice_date) ); ?></td>
                                    <td><?php echo  esc_html( FS_View_Context::format_date($invoice->due_date) ); ?></td>
                                    <td><?php echo  esc_html( FS_View_Context::format_currency($invoice->total) ); ?></td>
                                    <td><?php echo  wp_kses_post( FS_View_Context::status_badge($invoice->status) ); ?></td>
                                    <td class="column-actions">
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=edit&id=' . $invoice->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
            
        <?php elseif ($current_tab === 'expenses'): ?>
            <!-- Expenses Tab -->
            <div class="fs-tab-pane">
                <div class="fs-tab-header">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=add&project_id=' . $project->id) ); ?>" class="fs-btn fs-btn-primary">
                        <?php esc_html_e('Add Expense', 'freelance-studio'); ?>
                    </a>
                </div>
                
                <!-- Expense Stats -->
                <div class="fs-invoice-stats">
                    <div class="fs-stat-item">
                        <span class="fs-stat-label"><?php esc_html_e('Total Expenses', 'freelance-studio'); ?></span>
                        <span class="fs-stat-value"><?php echo  esc_html( FS_View_Context::format_currency($total_expenses) ); ?></span>
                    </div>
                </div>
                
                <?php if (empty($expenses)): ?>
                    <div class="fs-empty-state small">
                        <p><?php esc_html_e('No expenses for this project.', 'freelance-studio'); ?></p>
                    </div>
                <?php else: ?>
                    <table class="fs-table widefat">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Description', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Category', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Billable', 'freelance-studio'); ?></th>
                                <th class="column-actions"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($expenses as $expense): ?>
                                <tr>
                                    <td><?php echo  esc_html( FS_View_Context::format_date($expense->expense_date) ); ?></td>
                                    <td>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $expense->id) ); ?>">
                                            <?php echo esc_html($expense->expense_name); ?>
                                        </a>
                                    </td>
                                    <td><?php echo esc_html($expense->category); ?></td>
                                    <td><?php echo  esc_html( FS_View_Context::format_currency($expense->amount) ); ?></td>
                                    <td><?php echo $expense->is_billable ? '✓' : '-'; ?></td>
                                    <td class="column-actions">
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $expense->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                        <a href="#" class="fs-delete-btn text-danger" data-type="expense" data-id="<?php echo  intval( $expense->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
            
        <?php elseif ($current_tab === 'files'): ?>
            <!-- Files Tab -->
            <div class="fs-tab-pane" id="fs-files-tab">
                <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
                    <div class="fs-pro-overlay-wrapper" style="min-height: 200px;">
                        <div class="fs-pro-overlay">
                            <div class="fs-pro-overlay-content">
                                <span class="fs-upgrade-badge">PRO</span>
                                <h3><?php esc_html_e( 'Project File Management', 'freelance-studio' ); ?></h3>
                                <p><?php esc_html_e( 'Upload, organize, and share project files with clients. Available with Freelance Studio Pro.', 'freelance-studio' ); ?></p>
                                <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                                    <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
                                </a>
                            </div>
                        </div>
                        <div aria-hidden="true" style="opacity:0.5; pointer-events:none;">
                            <div class="fs-files-actions-bar">
                                <span class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e('All Categories', 'freelance-studio'); ?></span>
                                <span class="fs-btn fs-btn-primary fs-btn-small"><?php esc_html_e('Upload Files', 'freelance-studio'); ?></span>
                            </div>
                            <table class="widefat fs-table">
                                <thead><tr><th><?php esc_html_e('File', 'freelance-studio'); ?></th><th><?php esc_html_e('Category', 'freelance-studio'); ?></th><th><?php esc_html_e('Date', 'freelance-studio'); ?></th></tr></thead>
                                <tbody>
                                    <tr><td colspan="3" class="text-muted" style="text-align:center;padding:30px;"><?php esc_html_e('No files uploaded yet.', 'freelance-studio'); ?></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php else: ?>
                <!-- File Actions Bar -->
                <div class="fs-files-actions-bar">
                    <div class="fs-files-filters">
                        <select id="fs-file-category-filter" class="fs-select">
                            <option value=""><?php esc_html_e('All Categories', 'freelance-studio'); ?></option>
                            <?php foreach (FS_Project_File::get_categories() as $key => $label): ?>
                                <option value="<?php echo esc_attr($key); ?>"><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fs-files-actions">
                        <button type="button" id="fs-generate-upload-link" class="fs-btn fs-btn-secondary fs-btn-small">
                            <span class="dashicons dashicons-admin-links"></span>
                            <?php esc_html_e('Get Upload Link for Client', 'freelance-studio'); ?>
                        </button>
                    </div>
                </div>
                
                <!-- Upload Area -->
                <div class="fs-file-upload-area" id="fs-file-dropzone">
                    <div class="fs-dropzone-content">
                        <span class="dashicons dashicons-cloud-upload"></span>
                        <p class="fs-dropzone-text"><?php esc_html_e('Drag & drop files here, or click to select', 'freelance-studio'); ?></p>
                        <p class="fs-dropzone-hint"><?php esc_html_e('Maximum file size: 32MB', 'freelance-studio'); ?></p>
                    </div>
                    <input type="file" id="fs-file-input" multiple style="display: none;">
                </div>
                
                <!-- Upload Options (shown when files are selected) -->
                <div class="fs-upload-options" id="fs-upload-options" style="display: none;">
                    <div class="fs-upload-options-row">
                        <label>
                            <?php esc_html_e('Category:', 'freelance-studio'); ?>
                            <select id="fs-upload-category" class="fs-select">
                                <?php foreach (FS_Project_File::get_categories() as $key => $label): ?>
                                    <?php if ($key !== 'client_upload'): ?>
                                        <option value="<?php echo esc_attr($key); ?>"><?php echo esc_html($label); ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label class="fs-checkbox-label">
                            <input type="checkbox" id="fs-upload-share-client">
                            <?php esc_html_e('Share with client', 'freelance-studio'); ?>
                        </label>
                    </div>
                    <div class="fs-upload-queue" id="fs-upload-queue"></div>
                </div>
                
                <!-- Files Stats -->
                <div class="fs-files-stats" id="fs-files-stats">
                    <span class="fs-stat-item">
                        <strong id="fs-total-files">0</strong> <?php esc_html_e('files', 'freelance-studio'); ?>
                    </span>
                    <span class="fs-stat-item">
                        <strong id="fs-total-size">0 KB</strong> <?php esc_html_e('total', 'freelance-studio'); ?>
                    </span>
                    <span class="fs-stat-item">
                        <strong id="fs-shared-files">0</strong> <?php esc_html_e('shared with client', 'freelance-studio'); ?>
                    </span>
                </div>
                
                <!-- Files List -->
                <div class="fs-files-list" id="fs-files-list">
                    <div class="fs-loading-spinner" id="fs-files-loading">
                        <span class="spinner is-active"></span>
                    </div>
                    <div class="fs-empty-state small" id="fs-files-empty" style="display: none;">
                        <span class="dashicons dashicons-media-default"></span>
                        <p><?php esc_html_e('No files uploaded yet.', 'freelance-studio'); ?></p>
                    </div>
                    <table class="fs-table fs-files-table" id="fs-files-table" style="display: none;">
                        <thead>
                            <tr>
                                <th class="column-icon"></th>
                                <th class="column-name"><?php esc_html_e('File', 'freelance-studio'); ?></th>
                                <th class="column-category"><?php esc_html_e('Category', 'freelance-studio'); ?></th>
                                <th class="column-size"><?php esc_html_e('Size', 'freelance-studio'); ?></th>
                                <th class="column-uploaded"><?php esc_html_e('Uploaded', 'freelance-studio'); ?></th>
                                <th class="column-shared"><?php esc_html_e('Client Access', 'freelance-studio'); ?></th>
                                <th class="column-actions"></th>
                            </tr>
                        </thead>
                        <tbody id="fs-files-tbody"></tbody>
                    </table>
                </div>
            </div>
            
            <!-- Upload Link Modal -->
            <div class="fs-modal" id="fs-upload-link-modal" style="display: none;">
                <div class="fs-modal-overlay"></div>
                <div class="fs-modal-content">
                    <div class="fs-modal-header">
                        <h3><?php esc_html_e('Client Upload Link', 'freelance-studio'); ?></h3>
                        <button type="button" class="fs-modal-close">&times;</button>
                    </div>
                    <div class="fs-modal-body">
                        <p><?php esc_html_e('Share this link with your client so they can upload files directly to this project:', 'freelance-studio'); ?></p>
                        
                        <div class="fs-form-row">
                            <label for="fs-upload-link-expires"><?php esc_html_e('Link expires in:', 'freelance-studio'); ?></label>
                            <select id="fs-upload-link-expires" class="fs-select">
                                <option value="1"><?php esc_html_e('1 day', 'freelance-studio'); ?></option>
                                <option value="3"><?php esc_html_e('3 days', 'freelance-studio'); ?></option>
                                <option value="7" selected><?php esc_html_e('7 days', 'freelance-studio'); ?></option>
                                <option value="14"><?php esc_html_e('14 days', 'freelance-studio'); ?></option>
                                <option value="30"><?php esc_html_e('30 days', 'freelance-studio'); ?></option>
                            </select>
                        </div>
                        
                        <div class="fs-form-row" id="fs-upload-link-result" style="display: none;">
                            <label><?php esc_html_e('Upload Link:', 'freelance-studio'); ?></label>
                            <div class="fs-copy-input-wrapper">
                                <input type="text" id="fs-upload-link-url" class="fs-input" readonly>
                                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="fs-copy-upload-link">
                                    <span class="dashicons dashicons-clipboard"></span>
                                </button>
                            </div>
                            <p class="fs-hint" id="fs-upload-link-expiry-note"></p>
                        </div>
                    </div>
                    <div class="fs-modal-footer">
                        <button type="button" class="fs-btn fs-btn-secondary fs-modal-cancel"><?php esc_html_e('Close', 'freelance-studio'); ?></button>
                        <button type="button" class="fs-btn fs-btn-primary" id="fs-generate-link-btn"><?php esc_html_e('Generate Link', 'freelance-studio'); ?></button>
                    </div>
                </div>
            </div>
            
            <!-- File Edit Modal -->
            <div class="fs-modal" id="fs-file-edit-modal" style="display: none;">
                <div class="fs-modal-overlay"></div>
                <div class="fs-modal-content">
                    <div class="fs-modal-header">
                        <h3><?php esc_html_e('Edit File', 'freelance-studio'); ?></h3>
                        <button type="button" class="fs-modal-close">&times;</button>
                    </div>
                    <div class="fs-modal-body">
                        <input type="hidden" id="fs-edit-file-id">
                        
                        <div class="fs-form-row">
                            <label for="fs-edit-file-category"><?php esc_html_e('Category:', 'freelance-studio'); ?></label>
                            <select id="fs-edit-file-category" class="fs-select">
                                <?php foreach (FS_Project_File::get_categories() as $key => $label): ?>
                                    <option value="<?php echo esc_attr($key); ?>"><?php echo esc_html($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="fs-form-row">
                            <label class="fs-checkbox-label">
                                <input type="checkbox" id="fs-edit-file-shared">
                                <?php esc_html_e('Share with client (visible in client portal)', 'freelance-studio'); ?>
                            </label>
                        </div>
                        
                        <div class="fs-form-row">
                            <label for="fs-edit-file-notes"><?php esc_html_e('Notes:', 'freelance-studio'); ?></label>
                            <textarea id="fs-edit-file-notes" class="fs-textarea" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="fs-modal-footer">
                        <button type="button" class="fs-btn fs-btn-secondary fs-modal-cancel"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                        <button type="button" class="fs-btn fs-btn-primary" id="fs-save-file-btn"><?php esc_html_e('Save Changes', 'freelance-studio'); ?></button>
                    </div>
                </div>
            </div>
            
            <script>
            jQuery(document).ready(function($) {
                const projectId = <?php echo  intval( $project->id ); ?>;
                const categories = <?php echo json_encode(FS_Project_File::get_categories()); ?>;
                let uploadQueue = [];
                
                // Load files on tab load
                loadProjectFiles();
                
                // Drag and drop handling
                const dropzone = $('#fs-file-dropzone');
                const fileInput = $('#fs-file-input');
                
                dropzone.on('click', function() {
                    fileInput.trigger('click');
                });
                
                dropzone.on('dragover dragenter', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).addClass('fs-dropzone-active');
                });
                
                dropzone.on('dragleave dragend drop', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).removeClass('fs-dropzone-active');
                });
                
                dropzone.on('drop', function(e) {
                    const files = e.originalEvent.dataTransfer.files;
                    handleFiles(files);
                });
                
                fileInput.on('change', function() {
                    handleFiles(this.files);
                    this.value = ''; // Reset input
                });
                
                function handleFiles(files) {
                    if (files.length === 0) return;
                    
                    uploadQueue = Array.from(files);
                    showUploadQueue();
                    startUpload();
                }
                
                function showUploadQueue() {
                    const queue = $('#fs-upload-queue');
                    queue.empty();
                    
                    uploadQueue.forEach((file, index) => {
                        queue.append(`
                            <div class="fs-upload-item" data-index="${index}">
                                <span class="fs-upload-filename">${escapeHtml(file.name)}</span>
                                <span class="fs-upload-size">${formatFileSize(file.size)}</span>
                                <span class="fs-upload-status">
                                    <span class="spinner is-active"></span>
                                </span>
                            </div>
                        `);
                    });
                    
                    $('#fs-upload-options').show();
                }
                
                function startUpload() {
                    const category = $('#fs-upload-category').val();
                    const sharedWithClient = $('#fs-upload-share-client').is(':checked') ? 1 : 0;
                    
                    uploadQueue.forEach((file, index) => {
                        uploadFile(file, index, category, sharedWithClient);
                    });
                }
                
                function uploadFile(file, index, category, sharedWithClient) {
                    const formData = new FormData();
                    formData.append('action', 'fs_upload_project_file');
                    formData.append('nonce', fs_ajax.nonce);
                    formData.append('project_id', projectId);
                    formData.append('file', file);
                    formData.append('category', category);
                    formData.append('shared_with_client', sharedWithClient);
                    
                    const $item = $(`.fs-upload-item[data-index="${index}"]`);
                    
                    $.ajax({
                        url: fs_ajax.ajax_url,
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            if (response.success) {
                                $item.find('.fs-upload-status').html('<span class="dashicons dashicons-yes-alt fs-icon-success"></span>');
                                loadProjectFiles();
                            } else {
                                $item.find('.fs-upload-status').html('<span class="dashicons dashicons-warning fs-icon-danger" title="' + escapeHtml(response.data.message) + '"></span>');
                            }
                        },
                        error: function() {
                            $item.find('.fs-upload-status').html('<span class="dashicons dashicons-warning fs-icon-danger"></span>');
                        }
                    });
                }
                
                // Load project files
                function loadProjectFiles(category = '') {
                    $('#fs-files-loading').show();
                    $('#fs-files-table').hide();
                    $('#fs-files-empty').hide();
                    
                    $.post(fs_ajax.ajax_url, {
                        action: 'fs_get_project_files',
                        nonce: fs_ajax.nonce,
                        project_id: projectId,
                        category: category
                    }, function(response) {
                        $('#fs-files-loading').hide();
                        
                        if (response.success) {
                            renderFiles(response.data.files);
                            updateStats(response.data.stats);
                        }
                    });
                }
                
                function renderFiles(files) {
                    const tbody = $('#fs-files-tbody');
                    tbody.empty();
                    
                    if (files.length === 0) {
                        $('#fs-files-empty').show();
                        $('#fs-files-table').hide();
                        return;
                    }
                    
                    $('#fs-files-empty').hide();
                    $('#fs-files-table').show();
                    
                    files.forEach(file => {
                        const row = `
                            <tr data-file-id="${file.id}">
                                <td class="column-icon">
                                    ${file.is_image && file.thumbnail 
                                        ? `<img src="${file.thumbnail}" class="fs-file-thumb" alt="">`
                                        : `<span class="dashicons ${file.icon}"></span>`
                                    }
                                </td>
                                <td class="column-name">
                                    <a href="${file.url}" target="_blank" class="fs-file-name">${escapeHtml(file.filename)}</a>
                                    ${file.notes ? `<span class="fs-file-notes">${escapeHtml(file.notes)}</span>` : ''}
                                    ${file.uploaded_by_type === 'client' ? '<span class="fs-badge fs-badge-info">Client Upload</span>' : ''}
                                </td>
                                <td class="column-category">
                                    <span class="fs-category-badge fs-category-${file.category}">${categories[file.category] || file.category}</span>
                                </td>
                                <td class="column-size">${file.filesize_formatted}</td>
                                <td class="column-uploaded">
                                    <span class="fs-file-date">${formatDate(file.created_at)}</span>
                                    <span class="fs-file-uploader">${escapeHtml(file.uploader_name)}</span>
                                </td>
                                <td class="column-shared">
                                    <label class="fs-switch fs-switch-small">
                                        <input type="checkbox" class="fs-toggle-share" data-file-id="${file.id}" ${file.shared_with_client ? 'checked' : ''}>
                                        <span class="fs-slider"></span>
                                    </label>
                                </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="${file.url}" download><span class="dashicons dashicons-download"></span> <?php esc_html_e('Download', 'freelance-studio'); ?></a>
                                            <a href="${file.url}" target="_blank"><span class="dashicons dashicons-visibility"></span> <?php esc_html_e('Preview', 'freelance-studio'); ?></a>
                                            <a href="#" class="fs-edit-file" data-file-id="${file.id}"><span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                            <hr>
                                            <a href="#" class="fs-delete-file" data-file-id="${file.id}" class="fs-delete-link"><span class="dashicons dashicons-trash"></span> <?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        `;
                        tbody.append(row);
                    });
                }
                
                function updateStats(stats) {
                    $('#fs-total-files').text(stats.total_files);
                    $('#fs-total-size').text(stats.total_size_formatted);
                    $('#fs-shared-files').text(stats.shared_files);
                }
                
                // Category filter
                $('#fs-file-category-filter').on('change', function() {
                    loadProjectFiles($(this).val());
                });
                
                // Toggle share with client
                $(document).on('change', '.fs-toggle-share', function() {
                    const fileId = $(this).data('file-id');
                    const shared = $(this).is(':checked') ? 1 : 0;
                    
                    $.post(fs_ajax.ajax_url, {
                        action: 'fs_update_project_file',
                        nonce: fs_ajax.nonce,
                        file_id: fileId,
                        shared_with_client: shared
                    });
                });
                
                // Edit file
                $(document).on('click', '.fs-edit-file', function(e) {
                    e.preventDefault();
                    const fileId = $(this).data('file-id');
                    const row = $(this).closest('tr');
                    
                    // Get current values from row
                    const category = row.find('.fs-category-badge').attr('class').match(/fs-category-(\w+)/)?.[1] || 'general';
                    const shared = row.find('.fs-toggle-share').is(':checked');
                    
                    $('#fs-edit-file-id').val(fileId);
                    $('#fs-edit-file-category').val(category);
                    $('#fs-edit-file-shared').prop('checked', shared);
                    $('#fs-edit-file-notes').val('');
                    
                    $('#fs-file-edit-modal').show();
                });
                
                // Save file changes
                $('#fs-save-file-btn').on('click', function() {
                    const fileId = $('#fs-edit-file-id').val();
                    
                    $.post(fs_ajax.ajax_url, {
                        action: 'fs_update_project_file',
                        nonce: fs_ajax.nonce,
                        file_id: fileId,
                        category: $('#fs-edit-file-category').val(),
                        shared_with_client: $('#fs-edit-file-shared').is(':checked') ? 1 : 0,
                        notes: $('#fs-edit-file-notes').val()
                    }, function(response) {
                        if (response.success) {
                            $('#fs-file-edit-modal').hide();
                            loadProjectFiles($('#fs-file-category-filter').val());
                        } else {
                            alert(response.data.message);
                        }
                    });
                });
                
                // Delete file
                $(document).on('click', '.fs-delete-file', function(e) {
                    e.preventDefault();
                    const fileId = $(this).data('file-id');
                    
                    if (!confirm('<?php esc_html_e('Are you sure you want to delete this file? This cannot be undone.', 'freelance-studio'); ?>')) {
                        return;
                    }
                    
                    $.post(fs_ajax.ajax_url, {
                        action: 'fs_delete_project_file',
                        nonce: fs_ajax.nonce,
                        file_id: fileId
                    }, function(response) {
                        if (response.success) {
                            loadProjectFiles($('#fs-file-category-filter').val());
                        } else {
                            alert(response.data.message);
                        }
                    });
                });
                
                // Generate upload link modal
                $('#fs-generate-upload-link').on('click', function() {
                    $('#fs-upload-link-result').hide();
                    $('#fs-generate-link-btn').show();
                    $('#fs-upload-link-modal').show();
                });
                
                // Generate link
                $('#fs-generate-link-btn').on('click', function() {
                    const $btn = $(this);
                    const expiresDays = $('#fs-upload-link-expires').val();
                    
                    $btn.prop('disabled', true).text('<?php esc_html_e('Generating...', 'freelance-studio'); ?>');
                    
                    $.post(fs_ajax.ajax_url, {
                        action: 'fs_generate_upload_link',
                        nonce: fs_ajax.nonce,
                        project_id: projectId,
                        expires_days: expiresDays
                    }, function(response) {
                        $btn.prop('disabled', false).text('<?php esc_html_e('Generate Link', 'freelance-studio'); ?>');
                        
                        if (response.success) {
                            $('#fs-upload-link-url').val(response.data.url);
                            $('#fs-upload-link-expiry-note').text('<?php esc_html_e('This link will expire in', 'freelance-studio'); ?> ' + expiresDays + ' <?php esc_html_e('days', 'freelance-studio'); ?>');
                            $('#fs-upload-link-result').show();
                            $btn.hide();
                        } else {
                            alert(response.data.message);
                        }
                    });
                });
                
                // Copy upload link
                $('#fs-copy-upload-link').on('click', function() {
                    const url = $('#fs-upload-link-url').val();
                    navigator.clipboard.writeText(url).then(function() {
                        const $btn = $('#fs-copy-upload-link');
                        $btn.find('.dashicons').removeClass('dashicons-clipboard').addClass('dashicons-yes');
                        setTimeout(function() {
                            $btn.find('.dashicons').removeClass('dashicons-yes').addClass('dashicons-clipboard');
                        }, 2000);
                    });
                });
                
                // Close modals
                $('.fs-modal-close, .fs-modal-cancel, .fs-modal-overlay').on('click', function() {
                    $(this).closest('.fs-modal').hide();
                });
                
                // Helper functions
                function escapeHtml(text) {
                    if (!text) return '';
                    const div = document.createElement('div');
                    div.textContent = text;
                    return div.innerHTML;
                }
                
                function formatFileSize(bytes) {
                    if (bytes === 0) return '0 Bytes';
                    const k = 1024;
                    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                }
                
                function formatDate(dateString) {
                    const date = new Date(dateString);
                    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                }
            });
            </script>
            <?php endif; // end premium files gate ?>
            
        <?php elseif ($current_tab === 'notes'): ?>
            <!-- Notes Tab - Inline WYSIWYG Editor -->
            <div class="fs-tab-pane">
                <div class="fs-notes-section">
                    <div class="fs-notes-editor-wrapper">
                        <?php 
                        $notes_content = $project->notes ?? '';
                        wp_editor($notes_content, 'fs_project_notes', array(
                            'media_buttons' => false,
                            'textarea_name' => 'project_notes',
                            'textarea_rows' => 12,
                            'teeny' => false,
                            'quicktags' => true,
                            'tinymce' => array(
                                'toolbar1' => 'bold,italic,underline,strikethrough,|,bullist,numlist,|,link,unlink,|,forecolor,|,undo,redo,|,removeformat',
                                'toolbar2' => '',
                                'block_formats' => 'Paragraph=p;Heading 3=h3;Heading 4=h4',
                                'content_css' => '',
                                'body_class' => 'fs-notes-editor-body',
                            ),
                        ));
                        ?>
                    </div>
                    <div class="fs-notes-save-bar">
                        <button type="button" id="fs-save-notes-btn" class="fs-btn fs-btn-primary">
                            <?php esc_html_e('Save Notes', 'freelance-studio'); ?>
                        </button>
                        <span id="fs-notes-save-status" class="fs-notes-save-status"></span>
                        <span class="fs-notes-hint"><?php esc_html_e('Internal notes — not visible to clients.', 'freelance-studio'); ?></span>
                    </div>
                </div>
            </div>
            
        <?php endif; ?>
        
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Save project notes inline
    $('#fs-save-notes-btn').on('click', function() {
        var $btn = $(this);
        var $status = $('#fs-notes-save-status');
        
        // Get content from TinyMCE or textarea fallback
        var content = '';
        if (typeof tinymce !== 'undefined' && tinymce.get('fs_project_notes')) {
            content = tinymce.get('fs_project_notes').getContent();
        } else {
            content = $('#fs_project_notes').val();
        }
        
        $btn.prop('disabled', true).text('<?php echo esc_js(__('Saving...', 'freelance-studio')); ?>');
        $status.text('').removeClass('saved error');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_project_notes',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                project_id: <?php echo intval($project->id); ?>,
                notes: content
            },
            success: function(response) {
                if (response.success) {
                    $status.text('<?php echo esc_js(__('Saved', 'freelance-studio')); ?>').addClass('saved');
                } else {
                    $status.text(response.data.message || '<?php echo esc_js(__('Error saving', 'freelance-studio')); ?>').addClass('error');
                }
            },
            error: function() {
                $status.text('<?php echo esc_js(__('Error saving', 'freelance-studio')); ?>').addClass('error');
            },
            complete: function() {
                $btn.prop('disabled', false).text('<?php echo esc_js(__('Save Notes', 'freelance-studio')); ?>');
                setTimeout(function() { $status.text('').removeClass('saved error'); }, 3000);
            }
        });
    });
    
    // Invoice from time button
    $('.fs-invoice-from-time').on('click', function() {
        var $btn = $(this);
        var projectId = $btn.data('project-id');
        
        if (!confirm('<?php esc_html_e('Create an invoice from all unbilled time entries for this project?', 'freelance-studio'); ?>')) {
            return;
        }
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Creating...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_generate_invoice_from_time',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                project_id: projectId
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = response.data.redirect_url;
                } else {
                    alert(response.data || '<?php esc_html_e('Error creating invoice', 'freelance-studio'); ?>');
                    $btn.prop('disabled', false).text('<?php esc_html_e('Invoice Time', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error creating invoice', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).text('<?php esc_html_e('Invoice Time', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Dropdown toggles
    $('.fs-dropdown-trigger').on('click', function(e) {
        e.preventDefault();
        $(this).next('.fs-dropdown-menu').toggle();
    });
    
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.fs-dropdown').length) {
            $('.fs-dropdown-menu').hide();
        }
    });
    
    // Apply template
    $('.apply-template-link').on('click', function(e) {
        e.preventDefault();
        var templateId = $(this).data('template-id');
        
        if (!confirm('<?php esc_html_e('Apply this template? This will add the template milestones and tasks to this project.', 'freelance-studio'); ?>')) {
            return;
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_apply_project_template',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                template_id: templateId,
                project_id: <?php echo  intval( $project->id ); ?>,
                start_date: '<?php echo  esc_html( $project->start_date ?: current_time('Y-m-d') ); ?>'
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || '<?php esc_html_e('Error applying template', 'freelance-studio'); ?>');
                }
            }
        });
    });
    
    // Inline task status change
    $(document).on('change', '.fs-task-status-select', function() {
        var $select = $(this);
        var taskId = $select.data('task-id');
        var newStatus = $select.val();
        var originalStatus = $select.data('original');
        
        $select.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_task_status',
                task_id: taskId,
                status: newStatus,
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $select.data('original', newStatus);
                    $select.removeClass('task-status-' + originalStatus).addClass('task-status-' + newStatus);
                    
                    var $row = $select.closest('tr');
                    if (newStatus === 'completed') {
                        $row.addClass('task-completed');
                        $row.find('.fs-task-checkbox-wrapper input').prop('checked', true);
                        $row.find('.fs-task-title-link').addClass('completed');
                    } else {
                        $row.removeClass('task-completed');
                        $row.find('.fs-task-checkbox-wrapper input').prop('checked', false);
                        $row.find('.fs-task-title-link').removeClass('completed');
                    }
                    
                    // Update progress bar and stats
                    var total = $('#tasks-list tbody tr').length;
                    var completed = $('#tasks-list tbody tr.task-completed').length;
                    var progress = total > 0 ? Math.round((completed / total) * 100) : 0;
                    
                    $('.fs-task-progress-fill-modern').css('width', progress + '%');
                    $('.fs-task-progress-percent').text(progress + '%');
                    $('.fs-task-stat .completed').closest('.fs-task-stat').find('.fs-stat-number').first().text(completed);
                    $('.fs-task-stat .pending').closest('.fs-task-stat').find('.fs-stat-number').first().text(total - completed);
                } else {
                    alert(response.data || '<?php echo esc_js(__("Error updating task status", "freelance-studio")); ?>');
                    $select.val(originalStatus);
                }
                $select.prop('disabled', false);
            },
            error: function() {
                alert('<?php echo esc_js(__("Error updating task status", "freelance-studio")); ?>');
                $select.val(originalStatus);
                $select.prop('disabled', false);
            }
        });
    });
    
    // Archive task
    $(document).on('click', '.archive-task-btn', function(e) {
        e.preventDefault();
        var taskId = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_archive_task', nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>', id: taskId },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(200, function() { location.reload(); });
                } else {
                    alert(response.data || '<?php echo esc_js(__("Error archiving task", "freelance-studio")); ?>');
                }
            }
        });
    });
    
    // Complete milestone (new button-based)
    $(document).on('click', '.fs-complete-milestone-btn', function() {
        var $btn = $(this);
        var milestoneId = $btn.data('id');
        var $card = $btn.closest('.fs-milestone-card');
        
        if (!confirm('<?php esc_html_e('Mark this milestone as complete?', 'freelance-studio'); ?>')) {
            return;
        }
        
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update"></span> <?php esc_html_e('Completing...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_complete_milestone',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: milestoneId
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.invoice_id) {
                        alert('<?php esc_html_e('Milestone completed! Invoice created.', 'freelance-studio'); ?>');
                    }
                    location.reload();
                } else {
                    alert(response.data || '<?php esc_html_e('Error completing milestone', 'freelance-studio'); ?>');
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Mark Complete', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error completing milestone', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Mark Complete', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Complete milestone from Terms tab sidebar preview
    $(document).on('click', '.fs-milestone-preview-item .fs-milestone-indicator', function() {
        var $item = $(this).closest('.fs-milestone-preview-item');
        var milestoneId = $item.data('milestone-id');
        
        // Don't allow toggling already-completed milestones from this view
        if ($item.hasClass('completed')) {
            return;
        }
        
        if (!confirm('<?php esc_html_e('Mark this milestone as complete?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var $indicator = $(this);
        $indicator.css('opacity', '0.5');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_complete_milestone',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: milestoneId
            },
            success: function(response) {
                if (response.success) {
                    // Update the indicator visually
                    $item.removeClass('current').addClass('completed');
                    $indicator.removeClass('current').addClass('completed');
                    $indicator.html('<span class="dashicons dashicons-yes"></span>');
                    $indicator.css('opacity', '1').attr('title', '<?php echo esc_js(__('Completed', 'freelance-studio')); ?>');
                    
                    if (response.data.invoice_id) {
                        alert('<?php esc_html_e('Milestone completed! Invoice created.', 'freelance-studio'); ?>');
                    }
                } else {
                    $indicator.css('opacity', '1');
                    alert(response.data || '<?php esc_html_e('Error completing milestone', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                $indicator.css('opacity', '1');
                alert('<?php esc_html_e('Error completing milestone', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Legacy: Complete milestone (checkbox - keep for backwards compatibility)
    $(document).on('change', '.milestone-complete-checkbox', function() {
        var milestoneId = $(this).data('id');
        var $row = $(this).closest('.fs-milestone-item-row');
        var isChecked = $(this).is(':checked');
        
        if (isChecked) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_complete_milestone',
                    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                    id: milestoneId
                },
                success: function(response) {
                    if (response.success) {
                        $row.find('.fs-task-title').addClass('completed');
                        if (response.data.invoice_id) {
                            alert('<?php esc_html_e('Milestone completed! Invoice created.', 'freelance-studio'); ?>');
                            location.reload();
                        }
                    } else {
                        alert(response.data || '<?php esc_html_e('Error completing milestone', 'freelance-studio'); ?>');
                    }
                }
            });
        }
    });
    
    // Delete task
    $(document).on('click', '.delete-task-btn', function(e) {
        e.preventDefault();
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this task?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var taskId = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_delete_task',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: taskId
            },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() { $(this).remove(); });
                } else {
                    alert(response.data || '<?php esc_html_e('Error deleting task', 'freelance-studio'); ?>');
                }
            }
        });
    });
    
    // Delete milestone
    $(document).on('click', '.delete-milestone-btn', function(e) {
        e.preventDefault();
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this milestone? Associated tasks will also be deleted.', 'freelance-studio'); ?>')) {
            return;
        }
        
        var milestoneId = $(this).data('id');
        var $card = $(this).closest('.fs-milestone-card, .fs-milestone-item-row');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_delete_milestone',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: milestoneId
            },
            success: function(response) {
                if (response.success) {
                    $card.fadeOut(300, function() { $(this).remove(); });
                } else {
                    alert(response.data || '<?php esc_html_e('Error deleting milestone', 'freelance-studio'); ?>');
                }
            }
        });
    });
    
    // Add milestone button - opens modal
    $('#add-milestone-btn, #add-first-milestone-btn').on('click', function() {
        openMilestoneModal();
    });
    
    // Edit milestone button
    $(document).on('click', '.edit-milestone-btn', function() {
        var milestoneId = $(this).data('id');
        
        // Fetch milestone data and open modal
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_get_milestone',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: milestoneId
            },
            success: function(response) {
                if (response.success) {
                    openMilestoneModal(response.data);
                } else {
                    alert(response.data || '<?php esc_html_e('Error loading milestone', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error loading milestone', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Open milestone modal
    function openMilestoneModal(milestone) {
        var $modal = $('#fs-milestone-modal');
        var isEdit = !!milestone;
        
        // Reset form
        $modal.find('#milestone-form')[0].reset();
        $modal.find('#milestone-id').val('');
        $modal.find('#milestone-invoice-options').hide();
        
        // Update title
        $modal.find('.fs-modal-title').text(isEdit ? '<?php esc_html_e('Edit Milestone', 'freelance-studio'); ?>' : '<?php esc_html_e('Add Milestone', 'freelance-studio'); ?>');
        $modal.find('.fs-milestone-save-btn').text(isEdit ? '<?php esc_html_e('Update Milestone', 'freelance-studio'); ?>' : '<?php esc_html_e('Add Milestone', 'freelance-studio'); ?>');
        
        // Populate form if editing
        if (isEdit) {
            $modal.find('#milestone-id').val(milestone.id);
            $modal.find('#milestone-name').val(milestone.name || '');
            $modal.find('#milestone-description').val(milestone.description || '');
            $modal.find('#milestone-due-date').val(milestone.due_date || '');
            
            if (milestone.invoice_on_completion == 1) {
                $modal.find('#milestone-invoice-on-completion').prop('checked', true);
                $modal.find('#milestone-invoice-options').show();
                $modal.find('#milestone-invoice-percentage').val(milestone.invoice_percentage || '');
            }
        }
        
        // Show modal
        $modal.addClass('active');
    }
    
    // Close milestone modal
    $(document).on('click', '#fs-milestone-modal .fs-modal-close, #fs-milestone-modal .fs-modal-cancel', function() {
        $('#fs-milestone-modal').removeClass('active');
    });
    
    $('#fs-milestone-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).removeClass('active');
        }
    });
    
    // Toggle invoice options
    $(document).on('change', '#milestone-invoice-on-completion', function() {
        if ($(this).is(':checked')) {
            $('#milestone-invoice-options').slideDown();
        } else {
            $('#milestone-invoice-options').slideUp();
        }
    });
    
    // Save milestone
    $(document).on('click', '.fs-milestone-save-btn', function() {
        var $form = $('#milestone-form');
        var $btn = $(this);
        var name = $form.find('#milestone-name').val();
        
        if (!name.trim()) {
            alert('<?php esc_html_e('Please enter a milestone name', 'freelance-studio'); ?>');
            return;
        }
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Saving...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_save_milestone',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: $form.find('#milestone-id').val(),
                project_id: <?php echo  intval( $project->id ); ?>,
                name: name,
                description: $form.find('#milestone-description').val(),
                due_date: $form.find('#milestone-due-date').val(),
                invoice_on_completion: $form.find('#milestone-invoice-on-completion').is(':checked') ? 1 : 0,
                invoice_percentage: $form.find('#milestone-invoice-percentage').val()
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || '<?php esc_html_e('Error saving milestone', 'freelance-studio'); ?>');
                    $btn.prop('disabled', false).text($form.find('#milestone-id').val() ? '<?php esc_html_e('Update Milestone', 'freelance-studio'); ?>' : '<?php esc_html_e('Add Milestone', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error saving milestone', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).text($form.find('#milestone-id').val() ? '<?php esc_html_e('Update Milestone', 'freelance-studio'); ?>' : '<?php esc_html_e('Add Milestone', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Add task button - opens modal (uses shared task modal)
    $('#add-task-btn, #add-first-task-btn').on('click', function() {
        openTaskModal();
    });
    
    // Task filter
    $('#task-filter-assignee, #task-filter-status').on('change', function() {
        var assigneeFilter = $('#task-filter-assignee').val();
        var statusFilter = $('#task-filter-status').val();
        
        $('#tasks-list tbody tr').each(function() {
            var $row = $(this);
            var assignee = $row.data('assignee');
            var status = $row.data('status');
            
            var assigneeMatch = !assigneeFilter || assignee === assigneeFilter;
            var statusMatch = !statusFilter || status === statusFilter || (statusFilter === 'completed' && status === 'archived');
            
            if (assigneeMatch && statusMatch) {
                $row.show();
            } else {
                $row.hide();
            }
        });
    });
});
</script>

<!-- Task Modal Config -->
<script>
window.fsTaskModal = {
    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
    context: 'project',
    strings: {
        addTask: '<?php echo esc_js(__('Add Task', 'freelance-studio')); ?>',
        editTask: '<?php echo esc_js(__('Edit Task', 'freelance-studio')); ?>',
        createTask: '<?php echo esc_js(__('Add Task', 'freelance-studio')); ?>',
        updateTask: '<?php echo esc_js(__('Update Task', 'freelance-studio')); ?>',
        errorLoading: '<?php echo esc_js(__('Error loading task', 'freelance-studio')); ?>',
        errorSaving: '<?php echo esc_js(__('Error saving task', 'freelance-studio')); ?>',
        saving: '<?php echo esc_js(__('Saving...', 'freelance-studio')); ?>'
    }
};
</script>

<!-- Project Terms Inline Editing JavaScript -->
<script>
jQuery(document).ready(function($) {
    var projectId = <?php echo  intval( $project->id ); ?>;
    var ajaxNonce = '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>';
    
    // Toggle between display and edit modes
    $('.fs-inline-edit-trigger').on('click', function() {
        var section = $(this).data('section');
        var $sectionEl;
        
        if (section === 'billing-schedule') {
            $sectionEl = $('#billing-schedule-section');
        } else if (section === 'services') {
            $sectionEl = $('#services-section');
        } else if (section === 'deposit') {
            $sectionEl = $('#deposit-section');
        }
        
        if ($sectionEl) {
            $sectionEl.find('.fs-display-mode').hide();
            $sectionEl.find('.fs-edit-mode').show();
        }
    });
    
    // Cancel edit
    $('.fs-cancel-edit').on('click', function() {
        var $section = $(this).closest('.fs-project-card, .fs-project-section');
        $section.find('.fs-edit-mode').hide();
        $section.find('.fs-display-mode').show();
    });
    
    // Save billing schedule
    $('.fs-save-billing-schedule').on('click', function() {
        var $btn = $(this);
        var $section = $('#billing-schedule-section');
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Saving...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_project_billing_schedule',
                nonce: ajaxNonce,
                project_id: projectId,
                start_date: $section.find('input[name="start_date"]').val(),
                due_date: $section.find('input[name="due_date"]').val(),
                first_invoice_date: $section.find('input[name="first_invoice_date"]').val(),
                billing_frequency: $section.find('select[name="billing_frequency"]').val()
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Error saving', 'freelance-studio'); ?>');
                    $btn.prop('disabled', false).text('<?php esc_html_e('Save', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error saving', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).text('<?php esc_html_e('Save', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Add service
    var serviceIndex = $('#fs-services-container .fs-service-item').length;
    
    $('.fs-add-service-btn').off('click').on('click', function() {
        var template = $('#fs-service-template').html();
        template = template.replace(/\{\{index\}\}/g, serviceIndex);
        $('#fs-services-container').append(template);
        serviceIndex++;
        updateServicesTotal();
    });
    
    // Remove service
    $(document).on('click', '.fs-remove-service', function() {
        $(this).closest('.fs-service-item').remove();
        updateServicesTotal();
    });
    
    // Calculate service amount when rate or quantity changes
    $(document).on('input', '.fs-service-rate, .fs-service-quantity', function() {
        var $item = $(this).closest('.fs-service-item');
        var rate = parseFloat($item.find('.fs-service-rate').val()) || 0;
        var qty = parseFloat($item.find('.fs-service-quantity').val()) || 0;
        var amount = rate * qty;
        $item.find('.fs-service-amount').val(amount.toFixed(2));
        updateServicesTotal();
    });
    
    function updateServicesTotal() {
        var total = 0;
        var trackedHours = <?php echo floatval($tracked_hours); ?>;
        var hoursByActivity = <?php echo json_encode($hours_by_activity ?? array()); ?>;
        
        $('#fs-services-container .fs-service-item').each(function() {
            var $item = $(this);
            var pricingType = $item.find('.fs-service-pricing-type').val();
            var hourlySource = $item.find('.fs-hourly-source').val();
            var rate = parseFloat($item.find('.fs-service-rate').val()) || 0;
            
            if (pricingType === 'hourly' && hourlySource === 'tracked') {
                // Get activity-specific hours or all hours
                var activity = $item.find('.fs-service-activity').val();
                var hours = trackedHours;
                if (activity && hoursByActivity[activity] !== undefined) {
                    hours = hoursByActivity[activity];
                }
                var amount = rate * hours;
                $item.find('.fs-service-amount').val(amount.toFixed(2));
                $item.find('.fs-activity-hours').text(hours.toFixed(2));
                total += amount;
            } else {
                total += parseFloat($item.find('.fs-service-amount').val()) || 0;
            }
        });
        $('#fs-services-edit-total').text('$' + total.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ','));
    }
    
    // Handle pricing type change
    $(document).on('change', '.fs-service-pricing-type', function() {
        var $item = $(this).closest('.fs-service-item');
        var pricingType = $(this).val();
        
        if (pricingType === 'hourly') {
            $item.find('.fs-hourly-options').show();
            // Trigger hourly source change to update visibility
            $item.find('.fs-hourly-source').trigger('change');
        } else {
            $item.find('.fs-hourly-options').hide();
            $item.find('.fs-service-quantity').show();
            $item.find('.fs-qty-separator').show();
            $item.find('.fs-tracked-hours-display').hide();
            $item.find('.fs-service-activity').hide();
        }
        
        updateServicesTotal();
    });
    
    // Handle hourly source change
    $(document).on('change', '.fs-hourly-source', function() {
        var $item = $(this).closest('.fs-service-item');
        var hourlySource = $(this).val();
        
        if (hourlySource === 'tracked') {
            $item.find('.fs-service-quantity').hide();
            $item.find('.fs-qty-separator').hide();
            $item.find('.fs-tracked-hours-display').show();
            $item.find('.fs-service-activity').show();
        } else {
            $item.find('.fs-service-quantity').show();
            $item.find('.fs-qty-separator').show();
            $item.find('.fs-tracked-hours-display').hide();
            $item.find('.fs-service-activity').hide();
        }
        
        updateServicesTotal();
    });
    
    // Handle activity change
    $(document).on('change', '.fs-service-activity', function() {
        updateServicesTotal();
    });
    
    // Save services
    $('.fs-save-services').on('click', function() {
        var $btn = $(this);
        var services = [];
        
        $('#fs-services-container .fs-service-item').each(function() {
            var $item = $(this);
            services.push({
                name:                       $item.find('.fs-service-name-input').val(),
                description:                $item.find('.fs-service-description').val(),
                pricing_type:               $item.find('.fs-service-pricing-type').val(),
                hourly_source:              $item.find('.fs-hourly-source').val(),
                activity:                   $item.find('.fs-service-activity').val(),
                rate:                       $item.find('.fs-service-rate').val(),
                quantity:                   $item.find('.fs-service-quantity').val(),
                amount:                     $item.find('.fs-service-amount').val(),
                // Hour cap fields
                hour_cap_enabled:           $item.find('.fs-hour-cap-checkbox').is(':checked') ? 1 : 0,
                hour_cap:                   $item.find('.fs-hour-cap-input').val(),
                hour_cap_notify_client:     $item.find('.fs-hour-cap-notify-checkbox').is(':checked') ? 1 : 0,
                hour_cap_notify_contact_id: $item.find('.fs-hour-cap-contact-select').val(),
                hour_cap_notify_freelancer: $item.find('.fs-hour-cap-notify-freelancer-checkbox').is(':checked') ? 1 : 0,
                hour_cap_overage_rate:      $item.find('.fs-hour-cap-overage-rate').val(),
                hour_cap_warn_threshold:    $item.find('.fs-hour-cap-warn-threshold').val(),
                // Retainer fields
                retainer_amount:            $item.find('.fs-retainer-amount').val(),
                retainer_hours:             $item.find('.fs-retainer-hours').val(),
                retainer_overage_rate:      $item.find('.fs-retainer-overage').val(),
                retainer_rollover:          $item.find('.fs-retainer-rollover').is(':checked') ? 1 : 0
            });
        });
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Saving...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_project_services',
                nonce: ajaxNonce,
                project_id: projectId,
                services: services
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Error saving', 'freelance-studio'); ?>');
                    $btn.prop('disabled', false).text('<?php esc_html_e('Save', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error saving', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).text('<?php esc_html_e('Save', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Deposit type change
    $('#deposit-type-select').on('change', function() {
        var type = $(this).val();
        if (type === 'none') {
            $('.fs-deposit-fields').hide();
        } else {
            $('.fs-deposit-fields').show();
            if (type === 'percentage') {
                $('.fs-deposit-percentage-field').show();
                $('.fs-deposit-amount-field').hide();
            } else {
                $('.fs-deposit-percentage-field').hide();
                $('.fs-deposit-amount-field').show();
            }
        }
    });
    
    // Save deposit
    $('.fs-save-deposit').on('click', function() {
        var $btn = $(this);
        var $section = $('#deposit-section');
        var depositType = $section.find('select[name="deposit_type"]').val();
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Saving...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_project_deposit',
                nonce: ajaxNonce,
                project_id: projectId,
                deposit_type: depositType,
                deposit_percentage: $section.find('input[name="deposit_percentage"]').val(),
                deposit_amount: $section.find('input[name="deposit_amount"]').val(),
                deposit_paid: $section.find('input[name="deposit_paid"]').is(':checked') ? 1 : 0
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Error saving', 'freelance-studio'); ?>');
                    $btn.prop('disabled', false).text('<?php esc_html_e('Save', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error saving', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).text('<?php esc_html_e('Save', 'freelance-studio'); ?>');
            }
        });
    });
});
</script>

<!-- Task Modal -->
<!-- Task Modal (shared partial) -->
<?php
$task_modal_context = 'project';
$task_modal_project_id = $project->id;
$task_modal_milestones = $milestones;
include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/task-modal.php';
?>

<!-- Milestone Modal -->
<div id="fs-milestone-modal" class="fs-modal">
    <div class="fs-modal-content">
        <div class="fs-modal-header">
            <h2 class="fs-modal-title"><?php esc_html_e('Add Milestone', 'freelance-studio'); ?></h2>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <form id="milestone-form">
                <input type="hidden" id="milestone-id" name="id" value="">
                
                <div class="fs-form-row">
                    <div class="fs-form-group fs-form-group-full">
                        <label for="milestone-name"><?php esc_html_e('Milestone Name', 'freelance-studio'); ?> <span class="required">*</span></label>
                        <input type="text" id="milestone-name" name="name" class="regular-text" required>
                    </div>
                </div>
                
                <div class="fs-form-row">
                    <div class="fs-form-group fs-form-group-full">
                        <label for="milestone-description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                        <textarea id="milestone-description" name="description" rows="3"></textarea>
                    </div>
                </div>
                
                <div class="fs-form-row">
                    <div class="fs-form-group fs-form-group-full">
                        <label for="milestone-due-date"><?php esc_html_e('Due Date', 'freelance-studio'); ?></label>
                        <input type="date" id="milestone-due-date" name="due_date">
                    </div>
                </div>
                
                <div class="fs-form-row">
                    <div class="fs-form-group fs-form-group-full">
                        <label class="fs-checkbox-label">
                            <input type="checkbox" id="milestone-invoice-on-completion" name="invoice_on_completion" value="1">
                            <?php esc_html_e('Generate invoice when milestone is completed', 'freelance-studio'); ?>
                        </label>
                    </div>
                </div>
                
                <div class="fs-form-row" id="milestone-invoice-options" style="display: none;">
                    <div class="fs-form-group fs-form-group-full">
                        <label for="milestone-invoice-percentage"><?php esc_html_e('Invoice Percentage of Project Total', 'freelance-studio'); ?></label>
                        <input type="number" id="milestone-invoice-percentage" name="invoice_percentage" step="0.01" min="0" max="100" placeholder="e.g., 25">
                        <p class="description"><?php esc_html_e('Enter the percentage of the project total to invoice (e.g., 25 for 25%)', 'freelance-studio'); ?></p>
                    </div>
                </div>
            </form>
        </div>
        <div class="fs-modal-footer">
            <button type="button" class="fs-btn fs-btn-secondary fs-modal-cancel"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
            <button type="button" class="fs-btn fs-btn-primary fs-milestone-save-btn"><?php esc_html_e('Add Milestone', 'freelance-studio'); ?></button>
        </div>
    </div>
</div>

<!-- Invoice Project Modal -->
<div id="fs-invoice-project-modal" class="fs-modal" style="display:none;">
    <div class="fs-modal-content">
        <div class="fs-modal-header">
            <h2><?php esc_html_e('Create Invoice from Project', 'freelance-studio'); ?></h2>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <p><?php esc_html_e('Select what to include in the invoice:', 'freelance-studio'); ?></p>
            
            <?php
            // Get services summary
            $services = $project->services;
            if (is_string($services)) {
                $services = json_decode($services, true);
            }
            $has_services = !empty($services) && is_array($services);
            $services_total = 0;
            if ($has_services) {
                foreach ($services as $svc) {
                    $services_total += isset($svc['amount']) ? floatval($svc['amount']) : 0;
                }
            }

            // Get unbilled time summary
            $unbilled_summary = FS_Time_Entry::get_summary(array(
                'project_id' => $project->id,
                'billable' => true,
                'invoiced' => false,
            ));
            $has_unbilled_time = ($unbilled_summary->uninvoiced_billable_seconds ?? 0) > 0;
            $unbilled_hours = ($unbilled_summary->uninvoiced_billable_seconds ?? 0) / 3600;
            $unbilled_amount = $unbilled_summary->uninvoiced_amount ?? 0;

            // Retainer billing
            $is_retainer = !empty($project->is_retainer) && $project->is_retainer;
            $retainer_period = null;
            $retainer_already_invoiced = false;
            if ($is_retainer) {
                $retainer_period = FS_Retainer_Period::get_current_period($project->id);
                if ($retainer_period) {
                    $retainer_already_invoiced = !empty($retainer_period->invoiced) && intval($retainer_period->invoiced) === 1;
                }
            }
            $has_retainer_to_bill = $is_retainer && $retainer_period && !$retainer_already_invoiced;
            ?>

            <?php if ($is_retainer): ?>
            <!-- Retainer projects: show retainer billing as the primary option -->
            <div class="fs-invoice-options">
                <div class="fs-invoice-option <?php echo $has_retainer_to_bill ? '' : 'fs-muted'; ?>">
                    <label class="fs-checkbox-label">
                        <input type="checkbox" id="invoice-include-retainer" value="1" <?php echo $has_retainer_to_bill ? 'checked' : 'disabled'; ?>>
                        <strong><?php esc_html_e('Monthly Retainer Fee', 'freelance-studio'); ?></strong>
                    </label>
                    <?php if ($has_retainer_to_bill): ?>
                    <p class="description">
                        <?php
                        $period_label = date_i18n('F j', strtotime($retainer_period->period_start))
                            . ' – ' . date_i18n('F j, Y', strtotime($retainer_period->period_end));
                        echo esc_html($period_label); ?> — 
                        <?php echo  esc_html( FS_View_Context::format_currency(floatval($retainer_period->amount)) ); ?>
                    </p>
                    <p class="description fs-note">
                        <em><?php
                        printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                            /* translators: 1. recipient name, 2. used of value */
                            __('Hours this period: %1$s used of %2$s included.', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                            number_format(floatval($retainer_period->hours_used), 1),
                            number_format(floatval($retainer_period->hours_included) + floatval($retainer_period->hours_rollover_in), 1)
                        );
                        ?></em>
                    </p>
                    <?php elseif ($retainer_already_invoiced): ?>
                    <p class="description fs-muted">
                        <?php esc_html_e('The current retainer period has already been invoiced.', 'freelance-studio'); ?>
                    </p>
                    <?php else: ?>
                    <p class="description fs-muted">
                        <?php esc_html_e('No active retainer period found. A new period will be generated automatically at the start of your next billing cycle.', 'freelance-studio'); ?>
                    </p>
                    <?php endif; ?>
                </div>

                <div class="fs-invoice-option">
                    <label class="fs-checkbox-label">
                        <input type="checkbox" id="invoice-include-time" value="1" <?php echo $has_unbilled_time ? '' : 'disabled'; ?>>
                        <strong><?php esc_html_e('Overage / Unbilled Time', 'freelance-studio'); ?></strong>
                    </label>
                    <?php if ($has_unbilled_time): ?>
                    <p class="description">
                        <?php echo number_format($unbilled_hours, 2); ?> <?php esc_html_e('hours', 'freelance-studio'); ?> — 
                        <?php echo  esc_html( FS_View_Context::format_currency($unbilled_amount) ); ?>
                    </p>
                    <?php else: ?>
                    <p class="description fs-muted">
                        <?php esc_html_e('No unbilled time entries for this project.', 'freelance-studio'); ?>
                    </p>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (!$has_retainer_to_bill && !$has_unbilled_time): ?>
            <div class="fs-notice fs-notice-warning">
                <p><?php esc_html_e('Nothing to invoice at this time. The current retainer period has already been invoiced and there are no unbilled time entries.', 'freelance-studio'); ?></p>
            </div>
            <?php endif; ?>

            <?php else: ?>
            <!-- Non-retainer projects: standard services + time -->
            <div class="fs-invoice-options">
                <?php if ($has_services): ?>
                <div class="fs-invoice-option">
                    <label class="fs-checkbox-label">
                        <input type="checkbox" id="invoice-include-services" value="1" checked disabled>
                        <strong><?php esc_html_e('Project Services', 'freelance-studio'); ?></strong>
                    </label>
                    <p class="description">
                        <?php echo count($services); ?> <?php esc_html_e('service(s)', 'freelance-studio'); ?> — 
                        <?php echo  esc_html( FS_View_Context::format_currency($services_total) ); ?>
                    </p>
                </div>
                <?php else: ?>
                <div class="fs-invoice-option fs-muted">
                    <p><em><?php esc_html_e('No services defined for this project.', 'freelance-studio'); ?></em></p>
                </div>
                <?php endif; ?>
                
                <div class="fs-invoice-option">
                    <label class="fs-checkbox-label">
                        <input type="checkbox" id="invoice-include-time" value="1" <?php echo $has_unbilled_time ? '' : 'disabled'; ?>>
                        <strong><?php esc_html_e('Unbilled Tracked Time', 'freelance-studio'); ?></strong>
                    </label>
                    <?php if ($has_unbilled_time): ?>
                    <p class="description">
                        <?php echo number_format($unbilled_hours, 2); ?> <?php esc_html_e('hours', 'freelance-studio'); ?> — 
                        <?php echo  esc_html( FS_View_Context::format_currency($unbilled_amount) ); ?>
                    </p>
                    <p class="description fs-note">
                        <em><?php esc_html_e('Note: If included, hourly services will be replaced with actual tracked time.', 'freelance-studio'); ?></em>
                    </p>
                    <?php else: ?>
                    <p class="description fs-muted">
                        <?php esc_html_e('No unbilled time entries for this project.', 'freelance-studio'); ?>
                    </p>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (!$has_services && !$has_unbilled_time): ?>
            <div class="fs-notice fs-notice-warning">
                <p><?php esc_html_e('This project has no services or unbilled time to invoice. Add services to the project or track time first.', 'freelance-studio'); ?></p>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
        <div class="fs-modal-footer">
            <button type="button" class="fs-btn fs-btn-secondary fs-modal-cancel"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
            <?php if ($is_retainer ? ($has_retainer_to_bill || $has_unbilled_time) : ($has_services || $has_unbilled_time)): ?>
            <button type="button" class="fs-btn fs-btn-primary" id="fs-create-invoice-btn"
                data-project-id="<?php echo  intval( $project->id ); ?>"
                <?php if ($is_retainer && $retainer_period): ?>
                data-retainer-period-id="<?php echo intval($retainer_period->id); ?>"
                data-retainer-amount="<?php echo floatval($retainer_period->amount); ?>"
                data-retainer-period-label="<?php echo esc_attr(date_i18n('F Y', strtotime($retainer_period->period_start))); ?>"
                <?php endif; ?>>
                <?php esc_html_e('Create Invoice', 'freelance-studio'); ?>
            </button>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php // Include Invoice Wizard Modal ?>
<?php include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/invoice-wizard-modal.php'; ?>
