{% extends "layout.html.twig" %}

{% block title %}{{ title }}{% endblock %}

{% block content %}
<div class="container-fluid px-0">
    <!-- Header Section -->
    <div class="row g-0 bg-light border-bottom mb-4">
        <div class="col-12 p-3">
            <div class="container">
                <div class="row align-items-start">
                    <!-- Left 1/2: Logo and Title -->
                    <div class="col-md-6">
                        <div class="d-flex align-items-center">
                            <img src="/lendables/logo_hoursoffered_600.png" 
                                 alt="Hours Offered" 
                                 style="width: 100px; height: 100px; object-fit: contain;" 
                                 class="me-3">
                            <div>
                                <h1 class="h3 mb-0">Browse Offered Hours</h1>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Right 1/2: Subtitle -->
                    <div class="col-md-6">
                        <div class="midi">
                            We mean <b>one hour only.</b> Any of us might need someone to hold the ladder while we paint, or to drive us to the store, or run an errand, or put in screens. An hour can make a huge difference!
                            <br><br>
                            Note that this is not a handyman or housecleaning or furniture-moving service. It's a way for folks to schedule a bit of time for others.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- View Toggle Buttons -->
        <div class="row mb-4">
            <div class="col-12 text-center">
                <div class="btn-group" role="group" aria-label="View Toggle">
                    <button type="button" class="btn btn-outline-primary" id="listViewBtn">
                        <i class="fas fa-list"></i> List View
                    </button>
                    <button type="button" class="btn btn-outline-primary" id="calendarViewBtn">
                        <i class="fas fa-calendar"></i> Calendar View
                    </button>
                    <button type="button" class="btn btn-primary active" id="myHoursBtn">
                        <i class="fas fa-user"></i> My Hours, Give or Take
                    </button>
                    <button type="button" class="btn btn-success" id="addNewOfferingBtn">
                        <i class="fas fa-plus"></i> Add New Hour Offering
                    </button>
                </div>
            </div>
        </div>

        <!-- List View -->
        <div id="listView" style="display: none;">
            {% if hourOfferings|length > 0 %}
                <div class="row">
                    {% for offering in hourOfferings %}
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card h-100">
                                <div class="card-body">
                                    <div class="d-flex align-items-center mb-3">
                                        <img src="/lendables/{{ offering.offerUserAvatar ?: 'f1.jpg' }}" 
                                             alt="User Avatar" 
                                             class="rounded-circle me-3" 
                                             style="width: 48px; height: 48px; object-fit: cover;">
                                        <div>
                                            <h5 class="card-title mb-0">{{ offering.offerUserShowName ?: offering.offerUserFirstName }}</h5>
                                            <small class="text-muted">Available Helper</small>
                                        </div>
                                    </div>
                                    
                                    <h6 class="fw-bold text-primary">{{ offering.title }}</h6>
                                    <p class="card-text">{{ offering.description }}</p>
                                    
                                    <div class="mb-2">
                                        <small class="text-muted">
                                            <i class="fas fa-clock"></i> 
                                            {{ offering.startTime|date('g:i A') }} - {{ offering.endTime|date('g:i A') }}
                                        </small>
                                    </div>
                                    
                                    <div class="mb-2">
                                        <small class="text-muted">
                                            <i class="fas fa-calendar"></i> 
                                            {{ offering.offerDate|date('M j, Y') }}
                                        </small>
                                    </div>
                                    
                                    {% if offering.isRecurring %}
                                        <div class="mb-3">
                                            <span class="badge bg-info">
                                                <i class="fas fa-sync-alt"></i> Recurring {{ offering.recurringType|title }}
                                            </span>
                                        </div>
                                    {% endif %}
                                </div>
                                
                                <div class="card-footer bg-transparent">
                                    {% if currentUser %}
                                        <button type="button" 
                                                class="btn btn-primary btn-sm w-100 contact-helper-btn"
                                                data-offering-id="{{ offering.id }}"
                                                data-helper-name="{{ offering.offerUserShowName ?: offering.offerUserFirstName }}"
                                                data-offering-title="{{ offering.title }}">
                                            <i class="fas fa-envelope"></i> Contact Helper
                                        </button>
                                    {% else %}
                                        <a href="/login" class="btn btn-outline-primary btn-sm w-100">
                                            Login to Contact
                                        </a>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    {% endfor %}
                </div>
            {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-clock fa-3x text-muted mb-3"></i>
                    <h5>No Hour Offerings Available</h5>
                    <p class="text-muted">Be the first to offer your time and skills!</p>
                    <a href="/offer-hour" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Offer an Hour
                    </a>
                </div>
            {% endif %}
        </div>

        <!-- Calendar View -->
        <div id="calendarView" style="display: none;">
            <div class="row">
                <div class="col-12">
                    <!-- Calendar Navigation -->
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <button type="button" class="btn btn-outline-secondary" id="prevMonthBtn">
                            <i class="fas fa-chevron-left"></i> Previous
                        </button>
                        <h4 id="currentMonthYear" class="mb-0"></h4>
                        <button type="button" class="btn btn-outline-secondary" id="nextMonthBtn">
                            Next <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>

                    <!-- Calendar Grid -->
                    <div class="table-responsive">
                        <table class="table table-bordered calendar-table">
                            <thead class="table-light">
                                <tr>
                                    <th>Sun</th>
                                    <th>Mon</th>
                                    <th>Tue</th>
                                    <th>Wed</th>
                                    <th>Thu</th>
                                    <th>Fri</th>
                                    <th>Sat</th>
                                </tr>
                            </thead>
                            <tbody id="calendarBody">
                                <!-- Calendar dates will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>

                    <!-- Calendar Legend -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="d-flex justify-content-center flex-wrap gap-3">
                                <div class="d-flex align-items-center">
                                    <div class="calendar-legend-color me-2" style="background-color: #4caf50;"></div>
                                    <small>Has Offerings</small>
                                </div>
                                <div class="d-flex align-items-center">
                                    <div class="calendar-legend-color bg-light border me-2"></div>
                                    <small>No Offerings</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- My Hours, Give or Take View -->
        <div id="myHoursView">
            <div class="row">
                <div class="col-12">
                    <h4 class="mb-4">My Hour Offerings & Scheduled Hours</h4>
                    
                    <!-- My Hour Offerings -->
                    <div class="mb-5">
                        <h5 class="text-primary mb-3">
                            <i class="fas fa-hand-holding-heart"></i> Hours I'm Offering in the next 30 days
                        </h5>
                        <div id="myOfferingsContainer">
                            <!-- Will be populated by JavaScript -->
                        </div>
                    </div>
                    
                    <!-- Hours I've Scheduled from Others -->
                    <div class="mb-5">
                        <h5 class="text-success mb-3">
                            <i class="fas fa-calendar-check"></i> Hours I've Scheduled
                        </h5>
                        <div id="myScheduledContainer">
                            <!-- Will be populated by JavaScript -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Contact Helper Modal -->
<div class="modal fade" id="contactHelperModal" tabindex="-1" aria-labelledby="contactHelperModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="contactHelperModalLabel">Contact Helper</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="contactHelperForm">
                    <div class="mb-3">
                        <label for="helperName" class="form-label">Helper</label>
                        <input type="text" class="form-control" id="helperName" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="offeringTitle" class="form-label">Service</label>
                        <input type="text" class="form-control" id="offeringTitle" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="contactMessage" class="form-label">Your Message</label>
                        <textarea class="form-control" id="contactMessage" rows="4" 
                                  placeholder="Hi! I'm interested in your hour offering. Could you help me with..."></textarea>
                    </div>
                    <input type="hidden" id="offeringId">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="sendContactBtn">
                    <i class="fas fa-paper-plane"></i> Send Message
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Calendar Day Detail Modal -->
<div class="modal fade" id="calendarDayModal" tabindex="-1" aria-labelledby="calendarDayModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="calendarDayModalLabel">Hour Offerings</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="calendarDayContent">
                <!-- Day offerings will be populated by JavaScript -->
            </div>
        </div>
    </div>
</div>

<!-- Edit Hour Offering Modal -->
<div class="modal fade" id="editOfferingModal" tabindex="-1" aria-labelledby="editOfferingModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editOfferingModalLabel">Edit Your Hour Offering</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editOfferingForm">
                    <div class="mb-3">
                        <label for="editTitle" class="form-label fw-bold">Title</label>
                        <select class="form-control" id="editTitle" name="title" required>
                            <option value="Light Effort">Light Effort</option>
                            <option value="Driving Preferred">Driving Preferred</option>
                            <option value="Conversation time">Conversation time</option>
                            <option value="Anything">Anything</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="editDescription" class="form-label fw-bold">Description</label>
                        <textarea class="form-control" id="editDescription" name="description" rows="3" 
                                  placeholder="Describe what you're offering to help with"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editDate" class="form-label fw-bold">Date</label>
                        <input type="date" class="form-control" id="editDate" name="date" required>
                    </div>
                    <div class="row mb-3">
                        <div class="col-6">
                            <label for="editStartTime" class="form-label fw-bold">Start Time</label>
                            <select class="form-control" id="editStartTime" name="startTime" required>
                                <option value="">Select start time...</option>
                                <option value="06:00">6:00 AM</option>
                                <option value="06:30">6:30 AM</option>
                                <option value="07:00">7:00 AM</option>
                                <option value="07:30">7:30 AM</option>
                                <option value="08:00">8:00 AM</option>
                                <option value="08:30">8:30 AM</option>
                                <option value="09:00">9:00 AM</option>
                                <option value="09:30">9:30 AM</option>
                                <option value="10:00">10:00 AM</option>
                                <option value="10:30">10:30 AM</option>
                                <option value="11:00">11:00 AM</option>
                                <option value="11:30">11:30 AM</option>
                                <option value="12:00">12:00 PM</option>
                                <option value="12:30">12:30 PM</option>
                                <option value="13:00">1:00 PM</option>
                                <option value="13:30">1:30 PM</option>
                                <option value="14:00">2:00 PM</option>
                                <option value="14:30">2:30 PM</option>
                                <option value="15:00">3:00 PM</option>
                                <option value="15:30">3:30 PM</option>
                                <option value="16:00">4:00 PM</option>
                                <option value="16:30">4:30 PM</option>
                                <option value="17:00">5:00 PM</option>
                                <option value="17:30">5:30 PM</option>
                                <option value="18:00">6:00 PM</option>
                                <option value="18:30">6:30 PM</option>
                                <option value="19:00">7:00 PM</option>
                                <option value="19:30">7:30 PM</option>
                                <option value="20:00">8:00 PM</option>
                                <option value="20:30">8:30 PM</option>
                                <option value="21:00">9:00 PM</option>
                                <option value="21:30">9:30 PM</option>
                                <option value="22:00">10:00 PM</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label for="editEndTime" class="form-label fw-bold">End Time</label>
                            <select class="form-control" id="editEndTime" name="endTime" required>
                                <option value="">Select end time...</option>
                                <option value="06:30">6:30 AM</option>
                                <option value="07:00">7:00 AM</option>
                                <option value="07:30">7:30 AM</option>
                                <option value="08:00">8:00 AM</option>
                                <option value="08:30">8:30 AM</option>
                                <option value="09:00">9:00 AM</option>
                                <option value="09:30">9:30 AM</option>
                                <option value="10:00">10:00 AM</option>
                                <option value="10:30">10:30 AM</option>
                                <option value="11:00">11:00 AM</option>
                                <option value="11:30">11:30 AM</option>
                                <option value="12:00">12:00 PM</option>
                                <option value="12:30">12:30 PM</option>
                                <option value="13:00">1:00 PM</option>
                                <option value="13:30">1:30 PM</option>
                                <option value="14:00">2:00 PM</option>
                                <option value="14:30">2:30 PM</option>
                                <option value="15:00">3:00 PM</option>
                                <option value="15:30">3:30 PM</option>
                                <option value="16:00">4:00 PM</option>
                                <option value="16:30">4:30 PM</option>
                                <option value="17:00">5:00 PM</option>
                                <option value="17:30">5:30 PM</option>
                                <option value="18:00">6:00 PM</option>
                                <option value="18:30">6:30 PM</option>
                                <option value="19:00">7:00 PM</option>
                                <option value="19:30">7:30 PM</option>
                                <option value="20:00">8:00 PM</option>
                                <option value="20:30">8:30 PM</option>
                                <option value="21:00">9:00 PM</option>
                                <option value="21:30">9:30 PM</option>
                                <option value="22:00">10:00 PM</option>
                                <option value="22:30">10:30 PM</option>
                            </select>
                        </div>
                    </div>
                    <!-- Recurring Options for Edit -->
                    <div class="mb-4">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="editIsRecurring" name="isRecurring">
                            <label class="form-check-label" for="editIsRecurring">
                                This is a recurring offer (available weekly at this time)
                            </label>
                        </div>
                        <div id="editRecurringOptions" style="display: none;" class="mt-3 ps-4">
                            <label for="editRecurringCount" class="form-label fw-bold">How many times? (2-20 weeks)</label>
                            <select class="form-control" id="editRecurringCount" name="recurringCount">
                                <option value="">Select number of weeks...</option>
                                <option value="2">2 weeks</option>
                                <option value="3">3 weeks</option>
                                <option value="4">4 weeks</option>
                                <option value="5">5 weeks</option>
                                <option value="6">6 weeks</option>
                                <option value="8">8 weeks</option>
                                <option value="10">10 weeks</option>
                                <option value="12">12 weeks</option>
                                <option value="16">16 weeks</option>
                                <option value="20">20 weeks</option>
                            </select>
                        </div>
                    </div>
                    <input type="hidden" id="editOfferingId">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="saveChangesBtn">
                    <i class="fas fa-save"></i> Save Changes
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Hidden data for JavaScript -->
<div id="hourOfferingsData" style="display: none;" data-offerings="{{ hourOfferings|json_encode|e('html_attr') }}"></div>
<div id="userAuthData" style="display: none;" 
     data-authenticated="{{ currentUser ? 'true' : 'false' }}"
     data-user-id="{{ currentUser ? currentUser.id : '' }}"></div>

<style>
.calendar-table td {
    height: 80px;
    vertical-align: top;
    position: relative;
    cursor: pointer;
}

.calendar-table td:hover {
    background-color: #f8f9fa;
}

.calendar-date {
    font-weight: bold;
    margin-bottom: 5px;
}

.calendar-offerings {
    position: absolute;
    top: 25px;
    left: 5px;
    right: 5px;
}

.calendar-offering-badge {
    font-size: 0.7rem;
    margin-bottom: 2px;
    display: block;
}

.calendar-legend-color {
    width: 20px;
    height: 20px;
    border-radius: 3px;
}

.has-offerings {
    background-color: #e8f5e8 !important;
    border-color: #4caf50 !important;
}

.calendar-offering-count {
    position: absolute;
    top: 5px;
    right: 5px;
    background: #4caf50;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    font-size: 0.7rem;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>

{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Parse data from hidden elements
    const hourOfferingsElement = document.getElementById('hourOfferingsData');
    const userAuthElement = document.getElementById('userAuthData');
    
    let hourOfferings = [];
    let isAuthenticated = false;
    
    try {
        if (hourOfferingsElement) {
            const offeringsData = hourOfferingsElement.dataset.offerings;
            console.log('Raw offerings data:', offeringsData);
            
            if (offeringsData && offeringsData.trim() !== '') {
                hourOfferings = JSON.parse(offeringsData);
                console.log('Loaded hour offerings:', hourOfferings);
                console.log('Number of offerings:', hourOfferings.length);
            } else {
                console.log('No offerings data found');
                hourOfferings = [];
            }
        }
        if (userAuthElement) {
            isAuthenticated = userAuthElement.dataset.authenticated === 'true';
        }
    } catch (error) {
        console.error('Error parsing data:', error);
        console.error('Data that failed to parse:', hourOfferingsElement?.dataset.offerings);
        hourOfferings = [];
    }

    // Calendar functionality - declare variables first before any usage
    let currentDate = new Date();
    let calendarOfferings = {};

    // Timezone-aware time formatting function
    function formatLocalTime(utcDateString) {
        const utcDate = new Date(utcDateString);
        const timezoneOffset = utcDate.getTimezoneOffset() * 60000;
        const localDate = new Date(utcDate.getTime() + timezoneOffset);
        return localDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    }

    // My Hours functionality (define early before any usage)
    function loadMyHours() {
        // Get current user ID from session data
        const currentUserId = parseInt(userAuthElement?.dataset.userId || '42'); // Demo fallback
        
        console.log('Loading hours for user:', currentUserId);
        
        // Fetch fresh data from API instead of using stale cached data
        return fetch(`/api/hour-offerings/user/${currentUserId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.offerings) {
                    console.log('Loaded fresh user offerings:', data.offerings);
                    displayMyOfferings(data.offerings);
                    return data.offerings;
                } else {
                    console.error('No offerings data in response:', data);
                    displayMyOfferings([]);
                    return [];
                }
            })
            .catch(error => {
                console.error('Error loading user hour offerings:', error);
                // Fallback to cached data if API fails
                const userOfferings = hourOfferings ? hourOfferings.filter(offering => offering.userId === currentUserId) : [];
                displayMyOfferings(userOfferings);
                return userOfferings;
            });
    }
    
    function displayMyOfferings(offerings) {
        const container = document.getElementById('myOfferingsContainer');
        
        if (offerings.length === 0) {
            container.innerHTML = `
                <div class="card">
                    <div class="card-body text-center">
                        <p class="text-muted">You haven't offered any hours yet.</p>
                        <a href="/offer-hour" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Offer an Hour
                        </a>
                    </div>
                </div>
            `;
            return;
        }
        
        let html = '<div class="row">';
        offerings.forEach(offering => {
            html += `
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <h6 class="fw-bold text-primary">${offering.title}</h6>
                            <p class="card-text">${offering.description || 'No description'}</p>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-calendar"></i> 
                                    ${new Date(offering.offerDate).toLocaleDateString()}
                                </small>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-clock"></i> 
                                    ${formatLocalTime(offering.offerDate)} - 
                                    ${formatLocalTime(offering.endTime)}
                                </small>
                            </div>
                            <div class="mt-3 d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge ${offering.isBooked ? 'bg-success' : 'bg-primary'}">
                                        ${offering.isBooked ? 'Scheduled' : 'Available'}
                                    </span>
                                    ${offering.isRecurring ? `<span class="badge bg-info ms-1"><i class="fas fa-sync-alt"></i> Recurring</span>` : ''}
                                </div>
                                <div class="btn-group btn-group-sm" role="group">
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="editHourOffering(${offering.id})" title="Edit Offering">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteHourOffering(${offering.id})" title="Delete Offering">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
        container.innerHTML = html;
    }

    function displayMyScheduledHours(scheduled) {
        const container = document.getElementById('myScheduledContainer');
        
        if (scheduled.length === 0) {
            container.innerHTML = `
                <div class="card">
                    <div class="card-body text-center">
                        <p class="text-muted">You haven't scheduled any hours yet.</p>
                        <a href="#" class="btn btn-outline-primary">Browse Available Hours</a>
                    </div>
                </div>
            `;
            return;
        }
        
        let html = '<div class="row">';
        scheduled.forEach(item => {
            html += `
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <h6 class="fw-bold text-success">${item.title}</h6>
                            <p class="card-text">${item.description || 'Scheduled help'}</p>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-user"></i> With ${item.helperName}
                                </small>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-calendar"></i> 
                                    ${new Date(item.scheduledDate).toLocaleDateString()}
                                </small>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-clock"></i> 
                                    ${formatLocalTime(item.startTime)} - 
                                    ${formatLocalTime(item.endTime)}
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
        container.innerHTML = html;
    }

    function showLoginMessage() {
        const container = document.getElementById('myOfferingsContainer');
        container.innerHTML = `
            <div class="card">
                <div class="card-body text-center">
                    <p class="text-muted">Please log in to view your hour offerings.</p>
                    <a href="/login" class="btn btn-primary">Log In</a>
                </div>
            </div>
        `;
        
        const scheduledContainer = document.getElementById('myScheduledContainer');
        scheduledContainer.innerHTML = `
            <div class="card">
                <div class="card-body text-center">
                    <p class="text-muted">Please log in to view your scheduled hours.</p>
                    <a href="/login" class="btn btn-primary">Log In</a>
                </div>
            </div>
        `;
    }

    // View toggle functionality
    const listViewBtn = document.getElementById('listViewBtn');
    const calendarViewBtn = document.getElementById('calendarViewBtn');
    const myHoursBtn = document.getElementById('myHoursBtn');
    const listView = document.getElementById('listView');
    const calendarView = document.getElementById('calendarView');
    const myHoursView = document.getElementById('myHoursView');
    
    // Check URL parameters for tab auto-selection
    const urlParams = new URLSearchParams(window.location.search);
    const tabParam = urlParams.get('tab');
    
    // Initialize appropriate view based on URL parameter
    if (tabParam === 'my-hours') {
        // Switch to My Hours tab
        myHoursBtn.classList.add('active');
        myHoursBtn.classList.remove('btn-outline-primary');
        myHoursBtn.classList.add('btn-primary');
        
        listViewBtn.classList.remove('active');
        listViewBtn.classList.remove('btn-primary');
        listViewBtn.classList.add('btn-outline-primary');
        
        calendarViewBtn.classList.remove('active');
        calendarViewBtn.classList.remove('btn-primary');
        calendarViewBtn.classList.add('btn-outline-primary');
        
        listView.style.display = 'none';
        calendarView.style.display = 'none';
        myHoursView.style.display = 'block';
        if (isAuthenticated) {
            loadMyHours();
        } else {
            showLoginMessage();
        }
    } else {
        // Default view is List View
        listViewBtn.classList.add('active');
        listViewBtn.classList.remove('btn-outline-primary');
        listViewBtn.classList.add('btn-primary');
        
        calendarViewBtn.classList.remove('active');
        calendarViewBtn.classList.remove('btn-primary');
        calendarViewBtn.classList.add('btn-outline-primary');
        
        myHoursBtn.classList.remove('active');
        myHoursBtn.classList.remove('btn-primary');
        myHoursBtn.classList.add('btn-outline-primary');
        
        listView.style.display = 'block';
        calendarView.style.display = 'none';
        myHoursView.style.display = 'none';
    }

    listViewBtn.addEventListener('click', function() {
        listViewBtn.classList.add('active');
        listViewBtn.classList.remove('btn-outline-primary');
        listViewBtn.classList.add('btn-primary');
        
        calendarViewBtn.classList.remove('active');
        calendarViewBtn.classList.remove('btn-primary');
        calendarViewBtn.classList.add('btn-outline-primary');
        
        myHoursBtn.classList.remove('active');
        myHoursBtn.classList.remove('btn-primary');
        myHoursBtn.classList.add('btn-outline-primary');
        
        listView.style.display = 'block';
        calendarView.style.display = 'none';
        myHoursView.style.display = 'none';
    });

    calendarViewBtn.addEventListener('click', function() {
        calendarViewBtn.classList.add('active');
        calendarViewBtn.classList.remove('btn-outline-primary');
        calendarViewBtn.classList.add('btn-primary');
        
        listViewBtn.classList.remove('active');
        listViewBtn.classList.remove('btn-primary');
        listViewBtn.classList.add('btn-outline-primary');
        
        myHoursBtn.classList.remove('active');
        myHoursBtn.classList.remove('btn-primary');
        myHoursBtn.classList.add('btn-outline-primary');
        
        listView.style.display = 'none';
        calendarView.style.display = 'block';
        myHoursView.style.display = 'none';
        initializeCalendar();
    });

    myHoursBtn.addEventListener('click', function() {
        myHoursBtn.classList.add('active');
        myHoursBtn.classList.remove('btn-outline-primary');
        myHoursBtn.classList.add('btn-primary');
        
        listViewBtn.classList.remove('active');
        listViewBtn.classList.remove('btn-primary');
        listViewBtn.classList.add('btn-outline-primary');
        
        calendarViewBtn.classList.remove('active');
        calendarViewBtn.classList.remove('btn-primary');
        calendarViewBtn.classList.add('btn-outline-primary');
        
        listView.style.display = 'none';
        calendarView.style.display = 'none';
        myHoursView.style.display = 'block';
        if (isAuthenticated) {
            loadMyHours();
        } else {
            showLoginMessage();
        }
    });

    // Add New Hour Offering button
    const addNewOfferingBtn = document.getElementById('addNewOfferingBtn');
    addNewOfferingBtn.addEventListener('click', function() {
        if (isAuthenticated) {
            window.location.href = '/offer-hour';
        } else {
            LocalLendables.showToast('Login Required', 'Please log in to add hour offerings.', 'error');
        }
    });

    // Contact helper functionality
    const contactHelperBtns = document.querySelectorAll('.contact-helper-btn');
    const contactHelperModal = new bootstrap.Modal(document.getElementById('contactHelperModal'));
    
    contactHelperBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const offeringId = this.dataset.offeringId;
            const helperName = this.dataset.helperName;
            const offeringTitle = this.dataset.offeringTitle;
            
            document.getElementById('offeringId').value = offeringId;
            document.getElementById('helperName').value = helperName;
            document.getElementById('offeringTitle').value = offeringTitle;
            
            contactHelperModal.show();
        });
    });

    // Send contact message
    document.getElementById('sendContactBtn').addEventListener('click', function() {
        const offeringId = document.getElementById('offeringId').value;
        const message = document.getElementById('contactMessage').value.trim();
        
        if (!message) {
            LocalLendables.showToast('Message Required', 'Please enter a message.', 'error');
            return;
        }

        // Send contact request
        fetch('/api/hour-offerings/contact', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                offeringId: offeringId,
                message: message
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                LocalLendables.showToast('Message Sent', 'Your message has been sent!', 'success');
                contactHelperModal.hide();
                document.getElementById('contactMessage').value = '';
            } else {
                LocalLendables.showToast('Error', 'Error sending message: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            LocalLendables.showToast('Error', 'Error sending message. Please try again.', 'error');
        });
    });

    function initializeCalendar() {
        loadCalendarData();
    }

    function loadCalendarData() {
        // Calculate date range for current month
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const startDate = new Date(year, month, 1);
        const endDate = new Date(year, month + 1, 0);
        
        const startDateStr = startDate.toISOString().split('T')[0];
        const endDateStr = endDate.toISOString().split('T')[0];
        
        // Fetch expanded hour offerings from API
        fetch(`/api/hour-offerings/calendar/${startDateStr}/${endDateStr}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.offerings) {
                    console.log('Loaded calendar hour offerings:', data.offerings);
                    console.log('Number of offerings:', data.offerings.length);
                    
                    // Use the expanded offerings from API instead of template data
                    hourOfferings = data.offerings;
                    processOfferingsForCalendar();
                    renderCalendar();
                } else {
                    console.error('Failed to load calendar data:', data);
                    // Fallback to template data
                    processOfferingsForCalendar();
                    renderCalendar();
                }
            })
            .catch(error => {
                console.error('Error loading calendar data:', error);
                // Fallback to template data
                processOfferingsForCalendar();
                renderCalendar();
            });
    }

    function processOfferingsForCalendar() {
        calendarOfferings = {};
        
        hourOfferings.forEach(offering => {
            // Handle different date formats and field names
            let dateValue = offering.offerDate || offering.offer_date || offering.date;
            let dateKey;
            
            console.log('Processing offering:', offering);
            console.log('Date value found:', dateValue);
            
            if (typeof dateValue === 'string') {
                if (dateValue.includes('T')) {
                    // ISO format: 2025-06-30T16:11:00.000Z
                    dateKey = dateValue.split('T')[0];
                } else if (dateValue.includes(' ')) {
                    // SQL format: 2025-06-30 16:11:00
                    dateKey = dateValue.split(' ')[0];
                } else {
                    // Already just date: 2025-06-30
                    dateKey = dateValue;
                }
            } else if (dateValue) {
                // Date object
                const date = new Date(dateValue);
                dateKey = date.getFullYear() + '-' + 
                         String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                         String(date.getDate()).padStart(2, '0');
            } else {
                console.warn('No date found for offering:', offering);
                return; // Skip this offering if no date
            }
            
            console.log('Mapped to date key:', dateKey);
            
            if (!calendarOfferings[dateKey]) {
                calendarOfferings[dateKey] = [];
            }
            calendarOfferings[dateKey].push(offering);
        });
    }

    function renderCalendar() {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        
        // Update month/year display
        const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
                           'July', 'August', 'September', 'October', 'November', 'December'];
        document.getElementById('currentMonthYear').textContent = monthNames[month] + ' ' + year;
        
        // Get first day of month and number of days
        const firstDay = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        
        // Clear calendar body
        const calendarBody = document.getElementById('calendarBody');
        calendarBody.innerHTML = '';
        
        let date = 1;
        
        // Create calendar rows
        for (let week = 0; week < 6; week++) {
            const row = document.createElement('tr');
            
            for (let day = 0; day < 7; day++) {
                const cell = document.createElement('td');
                
                if (week === 0 && day < firstDay) {
                    // Empty cell before month starts
                    cell.innerHTML = '';
                } else if (date > daysInMonth) {
                    // Empty cell after month ends
                    cell.innerHTML = '';
                } else {
                    const cellDate = new Date(year, month, date);
                    const dateString = cellDate.getFullYear() + '-' + 
                                     String(cellDate.getMonth() + 1).padStart(2, '0') + '-' + 
                                     String(cellDate.getDate()).padStart(2, '0');
                    
                    const hasOfferings = calendarOfferings[dateString];
                    
                    cell.innerHTML = '<div class="calendar-date">' + date + '</div>';
                    
                    if (hasOfferings) {
                        cell.classList.add('has-offerings');
                        const count = hasOfferings.length;
                        cell.innerHTML += '<div class="calendar-offering-count">' + count + '</div>';
                        
                        // Add click handler for day with offerings
                        cell.addEventListener('click', function() {
                            showDayOfferings(dateString, hasOfferings);
                        });
                    }
                    
                    date++;
                }
                
                row.appendChild(cell);
            }
            
            calendarBody.appendChild(row);
            
            // Stop if we've shown all days of the month
            if (date > daysInMonth) {
                break;
            }
        }
    }

    function showDayOfferings(dateString, offerings) {
        const modal = new bootstrap.Modal(document.getElementById('calendarDayModal'));
        const content = document.getElementById('calendarDayContent');
        
        const dateObj = new Date(dateString + ' 00:00:00');
        const formattedDate = dateObj.toLocaleDateString('en-US', { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric' 
        });
        
        document.getElementById('calendarDayModalLabel').textContent = 'Hour Offerings for ' + formattedDate;
        
        let html = '<div class="row">';
        
        offerings.forEach(offering => {
            html += '<div class="col-12 mb-3">';
            html += '<div class="card">';
            html += '<div class="card-body">';
            html += '<div class="d-flex align-items-center mb-2">';
            html += '<img src="/lendables/' + (offering.offerUserAvatar || 'f1.jpg') + '" ';
            html += 'alt="User Avatar" class="rounded-circle me-3" ';
            html += 'style="width: 40px; height: 40px; object-fit: cover;">';
            html += '<div>';
            html += '<h6 class="mb-0">' + (offering.offerUserShowName || offering.offerUserFirstName || 'Helper') + '</h6>';
            html += '<small class="text-muted">Available Helper</small>';
            html += '</div>';
            html += '</div>';
            html += '<h6 class="fw-bold text-primary">' + offering.title + '</h6>';
            html += '<p class="mb-2">' + (offering.description || 'Available to help') + '</p>';
            html += '<div class="mb-2">';
            html += '<small class="text-muted">';
            html += '<i class="fas fa-clock"></i> ';
            html += formatLocalTime(offering.startTime);
            html += ' - ';
            html += formatLocalTime(offering.endTime);
            html += '</small>';
            html += '</div>';
            
            if (offering.isRecurring) {
                html += '<div class="mb-2">';
                html += '<span class="badge bg-info">';
                html += '<i class="fas fa-sync-alt"></i> Recurring ' + (offering.recurringType || 'weekly');
                if (offering.recurringCount) {
                    html += ' (' + offering.recurringCount + ' times)';
                }
                html += '</span>';
                html += '</div>';
            }
            
            if (isAuthenticated) {
                html += '<button type="button" class="btn btn-primary btn-sm contact-helper-btn" ';
                html += 'data-offering-id="' + offering.id + '" ';
                html += 'data-helper-name="' + (offering.offerUserShowName || offering.offerUserFirstName) + '" ';
                html += 'data-offering-title="' + offering.title + '">';
                html += '<i class="fas fa-envelope"></i> Contact Helper';
                html += '</button>';
            } else {
                html += '<a href="/login" class="btn btn-outline-primary btn-sm">';
                html += 'Login to Contact';
                html += '</a>';
            }
            
            html += '</div>';
            html += '</div>';
            html += '</div>';
        });
        
        html += '</div>';
        content.innerHTML = html;
        
        // Re-attach event listeners for new contact buttons
        content.querySelectorAll('.contact-helper-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                modal.hide();
                
                const offeringId = this.dataset.offeringId;
                const helperName = this.dataset.helperName;
                const offeringTitle = this.dataset.offeringTitle;
                
                document.getElementById('offeringId').value = offeringId;
                document.getElementById('helperName').value = helperName;
                document.getElementById('offeringTitle').value = offeringTitle;
                
                contactHelperModal.show();
            });
        });
        
        modal.show();
    }

    // My Hours functionality (make globally accessible)
    window.loadMyHours = function loadMyHours() {
        // Get current user ID from session data
        const currentUserId = parseInt(userAuthElement?.dataset.userId || '42'); // Demo fallback
        
        // Fetch fresh data from API instead of using stale cached data
        return fetch(`/api/hour-offerings/user/${currentUserId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.offerings) {
                    console.log('Loaded fresh user offerings:', data.offerings);
                    displayMyOfferings(data.offerings);
                    return data.offerings;
                } else {
                    console.error('No offerings data in response:', data);
                    displayMyOfferings([]);
                    return [];
                }
            })
            .catch(error => {
                console.error('Error loading user hour offerings:', error);
                // Fallback to cached data if API fails
                const userOfferings = hourOfferings ? hourOfferings.filter(offering => offering.userId === currentUserId) : [];
                displayMyOfferings(userOfferings);
                return userOfferings;
            });
        
        // TODO: Load scheduled hours from others (would need API endpoint)
        displayMyScheduledHours([]);
    }
    
    // Make display functions globally accessible
    window.displayMyOfferings = function displayMyOfferings(offerings) {
        const container = document.getElementById('myOfferingsContainer');
        
        if (offerings.length === 0) {
            container.innerHTML = `
                <div class="card">
                    <div class="card-body text-center">
                        <p class="text-muted">You haven't offered any hours yet.</p>
                        <a href="/offer-hour" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Offer an Hour
                        </a>
                    </div>
                </div>
            `;
            return;
        }
        
        let html = '<div class="row">';
        offerings.forEach(offering => {
            html += `
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <h6 class="fw-bold text-primary">${offering.title}</h6>
                            <p class="card-text">${offering.description || 'No description'}</p>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-calendar"></i> 
                                    ${new Date(offering.offerDate).toLocaleDateString()}
                                </small>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-clock"></i> 
                                    ${formatLocalTime(offering.offerDate)} - 
                                    ${formatLocalTime(offering.endTime)}
                                </small>
                            </div>
                            <div class="mt-3 d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge ${offering.isBooked ? 'bg-success' : 'bg-primary'}">
                                        ${offering.isBooked ? 'Scheduled' : 'Available'}
                                    </span>
                                    ${offering.isRecurring ? `<span class="badge bg-info ms-1"><i class="fas fa-sync-alt"></i> Recurring</span>` : ''}
                                </div>
                                <div class="btn-group btn-group-sm" role="group">
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="editHourOffering(${offering.id})" title="Edit Offering">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteHourOffering(${offering.id})" title="Delete Offering">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
        container.innerHTML = html;
    }
    
    function displayMyScheduledHours(scheduledHours) {
        const container = document.getElementById('myScheduledContainer');
        
        container.innerHTML = `
            <div class="card">
                <div class="card-body text-center">
                    <p class="text-muted">Feature coming soon: View hours you've scheduled from other helpers.</p>
                </div>
            </div>
        `;
    }
    
    function showLoginMessage() {
        const container = document.getElementById('myOfferingsContainer');
        container.innerHTML = `
            <div class="card">
                <div class="card-body text-center">
                    <h5>Login Required</h5>
                    <p class="text-muted">Please log in to view your hour offerings and scheduled hours.</p>
                    <a href="/login" class="btn btn-primary">
                        <i class="fas fa-sign-in-alt"></i> Login
                    </a>
                </div>
            </div>
        `;
        
        const scheduledContainer = document.getElementById('myScheduledContainer');
        scheduledContainer.innerHTML = '';
    }

    function editHourOffering(offeringId) {
        // Find the offering in the cached data or fetch it
        fetch(`/api/hour-offerings/${offeringId}`)
            .then(response => response.json())
            .then(data => {
                if (data.offering) {
                    showEditModal(data.offering);
                } else {
                    console.error('Offering not found:', data);
                    try {
                        LocalLendables.showToast('Error', 'Could not load offering data', 'error');
                    } catch (toastError) {
                        alert('Error: Could not load offering data');
                    }
                }
            })
            .catch(error => {
                console.error('Error fetching offering:', error);
                try {
                    LocalLendables.showToast('Error', 'Error loading offering data', 'error');
                } catch (toastError) {
                    alert('Error: Error loading offering data');
                }
            });
    }

    function deleteHourOffering(offeringId) {
        if (confirm('Are you sure you want to delete this hour offering? This action cannot be undone.')) {
            fetch(`/api/hour-offerings/${offeringId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    try {
                        LocalLendables.showToast('Success', 'Hour offering deleted successfully', 'success');
                    } catch (toastError) {
                        alert('Success: Hour offering deleted successfully');
                    }
                    // Reload the my hours view
                    loadMyHours();
                } else {
                    try {
                        LocalLendables.showToast('Error', 'Error deleting hour offering', 'error');
                    } catch (toastError) {
                        alert('Error: Error deleting hour offering');
                    }
                }
            })
            .catch(error => {
                console.error('Error deleting offering:', error);
                try {
                    LocalLendables.showToast('Error', 'Error deleting hour offering', 'error');
                } catch (toastError) {
                    alert('Error: Error deleting hour offering');
                }
            });
        }
    }

    function showEditModal(offering) {
        // Populate the edit modal with offering data
        document.getElementById('editOfferingId').value = offering.id;
        document.getElementById('editTitle').value = offering.title;
        document.getElementById('editDescription').value = offering.description || '';
        
        // Format dates for inputs - handle timezone properly for UTC stored data
        const offerDate = new Date(offering.offerDate);
        const endTime = new Date(offering.endTime);
        
        // Convert UTC stored time back to local time for display
        // The data is stored as UTC but represents local time, so we need to adjust
        const timezoneOffset = offerDate.getTimezoneOffset() * 60000;
        const localOfferDate = new Date(offerDate.getTime() + timezoneOffset);
        const localEndTime = new Date(endTime.getTime() + timezoneOffset);
        
        // Use local date for date input
        const year = localOfferDate.getFullYear();
        const month = String(localOfferDate.getMonth() + 1).padStart(2, '0');
        const day = String(localOfferDate.getDate()).padStart(2, '0');
        document.getElementById('editDate').value = `${year}-${month}-${day}`;
        
        // Format time for dropdown selection (HH:MM format) - use converted local time
        const startHours = String(localOfferDate.getHours()).padStart(2, '0');
        const startMinutes = String(localOfferDate.getMinutes()).padStart(2, '0');
        const endHours = String(localEndTime.getHours()).padStart(2, '0');
        const endMinutes = String(localEndTime.getMinutes()).padStart(2, '0');
        
        const startTimeFormatted = `${startHours}:${startMinutes}`;
        const endTimeFormatted = `${endHours}:${endMinutes}`;
        
        console.log('Setting start time:', startTimeFormatted, 'from UTC date:', offerDate.toString(), 'converted local:', localOfferDate.toString());
        console.log('Setting end time:', endTimeFormatted, 'from UTC date:', endTime.toString(), 'converted local:', localEndTime.toString());
        
        // Set the dropdown values
        const startTimeElement = document.getElementById('editStartTime');
        const endTimeElement = document.getElementById('editEndTime');
        
        startTimeElement.value = startTimeFormatted;
        endTimeElement.value = endTimeFormatted;
        
        console.log('Start time element value set to:', startTimeElement.value);
        console.log('End time element value set to:', endTimeElement.value);
        
        // If the values don't match any options, log available options
        if (startTimeElement.value !== startTimeFormatted) {
            console.log('Start time value not found in options. Available options:', Array.from(startTimeElement.options).map(o => o.value));
        }
        if (endTimeElement.value !== endTimeFormatted) {
            console.log('End time value not found in options. Available options:', Array.from(endTimeElement.options).map(o => o.value));
        }
        
        // Handle recurring options
        document.getElementById('editIsRecurring').checked = offering.isRecurring || false;
        if (offering.isRecurring && offering.recurringCount) {
            document.getElementById('editRecurringCount').value = offering.recurringCount;
            document.getElementById('editRecurringOptions').style.display = 'block';
        } else {
            document.getElementById('editRecurringOptions').style.display = 'none';
        }
        
        // Set up recurring checkbox toggle for edit modal
        const editRecurringCheckbox = document.getElementById('editIsRecurring');
        const editRecurringOptions = document.getElementById('editRecurringOptions');
        
        editRecurringCheckbox.addEventListener('change', function() {
            if (this.checked) {
                editRecurringOptions.style.display = 'block';
            } else {
                editRecurringOptions.style.display = 'none';
                document.getElementById('editRecurringCount').value = '';
            }
        });
        
        // Show the modal
        const editModal = new bootstrap.Modal(document.getElementById('editOfferingModal'));
        editModal.show();
    }

    // Make functions globally accessible for onclick handlers
    window.loadMyHours = loadMyHours;
    window.displayMyOfferings = displayMyOfferings;
    window.displayMyScheduledHours = displayMyScheduledHours;
    window.showLoginMessage = showLoginMessage;
    window.editHourOffering = editHourOffering;
    window.deleteHourOffering = deleteHourOffering;

    // Calendar navigation
    document.getElementById('prevMonthBtn').addEventListener('click', function() {
        currentDate.setMonth(currentDate.getMonth() - 1);
        loadCalendarData();
    });

    document.getElementById('nextMonthBtn').addEventListener('click', function() {
        currentDate.setMonth(currentDate.getMonth() + 1);
        loadCalendarData();
    });

    // Save changes functionality (moved inside DOMContentLoaded for scope access)
    document.addEventListener('click', function(e) {
        if (e.target && e.target.id === 'saveChangesBtn') {
            e.preventDefault();
            
            const offeringId = document.getElementById('editOfferingId').value;
            const title = document.getElementById('editTitle').value;
            const description = document.getElementById('editDescription').value;
            const date = document.getElementById('editDate').value;
            const startTime = document.getElementById('editStartTime').value;
            const endTime = document.getElementById('editEndTime').value;
            const isRecurring = document.getElementById('editIsRecurring').checked;
            const recurringCount = isRecurring ? document.getElementById('editRecurringCount').value : null;
            
            // Basic validation
            if (!title || !date || !startTime || !endTime) {
                try {
                    LocalLendables.showToast('Error', 'Please fill in all required fields', 'error');
                } catch (toastError) {
                    alert('Error: Please fill in all required fields');
                }
                return;
            }
            
            if (isRecurring && !recurringCount) {
                try {
                    LocalLendables.showToast('Error', 'Please select recurring count for recurring offerings', 'error');
                } catch (toastError) {
                    alert('Error: Please select recurring count for recurring offerings');
                }
                return;
            }
            
            const data = {
                title: title,
                description: description || '',
                date: date,
                startTime: startTime,
                endTime: endTime,
                isRecurring: isRecurring,
                recurringCount: recurringCount ? parseInt(recurringCount) : null
            };
            
            console.log('Updating offering with data:', data);
            
            fetch(`/api/hour-offerings/${offeringId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(result => {
                console.log('Update result:', result);
                if (result.offering || result.success) {
                    // Show success toast safely
                    try {
                        LocalLendables.showToast('Success', 'Hour offering updated successfully', 'success');
                    } catch (toastError) {
                        console.error('Toast error:', toastError);
                        alert('Success: Hour offering updated successfully');
                    }
                    
                    // Hide modal safely
                    try {
                        const modal = bootstrap.Modal.getInstance(document.getElementById('editOfferingModal'));
                        if (modal) {
                            modal.hide();
                        }
                    } catch (modalError) {
                        console.error('Modal error:', modalError);
                    }
                    
                    // Reload hours with proper error handling (now has access to loadMyHours)
                    setTimeout(() => {
                        console.log('About to reload hours...');
                        loadMyHours()
                            .then(() => {
                                console.log('Hours reloaded successfully');
                            })
                            .catch(error => {
                                console.error('Error reloading hours after update:', error);
                                // Don't show error to user since update was successful
                            });
                    }, 100);
                } else {
                    console.log('Update failed with result:', result);
                    try {
                        LocalLendables.showToast('Error', result.message || 'Error updating hour offering', 'error');
                    } catch (toastError) {
                        console.error('Toast error:', toastError);
                        alert('Error: ' + (result.message || 'Error updating hour offering'));
                    }
                }
            })
            .catch(error => {
                console.error('Error updating offering:', error);
                try {
                    LocalLendables.showToast('Error', 'Network error updating hour offering. Please try again.', 'error');
                } catch (toastError) {
                    console.error('Toast error:', toastError);
                    alert('Error: Network error updating hour offering. Please try again.');
                }
            });
        }
    });
});

// Hour offering editing and deletion functions
function editHourOffering(offeringId) {
    // Find the offering data
    fetch(`/api/hour-offerings/${offeringId}`)
        .then(response => response.json())
        .then(data => {
            if (data.offering) {
                showEditModal(data.offering);
            } else {
                LocalLendables.showToast('Error', 'Error loading offering details', 'error');
            }
        })
        .catch(error => {
            console.error('Error fetching offering:', error);
            LocalLendables.showToast('Error', 'Error loading offering details', 'error');
        });
}

function deleteHourOffering(offeringId) {
    if (confirm('Are you sure you want to delete this hour offering? This action cannot be undone.')) {
        fetch(`/api/hour-offerings/${offeringId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                LocalLendables.showToast('Success', 'Hour offering deleted successfully', 'success');
                // Reload the my hours view
                loadMyHours();
            } else {
                LocalLendables.showToast('Error', 'Error deleting hour offering', 'error');
            }
        })
        .catch(error => {
            console.error('Error deleting offering:', error);
            LocalLendables.showToast('Error', 'Error deleting hour offering', 'error');
        });
    }
}

function showEditModal(offering) {
    // Populate the edit modal with offering data
    document.getElementById('editOfferingId').value = offering.id;
    document.getElementById('editTitle').value = offering.title;
    document.getElementById('editDescription').value = offering.description || '';
    
    // Format dates for inputs
    const offerDate = new Date(offering.offerDate);
    const endTime = new Date(offering.endTime);
    
    document.getElementById('editDate').value = offerDate.toISOString().split('T')[0];
    
    // Format time for dropdown selection (HH:MM format)
    const startTimeFormatted = offerDate.toTimeString().substring(0, 5);
    const endTimeFormatted = endTime.toTimeString().substring(0, 5);
    
    document.getElementById('editStartTime').value = startTimeFormatted;
    document.getElementById('editEndTime').value = endTimeFormatted;
    
    // Handle recurring options
    document.getElementById('editIsRecurring').checked = offering.isRecurring || false;
    if (offering.isRecurring && offering.recurringCount) {
        document.getElementById('editRecurringCount').value = offering.recurringCount;
        document.getElementById('editRecurringOptions').style.display = 'block';
    } else {
        document.getElementById('editRecurringOptions').style.display = 'none';
    }
    
    // Set up recurring checkbox toggle for edit modal
    const editRecurringCheckbox = document.getElementById('editIsRecurring');
    const editRecurringOptions = document.getElementById('editRecurringOptions');
    
    editRecurringCheckbox.addEventListener('change', function() {
        if (this.checked) {
            editRecurringOptions.style.display = 'block';
        } else {
            editRecurringOptions.style.display = 'none';
            document.getElementById('editRecurringCount').value = '';
        }
    });
    
    // Show the modal
    const editModal = new bootstrap.Modal(document.getElementById('editOfferingModal'));
    editModal.show();
}



// Helper function to format time for input fields
function formatTimeForInput(dateTimeString) {
    if (!dateTimeString) return '';
    const date = new Date(dateTimeString);
    return date.toTimeString().substring(0, 5);
}
</script>
{% endblock %}