<?php
/**
 * Time Tracking List View (Timer View)
 *
 * @package Freelance_Studio
 */

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

<?php FS_View_Context::render_custom_activity_css(); ?>
<div class="wrap fs-wrap">
    <div class="fs-list-header">
        <h1><?php esc_html_e('Time Tracking', 'freelance-studio'); ?></h1>
        <div class="fs-header-actions">
            <button type="button" class="fs-btn fs-btn-primary fs-open-invoice-wizard" id="fs-open-invoice-wizard-time">
                <span class="dashicons dashicons-text-page"></span>
                <?php esc_html_e('Invoice Wizard', 'freelance-studio'); ?>
            </button>
        </div>
    </div>
    
    <!-- Tab Navigation -->
    <div class="fs-tab-nav">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking') ); ?>" class="fs-tab active"><?php esc_html_e('Timer view', 'freelance-studio'); ?></a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking&action=week') ); ?>" class="fs-tab"><?php esc_html_e('Week view', 'freelance-studio'); ?></a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking&action=reports') ); ?>" class="fs-tab"><?php esc_html_e('Reports', 'freelance-studio'); ?></a>
    </div>

    <!-- Timer and Quick Add Section -->
    <div class="fs-timer-quickadd-container">
        <?php 
        // Use active projects only for timer/quickadd dropdowns
        $projects_for_widgets = $active_projects;
        $projects_backup = $projects;
        $projects = $projects_for_widgets;
        
        // Timer Widget
        $timer_context = 'main';
        include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/timer-widget.php';
        
        // Quick Add Widget
        $quickadd_context = 'main';
        $show_project_field = true;
        include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/quickadd-time-entry.php';
        
        // Restore full project list for filters
        $projects = $projects_backup;
        ?>
    </div>

    <!-- Filters -->
    <div class="fs-filters">
        <form method="get" action="" class="fs-filter-form">
            <input type="hidden" name="page" value="fs-time-tracking">
            
            <div class="fs-filter-group">
                <label><?php esc_html_e('Date range', 'freelance-studio'); ?></label>
                <select name="date_range">
                    <option value="this_year" <?php selected($filters['date_range'], 'this_year'); ?>><?php esc_html_e('This year', 'freelance-studio'); ?></option>
                    <option value="today" <?php selected($filters['date_range'], 'today'); ?>><?php esc_html_e('Today', 'freelance-studio'); ?></option>
                    <option value="yesterday" <?php selected($filters['date_range'], 'yesterday'); ?>><?php esc_html_e('Yesterday', 'freelance-studio'); ?></option>
                    <option value="this_week" <?php selected($filters['date_range'], 'this_week'); ?>><?php esc_html_e('This week', 'freelance-studio'); ?></option>
                    <option value="last_week" <?php selected($filters['date_range'], 'last_week'); ?>><?php esc_html_e('Last week', 'freelance-studio'); ?></option>
                    <option value="this_month" <?php selected($filters['date_range'], 'this_month'); ?>><?php esc_html_e('This month', 'freelance-studio'); ?></option>
                    <option value="last_month" <?php selected($filters['date_range'], 'last_month'); ?>><?php esc_html_e('Last month', 'freelance-studio'); ?></option>
                    <option value="all" <?php selected($filters['date_range'], 'all'); ?>><?php esc_html_e('All time', 'freelance-studio'); ?></option>
                </select>
            </div>
            
            <div class="fs-filter-group">
                <label><?php esc_html_e('Client', 'freelance-studio'); ?></label>
                <select name="client_id">
                    <option value=""><?php esc_html_e('All clients', 'freelance-studio'); ?></option>
                    <?php foreach ($clients as $client): ?>
                        <option value="<?php echo esc_attr($client->id); ?>" <?php selected($filters['client_id'], $client->id); ?>>
                            <?php echo esc_html($client->company_name ?: $client->name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="fs-filter-group">
                <label><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                <select name="project_id">
                    <option value=""><?php esc_html_e('All projects', 'freelance-studio'); ?></option>
                    <?php foreach ($projects as $project): ?>
                        <option value="<?php echo esc_attr($project->id); ?>" <?php selected($filters['project_id'], $project->id); ?>>
                            <?php echo esc_html($project->name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="fs-filter-group">
                <label><?php esc_html_e('Activity', 'freelance-studio'); ?></label>
                <select name="activity">
                    <option value=""><?php esc_html_e('All activities', 'freelance-studio'); ?></option>
                    <?php foreach ($activity_types as $key => $label): ?>
                        <option value="<?php echo esc_attr($key); ?>" <?php selected($filters['activity'], $key); ?>>
                            <?php echo esc_html($label); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="fs-filter-group">
                <label><?php esc_html_e('Task', 'freelance-studio'); ?></label>
                <select name="task_id">
                    <option value=""><?php esc_html_e('All tasks', 'freelance-studio'); ?></option>
                    <?php foreach ($tasks as $task): ?>
                        <option value="<?php echo esc_attr($task->id); ?>" <?php selected($filters['task_id'], $task->id); ?>>
                            <?php echo esc_html($task->title); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="fs-filter-group">
                <label><?php esc_html_e('Invoiced status', 'freelance-studio'); ?></label>
                <select name="invoiced">
                    <option value=""><?php esc_html_e('All statuses', 'freelance-studio'); ?></option>
                    <option value="0" <?php selected($filters['invoiced'], '0'); ?>><?php esc_html_e('Not invoiced', 'freelance-studio'); ?></option>
                    <option value="1" <?php selected($filters['invoiced'], '1'); ?>><?php esc_html_e('Invoiced', 'freelance-studio'); ?></option>
                </select>
            </div>
            
            <div class="fs-filter-actions">
                <button type="submit" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e('Filter', 'freelance-studio'); ?></button>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking') ); ?>" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e('Reset', 'freelance-studio'); ?></a>
            </div>
        </form>
    </div>

    <!-- Summary Stats -->
    <?php if ($summary): 
        $rounding_minutes = intval(get_option('fs_time_rounding', 0));
        $has_rounding = $rounding_minutes > 0;
    ?>
    <div class="fs-summary-bar">
        <div class="fs-summary-stat">
            <span class="fs-summary-label"><?php esc_html_e('Total Time', 'freelance-studio'); ?></span>
            <span class="fs-summary-value"><?php echo esc_html(FS_Time_Entry::format_duration($summary->total_seconds ?: 0)); ?></span>
        </div>
        <div class="fs-summary-stat">
            <span class="fs-summary-label"><?php esc_html_e('Billable', 'freelance-studio'); ?></span>
            <span class="fs-summary-value"><?php echo esc_html(FS_Time_Entry::format_duration($summary->billable_seconds ?: 0)); ?></span>
            <?php if ($has_rounding && ($summary->rounded_billable_hours ?? 0) > 0): ?>
                <span class="fs-summary-sub"><?php 
                    /* translators: 1. hours value, 2. rounding interval in minutes */
                    printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        /* translators: 1. hours value, 2. rounding interval in minutes */
                        __('%1$s hrs rounded (%2$d-min)', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        number_format($summary->rounded_billable_hours, 2),
                        $rounding_minutes // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    ); 
                ?></span>
            <?php endif; ?>
        </div>
        <div class="fs-summary-stat">
            <span class="fs-summary-label"><?php esc_html_e('Uninvoiced', 'freelance-studio'); ?></span>
            <span class="fs-summary-value"><?php echo  esc_html( FS_View_Context::format_currency($summary->uninvoiced_amount ?: 0) ); ?></span>
            <?php if ($has_rounding && ($summary->rounded_uninvoiced_hours ?? 0) > 0): ?>
                <span class="fs-summary-sub"><?php 
                    printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        /* translators: 1. hours value */
                        __('%s hrs rounded', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        number_format($summary->rounded_uninvoiced_hours, 2)
                    ); 
                ?></span>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Bulk Actions Form -->
    <form id="fs-bulk-time-form" method="post">
        <?php wp_nonce_field('fs_bulk_time_action', 'fs_bulk_nonce'); ?>
        
        <div class="fs-bulk-actions-bar" style="display: none;">
            <span class="fs-selected-count">0 <?php esc_html_e('selected', 'freelance-studio'); ?></span>
            <select name="bulk_action" id="fs-bulk-action">
                <option value=""><?php esc_html_e('Bulk Actions', 'freelance-studio'); ?></option>
                <option value="mark_billable"><?php esc_html_e('Mark as Billable', 'freelance-studio'); ?></option>
                <option value="mark_non_billable"><?php esc_html_e('Mark as Non-Billable', 'freelance-studio'); ?></option>
                <option value="mark_invoiced"><?php esc_html_e('Mark as Invoiced', 'freelance-studio'); ?></option>
                <option value="delete"><?php esc_html_e('Delete', 'freelance-studio'); ?></option>
            </select>
            <button type="button" class="button" id="fs-apply-bulk"><?php esc_html_e('Apply', 'freelance-studio'); ?></button>
        </div>

        <!-- Time Entries List -->
        <!-- Mobile Time Entry List -->
        <div class="fs-invoice-mobile-list fs-mobile-only">
            <?php if (!empty($entries)): ?>
                <?php foreach ($entries as $entry): 
                    $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');
                    $client_display = $entry->company_name ?: ($entry->client_name ?: '');
                    $is_running = ($entry->end_time === null);
                ?>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking&action=edit&id=' . $entry->id) ); ?>" class="fs-invoice-mobile-row<?php echo esc_attr( $is_running ? ' fs-running' : '' ); ?>">
                        <div class="fs-invoice-mobile-left">
                            <span class="fs-invoice-mobile-client">
                                <strong>
                                    <?php if ($is_running): ?>
                                        <span class="fs-live-duration" data-start="<?php echo esc_attr(strtotime($entry->start_time . ' UTC')); ?>">--:--:--</span>
                                    <?php else: ?>
                                        <?php echo esc_html(FS_Time_Entry::format_duration($entry->duration)); ?>
                                        <?php 
                                        if ($entry->billable) {
                                            $rounding_min = intval(get_option('fs_time_rounding', 0));
                                            if ($rounding_min > 0) {
                                                $rounded_sec = FS_Time_Entry::round_duration($entry->duration);
                                                if ($rounded_sec !== intval($entry->duration)) {
                                                    echo '<span class="fs-rounded-duration">→ ' . esc_html(FS_Time_Entry::format_duration($rounded_sec)) . '</span>';
                                                }
                                            }
                                        }
                                        ?>
                                    <?php endif; ?>
                                </strong>
                                · <?php echo esc_html($activity_types[$entry->activity] ?? $entry->activity); ?>
                            </span>
                            <span class="fs-invoice-mobile-number">
                                <?php echo esc_html($entry->project_name ?: __('No project', 'freelance-studio')); ?><?php if ($client_display): ?> · <?php echo esc_html($client_display); ?><?php endif; ?>
                            </span>
                        </div>
                        <div class="fs-invoice-mobile-right">
                            <span class="fs-invoice-mobile-date"><?php echo esc_html($local_time); ?></span>
                            <span class="fs-invoice-mobile-date"><?php echo esc_html($local_date); ?></span>
                            <?php if ($entry->invoiced): ?>
                                <span class="fs-status-dot-inline fs-dot-invoiced" title="<?php esc_attr_e('Invoiced', 'freelance-studio'); ?>"></span>
                            <?php elseif ($entry->billable): ?>
                                <span class="fs-status-dot-inline fs-dot-billable" title="<?php esc_attr_e('Billable', 'freelance-studio'); ?>"></span>
                            <?php endif; ?>
                        </div>
                    </a>
                <?php endforeach; ?>
            <?php else: ?>
                <div style="padding: 24px; text-align: center; color: var(--fs-gray-500);">
                    <?php esc_html_e('No time entries found.', 'freelance-studio'); ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Desktop Time Entries Table -->
        <div class="fs-table-responsive fs-desktop-only">
            <table class="wp-list-table widefat fixed striped fs-time-entries-table">
            <thead>
                <tr>
                    <th class="check-column col-checkbox">
                        <input type="checkbox" id="fs-select-all-entries">
                    </th>
                    <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('Project', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Task', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Client', '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 if (empty($entries)): ?>
                    <tr>
                        <td colspan="9"><?php esc_html_e('No time entries found.', 'freelance-studio'); ?></td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($entries as $entry): ?>
                        <tr class="<?php echo  esc_attr( $entry->end_time === null ? 'fs-running' : '' ); ?>" data-entry-id="<?php echo  intval( $entry->id ); ?>">
                            <td class="check-column">
                                <?php if ($entry->end_time !== null): ?>
                                <input type="checkbox" name="entry_ids[]" value="<?php echo  intval( $entry->id ); ?>" class="fs-entry-checkbox">
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong>
                                    <?php 
                                    if ($entry->end_time === null) {
                                        // Running timer - data-start needs UTC timestamp for JS calculation
                                        // strtotime with UTC suffix ensures correct timestamp
                                        echo '<span class="fs-live-duration" data-start="' . esc_attr(strtotime($entry->start_time . ' UTC')) . '">--:--:--</span>';
                                    } else {
                                        echo esc_html(FS_Time_Entry::format_duration($entry->duration));
                                    }
                                    ?>
                                </strong>
                                <?php 
                                // Show rounded billable time if rounding is enabled and differs from actual
                                if ($entry->end_time !== null && $entry->billable) {
                                    $rounding_min = intval(get_option('fs_time_rounding', 0));
                                    if ($rounding_min > 0) {
                                        $rounded_sec = FS_Time_Entry::round_duration($entry->duration);
                                        if ($rounded_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'), $rounding_min)) . '">';
                                            echo '→ ' . esc_html(FS_Time_Entry::format_duration($rounded_sec));
                                            echo '</span>';
                                        }
                                    }
                                }
                                ?>
                            </td>
                            <td>
                                <?php 
                                // Convert UTC time to local for display
                                $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($activity_types[$entry->activity] ?? $entry->activity); ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($entry->project_name): ?>
                                <span class="dashicons dashicons-portfolio"></span>
                                <?php echo esc_html($entry->project_name); ?>
                            <?php else: ?>
                                <span class="fs-no-project"><?php esc_html_e('No project', 'freelance-studio'); ?></span>
                            <?php endif; ?>
                            <?php if ($entry->description): ?>
                                <br><small class="fs-entry-description"><?php echo esc_html($entry->description); ?></small>
                            <?php endif; ?>
                        </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->company_name) {
                                echo esc_html($entry->company_name);
                            } elseif ($entry->client_name) {
                                echo esc_html($entry->client_name);
                            } else {
                                echo '<span class="fs-no-client">—</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="<?php echo  esc_url( admin_url('admin.php?page=fs-time-tracking&action=edit&id=' . $entry->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                        <a href="#" class="fs-duplicate-entry" data-id="<?php echo esc_attr($entry->id); ?>"><?php esc_html_e('Duplicate', '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; ?>
            <?php endif; ?>
        </tbody>
    </table>
    
    <?php if (isset($total_pages) && $total_pages > 1): ?>
    <div class="fs-pagination">
        <span class="fs-pagination-info">
            <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                /* translators: 1. start number, 2. end number, 3. total entries */
                __('Showing %1$d–%2$d of %3$d entries', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                $offset + 1, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                min($offset + $per_page, $total_entries), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                $total_entries // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            ); ?>
        </span>
        <div class="fs-pagination-links">
            <?php
            $base_url = admin_url('admin.php?page=fs-time-tracking');
            // Preserve current filters in pagination links
            $query_params = array();
            if (!empty($filters['client_id'])) $query_params['client_id'] = $filters['client_id'];
            if (!empty($filters['project_id'])) $query_params['project_id'] = $filters['project_id'];
            if (!empty($filters['activity'])) $query_params['activity'] = $filters['activity'];
            if (!empty($filters['invoiced'])) $query_params['invoiced'] = $filters['invoiced'];
            if (!empty($filters['date_range'])) $query_params['date_range'] = $filters['date_range'];
            $base_url = add_query_arg($query_params, $base_url);
            ?>
            <?php if ($current_page > 1): ?>
                <a href="<?php echo esc_url(add_query_arg('paged', $current_page - 1, $base_url)); ?>" class="fs-btn fs-btn-secondary fs-btn-small">&laquo; <?php esc_html_e('Prev', 'freelance-studio'); ?></a>
            <?php endif; ?>
            
            <?php
            $start_page = max(1, $current_page - 2);
            $end_page = min($total_pages, $current_page + 2);
            for ($i = $start_page; $i <= $end_page; $i++):
            ?>
                <?php if ($i == $current_page): ?>
                    <span class="fs-pagination-current"><?php echo  esc_html( $i ); ?></span>
                <?php else: ?>
                    <a href="<?php echo esc_url(add_query_arg('paged', $i, $base_url)); ?>" class="fs-pagination-link"><?php echo esc_html( $i ); ?></a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if ($current_page < $total_pages): ?>
                <a href="<?php echo esc_url(add_query_arg('paged', $current_page + 1, $base_url)); ?>" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e('Next', 'freelance-studio'); ?> &raquo;</a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
    
    </div>
    </form>
</div>

<script>
jQuery(document).ready(function($) {
    // Timer functionality
    var timerInterval = null;
    var timerStartTime = $('#fs-running-timer-start').val();
    var isRunning = timerStartTime ? true : false;
    var isPaused = $('#fs-timer-paused').val() === '1';
    var pausedDuration = parseInt($('#fs-timer-paused-duration').val()) || 0;
    
    function updateTimerDisplay() {
        if (timerStartTime && !isPaused) {
            var elapsed = Math.floor(Date.now() / 1000) - parseInt(timerStartTime) + pausedDuration;
            var hours = Math.floor(elapsed / 3600);
            var minutes = Math.floor((elapsed % 3600) / 60);
            var seconds = elapsed % 60;
            
            $('#fs-timer-display .fs-timer-hours').text(String(hours).padStart(2, '0'));
            $('#fs-timer-display .fs-timer-mins').text(String(minutes).padStart(2, '0'));
            $('#fs-timer-display .fs-timer-secs').text(String(seconds).padStart(2, '0'));
            
            // Animate progress ring
            var progressPercent = (minutes * 60 + seconds) / 3600 * 100;
            var circumference = 2 * Math.PI * 52;
            var offset = circumference - (progressPercent / 100 * circumference);
            $('#timer-progress-ring').css('stroke-dashoffset', offset);
        }
    }
    
    function updateLiveDurations() {
        $('.fs-live-duration').each(function() {
            var start = $(this).data('start');
            var elapsed = Math.floor(Date.now() / 1000) - parseInt(start);
            var hours = Math.floor(elapsed / 3600);
            var minutes = Math.floor((elapsed % 3600) / 60);
            var seconds = elapsed % 60;
            $(this).text(
                String(hours).padStart(2, '0') + ':' + 
                String(minutes).padStart(2, '0') + ':' + 
                String(seconds).padStart(2, '0')
            );
        });
    }
    
    // Start interval if timer is running and not paused
    if (timerStartTime && !isPaused) {
        timerInterval = setInterval(function() {
            updateTimerDisplay();
            updateLiveDurations();
        }, 1000);
        updateTimerDisplay();
        updateLiveDurations();
        
        // Pause/resume interval when tab visibility changes (saves energy in background)
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                if (timerInterval) { clearInterval(timerInterval); timerInterval = null; }
            } else {
                updateTimerDisplay();
                updateLiveDurations();
                if (!timerInterval) {
                    timerInterval = setInterval(function() {
                        updateTimerDisplay();
                        updateLiveDurations();
                    }, 1000);
                }
            }
        });
    }
    
    // Timer toggle (Start or Stop)
    $('#fs-timer-toggle').on('click', function() {
        var $btn = $(this);
        var runningTimerId = $('#fs-running-timer-id').val();
        
        $btn.prop('disabled', true);
        
        if (isRunning && runningTimerId) {
            // Stop timer - include current field values
            $btn.html('<span class="dashicons dashicons-update"></span> Stopping...');
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_stop_timer',
                    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                    entry_id: runningTimerId,
                    project_id: $('#fs-timer-project').val(),
                    task_id: $('#fs-timer-task').val(),
                    activity: $('#fs-timer-activity').val() || 'development',
                    description: $('#fs-timer-description').val()
                },
                success: function(response) {
                    if (response.success) {
                        // Notify other windows/tabs
                        try {
                            var bc = new BroadcastChannel('fs_timer_sync');
                            bc.postMessage({ type: 'timer_stopped', entry_id: runningTimerId });
                            bc.close();
                        } catch(e) {}
                        location.reload();
                    } else {
                        alert(response.data || 'Error stopping timer');
                        $btn.prop('disabled', false).html('<svg class="fs-icon-stop" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><rect x="9" y="9" width="6" height="6" rx="1"/></svg> Stop');
                    }
                },
                error: function(xhr, status, error) {
                    alert('AJAX Error: ' + error);
                    $btn.prop('disabled', false).html('<svg class="fs-icon-stop" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><rect x="9" y="9" width="6" height="6" rx="1"/></svg> Stop');
                }
            });
        } else {
            // Start timer
            var description = $('#fs-timer-description').val();
            var projectId = $('#fs-timer-project').val();
            var taskId = $('#fs-timer-task').val();
            var activity = $('#fs-timer-activity').val() || 'development';
            
            $btn.html('<span class="dashicons dashicons-update"></span> Starting...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_start_timer',
                    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                    description: description,
                    project_id: projectId,
                    task_id: taskId,
                    activity: activity
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.data || 'Error starting timer');
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-controls-play"></span> Start Timer');
                    }
                },
                error: function(xhr, status, error) {
                    alert('AJAX Error: ' + error);
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-controls-play"></span> Start Timer');
                }
            });
        }
    });
    
    // Pause timer
    $('#fs-pause-timer').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var timerId = $('#fs-running-timer-id').val();
        
        if (!timerId) return;
        
        $btn.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_pause_timer',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                entry_id: timerId
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error pausing timer');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                $btn.prop('disabled', false);
            }
        });
    });
    
    // Resume timer
    $('#fs-resume-timer').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var timerId = $('#fs-running-timer-id').val();
        
        if (!timerId) return;
        
        $btn.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_resume_timer',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                entry_id: timerId
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error resuming timer');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                $btn.prop('disabled', false);
            }
        });
    });
    
    // Discard timer (delete without saving)
    $('#fs-discard-timer').on('click', function(e) {
        e.preventDefault();
        
        if (!confirm('<?php esc_html_e('Discard this timer without saving?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var $btn = $(this);
        var timerId = $('#fs-running-timer-id').val();
        
        if (!timerId) return;
        
        $btn.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_delete_time_entry',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                entry_id: timerId
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error discarding timer');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                $btn.prop('disabled', false);
            }
        });
    });
    
    // Delete entry
    $('.fs-delete-entry').on('click', function(e) {
        e.preventDefault();
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this time entry?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var entryId = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_delete_time_entry',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                entry_id: entryId
            },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() { $(this).remove(); });
                } else {
                    alert(response.data || 'Error deleting entry');
                }
            }
        });
    });
    
    // Dropdown toggle
    $('.fs-dropdown-trigger').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var $dropdown = $(this).closest('.fs-dropdown');
        
        // Close other dropdowns
        $('.fs-dropdown').not($dropdown).removeClass('open');
        
        // Toggle this dropdown
        $dropdown.toggleClass('open');
    });
    
    // Close dropdowns when clicking outside
    $(document).on('click', function() {
        $('.fs-dropdown').removeClass('open');
    });
    
    // Duplicate entry
    $('.fs-duplicate-entry').on('click', function(e) {
        e.preventDefault();
        var entryId = $(this).data('id');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_duplicate_time_entry',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                entry_id: entryId
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error duplicating entry');
                }
            }
        });
    });
    
    // Toggle billable status
    $('.fs-toggle-billable').on('click', function(e) {
        e.preventDefault();
        var entryId = $(this).data('id');
        var billable = $(this).data('billable');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_toggle_time_billable',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                entry_id: entryId,
                billable: billable
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error updating entry');
                }
            }
        });
    });
    
    // Bulk Actions
    function updateBulkBar() {
        var checkedCount = $('.fs-entry-checkbox:checked').length;
        if (checkedCount > 0) {
            $('.fs-bulk-actions-bar').show();
            $('.fs-selected-count').text(checkedCount + ' <?php esc_html_e('selected', 'freelance-studio'); ?>');
        } else {
            $('.fs-bulk-actions-bar').hide();
        }
    }
    
    // Select all checkbox
    $('#fs-select-all-entries').on('change', function() {
        var isChecked = $(this).is(':checked');
        $('.fs-entry-checkbox').prop('checked', isChecked);
        updateBulkBar();
    });
    
    // Individual checkbox
    $('.fs-entry-checkbox').on('change', function() {
        updateBulkBar();
        
        // Update select all checkbox state
        var totalCheckboxes = $('.fs-entry-checkbox').length;
        var checkedCheckboxes = $('.fs-entry-checkbox:checked').length;
        $('#fs-select-all-entries').prop('checked', totalCheckboxes === checkedCheckboxes);
    });
    
    // Apply bulk action
    $('#fs-apply-bulk').on('click', function() {
        var action = $('#fs-bulk-action').val();
        var selectedIds = [];
        
        $('.fs-entry-checkbox:checked').each(function() {
            selectedIds.push($(this).val());
        });
        
        if (!action) {
            alert('<?php esc_html_e('Please select an action', 'freelance-studio'); ?>');
            return;
        }
        
        if (selectedIds.length === 0) {
            alert('<?php esc_html_e('Please select at least one entry', 'freelance-studio'); ?>');
            return;
        }
        
        if (action === 'delete') {
            if (!confirm('<?php esc_html_e('Are you sure you want to delete the selected entries?', 'freelance-studio'); ?>')) {
                return;
            }
        }
        
        var $btn = $(this);
        $btn.prop('disabled', true).text('<?php esc_html_e('Processing...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_bulk_time_action',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                bulk_action: action,
                entry_ids: selectedIds
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error processing bulk action');
                    $btn.prop('disabled', false).text('<?php esc_html_e('Apply', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                $btn.prop('disabled', false).text('<?php esc_html_e('Apply', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Open Invoice Wizard from Time Tracking page
    $('#fs-open-invoice-wizard-time').on('click', function() {
        if (typeof FS_Admin !== 'undefined' && FS_Admin.openInvoiceWizard) {
            FS_Admin.openInvoiceWizard();
        }
    });
    
    // Listen for timer state changes from other windows (popup timer, other tabs)
    try {
        var fsTimerChannel = new BroadcastChannel('fs_timer_sync');
        fsTimerChannel.onmessage = function(event) {
            var type = event.data.type;
            if (type === 'timer_stopped' || type === 'timer_started' || type === 'timer_paused' || type === 'timer_resumed') {
                location.reload();
            }
        };
    } catch(e) {}
});
</script>

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