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

{% block title %}{{ item.title }} - Local Lendables{% endblock %}

{% block head %}
<style>
.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 5px;
    max-width: 400px;
    margin: 0 auto;
}

.calendar-day {
    aspect-ratio: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    font-size: 0.9rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.calendar-day:hover {
    transform: scale(1.05);
}

.calendar-day-header {
    font-weight: bold;
    background-color: #f8f9fa;
    border: none;
    cursor: default;
}

.calendar-day-header:hover {
    transform: none;
}

.day-available {
    background-color: #d4edda;
    color: #155724;
    border-color: #c3e6cb;
}

.day-reserved {
    background-color: #fff3cd;
    color: #856404;
    border-color: #ffeaa7;
}

.day-on-loan {
    background-color: #f8d7da;
    color: #721c24;
    border-color: #f5c6cb;
}

.day-empty {
    background-color: transparent;
    border: none;
    cursor: default;
}

.day-empty:hover {
    transform: none;
}
</style>
{% endblock %}

{% block content %}

<!-- Main Content -->
                        <!-- Back to Dashboard -->
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-2" href="/dashboard">
                                <div class="rounded-circle bg-primary text-white me-3 d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                    <i class="fas fa-tachometer-alt"></i>
                                </div>
                                <span>Back to My Dashboard</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- My Lendables Actions -->
                        <li class="dropdown-header fw-bold">My Lendables Actions:</li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/browse">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-search"></i>
                                </div>
                                <span>Find an Item to Borrow or Lend</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/create-item">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-plus"></i>
                                </div>
                                <span>Create a Lendable Item</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/create-wish" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-heart"></i>
                                </div>
                                <span>Create a Wish List Item</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/return-item" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-undo"></i>
                                </div>
                                <span>Return a Borrowed Item</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/send-reminder" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-bell"></i>
                                </div>
                                <span>Send a Reminder</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/edit-profile" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-user-edit"></i>
                                </div>
                                <span>Edit My Profile</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/my-statistics" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-chart-bar"></i>
                                </div>
                                <span>See My Statistics</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/logout">
                                <div class="rounded-circle bg-success text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-sign-out-alt"></i>
                                </div>
                                <span>Log Out</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- My Lendables Inventory -->
                        <li class="dropdown-header fw-bold">My Lendables Inventory</li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/my-borrowed" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-info text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-arrow-down"></i>
                                </div>
                                <span>Items I have Borrowed</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/my-loaned" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-info text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-arrow-up"></i>
                                </div>
                                <span>My Loaned-Out Items</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/my-items">
                                <div class="rounded-circle bg-info text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-list"></i>
                                </div>
                                <span>My Lendable Items on Offer</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/my-drafts" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-info text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-edit"></i>
                                </div>
                                <span>My Lendable Item Drafts</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- All Listed Lendables -->
                        <li class="dropdown-header fw-bold">All Listed Lendables (Items & Wishes)</li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/categories" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-tags"></i>
                                </div>
                                <span>View Categories</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/browse">
                                <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-random"></i>
                                </div>
                                <span>All Items, Random Browse</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/browse?sort=alphabetic">
                                <div class="rounded-circle bg-warning text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-sort-alpha-down"></i>
                                </div>
                                <span>All Items, Listed Alphabetically</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- Our Local Lendables -->
                        <li class="dropdown-header fw-bold">Our Local Lendables</li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/about-community" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-users"></i>
                                </div>
                                <span>About Our Community</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/our-manager" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-user-tie"></i>
                                </div>
                                <span>Our Manager</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/how-supported" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-life-ring"></i>
                                </div>
                                <span>How Lendables is Supported</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/invite-member" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-user-plus"></i>
                                </div>
                                <span>How to Invite a new Member</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/handshake-agreement" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-secondary text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-handshake"></i>
                                </div>
                                <span>View Lendable Handshake Agreement</span>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <!-- General Local Lendables -->
                        <li class="dropdown-header fw-bold">General Local Lendables</li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/what-are-we" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-question"></i>
                                </div>
                                <span>What are we?</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/ethical-model" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-balance-scale"></i>
                                </div>
                                <span>Our Ethical Business Model</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/faq" style="text-decoration: line-through;">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-question-circle"></i>
                                </div>
                                <span>Frequently Asked Questions</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center py-1" href="/demo">
                                <div class="rounded-circle bg-dark text-white me-3 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                    <i class="fas fa-play"></i>
                                </div>
                                <span>Local Lendables Demo</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="col col-lg-3 d-flex align-items-center">
                <a href="/dashboard/{{ user.id }}" class="navbar-brand me-0 onlycavolini d-flex align-items-center">
                    <img src="/local_circle_logo.png" 
                         class="img-fluid me-2" 
                         height="76" 
                         width="76"
                         alt="Local Lendables Logo">
                    <span class="headertitle text-white" style="line-height: 100%;">Local Lendables<br>&nbsp;&nbsp;Demo</span>
                </a>
            </div>
            <div class="col col-lg-9 d-flex align-items-center justify-content-end">

                <div class="d-flex align-items-center">
                    <!-- User Profile Dropdown -->
                    <div class="dropdown me-3">
                        <button class="btn btn-link text-white p-0 d-flex align-items-center" type="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-user-circle text-white me-2" style="font-size: 1.5rem;"></i>
                            <span class="text-white small d-none d-lg-inline">Demo User</span>
                            <i class="fas fa-chevron-down text-white ms-1"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/profile/demo">
                                    <i class="fas fa-user me-2"></i>
                                    My Profile
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/edit-profile" style="text-decoration: line-through;">
                                    <i class="fas fa-user-edit me-2"></i>
                                    Edit Profile
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item d-flex align-items-center" href="/my-statistics" style="text-decoration: line-through;">
                                    <i class="fas fa-chart-bar me-2"></i>
                                    My Statistics
                                </a>
                            </li>
                        </ul>
                    </div>
                    <button class="btn btn-outline-danger btn-sm px-2" onclick="performLogout()" title="Logout">
                        <i class="fas fa-power-off me-1"></i>Logout
                    </button>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Main Content -->
<main class="container-fluid py-4" style="background-color: #f8f9fa;">
    <div class="container">
        <div class="row">
            <!-- Left Sidebar Icon -->
            <div class="col-auto d-flex align-items-start">
                <div class="bg-white rounded-circle d-flex align-items-center justify-content-center shadow-sm" 
                     style="width: 120px; height: 120px; border: 3px solid #e9ecef;">
                    <img src="/lendables/logo_item_listing.png" 
                         alt="Item Listing" 
                         class="img-fluid"
                         style="max-width: 80px; max-height: 80px;"
                         onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                    <div class="text-center" style="display: none;">
                        <i class="fas fa-cube text-success mb-2" style="font-size: 2rem;"></i>
                        <div class="small text-muted fw-bold">ITEM<br>LISTING</div>
                    </div>
                </div>
            </div>
            
            <!-- Main Content Area -->
            <div class="col">
                <div class="row">
                    <!-- Item Details Section -->
                    <div class="col-lg-6">
                        <div class="mb-3">
                            <button onclick="history.back()" class="btn btn-outline-secondary btn-sm px-4 mb-4">
                                Go Back
                            </button>
                        </div>
                        
                        <h1 class="display-6 fw-bold text-dark mb-4">{{ item.title }}</h1>
                        
                        {% if item.description %}
                        <p class="text-muted mb-4" style="line-height: 1.6;">{{ item.description }}</p>
                        {% endif %}
                        
                        <div class="mb-3">
                            <strong>In Category - </strong>
                            <span class="text-success fw-semibold">{{ item.category }}</span>
                        </div>
                        
                        <div class="mb-3">
                            <strong>Offered By - </strong>
                            <div class="d-inline-flex align-items-center">
                                <a href="/dashboard/{{ item.userId }}" class="text-decoration-none me-2">
                                    <img src="/ll_images/{{ item.ownerAvatar }}" 
                                         alt="{{ item.ownerFirstName }} {{ item.ownerLastName }}" 
                                         class="rounded-circle" 
                                         width="40" 
                                         height="40"
                                         style="object-fit: cover; border: 2px solid #ddd;">
                                </a>
                                <a href="/dashboard/{{ item.userId }}" class="text-decoration-none text-primary fw-semibold">
                                    {% if item.ownerShowName %}{{ item.ownerShowName }}{% else %}{{ item.ownerFirstName }}{% endif %} {{ item.ownerLastName }}
                                </a>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <strong>Added On - </strong>
                            <span class="text-muted">{{ item.createdAt|date('M j Y') }}</span>
                        </div>
                        
                        {% if item.dailyRate %}
                        <div class="mb-4">
                            <strong>Daily Rate - </strong>
                            <span class="text-success fw-bold">${{ item.dailyRate }}/day</span>
                        </div>
                        {% endif %}
                        
                        {% if item.condition %}
                        <div class="mb-4">
                            <strong>Condition - </strong>
                            <span class="badge bg-{{ item.condition == 'excellent' ? 'success' : (item.condition == 'good' ? 'primary' : 'warning') }}">
                                {{ item.condition|capitalize }}
                            </span>
                        </div>
                        {% endif %}
                        
                        <div class="mb-4">
                            <strong>Availability - </strong>
                            {% if loanStatus and loanStatus.isOnLoan %}
                                <span class="badge bg-warning">On Loan</span>
                                {% if loanStatus.borrowerAvatar and loanStatus.borrowerId %}
                                <div class="mt-2">
                                    <small class="text-muted">Currently borrowed by:</small>
                                    <div class="d-flex align-items-center mt-1">
                                        <a href="/dashboard/{{ loanStatus.borrowerId }}" class="text-decoration-none me-2">
                                            <img src="/ll_images/{{ loanStatus.borrowerAvatar }}" 
                                                 alt="{{ loanStatus.borrowerName }}" 
                                                 class="rounded-circle" 
                                                 width="32" 
                                                 height="32"
                                                 style="object-fit: cover; border: 1px solid #ddd;">
                                        </a>
                                        <a href="/dashboard/{{ loanStatus.borrowerId }}" class="text-decoration-none text-primary">
                                            {{ loanStatus.borrowerName }}
                                        </a>
                                        {% if loanStatus.loanStartDate %}
                                        <small class="text-muted ms-2">since {{ loanStatus.loanStartDate|date('M j') }}</small>
                                        {% endif %}
                                    </div>
                                </div>
                                {% endif %}
                            {% else %}
                                <span class="badge bg-{{ item.availability == 'available' ? 'success' : 'warning' }}">
                                    {{ item.availability|capitalize }}
                                </span>
                            {% endif %}
                        </div>
                        
                        <!-- Item Calendar -->
                        <div class="mt-4">
                            <h6 class="text-primary mb-3">
                                <i class="fas fa-calendar-alt me-2"></i>Item Calendar & Availability
                            </h6>
                            <div id="itemCalendar" class="border rounded p-3 mb-3" style="background-color: #f8f9fa;">
                                <div class="row text-center mb-2">
                                    <div class="col">
                                        <button class="btn btn-sm btn-outline-secondary" onclick="changeCalendarMonth(-1)">
                                            <i class="fas fa-chevron-left"></i>
                                        </button>
                                    </div>
                                    <div class="col">
                                        <h6 id="calendarMonth" class="mb-0"></h6>
                                    </div>
                                    <div class="col">
                                        <button class="btn btn-sm btn-outline-secondary" onclick="changeCalendarMonth(1)">
                                            <i class="fas fa-chevron-right"></i>
                                        </button>
                                    </div>
                                </div>
                                <div id="calendarGrid" class="calendar-grid">
                                    <!-- Calendar will be populated by JavaScript -->
                                </div>
                                <div class="mt-2 small">
                                    <span class="badge bg-success me-2">Available</span>
                                    <span class="badge bg-warning me-2">On Loan</span>
                                    <span class="badge bg-secondary">Past Date</span>
                                </div>
                            </div>
                            
                            <!-- Action Buttons -->
                            {% if loanStatus and loanStatus.isOnLoan %}
                            <div class="d-flex gap-2 flex-wrap">
                                <button class="btn btn-warning btn-lg px-4" disabled>
                                    <i class="fas fa-clock me-2"></i>On Loan to {{ loanStatus.borrowerName }}
                                    {% if loanStatus.loanStartDate %}
                                    <small class="d-block">Since {{ loanStatus.loanStartDate|date('M j') }}</small>
                                    {% endif %}
                                </button>
                                <button class="btn btn-outline-primary btn-lg px-4" onclick="chatWithOwner({{ item.userId }}, '{% if item.ownerShowName %}{{ item.ownerShowName }}{% else %}{{ item.ownerFirstName }}{% endif %}', {{ item.id }})">
                                    <i class="fas fa-comments me-2"></i>Chat with Owner
                                </button>
                            </div>
                            {% elseif item.availability == 'available' %}
                            <div class="d-flex gap-2 flex-wrap">
                                <button class="btn btn-success btn-lg px-4" onclick="requestLoan()">
                                    <i class="fas fa-handshake me-2"></i>Request to Borrow
                                </button>
                                <button class="btn btn-outline-primary btn-lg px-4" onclick="chatWithOwner({{ item.userId }}, '{% if item.ownerShowName %}{{ item.ownerShowName }}{% else %}{{ item.ownerFirstName }}{% endif %}', {{ item.id }})">
                                    <i class="fas fa-comments me-2"></i>Chat with Owner
                                </button>
                            </div>
                            {% else %}
                            <div class="d-flex gap-2 flex-wrap">
                                <button class="btn btn-info btn-lg px-4" onclick="toggleCalendar()">
                                    <i class="fas fa-calendar-alt me-2"></i>View Availability Calendar
                                </button>
                                <button class="btn btn-outline-primary btn-lg px-4" onclick="chatWithOwner({{ item.userId }}, '{% if item.ownerShowName %}{{ item.ownerShowName }}{% else %}{{ item.ownerFirstName }}{% endif %}', {{ item.id }})">
                                    <i class="fas fa-comments me-2"></i>Chat with Owner
                                </button>
                            </div>
                            {% endif %}
                        </div>
                        
                        <!-- Item Calendar Section -->
                        <div id="itemCalendar" class="mt-4" style="display: none;">
                            <div class="card">
                                <div class="card-header bg-light">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">
                                            <i class="fas fa-calendar-alt me-2"></i>
                                            <span id="calendarTitle">Availability Calendar</span>
                                        </h5>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="previousMonth()">
                                                <i class="fas fa-chevron-left"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="nextMonth()">
                                                <i class="fas fa-chevron-right"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-12">
                                            <div class="d-flex gap-3 justify-content-center flex-wrap">
                                                <span class="badge bg-success">Available</span>
                                                <span class="badge bg-warning text-dark">Reserved</span>
                                                <span class="badge bg-danger">On Loan</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="calendarGrid" class="calendar-grid">
                                        <!-- Calendar will be populated by JavaScript -->
                                    </div>
                                    <div id="loanDetails" class="mt-3">
                                        <!-- Loan details will be populated by JavaScript -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Image Section -->
                    <div class="col-lg-6">
                        <div class="text-center">
                            {% if item.primaryLogo or item.imageUrl %}
                                {% set mainImage = item.primaryLogo ?: item.imageUrl %}
                                <img src="/lendable_items/{{ mainImage }}" 
                                     class="img-fluid rounded shadow-sm mb-3" 
                                     style="max-width: 100%; max-height: 400px; object-fit: contain;"
                                     alt="{{ item.title }}"
                                     onerror="this.style.display='none'">
                                
                                <!-- Extra Images Carousel -->
                                {% if item.extraImages %}
                                    {% set extraImageList = item.extraImages|split(',') %}
                                    {% if extraImageList|length > 0 %}
                                    <div class="row g-2 mt-3">
                                        {% for extraImage in extraImageList %}
                                        <div class="col-4">
                                            <img src="/lendable_items/{{ extraImage|trim }}" 
                                                 class="img-fluid rounded border" 
                                                 style="height: 80px; width: 100%; object-fit: cover; cursor: pointer;"
                                                 alt="{{ item.title }} - Additional Image"
                                                 onclick="changeMainImage('{{ extraImage|trim }}')"
                                                 onerror="this.style.display='none'">
                                        </div>
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                {% endif %}
                            {% else %}
                                <div class="bg-light rounded d-flex align-items-center justify-content-center" 
                                     style="height: 300px;">
                                    <div class="text-center text-muted">
                                        <i class="fas fa-image mb-2" style="font-size: 3rem;"></i>
                                        <p>No image available</p>
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- JavaScript for interactions -->
<script>
function changeMainImage(imageName) {
    const mainImg = document.querySelector('img[src*="/lendable_items/"]');
    if (mainImg) {
        mainImg.src = '/lendable_items/' + imageName;
    }
}

function requestLoan() {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Request to Borrow',
            text: 'Would you like to send a loan request for this item?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Send Request',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#28a745'
        }).then((result) => {
            if (result.isConfirmed) {
                // Send loan request
                fetch('/api/loans/request', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        itemId: {{ item.id }},
                        lenderId: {{ item.userId }},
                        message: 'I would like to borrow this item.'
                    })
                })
                .then(response => response.json())
                .then(data => {
                    Swal.fire({
                        title: 'Request Sent!',
                        text: 'Your loan request has been sent to the owner.',
                        icon: 'success',
                        confirmButtonColor: '#28a745'
                    });
                })
                .catch(error => {
                    Swal.fire({
                        title: 'Error',
                        text: 'Failed to send loan request. Please try again.',
                        icon: 'error',
                        confirmButtonColor: '#dc3545'
                    });
                });
            }
        });
    } else {
        alert('Feature coming soon!');
    }
}

function contactOwner() {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Contact {{ item.ownerFirstName }}',
            text: 'This feature will connect you with the item owner.',
            icon: 'info',
            confirmButtonText: 'OK',
            confirmButtonColor: '#007bff'
        });
    } else {
        alert('Contact feature coming soon!');
    }
}

// Logout function with browser history prevention
function performLogout() {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Logout Confirmation',
            text: 'Are you sure you want to logout?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Logout',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Clear browser history and redirect to demo
                window.location.replace('/logout');
            }
        });
    } else {
        if (confirm('Are you sure you want to logout?')) {
            window.location.replace('/logout');
        }
    }
}

// Calendar functionality
let currentCalendarDate = new Date();
let currentItemId = {{ item.id }};

// Calendar CSS
const calendarStyles = `
    <style>
    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 1px;
        background-color: #dee2e6;
        border: 1px solid #dee2e6;
    }
    .calendar-day {
        background-color: white;
        padding: 8px 4px;
        text-align: center;
        font-size: 12px;
        min-height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    .calendar-day:hover {
        background-color: #f8f9fa;
    }
    .calendar-day.header {
        background-color: #e9ecef;
        font-weight: bold;
        cursor: default;
    }
    .calendar-day.available {
        background-color: #d1eddd;
        color: #155724;
    }
    .calendar-day.on-loan {
        background-color: #fff3cd;
        color: #856404;
    }
    .calendar-day.past {
        background-color: #f8f9fa;
        color: #6c757d;
    }
    .calendar-day.today {
        border: 2px solid #007bff;
        font-weight: bold;
    }
    </style>
`;

// Add calendar styles to head
document.head.insertAdjacentHTML('beforeend', calendarStyles);

async function renderCalendar() {
    const monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"];
    const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    
    const year = currentCalendarDate.getFullYear();
    const month = currentCalendarDate.getMonth();
    
    document.getElementById('calendarMonth').textContent = `${monthNames[month]} ${year}`;
    
    // Fetch authentic availability data from API
    let availabilityData = {};
    try {
        const response = await fetch(`/api/items/${currentItemId}/calendar/${year}/${month + 1}`);
        if (response.ok) {
            const data = await response.json();
            availabilityData = data.availability || {};
        }
    } catch (error) {
        console.log('Using fallback calendar data');
    }
    
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const startDate = new Date(firstDay);
    startDate.setDate(startDate.getDate() - firstDay.getDay());
    
    let html = '';
    
    // Add day headers
    dayNames.forEach(day => {
        html += `<div class="calendar-day header">${day}</div>`;
    });
    
    // Add calendar days
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    for (let d = new Date(startDate); d <= lastDay || d.getDay() !== 0; d.setDate(d.getDate() + 1)) {
        const dayOfMonth = d.getDate();
        const isCurrentMonth = d.getMonth() === month;
        const isPast = d < today;
        const isToday = d.getTime() === today.getTime();
        
        let classes = 'calendar-day';
        if (!isCurrentMonth) {
            classes += ' text-muted';
        } else if (isPast) {
            classes += ' past';
        } else {
            // Use authentic availability data
            const dayAvailability = availabilityData[dayOfMonth] || 'available';
            if (dayAvailability === 'on-loan') {
                classes += ' on-loan';
            } else if (dayAvailability === 'reserved') {
                classes += ' on-loan'; // Use same styling for reserved
            } else {
                classes += ' available';
            }
        }
        
        if (isToday) {
            classes += ' today';
        }
        
        html += `<div class="${classes}" onclick="selectCalendarDate('${d.toISOString().split('T')[0]}')">${dayOfMonth}</div>`;
    }
    
    document.getElementById('calendarGrid').innerHTML = html;
}

function changeCalendarMonth(direction) {
    currentCalendarDate.setMonth(currentCalendarDate.getMonth() + direction);
    renderCalendar();
}

function selectCalendarDate(dateString) {
    const selectedDate = new Date(dateString);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    if (selectedDate < today) {
        return; // Can't select past dates
    }
    
    // In a real implementation, this would allow scheduling/requesting specific dates
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Request for ' + selectedDate.toLocaleDateString(),
            text: 'Would you like to request this item for this date?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, request it!'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Request Sent!',
                    text: `Your request for ${selectedDate.toLocaleDateString()} has been sent to the owner.`,
                    icon: 'success',
                    confirmButtonColor: '#28a745'
                });
            }
        });
    }
}

function chatWithOwner(ownerId, ownerName, itemId) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: `Chat with ${ownerName}`,
            text: 'This feature will open a chat window with the item owner.',
            icon: 'info',
            confirmButtonText: 'OK',
            confirmButtonColor: '#007bff'
        });
    } else {
        alert(`Chat with ${ownerName} coming soon!`);
    }
}

// Calendar functionality
let currentMonth = new Date().getMonth();
let currentYear = new Date().getFullYear();

function toggleCalendar() {
    const calendar = document.getElementById('itemCalendar');
    if (calendar.style.display === 'none') {
        calendar.style.display = 'block';
        loadCalendarData();
    } else {
        calendar.style.display = 'none';
    }
}

function previousMonth() {
    currentMonth--;
    if (currentMonth < 0) {
        currentMonth = 11;
        currentYear--;
    }
    loadCalendarData();
}

function nextMonth() {
    currentMonth++;
    if (currentMonth > 11) {
        currentMonth = 0;
        currentYear++;
    }
    loadCalendarData();
}

function loadCalendarData() {
    const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
                       'July', 'August', 'September', 'October', 'November', 'December'];
    
    document.getElementById('calendarTitle').textContent = 
        `${monthNames[currentMonth]} ${currentYear} - Availability Calendar`;
    
    // Fetch calendar data from API
    fetch(`/api/items/{{ item.id }}/calendar/${currentYear}/${currentMonth + 1}`)
        .then(response => response.json())
        .then(data => {
            renderCalendarGrid(data.availability);
            renderLoanDetails(data.loans, data.isOwner);
        })
        .catch(error => {
            console.error('Error loading calendar data:', error);
            document.getElementById('calendarGrid').innerHTML = 
                '<div class="alert alert-warning">Unable to load calendar data</div>';
        });
}

function renderCalendarGrid(availability) {
    const grid = document.getElementById('calendarGrid');
    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    const firstDay = new Date(currentYear, currentMonth, 1).getDay();
    
    let html = '';
    
    // Day headers
    const dayHeaders = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    dayHeaders.forEach(day => {
        html += `<div class="calendar-day calendar-day-header">${day}</div>`;
    });
    
    // Empty cells for days before month starts
    for (let i = 0; i < firstDay; i++) {
        html += '<div class="calendar-day day-empty"></div>';
    }
    
    // Days of the month
    for (let day = 1; day <= daysInMonth; day++) {
        const status = availability[day] || 'available';
        const cssClass = `day-${status}`;
        html += `<div class="calendar-day ${cssClass}" title="${status}">${day}</div>`;
    }
    
    grid.innerHTML = html;
}

function renderLoanDetails(loans, isOwner) {
    const details = document.getElementById('loanDetails');
    
    if (loans && loans.length > 0) {
        const title = isOwner ? 'Loan History & Current Status:' : 'Current Status:';
        let html = `<h6 class="mb-2">${title}</h6>`;
        
        loans.forEach(loan => {
            const startDate = new Date(loan.borrowedDate).toLocaleDateString();
            const endDate = new Date(loan.expectedReturnDate).toLocaleDateString();
            let statusClass = 'secondary';
            
            if (loan.status === 'active') statusClass = 'danger';
            else if (loan.status === 'reserved') statusClass = 'warning';
            else if (loan.status === 'completed') statusClass = 'success';
            
            // Show different levels of detail based on ownership
            if (isOwner) {
                // Owners see full details including past history and borrower names
                html += `
                    <div class="alert alert-${statusClass} py-2 mb-2">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <strong>${loan.borrowerName}</strong><br>
                                <small class="text-muted">${startDate} to ${endDate}</small>
                            </div>
                            <span class="badge bg-${statusClass === 'success' ? 'success' : 'secondary'}">${loan.status}</span>
                        </div>
                    </div>
                `;
            } else {
                // Non-owners see limited information - no borrower names for privacy
                if (loan.status !== 'completed') {
                    html += `
                        <div class="alert alert-${statusClass} py-2 mb-2">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>${loan.borrowerName}</span>
                                <span class="badge bg-secondary">${loan.status}</span>
                            </div>
                            <small class="text-muted">${startDate} to ${endDate}</small>
                        </div>
                    `;
                }
            }
        });
        
        if (isOwner && loans.some(loan => loan.status === 'completed')) {
            html += '<small class="text-muted mt-2 d-block">✓ Past loans help you track item maintenance and user reliability</small>';
        }
        
        details.innerHTML = html;
    } else {
        const message = isOwner ? 'No loan history found' : 'Currently available';
        details.innerHTML = `<div class="text-muted">${message}</div>`;
    }
}

// Initialize calendar on page load
document.addEventListener('DOMContentLoaded', function() {
    renderCalendar();
});

// Increment view count
fetch('/api/items/{{ item.id }}/view', {
    method: 'POST'
}).catch(error => {
    console.log('View tracking unavailable');
});
</script>
{% endblock %}