<?php
/**
 * Popup Timer Window
 *
 * Lightweight timer page that opens in a small popup window.
 * Pre-populates with task and project info from query params.
 *
 * Query params:
 * - task_id: Task to track time for
 * - project_id: Project ID (auto-resolved from task if not provided)
 * - task_name: Display name for the task
 *
 * @package Freelance_Studio
 */

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

$task_id = isset($_GET['task_id']) ? intval($_GET['task_id']) : 0;
$project_id = isset($_GET['project_id']) ? intval($_GET['project_id']) : 0;
$task_name = isset($_GET['task_name']) ? sanitize_text_field(wp_unslash($_GET['task_name'])) : '';
$project_name = '';

// Load task data if task_id provided
if ($task_id) {
    $task = FS_Task::get($task_id);
    if ($task) {
        if (!$task_name) $task_name = $task->title;
        if (!$project_id && $task->project_id) $project_id = intval($task->project_id);
    }
}

// Load project name
if ($project_id) {
    $project = FS_Project::get($project_id);
    if ($project) {
        $project_name = $project->name;
    }
}

// Check for running timer
$running_timer = FS_Time_Entry::get_running();

// "This task" = timer matches the requested task_id (if task-specific),
// OR the popout was opened with no task_id (e.g. from floating bar) and a timer is running.
$is_this_task = $running_timer && (
    ($task_id > 0 && $running_timer->task_id == $task_id) ||
    ($task_id === 0 && $project_id > 0 && $running_timer->project_id == $project_id) ||
    ($task_id === 0 && $project_id === 0 && $running_timer)
);

// If opened generically (no task/project) and there's a running timer, show its context
if ($is_this_task && $running_timer) {
    if (!$task_name && $running_timer->task_id) {
        $rt_task = FS_Task::get($running_timer->task_id);
        if ($rt_task) $task_name = $rt_task->title;
    }
    if (!$project_name && $running_timer->project_id) {
        $rt_project = FS_Project::get($running_timer->project_id);
        if ($rt_project) $project_name = $rt_project->name;
    }
    if (!$project_id && $running_timer->project_id) {
        $project_id = intval($running_timer->project_id);
    }
}

// Get activity types
$activity_types = FS_Time_Entry::get_activity_types();
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo esc_html($task_name ? $task_name . ' — Timer' : __('Timer', 'freelance-studio')); ?></title>
    <?php $icon_base = plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/img/'; ?>
    <link rel="apple-touch-icon" sizes="180x180" href="<?php echo esc_url($icon_base . 'icon-180x180.png'); ?>">
    <link rel="icon" type="image/png" sizes="32x32" href="<?php echo esc_url($icon_base . 'favicon-32x32.png'); ?>">
    <meta name="theme-color" content="#1FBBA6">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="FS Timer">
    <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- Standalone popup window; wp_enqueue_style not available. ?>
    <link rel="stylesheet" href="<?php echo  esc_url( includes_url('css/dashicons.min.css') ); ?>">
    <style>
        :root {
            --fs-primary: #1FBBA6;
            --fs-primary-dark: #2BA891;
            --fs-primary-light: #77d5c9;
            --fs-primary-xtralight: #e0f7f3;
            --fs-accent: #FFA26E;
            --fs-danger: #E85A5A;
            --fs-gray-100: #F5F7FA;
            --fs-gray-200: #EEF1F5;
            --fs-gray-300: #E2E6EC;
            --fs-gray-400: #C5CAD3;
            --fs-gray-500: #9CA3AF;
            --fs-gray-600: #6B7280;
            --fs-gray-700: #4B5563;
            --fs-gray-800: #374151;
            --fs-gray-900: #1F2937;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #fff;
            color: var(--fs-gray-800);
            overflow: hidden;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .popup-timer {
            display: flex;
            flex-direction: column;
            height: 100vh;
            padding: 20px;
        }

        /* Header */
        .popup-timer-header {
            text-align: center;
            margin-bottom: 16px;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--fs-gray-200);
        }

        .popup-timer-task {
            font-size: 15px;
            font-weight: 600;
            color: var(--fs-gray-900);
            line-height: 1.3;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .popup-timer-project {
            font-size: 12px;
            color: var(--fs-primary-dark);
            font-weight: 500;
        }

        /* Timer display */
        .popup-timer-display {
            text-align: center;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        .popup-timer-time {
            font-size: 52px;
            font-weight: 700;
            font-variant-numeric: tabular-nums;
            letter-spacing: -1px;
            color: var(--fs-gray-900);
            line-height: 1;
            margin-bottom: 6px;
            transition: color 0.3s;
        }

        .popup-timer-time.running {
            color: var(--fs-primary-dark);
        }

        .popup-timer-time.paused {
            color: var(--fs-accent);
            animation: blink 1.2s ease-in-out infinite;
        }

        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.4; }
        }

        .popup-timer-status {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            font-weight: 600;
            margin-bottom: 16px;
        }

        .popup-timer-status.idle { color: var(--fs-gray-400); }
        .popup-timer-status.running { color: var(--fs-primary); }
        .popup-timer-status.paused { color: var(--fs-accent); }

        /* Activity + Description */
        .popup-timer-fields {
            margin-bottom: 16px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .popup-timer-fields select,
        .popup-timer-fields input {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid var(--fs-gray-300);
            border-radius: 6px;
            font-size: 13px;
            color: var(--fs-gray-700);
            background: var(--fs-gray-100);
            outline: none;
            transition: border-color 0.2s;
        }

        .popup-timer-fields select:focus,
        .popup-timer-fields input:focus {
            border-color: var(--fs-primary);
            background: #fff;
        }

        /* Controls */
        .popup-timer-controls {
            display: flex;
            gap: 8px;
            justify-content: center;
            padding-top: 12px;
            border-top: 1px solid var(--fs-gray-200);
        }

        .popup-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 10px 20px;
            border: none;
            border-radius: 50px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        .popup-btn:hover { transform: translateY(-1px); }
        .popup-btn:active { transform: translateY(0); }
        .popup-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

        .popup-btn-start {
            background: linear-gradient(135deg, var(--fs-primary-dark), var(--fs-primary));
            color: #fff;
            box-shadow: 0 4px 12px rgba(31, 187, 166, 0.3);
            flex: 1;
        }

        .popup-btn-start:hover {
            box-shadow: 0 6px 16px rgba(31, 187, 166, 0.4);
        }

        .popup-btn-stop {
            background: linear-gradient(135deg, #6366f1, #8b5cf6);
            color: #fff;
            box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
            flex: 1;
            min-width: 130px;
            justify-content: center;
        }

        .popup-btn-stop:hover {
            box-shadow: 0 6px 16px rgba(99, 102, 241, 0.4);
        }

        .popup-btn-stop .fs-icon-stop {
            vertical-align: middle;
            flex-shrink: 0;
        }

        .popup-btn-pause {
            background: #fff;
            border: 2px solid var(--fs-accent);
            color: var(--fs-accent);
            width: 40px;
            height: 40px;
            padding: 0;
            border-radius: 50%;
        }

        .popup-btn-pause:hover {
            background: var(--fs-accent);
            color: #fff;
        }

        .popup-btn-discard {
            background: #fff;
            border: 2px solid var(--fs-gray-300);
            color: var(--fs-gray-500);
            width: 40px;
            height: 40px;
            padding: 0;
            border-radius: 50%;
        }

        .popup-btn-discard:hover {
            border-color: var(--fs-danger);
            color: var(--fs-danger);
        }

        .popup-btn .dashicons {
            font-size: 18px;
            width: 18px;
            height: 18px;
            line-height: 18px;
            background-color: #fff;
        }

        /* Running timer in another task warning */
        .popup-timer-warning {
            background: #FFF3E0;
            border: 1px solid #FFB74D;
            border-radius: 8px;
            padding: 10px 12px;
            font-size: 12px;
            color: #E65100;
            margin-bottom: 12px;
            text-align: center;
            line-height: 1.4;
        }

        .popup-timer-warning strong { display: block; margin-bottom: 2px; }

        /* Saved confirmation */
        .popup-timer-saved {
            display: none;
            text-align: center;
            padding: 30px 20px;
            flex: 1;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        .popup-timer-saved.show {
            display: flex;
        }

        .popup-timer-saved .checkmark {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: var(--fs-primary-xtralight);
            color: var(--fs-primary-dark);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30px;
            margin-bottom: 12px;
        }

        .popup-timer-saved h3 {
            font-size: 16px;
            margin-bottom: 4px;
        }

        .popup-timer-saved p {
            font-size: 13px;
            color: var(--fs-gray-600);
        }

        /* Hide WP admin bar and other chrome */
        #wpadminbar, .notice, .update-nag { display: none !important; }
        html { margin-top: 0 !important; }
    </style>
</head>
<body>
    <div class="popup-timer" id="popup-timer-main">
        <!-- Header -->
        <div class="popup-timer-header">
            <?php if ($task_name): ?>
                <div class="popup-timer-task"><?php echo esc_html($task_name); ?></div>
            <?php endif; ?>
            <?php if ($project_name): ?>
                <div class="popup-timer-project"><?php echo esc_html($project_name); ?></div>
            <?php endif; ?>
        </div>

        <?php if ($running_timer && !$is_this_task): ?>
            <div class="popup-timer-warning">
                <strong><?php esc_html_e('A timer is already running', 'freelance-studio'); ?></strong>
                <?php echo esc_html($running_timer->description ?: ($running_timer->project_name ?: __('Untitled', 'freelance-studio'))); ?>
                — <?php echo esc_html(FS_Time_Entry::format_duration($running_timer->current_duration ?? 0)); ?>
            </div>
        <?php endif; ?>

        <!-- Timer display -->
        <div class="popup-timer-display">
            <div class="popup-timer-time <?php echo ($is_this_task && empty($running_timer->is_paused)) ? 'running' : (($is_this_task && !empty($running_timer->is_paused)) ? 'paused' : ''); ?>" id="popup-time">
                <?php
                if ($is_this_task) {
                    $elapsed = $running_timer->current_duration ?? 0;
                    echo esc_html( sprintf( '%02d:%02d:%02d', floor($elapsed / 3600), floor(($elapsed % 3600) / 60), $elapsed % 60) );
                } else {
                    echo '00:00:00';
                }
                ?>
            </div>
            <div class="popup-timer-status <?php echo $is_this_task ? (empty($running_timer->is_paused) ? 'running' : 'paused') : 'idle'; ?>" id="popup-status">
                <?php
                if ($is_this_task && empty($running_timer->is_paused)) {
                    esc_html_e('Running', 'freelance-studio');
                } elseif ($is_this_task && !empty($running_timer->is_paused)) {
                    esc_html_e('Paused', 'freelance-studio');
                } else {
                    esc_html_e('Ready', 'freelance-studio');
                }
                ?>
            </div>
        </div>

        <!-- Fields -->
        <div class="popup-timer-fields">
            <select id="popup-activity">
                <?php 
                $default_activity = get_option('fs_default_activity', 'development');
                foreach ($activity_types as $key => $label): 
                    $is_selected = ($is_this_task && isset($running_timer->activity)) 
                        ? selected($running_timer->activity, $key, false) 
                        : selected($default_activity, $key, false);
                ?>
                    <option value="<?php echo esc_attr($key); ?>" <?php echo  esc_attr( $is_selected ); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <input type="text" id="popup-description" placeholder="<?php esc_attr_e('What are you working on?', 'freelance-studio'); ?>"
                   value="<?php echo ($is_this_task && $running_timer) ? esc_attr($running_timer->description) : ''; ?>">
        </div>

        <!-- Controls -->
        <div class="popup-timer-controls" id="popup-controls">
            <?php if ($is_this_task): ?>
                <?php if (!empty($running_timer->is_paused)): ?>
                    <button class="popup-btn popup-btn-pause" id="popup-resume" title="<?php esc_attr_e('Resume', 'freelance-studio'); ?>">
                        <span class="dashicons dashicons-controls-play"></span>
                    </button>
                <?php else: ?>
                    <button class="popup-btn popup-btn-pause" id="popup-pause" title="<?php esc_attr_e('Pause', 'freelance-studio'); ?>">
                        <span class="dashicons dashicons-controls-pause"></span>
                    </button>
                <?php endif; ?>
                <button class="popup-btn popup-btn-stop" id="popup-stop">
                    <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>
                    <span><?php esc_html_e('Stop & Save', 'freelance-studio'); ?></span>
                </button>
                <button class="popup-btn popup-btn-discard" id="popup-discard" title="<?php esc_attr_e('Discard', 'freelance-studio'); ?>">
                    <span class="dashicons dashicons-trash"></span>
                </button>
            <?php else: ?>
                <button class="popup-btn popup-btn-start" id="popup-start" <?php echo ($running_timer && !$is_this_task) ? 'disabled' : ''; ?>>
                    <span class="dashicons dashicons-controls-play"></span>
                    <?php esc_html_e('Start Timer', 'freelance-studio'); ?>
                </button>
            <?php endif; ?>
        </div>
    </div>

    <!-- Saved Confirmation -->
    <div class="popup-timer-saved" id="popup-saved">
        <div class="checkmark">✓</div>
        <h3><?php esc_html_e('Time Saved', 'freelance-studio'); ?></h3>
        <p id="popup-saved-duration"></p>
    </div>

    <input type="hidden" id="popup-entry-id" value="<?php echo $is_this_task ? esc_attr($running_timer->id) : ''; ?>">
    <input type="hidden" id="popup-task-id" value="<?php echo esc_attr($task_id); ?>">
    <input type="hidden" id="popup-project-id" value="<?php echo esc_attr($project_id); ?>">
    <input type="hidden" id="popup-start-time" value="<?php echo $is_this_task ? esc_attr(strtotime($running_timer->start_time . ' UTC')) : ''; ?>">
    <input type="hidden" id="popup-is-paused" value="<?php echo ($is_this_task && !empty($running_timer->is_paused)) ? '1' : '0'; ?>">
    <input type="hidden" id="popup-paused-duration" value="<?php echo $is_this_task ? esc_attr(intval($running_timer->paused_duration)) : '0'; ?>">

    <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Standalone popup window; wp_enqueue_script not available. ?>
    <script src="<?php echo  esc_url( includes_url('js/jquery/jquery.min.js') ); ?>"></script>
    <script>var ajaxurl = '<?php echo  esc_url( admin_url('admin-ajax.php') ); ?>';</script>
    <script>
    jQuery(document).ready(function($) {
        var entryId = $('#popup-entry-id').val();
        var taskId = $('#popup-task-id').val();
        var projectId = $('#popup-project-id').val();
        var startTimestamp = parseInt($('#popup-start-time').val()) || 0;
        var isPaused = $('#popup-is-paused').val() === '1';
        var pausedDuration = parseInt($('#popup-paused-duration').val()) || 0;
        var timerInterval = null;
        var nonce = '<?php echo esc_attr( wp_create_nonce("fs_ajax_nonce") ); ?>';

        function formatTime(seconds) {
            var h = Math.floor(seconds / 3600);
            var m = Math.floor((seconds % 3600) / 60);
            var s = seconds % 60;
            return String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
        }

        function updateDisplay() {
            if (!startTimestamp || isPaused) return;
            var now = Math.floor(Date.now() / 1000);
            var elapsed = (now - startTimestamp) + pausedDuration;
            if (elapsed < 0) elapsed = 0;
            $('#popup-time').text(formatTime(elapsed));
            document.title = formatTime(elapsed) + ' — <?php echo esc_js($task_name ?: __("Timer", "freelance-studio")); ?>';
        }

        function startTicking() {
            if (timerInterval) clearInterval(timerInterval);
            timerInterval = setInterval(updateDisplay, 1000);
            updateDisplay();
        }

        function stopTicking() {
            if (timerInterval) { clearInterval(timerInterval); timerInterval = null; }
        }

        // Start the timer
        if (entryId && !isPaused) {
            startTicking();
        }
        
        // Pause/resume ticking when popup visibility changes
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                stopTicking();
            } else if (entryId && !isPaused) {
                startTicking();
            }
        });

        // Start button
        $('#popup-start').on('click', function() {
            var $btn = $(this);
            $btn.prop('disabled', true);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_start_timer',
                    nonce: nonce,
                    project_id: projectId,
                    task_id: taskId,
                    description: $('#popup-description').val(),
                    activity: $('#popup-activity').val()
                },
                success: function(response) {
                    if (response.success) {
                        entryId = response.data.entry_id;
                        startTimestamp = Math.floor(Date.now() / 1000);
                        pausedDuration = 0;
                        isPaused = false;
                        $('#popup-entry-id').val(entryId);
                        $('#popup-time').addClass('running').removeClass('paused');
                        $('#popup-status').text('<?php echo esc_js(__("Running", "freelance-studio")); ?>').attr('class', 'popup-timer-status running');

                        // Swap to stop controls
                        $('#popup-controls').html(
                            '<button class="popup-btn popup-btn-pause" id="popup-pause" title="<?php echo esc_js(__("Pause", "freelance-studio")); ?>"><span class="dashicons dashicons-controls-pause"></span></button>' +
                            '<button class="popup-btn popup-btn-stop" id="popup-stop"><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><span><?php echo esc_js(__("Stop & Save", "freelance-studio")); ?></span></button>' +
                            '<button class="popup-btn popup-btn-discard" id="popup-discard" title="<?php echo esc_js(__("Discard", "freelance-studio")); ?>"><span class="dashicons dashicons-trash"></span></button>'
                        );
                        startTicking();

                        // Notify other windows/tabs (dashboard, time tracking)
                        try {
                            var bc = new BroadcastChannel('fs_timer_sync');
                            bc.postMessage({ type: 'timer_started', entry_id: entryId });
                            bc.close();
                        } catch(e) {}
                    } else {
                        alert(response.data || '<?php echo esc_js(__("Error starting timer", "freelance-studio")); ?>');
                        $btn.prop('disabled', false);
                    }
                },
                error: function() {
                    alert('<?php echo esc_js(__("Error starting timer", "freelance-studio")); ?>');
                    $btn.prop('disabled', false);
                }
            });
        });

        // Stop button
        $(document).on('click', '#popup-stop', function() {
            if (!entryId) return;
            var $btn = $(this);
            $btn.prop('disabled', true);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_stop_timer',
                    nonce: nonce,
                    entry_id: entryId,
                    description: $('#popup-description').val(),
                    activity: $('#popup-activity').val()
                },
                success: function(response) {
                    if (response.success) {
                        stopTicking();
                        var duration = $('#popup-time').text();
                        $('#popup-saved-duration').text(duration);
                        $('#popup-timer-main').hide();
                        $('#popup-saved').addClass('show');
                        document.title = '✓ ' + duration + ' <?php echo esc_js(__("saved", "freelance-studio")); ?>';

                        // Notify other windows/tabs
                        try {
                            var bc = new BroadcastChannel('fs_timer_sync');
                            bc.postMessage({ type: 'timer_stopped', entry_id: entryId });
                            bc.close();
                        } catch(e) {}

                        // Auto-close after 3 seconds
                        setTimeout(function() { window.close(); }, 3000);
                    } else {
                        alert(response.data || '<?php echo esc_js(__("Error stopping timer", "freelance-studio")); ?>');
                        $btn.prop('disabled', false);
                    }
                }
            });
        });

        // Pause button
        $(document).on('click', '#popup-pause', function() {
            if (!entryId) return;
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: { action: 'fs_pause_timer', nonce: nonce, entry_id: entryId },
                success: function(response) {
                    if (response.success) {
                        isPaused = true;
                        stopTicking();
                        $('#popup-time').removeClass('running').addClass('paused');
                        $('#popup-status').text('<?php echo esc_js(__("Paused", "freelance-studio")); ?>').attr('class', 'popup-timer-status paused');
                        // Swap pause to resume
                        $('#popup-pause').attr('id', 'popup-resume').attr('title', '<?php echo esc_js(__("Resume", "freelance-studio")); ?>')
                            .html('<span class="dashicons dashicons-controls-play"></span>');
                        
                        // Notify other windows/tabs
                        try {
                            var bc = new BroadcastChannel('fs_timer_sync');
                            bc.postMessage({ type: 'timer_paused', entry_id: entryId });
                            bc.close();
                        } catch(e) {}
                    }
                }
            });
        });

        // Resume button
        $(document).on('click', '#popup-resume', function() {
            if (!entryId) return;
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: { action: 'fs_resume_timer', nonce: nonce, entry_id: entryId },
                success: function(response) {
                    if (response.success) {
                        isPaused = false;
                        // Fetch updated entry to get accurate paused_duration
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: { action: 'fs_get_time_entry', nonce: nonce, id: entryId },
                            success: function(r) {
                                if (r.success && r.data) {
                                    pausedDuration = parseInt(r.data.paused_duration) || 0;
                                }
                                startTicking();
                            }
                        });
                        $('#popup-time').addClass('running').removeClass('paused');
                        $('#popup-status').text('<?php echo esc_js(__("Running", "freelance-studio")); ?>').attr('class', 'popup-timer-status running');
                        $('#popup-resume').attr('id', 'popup-pause').attr('title', '<?php echo esc_js(__("Pause", "freelance-studio")); ?>')
                            .html('<span class="dashicons dashicons-controls-pause"></span>');
                        
                        // Notify other windows/tabs
                        try {
                            var bc = new BroadcastChannel('fs_timer_sync');
                            bc.postMessage({ type: 'timer_resumed', entry_id: entryId });
                            bc.close();
                        } catch(e) {}
                    }
                }
            });
        });

        // Discard button
        $(document).on('click', '#popup-discard', function() {
            if (!entryId || !confirm('<?php echo esc_js(__("Discard this timer?", "freelance-studio")); ?>')) return;
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: { action: 'fs_delete_time_entry', nonce: nonce, entry_id: entryId },
                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: entryId });
                            bc.close();
                        } catch(e) {}
                        window.close();
                    }
                }
            });
        });
    });
    </script>
</body>
</html>
<?php exit; ?>
