<?php
/**
 * Calendar View
 *
 * @package Freelance_Studio
 */

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

// Extract data
$year = $data['year'];
$month = $data['month'];
$view = $data['view'];
$week_start = $data['week_start'];
$events = $data['events'];
$month_name = $data['month_name'];

// Build navigation URLs
$prev_month = $month - 1;
$prev_year = $year;
if ($prev_month < 1) {
    $prev_month = 12;
    $prev_year--;
}

$next_month = $month + 1;
$next_year = $year;
if ($next_month > 12) {
    $next_month = 1;
    $next_year++;
}

// Week navigation
$prev_week = gmdate('Y-m-d', strtotime($week_start . ' -7 days'));
$next_week = gmdate('Y-m-d', strtotime($week_start . ' +7 days'));
$week_end = gmdate('Y-m-d', strtotime($week_start . ' +6 days'));

// Get first and last days for the calendar grid
$first_day_of_month = mktime(0, 0, 0, $month, 1, $year);
$days_in_month = gmdate('t', $first_day_of_month);
$day_of_week = gmdate('w', $first_day_of_month); // 0 (Sun) to 6 (Sat)

// Group events by date
$events_by_date = array();
foreach ($events as $event) {
    $date = $event['date'];
    if (!isset($events_by_date[$date])) {
        $events_by_date[$date] = array();
    }
    $events_by_date[$date][] = $event;
}

// Today's date for highlighting
$today = gmdate('Y-m-d');
?>

<div class="wrap fs-calendar-wrap">
    <h1 class="fs-page-title"><?php esc_html_e('Calendar', 'freelance-studio'); ?></h1>
    
    <!-- View Toggle & Navigation -->
    <div class="fs-calendar-header">
        <div class="fs-calendar-nav">
            <?php if ($view === 'month'): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&year=' . $prev_year . '&month=' . $prev_month)); ?>" class="button">
                    <span class="dashicons dashicons-arrow-left-alt2"></span>
                </a>
                <h2 class="fs-calendar-title"><?php echo esc_html($month_name . ' ' . $year); ?></h2>
                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&year=' . $next_year . '&month=' . $next_month)); ?>" class="button">
                    <span class="dashicons dashicons-arrow-right-alt2"></span>
                </a>
            <?php else: ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&view=week&week=' . $prev_week)); ?>" class="button">
                    <span class="dashicons dashicons-arrow-left-alt2"></span>
                </a>
                <h2 class="fs-calendar-title">
                    <?php echo  esc_html( gmdate('M j', strtotime($week_start)) . ' - ' . gmdate('M j, Y', strtotime($week_end)) ); ?>
                </h2>
                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&view=week&week=' . $next_week)); ?>" class="button">
                    <span class="dashicons dashicons-arrow-right-alt2"></span>
                </a>
            <?php endif; ?>
            
            <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar')); ?>" class="button" style="margin-left: 15px;">
                <?php esc_html_e('Today', 'freelance-studio'); ?>
            </a>
        </div>
        
        <div class="fs-calendar-view-toggle">
            <?php if (FS_Google_Calendar_Service::is_connected()): ?>
            <button type="button" id="fs-sync-calendar" class="button" title="<?php esc_attr_e('Sync with Google Calendar', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-update" style="margin-top: 3px;"></span>
                <?php esc_html_e('Sync', 'freelance-studio'); ?>
            </button>
            <?php endif; ?>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&view=month&year=' . $year . '&month=' . $month)); ?>" 
               class="button <?php echo $view === 'month' ? 'button-primary' : ''; ?>">
                <?php esc_html_e('Month', 'freelance-studio'); ?>
            </a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&view=week&week=' . gmdate('Y-m-d', strtotime('monday this week')))); ?>" 
               class="button <?php echo $view === 'week' ? 'button-primary' : ''; ?>">
                <?php esc_html_e('Week', 'freelance-studio'); ?>
            </a>
        </div>
    </div>
    
    <!-- Legend -->
    <div class="fs-calendar-legend fs-desktop-only">
        <span class="fs-legend-item"><span class="fs-legend-dot" style="background: #81A5DF;"></span> <?php esc_html_e('Projects', 'freelance-studio'); ?></span>
        <span class="fs-legend-item"><span class="fs-legend-dot" style="background: #3ECFB2;"></span> <?php esc_html_e('Milestones', 'freelance-studio'); ?></span>
        <span class="fs-legend-item"><span class="fs-legend-dot" style="background: #9CA3AF;"></span> <?php esc_html_e('Tasks', 'freelance-studio'); ?></span>
        <span class="fs-legend-item"><span class="fs-legend-dot" style="background: #FFA26E;"></span> <?php esc_html_e('Invoices', 'freelance-studio'); ?></span>
        <span class="fs-legend-item"><span class="fs-legend-dot" style="background: #E85A5A;"></span> <?php esc_html_e('Expiring', 'freelance-studio'); ?></span>
        <span class="fs-legend-item"><span class="fs-legend-dot" style="background: #5D4E80;"></span> <?php esc_html_e('Tax', 'freelance-studio'); ?></span>
    </div>
    
    <!-- Mobile Calendar View -->
    <div class="fs-calendar-mobile fs-mobile-only">
        <!-- Mini Calendar -->
        <div class="fs-card fs-widget">
            <div class="fs-sidebar-mini-cal" data-year="<?php echo  esc_attr( $year ); ?>" data-month="<?php echo  esc_attr( $month ); ?>">
                <div class="fs-sidebar-mini-cal-header">
                    <span class="fs-sidebar-mini-cal-title"><?php echo esc_html($month_name . ' ' . $year); ?></span>
                    <div class="fs-sidebar-mini-cal-nav">
                        <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&year=' . $prev_year . '&month=' . $prev_month)); ?>" class="fs-mini-nav-btn">
                            <span class="dashicons dashicons-arrow-left-alt2"></span>
                        </a>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&year=' . $next_year . '&month=' . $next_month)); ?>" class="fs-mini-nav-btn">
                            <span class="dashicons dashicons-arrow-right-alt2"></span>
                        </a>
                    </div>
                </div>
                <div class="fs-sidebar-mini-cal-grid">
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('S', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('M', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('T', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('W', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('T', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('F', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('S', 'freelance-studio'); ?></span>
                    <?php
                    $mob_start_offset = $day_of_week;
                    for ($i = 0; $i < $mob_start_offset; $i++): ?>
                        <span class="fs-sidebar-mini-cal-day fs-other-month"></span>
                    <?php endfor;
                    for ($day = 1; $day <= $days_in_month; $day++):
                        $date_str = sprintf('%04d-%02d-%02d', $year, $month, $day);
                        $is_today_m = $date_str === $today;
                        $has_events_m = isset($events_by_date[$date_str]);
                        $m_classes = array('fs-sidebar-mini-cal-day');
                        if ($is_today_m) $m_classes[] = 'fs-today';
                        if ($has_events_m) $m_classes[] = 'fs-has-events';
                    ?>
                        <span class="<?php echo  esc_attr( implode(' ', $m_classes) ); ?>">
                            <?php echo  esc_html( $day ); ?>
                            <?php if ($has_events_m): ?><span class="fs-mini-cal-dot"></span><?php endif; ?>
                        </span>
                    <?php endfor;
                    $remaining_m = (7 - (($mob_start_offset + $days_in_month) % 7)) % 7;
                    for ($i = 0; $i < $remaining_m; $i++): ?>
                        <span class="fs-sidebar-mini-cal-day fs-other-month"></span>
                    <?php endfor; ?>
                </div>
            </div>
        </div>
        
        <?php if (FS_Google_Calendar_Service::is_connected()): ?>
        <!-- Add Event Button -->
        <button type="button" id="fs-mobile-add-event-btn" class="fs-btn fs-btn-primary" style="width: 100%; margin: 16px 0;">
            <span class="dashicons dashicons-plus-alt2" style="margin-top: 2px;"></span>
            <?php esc_html_e('Add Event', 'freelance-studio'); ?>
        </button>
        <?php endif; ?>
        
        <!-- Events Timeline -->
        <div class="fs-card fs-widget">
            <div class="fs-card-header"><h3><?php echo esc_html($month_name . ' ' . $year); ?> — <?php esc_html_e('Events', 'freelance-studio'); ?></h3></div>
            <?php
            // Gather all events for this month, grouped by date
            $sorted_dates = array_keys($events_by_date);
            sort($sorted_dates);
            // Filter to only dates within the current month
            $month_dates = array_filter($sorted_dates, function($d) use ($year, $month) {
                return gmdate('Y', strtotime($d)) == $year && gmdate('n', strtotime($d)) == $month;
            });
            ?>
            <?php if (!empty($month_dates)): ?>
            <div class="fs-week-glance-widget">
                <div class="fs-week-glance-grid">
                    <?php foreach ($month_dates as $date_str):
                        $day_events = $events_by_date[$date_str];
                        $day_name = gmdate('D', strtotime($date_str));
                        $day_num = gmdate('j', strtotime($date_str));
                        $is_today_t = ($date_str === $today);
                        $is_weekend_t = (gmdate('N', strtotime($date_str)) >= 6);
                        $classes = array('fs-week-glance-day');
                        if ($is_today_t) $classes[] = 'fs-today';
                        if ($is_weekend_t) $classes[] = 'fs-weekend';
                    ?>
                        <div class="<?php echo  esc_attr( implode(' ', $classes) ); ?>">
                            <div class="fs-week-glance-day-header">
                                <span class="fs-week-glance-day-name"><?php echo  esc_html( strtoupper($day_name) ); ?></span>
                                <span class="fs-week-glance-day-num"><?php echo  intval( $day_num ); ?></span>
                            </div>
                            <div class="fs-week-glance-events">
                                <?php foreach ($day_events as $event):
                                    $is_gcal_editable = isset($event['gcal_editable']) && $event['gcal_editable'];
                                    $gcal_data = isset($event['gcal_data']) ? htmlspecialchars(json_encode($event['gcal_data']), ENT_QUOTES, 'UTF-8') : '';
                                    $event_type = isset($event['type']) ? $event['type'] : 'default';
                                ?>
                                    <?php if ($is_gcal_editable): ?>
                                    <a href="#" class="fs-week-glance-event fs-week-event-<?php echo esc_attr($event_type); ?> fs-gcal-event"
                                       style="background: <?php echo esc_attr($event['color']); ?>; --fs-task-accent: <?php echo esc_attr($event['color']); ?>;"
                                       title="<?php echo esc_attr($event['title']); ?>"
                                       data-gcal-event="<?php echo  esc_attr( $gcal_data ); ?>">
                                        <span class="fs-week-event-title"><?php echo esc_html(wp_trim_words($event['title'], 3, '…')); ?></span>
                                        <span class="fs-week-event-title-full"><?php echo esc_html($event['title']); ?></span>
                                        <?php if (!empty($event['time'])): ?>
                                            <span class="fs-week-event-time"><?php echo esc_html($event['time']); ?></span>
                                        <?php endif; ?>
                                    </a>
                                    <?php else: ?>
                                    <a href="<?php echo esc_url($event['url']); ?>" 
                                       class="fs-week-glance-event fs-week-event-<?php echo esc_attr($event_type); ?>"
                                       style="background: <?php echo esc_attr($event['color']); ?>; --fs-task-accent: <?php echo esc_attr($event['color']); ?>;"
                                       title="<?php echo esc_attr($event['title']); ?>">
                                        <span class="fs-week-event-title"><?php echo esc_html(wp_trim_words($event['title'], 3, '…')); ?></span>
                                        <span class="fs-week-event-title-full"><?php echo esc_html($event['title']); ?></span>
                                        <?php if (!empty($event['time'])): ?>
                                            <span class="fs-week-event-time"><?php echo esc_html($event['time']); ?></span>
                                        <?php endif; ?>
                                    </a>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php else: ?>
            <div class="fs-widget-no-events">
                <span class="dashicons dashicons-calendar-alt"></span>
                <p><?php esc_html_e('No events this month.', 'freelance-studio'); ?></p>
            </div>
            <?php endif; ?>
            <div class="fs-cal-mobile-nav">
                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&year=' . $prev_year . '&month=' . $prev_month)); ?>" class="fs-btn fs-btn-secondary fs-btn-small">
                    ← <?php echo  esc_html( gmdate('M', mktime(0, 0, 0, $prev_month, 1, $prev_year)) ); ?>
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar')); ?>" class="fs-btn fs-btn-secondary fs-btn-small">
                    <?php esc_html_e('Today', 'freelance-studio'); ?>
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-calendar&year=' . $next_year . '&month=' . $next_month)); ?>" class="fs-btn fs-btn-secondary fs-btn-small">
                    <?php echo  esc_html( gmdate('M', mktime(0, 0, 0, $next_month, 1, $next_year)) ); ?> →
                </a>
            </div>
        </div>
    </div>
    
    <?php if ($view === 'month'): ?>
    <!-- Month View -->
    <div class="fs-calendar-grid">
        <div class="fs-calendar-weekdays">
            <div class="fs-weekday fs-weekend"><?php esc_html_e('Sun', 'freelance-studio'); ?></div>
            <div class="fs-weekday"><?php esc_html_e('Mon', 'freelance-studio'); ?></div>
            <div class="fs-weekday"><?php esc_html_e('Tue', 'freelance-studio'); ?></div>
            <div class="fs-weekday"><?php esc_html_e('Wed', 'freelance-studio'); ?></div>
            <div class="fs-weekday"><?php esc_html_e('Thu', 'freelance-studio'); ?></div>
            <div class="fs-weekday"><?php esc_html_e('Fri', 'freelance-studio'); ?></div>
            <div class="fs-weekday fs-weekend"><?php esc_html_e('Sat', 'freelance-studio'); ?></div>
        </div>
        
        <div class="fs-calendar-days">
            <?php
            // Calculate starting point (may be in previous month)
            $start_offset = $day_of_week; // Days from Sunday
            $current_date = strtotime("-{$start_offset} days", $first_day_of_month);
            
            // Generate 6 weeks (42 days) to ensure full grid
            for ($i = 0; $i < 42; $i++):
                $date_str = gmdate('Y-m-d', $current_date);
                $day_num = gmdate('j', $current_date);
                $is_current_month = gmdate('n', $current_date) == $month;
                $is_today = $date_str === $today;
                $is_weekend = gmdate('w', $current_date) == 0 || gmdate('w', $current_date) == 6;
                $day_events = isset($events_by_date[$date_str]) ? $events_by_date[$date_str] : array();
                
                $classes = array('fs-calendar-day');
                if (!$is_current_month) $classes[] = 'fs-other-month';
                if ($is_today) $classes[] = 'fs-today';
                if ($is_weekend) $classes[] = 'fs-weekend';
                if (!empty($day_events)) $classes[] = 'fs-has-events';
            ?>
                <div class="<?php echo  esc_attr( implode(' ', $classes) ); ?>" data-date="<?php echo  esc_attr( $date_str ); ?>">
                    <div class="fs-day-number"><?php echo  intval( $day_num ); ?></div>
                    <div class="fs-day-events">
                        <?php 
                        $shown = 0;
                        $max_show = 3;
                        foreach ($day_events as $event): 
                            if ($shown >= $max_show) {
                                $remaining = count($day_events) - $max_show;
                                echo wp_kses_post( '<div class="fs-event-more">+' . $remaining . ' more</div>' );                                break;
                            }
                            $shown++;
                            
                            // Check if this is an editable Google Calendar event
                            $is_gcal_editable = isset($event['gcal_editable']) && $event['gcal_editable'];
                            $gcal_data = isset($event['gcal_data']) ? htmlspecialchars(json_encode($event['gcal_data']), ENT_QUOTES, 'UTF-8') : '';
                        ?>
                            <?php if ($is_gcal_editable): ?>
                            <a href="#" 
                               class="fs-calendar-event fs-gcal-event" 
                               style="border-left-color: <?php echo esc_attr($event['color']); ?>;"
                               title="<?php echo esc_attr($event['title'] . ' - ' . $event['subtitle']); ?>"
                               data-gcal-event="<?php echo  esc_attr( $gcal_data ); ?>">
                                <span class="fs-event-icon"><?php echo  esc_html( $event['icon'] ); ?></span>
                                <span class="fs-event-title"><?php echo esc_html($event['title']); ?></span>
                            </a>
                            <?php else: ?>
                            <a href="<?php echo esc_url($event['url']); ?>" 
                               class="fs-calendar-event" 
                               style="border-left-color: <?php echo esc_attr($event['color']); ?>;"
                               title="<?php echo esc_attr($event['title'] . ' - ' . $event['subtitle']); ?>">
                                <span class="fs-event-icon"><?php echo  esc_html( $event['icon'] ); ?></span>
                                <span class="fs-event-title"><?php echo esc_html($event['title']); ?></span>
                            </a>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php 
                $current_date = strtotime('+1 day', $current_date);
            endfor; 
            ?>
        </div>
    </div>
    
    <?php else: ?>
    <!-- Week View -->
    <div class="fs-calendar-week-view">
        <?php
        $week_date = strtotime($week_start);
        for ($i = 0; $i < 7; $i++):
            $date_str = gmdate('Y-m-d', $week_date);
            $is_today = $date_str === $today;
            $is_weekend = gmdate('N', $week_date) >= 6;
            $day_events = isset($events_by_date[$date_str]) ? $events_by_date[$date_str] : array();
            
            $classes = array('fs-week-day');
            if ($is_today) $classes[] = 'fs-today';
            if ($is_weekend) $classes[] = 'fs-weekend';
        ?>
            <div class="<?php echo  esc_attr( implode(' ', $classes) ); ?>">
                <div class="fs-week-day-header">
                    <span class="fs-week-day-name"><?php echo  esc_html( gmdate('l', $week_date) ); ?></span>
                    <span class="fs-week-day-date"><?php echo  esc_html( gmdate('M j', $week_date) ); ?></span>
                </div>
                <div class="fs-week-day-events">
                    <?php if (empty($day_events)): ?>
                        <div class="fs-no-events"><?php esc_html_e('No events', 'freelance-studio'); ?></div>
                    <?php else: ?>
                        <?php foreach ($day_events as $event): 
                            $is_gcal_editable = isset($event['gcal_editable']) && $event['gcal_editable'];
                            $gcal_data = isset($event['gcal_data']) ? htmlspecialchars(json_encode($event['gcal_data']), ENT_QUOTES, 'UTF-8') : '';
                        ?>
                            <?php if ($is_gcal_editable): ?>
                            <a href="#" 
                               class="fs-week-event fs-gcal-event" 
                               style="border-left-color: <?php echo esc_attr($event['color']); ?>;"
                               data-gcal-event="<?php echo  esc_attr( $gcal_data ); ?>">
                                <div class="fs-week-event-header">
                                    <span class="fs-event-icon"><?php echo  esc_html( $event['icon'] ); ?></span>
                                    <span class="fs-event-title"><?php echo esc_html($event['title']); ?></span>
                                </div>
                                <div class="fs-event-subtitle"><?php echo esc_html($event['subtitle']); ?></div>
                            </a>
                            <?php else: ?>
                            <a href="<?php echo esc_url($event['url']); ?>" 
                               class="fs-week-event" 
                               style="border-left-color: <?php echo esc_attr($event['color']); ?>;">
                                <div class="fs-week-event-header">
                                    <span class="fs-event-icon"><?php echo  esc_html( $event['icon'] ); ?></span>
                                    <span class="fs-event-title"><?php echo esc_html($event['title']); ?></span>
                                </div>
                                <div class="fs-event-subtitle"><?php echo esc_html($event['subtitle']); ?></div>
                            </a>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php 
            $week_date = strtotime('+1 day', $week_date);
        endfor; 
        ?>
    </div>
    <?php endif; ?>
    
    <!-- Upcoming Events Sidebar -->
    <div class="fs-calendar-sidebar">
        <!-- Mini Calendar -->
        <div class="fs-calendar-sidebar-section">
            <div class="fs-sidebar-mini-cal" id="fs-mini-calendar" 
                 data-year="<?php echo  esc_attr( $year ); ?>" 
                 data-month="<?php echo  esc_attr( $month ); ?>"
                 data-events='<?php echo json_encode(array_keys($events_by_date)); ?>'>
                <div class="fs-sidebar-mini-cal-header">
                    <span class="fs-sidebar-mini-cal-title"><?php echo esc_html($month_name . ', ' . $year); ?></span>
                    <div class="fs-sidebar-mini-cal-nav">
                        <button type="button" class="fs-mini-nav-btn" id="fs-mini-cal-prev" title="<?php esc_attr_e('Previous month', 'freelance-studio'); ?>">
                            <span class="dashicons dashicons-arrow-left-alt2"></span>
                        </button>
                        <button type="button" class="fs-mini-nav-btn" id="fs-mini-cal-next" title="<?php esc_attr_e('Next month', 'freelance-studio'); ?>">
                            <span class="dashicons dashicons-arrow-right-alt2"></span>
                        </button>
                    </div>
                </div>
                <div class="fs-sidebar-mini-cal-grid" id="fs-mini-cal-grid">
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('S', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('M', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('T', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('W', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('T', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('F', 'freelance-studio'); ?></span>
                    <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('S', 'freelance-studio'); ?></span>
                    <?php
                    // Build mini calendar grid
                    $mini_start_offset = $day_of_week; // Days from Sunday
                    $mini_current_date = strtotime("-{$mini_start_offset} days", $first_day_of_month);
                    
                    for ($i = 0; $i < 42; $i++):
                        $mini_date_str = gmdate('Y-m-d', $mini_current_date);
                        $mini_day_num = gmdate('j', $mini_current_date);
                        $mini_is_current_month = gmdate('n', $mini_current_date) == $month;
                        $mini_is_today = $mini_date_str === $today;
                        $mini_has_events = isset($events_by_date[$mini_date_str]) && !empty($events_by_date[$mini_date_str]);
                        
                        $mini_classes = array('fs-sidebar-mini-cal-day');
                        if (!$mini_is_current_month) $mini_classes[] = 'fs-other-month';
                        if ($mini_is_today) $mini_classes[] = 'fs-today';
                        if ($mini_has_events) $mini_classes[] = 'fs-has-events';
                    ?>
                        <a href="#" 
                           class="<?php echo  esc_attr( implode(' ', $mini_classes) ); ?>"
                           data-date="<?php echo esc_attr($mini_date_str); ?>"
                           <?php /* translators: 1. count/number */ ?>
                           title="<?php echo  esc_attr( $mini_has_events ? sprintf(__('%d event(s)', 'freelance-studio'), count($events_by_date[$mini_date_str])) : esc_attr(gmdate('F j, Y', $mini_current_date)) ); ?>">
                            <?php echo  intval( $mini_day_num ); ?>
                        </a>
                    <?php 
                        $mini_current_date = strtotime('+1 day', $mini_current_date);
                    endfor; 
                    ?>
                </div>
            </div>
        </div>
        
        <!-- Quick Add Task Button -->
        <button type="button" id="fs-add-task-btn" class="fs-calendar-quick-add-btn">
            <span class="dashicons dashicons-plus-alt2"></span>
            <?php esc_html_e('Add New Task', 'freelance-studio'); ?>
        </button>
        
        <!-- Upcoming Events -->
        <div class="fs-calendar-sidebar-section">
            <h3><?php esc_html_e('Upcoming', 'freelance-studio'); ?></h3>
            <?php 
            $upcoming = array_filter($events, function($e) use ($today) {
                return $e['date'] >= $today;
            });
            $upcoming = array_slice($upcoming, 0, 8);
            
            if (empty($upcoming)): 
            ?>
                <p class="fs-no-upcoming"><?php esc_html_e('No upcoming events.', 'freelance-studio'); ?></p>
            <?php else: ?>
                <div class="fs-upcoming-list">
                    <?php foreach ($upcoming as $event): ?>
                        <a href="<?php echo esc_url($event['url']); ?>" class="fs-upcoming-item">
                            <div class="fs-upcoming-date">
                                <span class="fs-upcoming-month"><?php echo  esc_html( gmdate('M', strtotime($event['date'])) ); ?></span>
                                <span class="fs-upcoming-day"><?php echo  esc_html( gmdate('j', strtotime($event['date'])) ); ?></span>
                            </div>
                            <div class="fs-upcoming-content">
                                <span class="fs-upcoming-icon" style="color: <?php echo esc_attr($event['color']); ?>;">
                                    <?php echo  esc_html( $event['icon'] ); ?>
                                </span>
                                <div class="fs-upcoming-details">
                                    <div class="fs-upcoming-title"><?php echo esc_html($event['title']); ?></div>
                                    <div class="fs-upcoming-subtitle"><?php echo esc_html($event['subtitle']); ?></div>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <?php if (FS_Google_Calendar_Service::is_connected()): ?>
                <div class="fs-calendar-sync-status">
                    <span class="dashicons dashicons-yes-alt" style="color: #4caf50;"></span>
                    <?php esc_html_e('Synced with Google Calendar', 'freelance-studio'); ?>
                </div>
            <?php else: ?>
                <div class="fs-calendar-sync-status">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-settings&tab=calendar') ); ?>">
                        <span class="dashicons dashicons-cloud"></span>
                        <?php esc_html_e('Connect to Google Calendar', 'freelance-studio'); ?>
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add Task Modal (always available) -->
<div id="fs-task-modal" class="fs-modal">
    <div class="fs-modal-content" style="max-width: 500px;">
        <div class="fs-modal-header">
            <h3><?php esc_html_e('Add New Task', 'freelance-studio'); ?></h3>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <form id="fs-task-form">
                <div class="fs-form-row">
                    <label for="fs-task-title"><?php esc_html_e('Task Title', 'freelance-studio'); ?> <span class="required">*</span></label>
                    <input type="text" name="title" id="fs-task-title" class="regular-text" required>
                </div>
                
                <div class="fs-form-row">
                    <label for="fs-task-project"><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                    <select name="project_id" id="fs-task-project" class="regular-text">
                        <option value=""><?php esc_html_e('— No Project —', 'freelance-studio'); ?></option>
                        <?php
                        $projects = FS_Project::get_all(array('status' => array('pending', 'active')));
                        foreach ($projects as $project):
                        ?>
                            <option value="<?php echo  intval( $project->id ); ?>"><?php echo esc_html($project->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="fs-form-row fs-form-row-inline">
                    <div>
                        <label for="fs-task-due-date"><?php esc_html_e('Due Date', 'freelance-studio'); ?></label>
                        <input type="date" name="due_date" id="fs-task-due-date">
                    </div>
                    <div>
                        <label for="fs-task-priority"><?php esc_html_e('Priority', 'freelance-studio'); ?></label>
                        <select name="priority" id="fs-task-priority">
                            <option value="low"><?php esc_html_e('Low', 'freelance-studio'); ?></option>
                            <option value="medium" selected><?php esc_html_e('Medium', 'freelance-studio'); ?></option>
                            <option value="high"><?php esc_html_e('High', 'freelance-studio'); ?></option>
                            <option value="urgent"><?php esc_html_e('Urgent', 'freelance-studio'); ?></option>
                        </select>
                    </div>
                </div>
                
                <div class="fs-form-row">
                    <label for="fs-task-description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                    <textarea name="description" id="fs-task-description" rows="3"></textarea>
                </div>
                
                <div class="fs-form-actions">
                    <button type="button" id="fs-task-cancel" class="button"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                    <button type="submit" id="fs-task-save" class="button button-primary"><?php esc_html_e('Add Task', 'freelance-studio'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Mini Calendar and Task Modal JavaScript -->
<script>
jQuery(document).ready(function($) {
    var miniCalYear = <?php echo  esc_html( $year ); ?>;
    var miniCalMonth = <?php echo  esc_html( $month ); ?>;
    var eventDates = <?php echo json_encode(array_keys($events_by_date)); ?>;
    var todayStr = '<?php echo  esc_html( $today ); ?>';
    var monthNames = ['<?php esc_html_e('January', 'freelance-studio'); ?>', '<?php esc_html_e('February', 'freelance-studio'); ?>', '<?php esc_html_e('March', 'freelance-studio'); ?>', '<?php esc_html_e('April', 'freelance-studio'); ?>', '<?php esc_html_e('May', 'freelance-studio'); ?>', '<?php esc_html_e('June', 'freelance-studio'); ?>', '<?php esc_html_e('July', 'freelance-studio'); ?>', '<?php esc_html_e('August', 'freelance-studio'); ?>', '<?php esc_html_e('September', 'freelance-studio'); ?>', '<?php esc_html_e('October', 'freelance-studio'); ?>', '<?php esc_html_e('November', 'freelance-studio'); ?>', '<?php esc_html_e('December', 'freelance-studio'); ?>'];
    
    // Mini calendar navigation
    function renderMiniCalendar(year, month) {
        var firstDay = new Date(year, month - 1, 1);
        var daysInMonth = new Date(year, month, 0).getDate();
        var startDay = firstDay.getDay(); // 0 = Sunday (already correct for Sunday start)
        
        // Update title
        $('.fs-sidebar-mini-cal-title').text(monthNames[month - 1] + ', ' + year);
        
        // Build grid HTML (keep weekday headers, replace days)
        var html = '';
        html += '<span class="fs-sidebar-mini-cal-weekday">S</span>';
        html += '<span class="fs-sidebar-mini-cal-weekday">M</span>';
        html += '<span class="fs-sidebar-mini-cal-weekday">T</span>';
        html += '<span class="fs-sidebar-mini-cal-weekday">W</span>';
        html += '<span class="fs-sidebar-mini-cal-weekday">T</span>';
        html += '<span class="fs-sidebar-mini-cal-weekday">F</span>';
        html += '<span class="fs-sidebar-mini-cal-weekday">S</span>';
        
        // Previous month days
        var prevMonth = month - 1;
        var prevYear = year;
        if (prevMonth < 1) {
            prevMonth = 12;
            prevYear--;
        }
        var daysInPrevMonth = new Date(prevYear, prevMonth, 0).getDate();
        
        for (var i = startDay - 1; i >= 0; i--) {
            var day = daysInPrevMonth - i;
            var dateStr = prevYear + '-' + String(prevMonth).padStart(2, '0') + '-' + String(day).padStart(2, '0');
            var hasEvents = eventDates.indexOf(dateStr) !== -1;
            var classes = 'fs-sidebar-mini-cal-day fs-other-month';
            if (hasEvents) classes += ' fs-has-events';
            html += '<a href="#" class="' + classes + '" data-date="' + dateStr + '">' + day + '</a>';
        }
        
        // Current month days
        for (var day = 1; day <= daysInMonth; day++) {
            var dateStr = year + '-' + String(month).padStart(2, '0') + '-' + String(day).padStart(2, '0');
            var hasEvents = eventDates.indexOf(dateStr) !== -1;
            var isToday = dateStr === todayStr;
            var classes = 'fs-sidebar-mini-cal-day';
            if (isToday) classes += ' fs-today';
            if (hasEvents) classes += ' fs-has-events';
            html += '<a href="#" class="' + classes + '" data-date="' + dateStr + '">' + day + '</a>';
        }
        
        // Next month days
        var totalCells = startDay + daysInMonth;
        var remaining = totalCells <= 35 ? 35 - totalCells : 42 - totalCells;
        var nextMonth = month + 1;
        var nextYear = year;
        if (nextMonth > 12) {
            nextMonth = 1;
            nextYear++;
        }
        
        for (var day = 1; day <= remaining; day++) {
            var dateStr = nextYear + '-' + String(nextMonth).padStart(2, '0') + '-' + String(day).padStart(2, '0');
            var hasEvents = eventDates.indexOf(dateStr) !== -1;
            var classes = 'fs-sidebar-mini-cal-day fs-other-month';
            if (hasEvents) classes += ' fs-has-events';
            html += '<a href="#" class="' + classes + '" data-date="' + dateStr + '">' + day + '</a>';
        }
        
        $('#fs-mini-cal-grid').html(html);
        miniCalYear = year;
        miniCalMonth = month;
    }
    
    // Previous month button
    $('#fs-mini-cal-prev').on('click', function(e) {
        e.preventDefault();
        var newMonth = miniCalMonth - 1;
        var newYear = miniCalYear;
        if (newMonth < 1) {
            newMonth = 12;
            newYear--;
        }
        renderMiniCalendar(newYear, newMonth);
    });
    
    // Next month button
    $('#fs-mini-cal-next').on('click', function(e) {
        e.preventDefault();
        var newMonth = miniCalMonth + 1;
        var newYear = miniCalYear;
        if (newMonth > 12) {
            newMonth = 1;
            newYear++;
        }
        renderMiniCalendar(newYear, newMonth);
    });
    
    // Mini calendar day click - scroll to and highlight day in main calendar
    $(document).on('click', '.fs-sidebar-mini-cal-day', function(e) {
        e.preventDefault();
        var date = $(this).data('date');
        if (date) {
            // Find the corresponding day in the main calendar grid
            var $targetDay = $('.fs-calendar-day[data-date="' + date + '"]');
            if ($targetDay.length) {
                // Scroll to the day
                $('html, body').animate({
                    scrollTop: $targetDay.offset().top - 100
                }, 300);
                
                // Add highlight effect
                $('.fs-calendar-day').removeClass('fs-highlight-day');
                $targetDay.addClass('fs-highlight-day');
                setTimeout(function() {
                    $targetDay.removeClass('fs-highlight-day');
                }, 2000);
            }
        }
    });
    
    // Add Task Modal
    $('#fs-add-task-btn').on('click', function() {
        $('#fs-task-form')[0].reset();
        $('#fs-task-due-date').val(todayStr);
        $('#fs-task-modal').addClass('active');
    });
    
    // Close task modal
    $('#fs-task-modal .fs-modal-close, #fs-task-cancel').on('click', function() {
        $('#fs-task-modal').removeClass('active');
    });
    
    // Close modal on outside click
    $('#fs-task-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).removeClass('active');
        }
    });
    
    // Save task
    $('#fs-task-form').on('submit', function(e) {
        e.preventDefault();
        
        var $btn = $('#fs-task-save');
        var originalText = $btn.text();
        $btn.text('<?php esc_html_e('Saving...', 'freelance-studio'); ?>').prop('disabled', true);
        
        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_save_task',
                nonce: fs_ajax.nonce,
                title: $('#fs-task-title').val(),
                project_id: $('#fs-task-project').val() || 0,
                due_date: $('#fs-task-due-date').val(),
                priority: $('#fs-task-priority').val(),
                description: $('#fs-task-description').val()
            },
            success: function(response) {
                if (response.success) {
                    $('#fs-task-modal').removeClass('active');
                    // Reload page to show new task on calendar
                    location.reload();
                } else {
                    alert(response.data || '<?php esc_html_e('Failed to create task', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('An error occurred', 'freelance-studio'); ?>');
            },
            complete: function() {
                $btn.text(originalText).prop('disabled', false);
            }
        });
    });
});
</script>
<style>
.fs-calendar-day.fs-highlight-day {
    background: rgba(235, 136, 97, 0.15) !important;
    box-shadow: inset 0 0 0 2px var(--fs-accent);
    transition: all 0.3s;
}
</style>

<!-- Add/Edit Event Modal -->
<?php if (FS_Google_Calendar_Service::is_connected()): ?>
<div id="fs-event-modal" class="fs-modal">
    <div class="fs-modal-content" style="max-width: 500px;">
        <div class="fs-modal-header">
            <h3 id="fs-event-modal-title"><?php esc_html_e('Add Event', 'freelance-studio'); ?></h3>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <form id="fs-event-form">
                <input type="hidden" name="event_id" id="fs-event-id" value="">
                
                <div class="fs-form-row">
                    <label for="fs-event-title"><?php esc_html_e('Title', 'freelance-studio'); ?> <span class="required">*</span></label>
                    <input type="text" name="title" id="fs-event-title" class="regular-text" required>
                </div>
                
                <div class="fs-form-row">
                    <label>
                        <input type="checkbox" name="all_day" id="fs-event-all-day" checked>
                        <?php esc_html_e('All day event', 'freelance-studio'); ?>
                    </label>
                </div>
                
                <div class="fs-form-row fs-form-row-inline">
                    <div>
                        <label for="fs-event-date"><?php esc_html_e('Start Date', 'freelance-studio'); ?> <span class="required">*</span></label>
                        <input type="date" name="date" id="fs-event-date" required>
                    </div>
                    <div class="fs-time-field" style="display: none;">
                        <label for="fs-event-start-time"><?php esc_html_e('Start Time', 'freelance-studio'); ?></label>
                        <input type="time" name="start_time" id="fs-event-start-time" value="09:00">
                    </div>
                </div>
                
                <div class="fs-form-row fs-form-row-inline">
                    <div>
                        <label for="fs-event-end-date"><?php esc_html_e('End Date', 'freelance-studio'); ?></label>
                        <input type="date" name="end_date" id="fs-event-end-date">
                    </div>
                    <div class="fs-time-field" style="display: none;">
                        <label for="fs-event-end-time"><?php esc_html_e('End Time', 'freelance-studio'); ?></label>
                        <input type="time" name="end_time" id="fs-event-end-time" value="10:00">
                    </div>
                </div>
                
                <div class="fs-form-row">
                    <label for="fs-event-description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                    <textarea name="description" id="fs-event-description" rows="3"></textarea>
                </div>
                
                <div class="fs-form-actions">
                    <button type="submit" class="button button-primary" id="fs-event-save">
                        <?php esc_html_e('Save Event', 'freelance-studio'); ?>
                    </button>
                    <button type="button" class="button" id="fs-event-cancel">
                        <?php esc_html_e('Cancel', 'freelance-studio'); ?>
                    </button>
                    <button type="button" class="button button-link-delete" id="fs-event-delete" style="display: none; margin-left: auto;">
                        <?php esc_html_e('Delete', 'freelance-studio'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    var currentEventId = null;
    
    // Toggle time fields based on all-day checkbox
    $('#fs-event-all-day').on('change', function() {
        if ($(this).is(':checked')) {
            $('.fs-time-field').hide();
        } else {
            $('.fs-time-field').show();
        }
    });
    
    // Open modal for new Google Calendar event
    $('#fs-add-gcal-event, #fs-mobile-add-event-btn').on('click', function() {
        currentEventId = null;
        $('#fs-event-modal-title').text('<?php esc_html_e('Add Event', 'freelance-studio'); ?>');
        $('#fs-event-form')[0].reset();
        $('#fs-event-id').val('');
        $('#fs-event-date').val('<?php echo  esc_html( gmdate('Y-m-d') ); ?>');
        $('#fs-event-all-day').prop('checked', true).trigger('change');
        $('#fs-event-delete').hide();
        $('#fs-event-modal').addClass('active');
    });
    
    // Close modal
    $('#fs-event-modal .fs-modal-close, #fs-event-cancel').on('click', function() {
        $('#fs-event-modal').removeClass('active');
    });
    
    // Close modal on outside click
    $('#fs-event-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).removeClass('active');
        }
    });
    
    // Save event
    $('#fs-event-form').on('submit', function(e) {
        e.preventDefault();
        
        var $btn = $('#fs-event-save');
        var originalText = $btn.text();
        $btn.text('<?php esc_html_e('Saving...', 'freelance-studio'); ?>').prop('disabled', true);
        
        var action = currentEventId ? 'fs_gcal_update_event' : 'fs_gcal_create_event';
        
        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: action,
                nonce: fs_ajax.nonce,
                event_id: currentEventId,
                title: $('#fs-event-title').val(),
                date: $('#fs-event-date').val(),
                end_date: $('#fs-event-end-date').val(),
                description: $('#fs-event-description').val(),
                all_day: $('#fs-event-all-day').is(':checked'),
                start_time: $('#fs-event-start-time').val(),
                end_time: $('#fs-event-end-time').val()
            },
            success: function(response) {
                if (response.success) {
                    $('#fs-event-modal').removeClass('active');
                    location.reload(); // Refresh to show new event
                } else {
                    alert(response.data.message || '<?php esc_html_e('Failed to save event', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('An error occurred', 'freelance-studio'); ?>');
            },
            complete: function() {
                $btn.text(originalText).prop('disabled', false);
            }
        });
    });
    
    // Delete event
    $('#fs-event-delete').on('click', function() {
        if (!currentEventId) return;
        
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this event?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var $btn = $(this);
        $btn.text('<?php esc_html_e('Deleting...', 'freelance-studio'); ?>').prop('disabled', true);
        
        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_gcal_delete_event',
                nonce: fs_ajax.nonce,
                event_id: currentEventId
            },
            success: function(response) {
                if (response.success) {
                    $('#fs-event-modal').removeClass('active');
                    location.reload();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Failed to delete event', 'freelance-studio'); ?>');
                    $btn.text('<?php esc_html_e('Delete', 'freelance-studio'); ?>').prop('disabled', false);
                }
            },
            error: function() {
                alert('<?php esc_html_e('An error occurred', 'freelance-studio'); ?>');
                $btn.text('<?php esc_html_e('Delete', 'freelance-studio'); ?>').prop('disabled', false);
            }
        });
    });
    
    // Click on calendar day to add event
    $('.fs-calendar-day').on('click', function(e) {
        if ($(e.target).closest('.fs-calendar-event').length) {
            return; // Don't trigger if clicking on an event
        }
        
        <?php if (FS_Google_Calendar_Service::is_connected()): ?>
        var date = $(this).data('date');
        if (date) {
            currentEventId = null;
            $('#fs-event-modal-title').text('<?php esc_html_e('Add Event', 'freelance-studio'); ?>');
            $('#fs-event-form')[0].reset();
            $('#fs-event-id').val('');
            $('#fs-event-date').val(date);
            $('#fs-event-all-day').prop('checked', true).trigger('change');
            $('#fs-event-delete').hide();
            $('#fs-event-modal').addClass('active');
        }
        <?php endif; ?>
    });
    
    // Click on Google Calendar event to edit
    $(document).on('click', '.fs-gcal-event', function(e) {
        e.preventDefault();
        
        var eventData = $(this).data('gcal-event');
        if (!eventData) return;
        
        currentEventId = eventData.id;
        $('#fs-event-modal-title').text('<?php esc_html_e('Edit Event', 'freelance-studio'); ?>');
        $('#fs-event-title').val(eventData.title);
        $('#fs-event-date').val(eventData.date);
        $('#fs-event-end-date').val(eventData.end_date !== eventData.date ? eventData.end_date : '');
        $('#fs-event-description').val(eventData.description || '');
        $('#fs-event-all-day').prop('checked', eventData.all_day).trigger('change');
        
        if (!eventData.all_day) {
            $('#fs-event-start-time').val(eventData.start_time || '09:00');
            $('#fs-event-end-time').val(eventData.end_time || '10:00');
        }
        
        $('#fs-event-delete').show();
        $('#fs-event-modal').addClass('active');
    });
    
    // Sync button
    $('#fs-sync-calendar').on('click', function() {
        var $btn = $(this);
        var originalHtml = $btn.html();
        
        $btn.html('<span class="dashicons dashicons-update spin" style="margin-top: 3px;"></span> <?php esc_html_e('Syncing...', 'freelance-studio'); ?>').prop('disabled', true);
        
        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_gcal_full_sync',
                nonce: fs_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Reload to show updated events
                    location.reload();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Sync failed', 'freelance-studio'); ?>');
                    $btn.html(originalHtml).prop('disabled', false);
                }
            },
            error: function() {
                alert('<?php esc_html_e('An error occurred during sync', 'freelance-studio'); ?>');
                $btn.html(originalHtml).prop('disabled', false);
            }
        });
    });
});
</script>
<style>
.spin {
    animation: spin 1s linear infinite;
}
@keyframes spin {
    100% { transform: rotate(360deg); }
}
</style>
<?php endif; ?>
