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

{% block title %}My Spreadsheet - {{ user.showName ?? user.firstName }}{% endblock %}

{% block content %}
<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <!-- Header -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h1 class="mb-2">
                        <i class="fas fa-table me-2 text-primary"></i>
                        My Spreadsheet
                    </h1>
                    <p class="text-muted mb-0">Unified view of all your items, borrowing, wish list, and offered hours</p>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-primary btn-sm" onclick="exportSpreadsheet()">
                        <i class="fas fa-download me-1"></i>Export
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" onclick="refreshData()">
                        <i class="fas fa-sync-alt me-1"></i>Refresh
                    </button>
                </div>
            </div>

            <!-- Summary Stats -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card bg-success text-white">
                        <div class="card-body text-center">
                            <h4 class="mb-1" id="myItemsCount">{{ myItems|length }}</h4>
                            <small>My Items</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-info text-white">
                        <div class="card-body text-center">
                            <h4 class="mb-1" id="borrowedCount">{{ borrowedItems|length }}</h4>
                            <small>Items Borrowed</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-warning text-white">
                        <div class="card-body text-center">
                            <h4 class="mb-1" id="wishListCount">{{ wishListItems|length }}</h4>
                            <small>Wish List</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-secondary text-white">
                        <div class="card-body text-center">
                            <h4 class="mb-1" id="offeredHoursCount">{{ offeredHours|length }}</h4>
                            <small>Offered Hours</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filter Controls -->
            <div class="card mb-4">
                <div class="card-body">
                    <div class="row align-items-end">
                        <div class="col-md-3">
                            <label class="form-label small fw-bold">Type Filter</label>
                            <select class="form-select form-select-sm" id="categoryFilter">
                                <option value="">All Types</option>
                                <option value="my-items">My Items</option>
                                <option value="borrowed">Items Borrowed</option>
                                <option value="wish-list">Wish List</option>
                                <option value="offered-hours">Offered Hours</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small fw-bold">Status Filter</label>
                            <select class="form-select form-select-sm" id="statusFilter">
                                <option value="">All Statuses</option>
                                <option value="lendable">Lendable</option>
                                <option value="out-on-loan">Out on Loan</option>
                                <option value="pending">Pending</option>
                                <option value="active">Active</option>
                                <option value="overdue">Overdue</option>
                                <option value="returned">Returned</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small fw-bold">Date Range</label>
                            <select class="form-select form-select-sm" id="dateFilter">
                                <option value="">All Dates</option>
                                <option value="overdue">Overdue</option>
                                <option value="due-soon">Due Soon (7 days)</option>
                                <option value="this-month">This Month</option>
                                <option value="next-month">Next Month</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-outline-secondary btn-sm w-100" onclick="clearFilters()">
                                <i class="fas fa-times me-1"></i>Clear Filters
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Spreadsheet Table -->
            <div class="card">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0" id="spreadsheetTable">
                            <thead class="table-dark sticky-top">
                                <tr>
                                    <th width="20%">
                                        <i class="fas fa-sort me-1"></i>Item Name
                                    </th>
                                    <th width="12%">Category</th>
                                    <th width="10%">Type</th>
                                    <th width="10%">Status</th>
                                    <th width="12%">Due Date</th>
                                    <th width="10%">Other Party</th>
                                    <th width="8%">Duration</th>
                                    <th width="18%">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="spreadsheetBody">
                                <!-- MY ITEMS SECTION HEADER -->
                                <tr class="table-primary">
                                    <td colspan="8" class="fw-bold text-center py-3">
                                        <i class="fas fa-box me-2"></i>MY ITEMS ({{ myItems|length }}) - Items I Own & Lend
                                    </td>
                                </tr>
                                <!-- My Items -->
                                {% for item in myItems %}
                                <tr data-category="my-items" data-status="{{ item.status|lower }}" data-item-id="{{ item.id }}">
                                    <td>
                                        <a href="/item/{{ item.id }}" class="text-decoration-none fw-bold" title="{{ item.name }}">
                                            {{ item.name|length > 20 ? item.name|slice(0, 20) ~ '...' : item.name }}
                                        </a>
                                    </td>
                                    <td><span class="badge bg-light text-dark">{{ (item.categoryName ?? 'General')|length > 15 ? (item.categoryName ?? 'General')|slice(0, 15) ~ '...' : (item.categoryName ?? 'General') }}</span></td>
                                    <td><span class="badge bg-success">My Item</span></td>
                                    <td>
                                        {% if item.isOnLoan %}
                                            {% if item.isOverdue %}
                                                <span class="badge bg-danger">Overdue</span>
                                            {% else %}
                                                <span class="badge bg-warning text-dark">Out on Loan</span>
                                            {% endif %}
                                        {% else %}
                                            <span class="badge bg-success badge-nowrap">Lendable</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.expectedReturnDate %}
                                            <a href="/item/{{ item.id }}?calendar=open" class="text-decoration-none">
                                                {{ item.expectedReturnDate|date('M j, Y') }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.borrowerName %}
                                            <a href="/item/{{ item.id }}?chat=open" class="text-decoration-none text-primary fw-bold" title="View Item Chat with {{ item.borrowerName }}">
                                                {{ item.borrowerName }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.borrowedDays %}
                                            <span class="mini">{{ item.borrowedDays }} days</span>
                                        {% else %}
                                            <span class="text-muted mini"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="/edit-item/{{ item.id }}" class="btn btn-outline-secondary btn-sm" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            {% if item.isOnLoan %}
                                                <button class="btn btn-outline-warning btn-sm" onclick="contactBorrower({{ item.id }})" title="Contact Borrower">
                                                    <i class="fas fa-comments"></i>
                                                </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}

                                <!-- CURRENT BORROWED ITEMS SECTION -->
                                {% set currentBorrowedItems = [] %}
                                {% for item in borrowedItems %}
                                    {% if item.isCurrent %}
                                        {% set currentBorrowedItems = currentBorrowedItems|merge([item]) %}
                                    {% endif %}
                                {% endfor %}
                                {% if currentBorrowedItems|length > 0 %}
                                <tr class="table-info">
                                    <td colspan="8" class="fw-bold text-center py-3">
                                        <i class="fas fa-hand-holding me-2"></i>ITEMS I'M BORROWING ({{ currentBorrowedItems|length }}) - Items I'm Currently Using
                                    </td>
                                </tr>
                                {% endif %}
                                {% for item in currentBorrowedItems %}
                                <tr data-category="borrowed" data-status="{{ item.status|lower }}" data-item-id="{{ item.id }}">
                                    <td>
                                        <a href="/item/{{ item.id }}" class="text-decoration-none fw-bold" title="{{ item.name }}">
                                            {{ item.name|length > 20 ? item.name|slice(0, 20) ~ '...' : item.name }}
                                        </a>
                                    </td>
                                    <td><span class="badge bg-light text-dark">{{ (item.categoryName ?? 'General')|length > 15 ? (item.categoryName ?? 'General')|slice(0, 15) ~ '...' : (item.categoryName ?? 'General') }}</span></td>
                                    <td><span class="badge bg-info">Borrowed</span></td>
                                    <td>
                                        {% if item.displayStatus == 'Overdue' %}
                                            <span class="badge bg-danger text-white">Overdue Return</span>
                                        {% elseif item.displayStatus == 'Reserved' %}
                                            <span class="badge bg-warning text-dark">Reserved</span>
                                        {% elseif item.displayStatus == 'Borrowed' %}
                                            <span class="badge bg-success text-white">Currently Borrowed</span>
                                        {% elseif item.status == 'pending' %}
                                            <span class="badge bg-warning text-dark">Approval Pending</span>
                                        {% else %}
                                            <span class="badge bg-primary text-white">{{ item.displayStatus }}</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.expectedReturnDate %}
                                            <a href="/item/{{ item.id }}?calendar=open" class="text-decoration-none">
                                                {{ item.expectedReturnDate|date('M j, Y') }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.ownerName %}
                                            <a href="/item/{{ item.id }}?chat=open" class="text-decoration-none text-primary fw-bold" title="View Item Chat with {{ item.ownerName }}">
                                                {{ item.ownerName }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted">Unknown</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.borrowedDays %}
                                            <span class="mini">{{ item.borrowedDays }} days</span>
                                        {% else %}
                                            <span class="text-muted mini"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            {% if item.displayStatus == 'Borrowed' or item.displayStatus == 'Overdue' %}
                                                <a href="/return-item/{{ item.id }}" class="btn btn-outline-warning btn-sm" title="Return Item">
                                                    <i class="fas fa-undo"></i>
                                                </a>
                                            {% endif %}
                                            <button class="btn btn-outline-secondary btn-sm" onclick="contactOwner({{ item.id }})" title="Contact Owner">
                                                <i class="fas fa-comments"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}

                                <!-- ARCHIVE SECTION - Declined/Expired Items -->
                                {% set archivedBorrowedItems = [] %}
                                {% for item in borrowedItems %}
                                    {% if not item.isCurrent %}
                                        {% set archivedBorrowedItems = archivedBorrowedItems|merge([item]) %}
                                    {% endif %}
                                {% endfor %}
                                {% if archivedBorrowedItems|length > 0 %}
                                <tr class="table-secondary">
                                    <td colspan="8" class="fw-bold text-center py-3">
                                        <i class="fas fa-archive me-2"></i>ARCHIVE ({{ archivedBorrowedItems|length }}) - Declined or Expired Requests
                                    </td>
                                </tr>
                                {% endif %}
                                {% for item in archivedBorrowedItems %}
                                <tr data-category="borrowed" data-status="{{ item.status|lower }}" data-item-id="{{ item.id }}">
                                    <td>
                                        <a href="/item/{{ item.id }}" class="text-decoration-none fw-bold" title="{{ item.name }}">
                                            {{ item.name|length > 20 ? item.name|slice(0, 20) ~ '...' : item.name }}
                                        </a>
                                    </td>
                                    <td><span class="badge bg-light text-dark">{{ (item.categoryName ?? 'General')|length > 15 ? (item.categoryName ?? 'General')|slice(0, 15) ~ '...' : (item.categoryName ?? 'General') }}</span></td>
                                    <td><span class="badge bg-secondary">Archived</span></td>
                                    <td>
                                        {% if item.displayStatus == 'declined' %}
                                            <span class="badge bg-danger text-white">Declined</span>
                                        {% elseif item.displayStatus == 'Request Dismissed' %}
                                            <span class="badge bg-warning text-dark">Dismissed</span>
                                        {% elseif item.displayStatus == 'Request Expired' %}
                                            <span class="badge bg-secondary text-white">Expired</span>
                                        {% else %}
                                            <span class="badge bg-secondary text-white">{{ item.displayStatus }}</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.expectedReturnDate %}
                                            {{ item.expectedReturnDate|date('M j, Y') }}
                                        {% else %}
                                            <span class="text-muted"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.ownerName %}
                                            <a href="/item/{{ item.id }}?chat=open" class="text-decoration-none text-primary fw-bold" title="View Item Chat with {{ item.ownerName }}">
                                                {{ item.ownerName }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted">Unknown</span>
                                        {% endif %}
                                    </td>
                                    <td><span class="text-muted mini"></span></td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <button class="btn btn-outline-secondary btn-sm" onclick="contactOwner({{ item.id }})" title="Contact Owner">
                                                <i class="fas fa-comments"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}

                                <!-- WISH LIST SECTION HEADER -->
                                {% if wishListItems|length > 0 %}
                                <tr class="table-warning">
                                    <td colspan="8" class="fw-bold text-center py-3">
                                        <i class="fas fa-heart me-2"></i>MY WISH LIST ({{ wishListItems|length }}) - Items I'm Looking For
                                    </td>
                                </tr>
                                {% endif %}
                                <!-- Wish List Items -->
                                {% for item in wishListItems %}
                                <tr data-category="wish-list" data-status="wishlist" data-item-id="{{ item.id }}">
                                    <td>
                                        <a href="/item/{{ item.id }}" class="text-decoration-none fw-bold" title="{{ item.name }}">
                                            {{ item.name|length > 20 ? item.name|slice(0, 20) ~ '...' : item.name }}
                                        </a>
                                    </td>
                                    <td><span class="badge bg-light text-dark">{{ (item.categoryName ?? 'General')|length > 15 ? (item.categoryName ?? 'General')|slice(0, 15) ~ '...' : (item.categoryName ?? 'General') }}</span></td>
                                    <td><span class="badge bg-warning text-dark">Wish List</span></td>
                                    <td><span class="badge bg-secondary">Requesting</span></td>
                                    <td><span class="text-muted"></span></td>
                                    <td><span class="text-muted">Anyone</span></td>
                                    <td><span class="text-muted"></span></td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="/edit-item/{{ item.id }}" class="btn btn-outline-secondary btn-sm" title="Edit Request">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}

                                <!-- HOUR OFFERINGS SECTION HEADER -->
                                {% if offeredHours|length > 0 %}
                                <tr class="table-success">
                                    <td colspan="8" class="fw-bold text-center py-3">
                                        <i class="fas fa-clock me-2"></i>MY HOUR OFFERINGS ({{ offeredHours|length }}) - Time I'm Offering
                                    </td>
                                </tr>
                                {% endif %}
                                <!-- Offered Hours -->
                                {% for offering in offeredHours %}
                                <tr data-category="offered-hours" data-status="offered" data-item-id="{{ offering.id }}">
                                    <td>
                                        <span class="fw-bold" title="{{ offering.title }}">
                                            {{ offering.title|length > 20 ? offering.title|slice(0, 20) ~ '...' : offering.title }}
                                        </span>
                                    </td>
                                    <td><span class="badge bg-light text-dark">Hours</span></td>
                                    <td><span class="badge bg-secondary">Hour Offering</span></td>
                                    <td>
                                        {% if offering.isRecurring %}
                                            <span class="badge bg-info">Recurring</span>
                                        {% else %}
                                            <span class="badge bg-primary">One-time</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <a href="/browse-hours?date={{ offering.offerDate|date('Y-m-d') }}" class="text-decoration-none">
                                            {{ offering.offerDate|date('M j, Y') }}
                                        </a>
                                    </td>
                                    <td><span class="text-muted">Community</span></td>
                                    <td class="mini">
                                        {% if offering.startTime and offering.endTime %}
                                            {{ offering.startTime }} - {{ offering.endTime }}
                                        {% else %}
                                            <span class="text-muted"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="/browse-hours" class="btn btn-outline-primary btn-sm" title="View in Calendar">
                                                <i class="fas fa-calendar"></i>
                                            </a>
                                            <button class="btn btn-outline-secondary btn-sm" onclick="editHourOffering({{ offering.id }})" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-outline-danger btn-sm" onclick="deleteHourOffering({{ offering.id }})" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}

                                <!-- INACTIVE ITEMS SECTION HEADER -->
                                {% if inactiveItems and inactiveItems|length > 0 %}
                                <tr class="table-secondary">
                                    <td colspan="8" class="fw-bold text-center py-3">
                                        <i class="fas fa-archive me-2"></i>INACTIVE ITEMS ({{ inactiveItems|length }}) - Items I Own But Aren't Available for Lending
                                    </td>
                                </tr>
                                <!-- Inactive Items -->
                                {% for item in inactiveItems %}
                                <tr data-category="inactive" data-status="inactive" data-item-id="{{ item.id }}">
                                    <td>
                                        <a href="/item/{{ item.id }}" class="text-decoration-none fw-bold" title="{{ item.name }}">
                                            {{ item.name|length > 20 ? item.name|slice(0, 20) ~ '...' : item.name }}
                                        </a>
                                    </td>
                                    <td><span class="badge bg-light text-dark">{{ (item.categoryName ?? 'General')|length > 15 ? (item.categoryName ?? 'General')|slice(0, 15) ~ '...' : (item.categoryName ?? 'General') }}</span></td>
                                    <td><span class="badge bg-secondary">My Item</span></td>
                                    <td><span class="badge bg-light text-dark">Inactive</span></td>
                                    <td>
                                        {% if item.addedOn %}
                                            <a href="/item/{{ item.id }}" class="text-decoration-none">
                                                {{ item.addedOn|date('M j, Y') }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted"></span>
                                        {% endif %}
                                    </td>
                                    <td>You</td>
                                    <td>
                                        {% if item.pricePerDay or item.deposit %}
                                            {% if item.pricePerDay %}${{ item.pricePerDay }}/day{% endif %}
                                            {% if item.deposit %} + ${{ item.deposit }} deposit{% endif %}
                                        {% else %}
                                            <span class="text-muted">Free</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="/edit-item/{{ item.id }}" class="btn btn-outline-secondary btn-sm" title="Edit Item">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                                {% endif %}

                                <!-- ARCHIVE SECTION HEADER (for declined items) -->
                                {% set declinedItems = [] %}
                                {% for item in borrowedItems %}
                                    {% if not item.isCurrent and item.displayStatus == 'declined' %}
                                        {% set declinedItems = declinedItems|merge([item]) %}
                                    {% endif %}
                                {% endfor %}
                                {% if declinedItems|length > 0 %}
                                <tr class="table-light">
                                    <td colspan="8" class="fw-bold text-center py-3">
                                        <i class="fas fa-times-circle me-2"></i>ARCHIVE ({{ declinedItems|length }}) - Declined Borrowing Requests
                                    </td>
                                </tr>
                                {% endif %}
                                {% for item in declinedItems %}
                                <tr data-category="declined" data-status="declined" data-item-id="{{ item.id }}">
                                    <td>
                                        <a href="/item/{{ item.id }}" class="text-decoration-none fw-bold" title="{{ item.name }}">
                                            {{ item.name|length > 20 ? item.name|slice(0, 20) ~ '...' : item.name }}
                                        </a>
                                    </td>
                                    <td><span class="badge bg-light text-dark">{{ (item.categoryName ?? 'General')|length > 15 ? (item.categoryName ?? 'General')|slice(0, 15) ~ '...' : (item.categoryName ?? 'General') }}</span></td>
                                    <td><span class="badge bg-secondary">Previously Requested</span></td>
                                    <td><span class="badge bg-danger text-white">declined</span></td>
                                    <td>
                                        {% if item.borrowedDate %}
                                            <a href="/item/{{ item.id }}" class="text-decoration-none">
                                                {{ item.borrowedDate|date('M j, Y') }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted"></span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if item.ownerName %}
                                            <span class="text-muted">{{ item.ownerName }}</span>
                                        {% else %}
                                            <span class="text-muted">Unknown</span>
                                        {% endif %}
                                    </td>
                                    <td><span class="text-muted mini"></span></td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="/item/{{ item.id }}" class="btn btn-outline-primary btn-sm" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <button class="btn btn-outline-secondary btn-sm" onclick="contactOwner({{ item.id }})" title="Contact Owner">
                                                <i class="fas fa-comments"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Empty State -->
            <div id="emptyState" class="text-center py-5" style="display: none;">
                <i class="fas fa-table text-muted" style="font-size: 4rem;"></i>
                <h4 class="text-muted mt-3">No data matches your filters</h4>
                <p class="text-muted">Try adjusting your filter criteria or clear all filters</p>
                <button class="btn btn-outline-primary" onclick="clearFilters()">Clear All Filters</button>
            </div>
        </div>
    </div>
</div>

<style>
/* Spreadsheet-specific styles */
#spreadsheetTable {
    font-size: 0.875rem;
}

#spreadsheetTable th {
    font-weight: 600;
    border-bottom: 2px solid #dee2e6;
    position: sticky;
    top: 0;
    z-index: 10;
    line-height: 1.0 !important;
    padding: 2pt !important;
    margin: 2pt !important;
}

#spreadsheetTable td {
    vertical-align: middle;
    border-bottom: 1px solid #f0f0f0;
    line-height: 1.0 !important;
    padding: 2pt !important;
    margin: 2pt !important;
}

.table-hover tbody tr:hover {
    background-color: #f8f9fa;
}

.badge {
    font-size: 0.6rem;
    font-weight: 500;
    padding: 0.2em 0.4em;
    line-height: 1;
    white-space: nowrap;
}

.btn-group-sm .btn {
    padding: 0.25rem 0.4rem;
    font-size: 0.75rem;
}

/* Mini class for smaller text */
.mini {
    font-size: 0.75rem;
    font-weight: 400;
}

/* Section subheadings with 6px spacing using border-top */
.table-primary {
    border-top: 6px solid transparent !important;
}

.table-warning {
    border-top: 6px solid transparent !important;
}

.table-success {
    border-top: 6px solid transparent !important;
}

.table-secondary {
    border-top: 6px solid transparent !important;
}

.table-primary td, .table-warning td, .table-success td, .table-secondary td {
    padding: 15px 12px !important; /* Extra padding for better appearance */
}

/* Clickable item names */
tbody tr td:first-child a {
    color: #0d6efd;
    font-weight: 600;
}

tbody tr td:first-child a:hover {
    color: #0a58ca;
    text-decoration: underline !important;
}

/* Date links */
tbody tr a[href*="calendar"] {
    color: #198754;
    font-weight: 500;
}

tbody tr a[href*="calendar"]:hover {
    color: #146c43;
    text-decoration: underline !important;
}

/* Summary cards */
.card {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.card.bg-success,
.card.bg-info,
.card.bg-warning,
.card.bg-secondary {
    border: none;
}

/* Filter controls */
.form-select-sm {
    font-size: 0.8rem;
}

.form-label.small {
    margin-bottom: 0.25rem;
    color: #6c757d;
}
</style>

<script>
// Filter functionality
function applyFilters() {
    const categoryFilter = document.getElementById('categoryFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;
    const dateFilter = document.getElementById('dateFilter').value;
    
    const rows = document.querySelectorAll('#spreadsheetBody tr');
    let visibleCount = 0;
    
    rows.forEach(row => {
        let show = true;
        
        // Category filter
        if (categoryFilter && row.dataset.category !== categoryFilter) {
            show = false;
        }
        
        // Status filter
        if (statusFilter && row.dataset.status !== statusFilter) {
            show = false;
        }
        
        // Date filter logic would go here (simplified for now)
        
        row.style.display = show ? '' : 'none';
        if (show) visibleCount++;
    });
    
    // Show/hide empty state
    const emptyState = document.getElementById('emptyState');
    const table = document.getElementById('spreadsheetTable').parentElement.parentElement;
    
    if (visibleCount === 0) {
        emptyState.style.display = 'block';
        table.style.display = 'none';
    } else {
        emptyState.style.display = 'none';
        table.style.display = 'block';
    }
}

function clearFilters() {
    document.getElementById('categoryFilter').value = '';
    document.getElementById('statusFilter').value = '';
    document.getElementById('dateFilter').value = '';
    applyFilters();
}

function refreshData() {
    window.location.reload();
}

function exportSpreadsheet() {
    try {
        // CSV export functionality
        let csv = 'Item Name,Category,Type,Status,Due Date,Other Party,Duration\n';
        
        const rows = document.querySelectorAll('#spreadsheetBody tr');
        console.log('Found', rows.length, 'rows for export');
        
        rows.forEach(row => {
            if (row.style.display !== 'none') {
                const cells = row.querySelectorAll('td');
                console.log('Processing row with', cells.length, 'cells');
                
                const rowData = [];
                for (let i = 0; i < 7; i++) {
                    if (cells[i]) {
                        let cellText = cells[i].textContent?.trim() || '';
                        // Fix character encoding issues: replace em-dashes and special characters with empty string
                        cellText = cellText.replace(/[–−]/g, '').replace(/\u2014/g, '').replace(/â€¢/g, '');
                        // If cell is now empty or just whitespace, use empty string
                        if (!cellText || cellText.trim() === '') {
                            cellText = '';
                        }
                        rowData.push(cellText);
                    } else {
                        rowData.push('');
                    }
                }
                
                csv += rowData.map(cell => `"${cell.replace(/"/g, '""')}"`).join(',') + '\n';
            }
        });
        
        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'my-spreadsheet.csv';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        
        console.log('Export completed successfully');
    } catch (error) {
        console.error('Export error:', error);
        alert('Export failed: ' + error.message);
    }
}

// Contact functions
function contactBorrower(itemId) {
    window.location.href = `/item/${itemId}?chat=open`;
}

function contactOwner(itemId) {
    window.location.href = `/item/${itemId}?chat=open`;
}

// Hour offering functions
function editHourOffering(offeringId) {
    // This would open an edit modal - simplified for now
    alert('Edit functionality for hour offering ' + offeringId + ' - to be implemented');
}

function deleteHourOffering(offeringId) {
    if (confirm('Are you sure you want to delete this hour offering?')) {
        // Delete API call would go here
        alert('Delete functionality for hour offering ' + offeringId + ' - to be implemented');
    }
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Set up filter event listeners
    document.getElementById('categoryFilter').addEventListener('change', applyFilters);
    document.getElementById('statusFilter').addEventListener('change', applyFilters);
    document.getElementById('dateFilter').addEventListener('change', applyFilters);
    
    // Initial filter application
    applyFilters();
});
</script>
{% endblock %}