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

{% block title %}Edit Profile - {{ user.showName ? user.showName : user.firstName }}{% endblock %}

{% block head %}
<style>
.edit-profile-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 2rem 0;
}

.form-card {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    overflow: hidden;
}

.form-section {
    padding: 1.5rem;
    border-bottom: 1px solid #e9ecef;
}

.form-section:last-child {
    border-bottom: none;
}

.section-title {
    color: #495057;
    font-weight: 600;
    margin-bottom: 1rem;
    display: flex;
    align-items-center;
}

.section-title i {
    margin-right: 0.5rem;
    color: #6c757d;
}

.avatar-upload {
    position: relative;
    display: inline-block;
}

.avatar-preview {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid #e9ecef;
    transition: border-color 0.3s ease;
}

.avatar-upload:hover .avatar-preview {
    border-color: #007bff;
}

.avatar-upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.7);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    cursor: pointer;
}

.avatar-upload:hover .avatar-upload-overlay {
    opacity: 1;
}

.btn-save {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    border: none;
    padding: 0.75rem 2rem;
    font-weight: 600;
    border-radius: 8px;
    transition: transform 0.2s ease;
}

.btn-save:hover {
    transform: translateY(-1px);
}

.btn-cancel {
    background: #6c757d;
    border: none;
    padding: 0.75rem 2rem;
    font-weight: 600;
    border-radius: 8px;
}

.privacy-note {
    background: #f8f9fa;
    border-left: 4px solid #007bff;
    padding: 1rem;
    border-radius: 0 8px 8px 0;
    margin-bottom: 1.5rem;
}

/* Tooltip styling - Force circular background */
.tooltip-icon {
    margin-left: 5px;
    color: #fff !important;
    background-color: #6c757d !important;
    cursor: help;
    font-size: 0.7em;
    font-weight: bold;
    display: inline-flex !important;
    align-items: center;
    justify-content: center;
    width: 16px !important;
    height: 16px !important;
    border-radius: 50% !important;
    border: 1px solid #6c757d !important;
    position: relative;
    text-align: center;
    line-height: 1;
    vertical-align: middle;
    flex-shrink: 0;
}

.tooltip-icon:hover {
    background-color: #495057;
    border-color: #495057;
    transform: scale(1.1);
}

.tooltip-text {
    visibility: hidden;
    width: 250px;
    background-color: #333;
    color: #fff;
    text-align: left;
    border-radius: 6px;
    padding: 8px 12px;
    position: absolute;
    z-index: 1000;
    bottom: 150%;
    left: 50%;
    margin-left: -125px;
    opacity: 0;
    transition: opacity 0.3s;
    font-size: 0.875rem;
    line-height: 1.4;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    white-space: normal;
    pointer-events: none;
}

.tooltip-text::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #333 transparent transparent transparent;
}

.tooltip-icon:hover .tooltip-text {
    visibility: visible;
    opacity: 1;
}

/* Help Modal Styles */
.help-modal {
    display: none;
    position: fixed;
    z-index: 10000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.help-modal-content {
    background-color: white;
    margin: 15% auto;
    padding: 20px;
    border-radius: 8px;
    width: 80%;
    max-width: 400px;
    position: relative;
    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}

.help-modal-close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    position: absolute;
    right: 15px;
    top: 10px;
}

.help-modal-close:hover {
    color: #000;
}

.avatar-gallery {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    border-radius: 12px;
    padding: 0;
    border: 1px solid #dee2e6;
    box-shadow: 0 10px 25px rgba(0,0,0,0.15);
    width: 90vw;
    max-width: 600px;
    max-height: 80vh;
    z-index: 1050;
    display: flex;
    flex-direction: column;
}

.avatar-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #dee2e6;
}

.avatar-modal-header h6 {
    margin: 0;
    font-weight: 600;
}

.btn-close-gallery {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: #6c757d;
    padding: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar-tabs {
    display: flex;
    border-bottom: 1px solid #dee2e6;
    margin: 0;
    padding: 0 1.5rem;
}

.avatar-tab {
    background: none;
    border: none;
    padding: 12px 16px;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    color: #6c757d;
    font-weight: 500;
    transition: all 0.3s ease;
}

.avatar-tab.active {
    color: #007bff;
    border-bottom-color: #007bff;
}

.avatar-tab:hover {
    color: #007bff;
    background: #f8f9fa;
}

.avatar-category-section {
    flex: 1;
    overflow-y: auto;
    padding: 1rem 1.5rem;
}

.avatar-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
    gap: 12px;
    max-height: 400px;
    overflow-y: auto;
}

.avatar-option {
    width: 60px;
    height: auto;
    border-radius: 8px;
    object-fit: contain;
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.3s ease;
    background: #f8f9fa;
}

.avatar-option:hover {
    border-color: #007bff;
    transform: scale(1.05);
    box-shadow: 0 4px 8px rgba(0,123,255,0.2);
}

.avatar-option.selected {
    border-color: #28a745;
    box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.25);
    transform: scale(1.05);
}

.avatar-gallery-footer {
    border-top: 1px solid #dee2e6;
    padding: 1rem 1.5rem;
    text-align: right;
}

.avatar-gallery-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1040;
    display: none;
}

.camera-video, .camera-canvas, .captured-image {
    max-width: 100%;
    max-height: 400px;
    border-radius: 8px;
    border: 2px solid #dee2e6;
}

.camera-preview {
    display: flex;
    justify-content: center;
    align-items: center;
}

.camera-controls {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 10px;
}
</style>
{% endblock %}

{% block content %}

<div class="edit-profile-header" style="margin-top: 2rem;">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-start">
                        {% if user.avatar %}
                            <img src="/ll_images/{{ user.avatar }}" alt="{{ user.showName ?: user.firstName }}" 
                                 class="rounded-circle border border-3 border-white me-3" 
                                 style="width: 60px; height: 60px; object-fit: cover;">
                        {% else %}
                            <img src="/ll_images/na200.png" alt="Default Avatar" 
                                 class="rounded-circle border border-3 border-white me-3" 
                                 style="width: 60px; height: 60px; object-fit: cover;">
                        {% endif %}
                        <div>
                            <h1 class="mb-0" style="font-size: 2rem !important; font-family: 'Cavolini', 'Georgia', sans-serif !important; font-weight: bold !important; color: black !important;">
                                Edit My Profile
                            </h1>
                            <p class="mb-0 opacity-75">Update  personal information, preferences, and communication lines.</p>
                        </div>
                    </div>
                    <div>
                        <a href="/profile/{{ user.id }}" class="btn btn-light" style="color: #333; border: 1px solid #ccc;">
                            <i class="fas fa-arrow-left me-2"></i>Back to Profile
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="privacy-note">
                <h6 class="mb-2"><i class="fas fa-info-circle me-2"></i>Privacy Notice</h6>
                <p class="mb-0 small">Your information is only visible to community members. You control what name is displayed publicly through the "Show Name" field below.</p>
            </div>

            <form id="editProfileForm" action="/api/profile/{{ user.id }}/update" method="POST" enctype="multipart/form-data">
                <div class="form-card">
                    <!-- Avatar Section -->
                    <div class="form-section" style="margin-top: 2rem;">
                        <h5 class="section-title">
                            <i class="fas fa-camera"></i>&nbsp;&nbsp;Profile Picture
                        </h5>
                        


                        <!-- Avatar Selection -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <!-- Current Avatar with Side Buttons -->
                                <div class="row mb-4">
                                    <div class="col-md-8 d-flex justify-content-center align-items-center">
                                        <div class="avatar-upload" style="position: relative; display: inline-block;">
                                            {% if user.avatar %}
                                                <img src="/ll_images/{{ user.avatar }}" alt="Current Avatar" class="avatar-preview" id="avatarPreview" style="width: 120px; height: auto; border: 3px solid #007bff; object-fit: contain;">
                                            {% else %}
                                                <img src="/ll_images/na200.png" alt="Default Avatar" class="avatar-preview" id="avatarPreview" style="width: 120px; height: auto; border: 3px solid #007bff; object-fit: contain;">
                                            {% endif %}
                                            <div class="small mt-2 text-primary fw-bold text-center">Current Avatar</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 d-flex flex-column justify-content-center gap-2">
                                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="openCameraModal()">
                                            <i class="fas fa-camera me-1"></i>Take Selfie
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="document.getElementById('avatarInput').click()">
                                            <i class="fas fa-upload me-1"></i>Upload Photo
                                        </button>
                                        <button type="button" class="btn btn-outline-info btn-sm" onclick="openAvatarModal()">
                                            <i class="fas fa-user-circle me-1"></i>Choose Avatar
                                        </button>
                                    </div>
                                </div>


                            </div>
                        </div>

                        <!-- Avatar Gallery (Hidden by default) -->
                        <div id="avatarGallery" class="avatar-gallery" style="display: none;">
                            <div class="avatar-modal-header">
                                <h6 class="mb-3">Select Avatar</h6>
                                <button type="button" class="btn-close-gallery" onclick="hideAvatarGallery()">&times;</button>
                            </div>
                            
                            <!-- Category Tabs -->
                            <div class="avatar-tabs mb-3">
                                <button class="avatar-tab active" onclick="showAvatarCategory('female')">Female Icons</button>
                                <button class="avatar-tab" onclick="showAvatarCategory('male')">Male Icons</button>
                                <button class="avatar-tab" onclick="showAvatarCategory('general')">General Icons</button>
                            </div>
                            
                            <!-- Female Category -->
                            <div id="female-avatars" class="avatar-category-section active">
                                <div class="avatar-grid" id="femaleGrid">
                                    <!-- Will be populated by JavaScript -->
                                </div>
                            </div>
                            
                            <!-- Male Category -->
                            <div id="male-avatars" class="avatar-category-section" style="display: none;">
                                <div class="avatar-grid" id="maleGrid">
                                    <!-- Will be populated by JavaScript -->
                                </div>
                            </div>
                            
                            <!-- General/Abstract Category -->
                            <div id="general-avatars" class="avatar-category-section" style="display: none;">
                                <div class="avatar-grid" id="generalGrid">
                                    <!-- Will be populated by JavaScript -->
                                </div>
                            </div>
                            
                            <div class="avatar-gallery-footer">
                                <button type="button" class="btn btn-secondary" onclick="hideAvatarGallery()">Close</button>
                            </div>
                        </div>

                        <input type="file" id="avatarInput" name="avatar" accept="image/*" style="display: none;" onchange="previewAvatar(this)">
                        <input type="hidden" id="selectedAvatar" name="selectedAvatar" value="">
                    </div>
                    
                    <!-- Avatar Gallery Overlay -->
                    <div id="avatarGalleryOverlay" class="avatar-gallery-overlay" onclick="hideAvatarGallery()"></div>

                    <!-- Basic Information -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-user"></i>&nbsp;&nbsp;Basic Information
                        </h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="firstName" class="form-label">
                                    First Name <span class="text-danger">*</span>
                                    <span class="help-icon" data-help-text="{{ tooltips['profile.firstName'] ?: 'Your legal first name as it appears on official documents' }}" onclick="showHelpModal(this)" style="display: inline-block; width: 16px; height: 16px; border-radius: 50%; background: #007bff; color: white; text-align: center; font-size: 12px; line-height: 16px; cursor: pointer; margin-left: 5px;">?</span>
                                </label>
                                <input type="text" class="form-control" id="firstName" name="firstName" value="{{ user.firstName }}" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="lastName" class="form-label">
                                    Last Name <span class="text-danger">*</span>
                                    <span class="help-icon" data-help-text="{{ tooltips['profile.lastName'] ?: 'Your legal last name as it appears on official documents' }}" onclick="showHelpModal(this)" style="display: inline-block; width: 16px; height: 16px; border-radius: 50%; background: #007bff; color: white; text-align: center; font-size: 12px; line-height: 16px; cursor: pointer; margin-left: 5px;">?</span>
                                </label>
                                <input type="text" class="form-control" id="lastName" name="lastName" value="{{ user.lastName }}" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="showName" class="form-label">
                                Display Name (Public)
                                <span class="help-icon" data-help-text="{{ tooltips['profile.showName'] ?: 'Choose how your name appears to other community members. Leave blank to show only your first name publicly' }}" onclick="showHelpModal(this)" style="display: inline-block; width: 16px; height: 16px; border-radius: 50%; background: #007bff; color: white; text-align: center; font-size: 12px; line-height: 16px; cursor: pointer; margin-left: 5px;">?</span>
                            </label>
                            <input type="text" class="form-control" id="showName" name="showName" value="{{ user.showName }}" 
                                   placeholder="Leave empty to use First Name publicly">
                            <div class="form-text">This is the name other members will see. Leave empty to show your first name only.</div>
                        </div>
                        <div class="mb-3">
                            <label for="email" class="form-label">
                                Email Address <span class="text-danger">*</span>
                                <span class="help-icon" data-help-text="{{ tooltips['profile.email'] ?: 'Your primary email address for account notifications and communication' }}" onclick="showHelpModal(this)" style="display: inline-block; width: 16px; height: 16px; border-radius: 50%; background: #007bff; color: white; text-align: center; font-size: 12px; line-height: 16px; cursor: pointer; margin-left: 5px;">?</span> DO NOT CHANGE DEMO USER EMAIL
                            </label>
                            <input type="email" class="form-control" id="email" name="email" value="{{ user.email }}" required>
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" id="displayEmail" name="displayEmail" 
                                       {% if userPreferences and userPreferences.displayEmail is defined %}{{ userPreferences.displayEmail ? 'checked' : '' }}{% else %}checked{% endif %}>
                                <label class="form-check-label mini" for="displayEmail">
                                    display email to other Members?
                                </label>
                            </div>
                        </div>

                        <!-- Bio -->
                        <div class="mb-3">
                            <label for="bio" class="form-label">
                                Bio
                                <span class="help-icon" data-help-text="{{ tooltips['profile.bio'] ?: 'Tell the community about yourself, your interests, and what you like to lend or borrow' }}" onclick="showHelpModal(this)" style="display: inline-block; width: 16px; height: 16px; border-radius: 50%; background: #007bff; color: white; text-align: center; font-size: 12px; line-height: 16px; cursor: pointer; margin-left: 5px;">?</span>
                            </label>
                            <textarea class="form-control" id="bio" name="bio" rows="4" 
                                      placeholder="Tell others about yourself, your interests, or what you're looking to lend or borrow...">{{ user.bio|default('') }}</textarea>
                            <div class="form-text">Share a bit about yourself with the community. This helps others get to know you better.</div>
                        </div>
                    </div>

                    <!-- Contact Information -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-address-card"></i>&nbsp;&nbsp;Contact Information
                        </h5>
                        <div class="mb-3">
                            <label for="phone" class="form-label">Phone Number</label>
                            <input type="tel" class="form-control" id="phone" name="phone" value="{{ user.phone }}">
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" id="displayPhone" name="displayPhone" 
                                       {% if userPreferences and userPreferences.displayPhone is defined %}{{ userPreferences.displayPhone ? 'checked' : '' }}{% else %}checked{% endif %}>
                                <label class="form-check-label mini" for="displayPhone">
                                    display phone number to other Members?
                                </label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="address" class="form-label">Address</label>
                            <input type="text" class="form-control" id="address" name="address" value="{{ user.address }}" 
                                   placeholder="Street address">
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" id="displayAddress" name="displayAddress" 
                                       {% if userPreferences and userPreferences.displayAddress is defined %}{{ userPreferences.displayAddress ? 'checked' : '' }}{% else %}checked{% endif %}>
                                <label class="form-check-label mini" for="displayAddress">
                                    display address to other Members?
                                </label>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label for="town" class="form-label">City/Town</label>
                                <input type="text" class="form-control" id="town" name="town" value="{{ user.town }}">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="zipcode" class="form-label">ZIP Code</label>
                                <input type="text" class="form-control" id="zipcode" name="zipcode" value="{{ user.zipcode }}">
                            </div>
                        </div>
                    </div>

                    <!-- Personal Information -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-info"></i>&nbsp;&nbsp;Personal Information (Optional)
                        </h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="gender" class="form-label">Gender</label>
                                <select class="form-select" id="gender" name="gender">
                                    <option value="">Prefer not to say</option>
                                    <option value="male" {{ user.gender == 'male' ? 'selected' : '' }}>Male</option>
                                    <option value="female" {{ user.gender == 'female' ? 'selected' : '' }}>Female</option>
                                    <option value="other" {{ user.gender == 'other' ? 'selected' : '' }}>Other</option>
                                </select>
                                <div class="form-check mt-2">
                                    <input class="form-check-input" type="checkbox" id="displayGender" name="displayGender" 
                                           {% if userPreferences and userPreferences.displayGender is defined %}{{ userPreferences.displayGender ? 'checked' : '' }}{% else %}checked{% endif %}>
                                    <label class="form-check-label mini" for="displayGender">
                                        display gender to other Members?
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="age" class="form-label">Age Range</label>
                                <select class="form-select" id="age" name="age">
                                    <option value="">Prefer not to say</option>
                                    <option value="18-25" {{ user.age == '18-25' ? 'selected' : '' }}>18-25</option>
                                    <option value="26-35" {{ user.age == '26-35' ? 'selected' : '' }}>26-35</option>
                                    <option value="36-45" {{ user.age == '36-45' ? 'selected' : '' }}>36-45</option>
                                    <option value="46-55" {{ user.age == '46-55' ? 'selected' : '' }}>46-55</option>
                                    <option value="56-65" {{ user.age == '56-65' ? 'selected' : '' }}>56-65</option>
                                    <option value="65+" {{ user.age == '65+' ? 'selected' : '' }}>65+</option>
                                </select>
                                <div class="form-check mt-2">
                                    <input class="form-check-input" type="checkbox" id="displayAge" name="displayAge" 
                                           {% if userPreferences and userPreferences.displayAge is defined %}{{ userPreferences.displayAge ? 'checked' : '' }}{% else %}checked{% endif %}>
                                    <label class="form-check-label mini" for="displayAge">
                                        display age to other Members?
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Communication Preferences -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-envelope"></i>&nbsp;&nbsp;Communication Preferences
                        </h5>
                        <div class="row">
                            <div class="col-12">
                                <div class="card border-0" style="background: #f8f9fa;">
                                    <div class="card-body">
                                        <div class="mb-4">
                                            <h6 class="text-primary mb-3">
                                                <i class="fas fa-exclamation-circle me-2"></i>Required Communications
                                            </h6>
                                            <ul class="list-unstyled mb-0">
                                                <li class="mb-2">
                                                    <i class="fas fa-check-circle text-success me-2"></i>
                                                    <strong>Weekly Update:</strong> One email per week on Wednesdays
                                                </li>
                                                <li class="mb-0">
                                                    <i class="fas fa-check-circle text-success me-2"></i>
                                                    <strong>Daily Messages:</strong> Maximum one email per day, if you have Lendables Messages about your available or borrowed Items.
                                                </li>
                                            </ul>
                                        </div>
                                        
                                        <div>
                                            <h6 class="text-info mb-3">
                                                <i class="fas fa-cog me-2"></i>Optional Communications
                                            </h6>
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="checkbox" id="smsNotifications" name="smsNotifications">
                                                <label class="form-check-label" for="smsNotifications">
                                                    <strong>SMS Notifications</strong> - Send lendable item messages via SMS whenever they happen
                                                    <br><small class="text-muted">(Phone number must be provided)</small>
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="instantEmailNotifications" name="instantEmailNotifications">
                                                <label class="form-check-label" for="instantEmailNotifications">
                                                    <strong>Instant Email Notifications</strong> - Send lendable item messages via email whenever they happen
                                                    <br><small class="text-muted">(In addition to the daily summary)</small>
                                                </label>
                                            </div>
                                            <div class="mt-3">
                                                <small class="text-muted">
                                                    <i class="fas fa-info-circle me-1"></i>
                                                    SMS notifications require a valid phone number. If no phone number is provided, SMS notifications will be disabled automatically.
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Membership Status -->
                    <div class="form-section">
                        <h5 class="section-title">
                            <i class="fas fa-user-check"></i>&nbsp;&nbsp;Membership Status
                        </h5>
                        <div class="row">
                            <div class="col-12">
                                <div class="card border-0" style="background: #f8f9fa;">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="badge bg-{{ user.active ? 'success' : 'secondary' }} me-3">
                                                {{ user.active ? 'Active Member' : 'Inactive Member' }}
                                            </span>
                                            <small class="text-muted">
                                                Current Status
                                            </small>
                                        </div>
                                        
                                        <div id="statusSection">
                                            <!-- Status will be loaded dynamically -->
                                        </div>
                                        
                                        <div class="mt-3">
                                            <p class="small text-muted mb-2">
                                                <strong>About Membership Status:</strong>
                                            </p>
                                            <ul class="midi text-muted mb-0">
                                                <li>Setting your status to "Inactive" will hide you from community displays</li>
                                                <li>You can only go inactive when all your items have been returned</li>
                                                <li>Your lending history will be preserved</li>
                                                <li>You can reactivate anytime and restore your lendable items</li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="form-section text-center">
                        <button type="submit" class="btn btn-primary btn-save me-3">
                            <i class="fas fa-save me-2"></i>Save Changes
                        </button>
                        <a href="/profile/{{ user.id }}" class="btn btn-secondary btn-cancel">
                            <i class="fas fa-times me-2"></i>Cancel
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Camera Modal for Direct Selfie -->
<div id="cameraModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Take Selfie</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <div id="cameraContainer" style="position: relative;">
                    <video id="cameraVideo" class="camera-video" autoplay playsinline style="display: none; max-width: 100%; height: auto;"></video>
                    <canvas id="cameraCanvas" class="camera-canvas" style="display: none;"></canvas>
                    
                    <!-- Crop overlay for face positioning -->
                    <div id="cropOverlay" style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;">
                        <div id="cropBox" style="position: absolute; border: 3px solid #007bff; border-radius: 10px; background: rgba(0,123,255,0.1);">
                            <div style="position: absolute; top: -25px; left: 50%; transform: translateX(-50%); background: #007bff; color: white; padding: 2px 8px; border-radius: 3px; font-size: 12px;">Position your face here</div>
                        </div>
                    </div>
                    
                    <div id="cameraPreview" class="camera-preview" style="display: none; position: relative;">
                        <img id="capturedImage" class="captured-image" alt="Captured selfie" style="max-width: 100%; height: auto;">
                        <!-- Crop controls for captured image -->
                        <div id="cropControls" style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
                            <div id="cropSelection" style="position: absolute; border: 3px solid #28a745; border-radius: 10px; background: rgba(40,167,69,0.1); cursor: move;">
                                <div style="position: absolute; top: -25px; left: 50%; transform: translateX(-50%); background: #28a745; color: white; padding: 2px 8px; border-radius: 3px; font-size: 12px;">Drag to move • Use corners to resize square</div>
                                <!-- Corner handles for square resizing only -->
                                <div class="crop-handle" data-handle="nw" style="position: absolute; top: -8px; left: -8px; width: 16px; height: 16px; background: #28a745; border: 2px solid white; border-radius: 50%; cursor: nw-resize; z-index: 10;"></div>
                                <div class="crop-handle" data-handle="ne" style="position: absolute; top: -8px; right: -8px; width: 16px; height: 16px; background: #28a745; border: 2px solid white; border-radius: 50%; cursor: ne-resize; z-index: 10;"></div>
                                <div class="crop-handle" data-handle="sw" style="position: absolute; bottom: -8px; left: -8px; width: 16px; height: 16px; background: #28a745; border: 2px solid white; border-radius: 50%; cursor: sw-resize; z-index: 10;"></div>
                                <div class="crop-handle" data-handle="se" style="position: absolute; bottom: -8px; right: -8px; width: 16px; height: 16px; background: #28a745; border: 2px solid white; border-radius: 50%; cursor: se-resize; z-index: 10;"></div>
                            </div>
                        </div>
                    </div>
                    <div id="cameraError" class="alert alert-warning" style="display: none;">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <span id="errorMessage">Camera not available</span>
                    </div>
                </div>
                <div class="camera-controls mt-3">
                    <button id="startCamera" class="btn btn-primary me-2">
                        <i class="fas fa-camera me-2"></i>Start Camera
                    </button>
                    <button id="capturePhoto" class="btn btn-success me-2" style="display: none;">
                        <i class="fas fa-camera-retro me-2"></i>Take Photo
                    </button>
                    <span class="mini text-muted" style="display: none;" id="cropHint">(you will be able to crop this next)</span>
                    <button id="retakePhoto" class="btn btn-warning me-2" style="display: none;">
                        <i class="fas fa-redo me-2"></i>Retake
                    </button>
                    <button id="cropPhoto" class="btn btn-info me-2" style="display: none;">
                        <i class="fas fa-crop me-2"></i>Crop Face
                    </button>
                    <button id="usePhoto" class="btn btn-primary" style="display: none;">
                        <i class="fas fa-check me-2"></i>Use This Photo
                    </button>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

<script>
function previewAvatar(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('avatarPreview').src = e.target.result;
            document.getElementById('selectedAvatar').value = ''; // Clear selected avatar when uploading
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// Avatar data arrays
const femaleAvatars = [
    // PNG versions (modern style)
    'f200.png', 'f204.png', 'f205.png', 'f206.png', 'f207.png', 'f208.png', 'f209.png', 'f210.png',
    // JPG versions (classic style) - selection of best ones
    'f1.jpg', 'f2.jpg', 'f3.jpg', 'f4.jpg', 'f5.jpg', 'f6.jpg', 'f7.jpg', 'f8.jpg', 'f9.jpg', 'f10.jpg',
    'f11.jpg', 'f12.jpg', 'f13.jpg', 'f14.jpg', 'f15.jpg', 'f16.jpg', 'f17.jpg', 'f18.jpg', 'f19.jpg', 'f20.jpg',
    'f21.jpg', 'f22.jpg', 'f23.jpg', 'f24.jpg', 'f25.jpg', 'f26.jpg', 'f27.jpg', 'f28.jpg', 'f29.jpg', 'f30.jpg',
    'f31.jpg', 'f32.jpg', 'f33.jpg', 'f34.jpg', 'f35.jpg', 'f36.jpg', 'f37.jpg', 'f38.jpg', 'f39.jpg', 'f40.jpg'
];

const maleAvatars = [
    // PNG versions (modern style)
    'm200.png', 'm203.png', 'm204.png', 'm205.png', 'm206.png', 'm207.png', 'm208.png',
    // JPG versions (classic style) - selection of best ones
    'm1.jpg', 'm2.jpg', 'm3.jpg', 'm4.jpg', 'm5.jpg', 'm6.jpg', 'm7.jpg', 'm8.jpg', 'm9.jpg', 'm10.jpg',
    'm11.jpg', 'm12.jpg', 'm13.jpg', 'm14.jpg', 'm15.jpg', 'm16.jpg', 'm17.jpg', 'm18.jpg', 'm19.jpg', 'm20.jpg',
    'm21.jpg', 'm22.jpg', 'm23.jpg', 'm24.jpg', 'm25.jpg', 'm26.jpg', 'm27.jpg', 'm28.jpg', 'm29.jpg', 'm30.jpg',
    'm31.jpg', 'm32.jpg', 'm33.jpg', 'm34.jpg', 'm35.jpg', 'm36.jpg', 'm37.jpg', 'm38.jpg', 'm39.jpg', 'm40.jpg'
];

const generalAvatars = [
    // PNG versions (modern abstract style)
    'na200.png', 'na201.png', 'na202.png', 'na203.png', 'na204.png', 'na205.png', 'na206.png', 'na207.png', 'na208.png', 'na209.png',
    'na300.png', 'na301.png', 'na302.png', 'na303.png', 'na304.png', 'na305.png', 'na306.png', 'na307.png', 'na308.png', 'na309.png',
    'na310.png', 'na311.png', 'na312.png', 'na313.png', 'na314.png', 'na315.png', 'na316.png', 'na317.png', 'na318.png', 'na319.png',
    'na320.png', 'na321.png', 'na322.png', 'na323.png', 'na324.png', 'na325.png', 'na326.png', 'na327.png', 'na328.png', 'na329.png', 'na330.png',
    // JPG versions (classic neutral)
    'na1.jpg', 'na2.jpg', 'na3.jpg', 'na4.jpg', 'na5.jpg', 'na6.jpg', 'na7.jpg', 'na8.jpg', 'na9.jpg', 'na10.jpg',
    'na11.jpg', 'na12.jpg', 'na13.jpg', 'na14.jpg', 'na15.jpg', 'na16.jpg', 'na17.jpg', 'na18.jpg', 'na19.jpg', 'na20.jpg'
];

function showAvatarGallery() {
    const gallery = document.getElementById('avatarGallery');
    const overlay = document.getElementById('avatarGalleryOverlay');
    
    // Show overlay and gallery
    overlay.style.display = 'block';
    gallery.style.display = 'flex';
    
    // Populate grids if they're empty
    if (!document.getElementById('femaleGrid').hasChildNodes()) {
        populateAvatarGrids();
    }
    
    // Prevent body scroll
    document.body.style.overflow = 'hidden';
}

function hideAvatarGallery() {
    const gallery = document.getElementById('avatarGallery');
    const overlay = document.getElementById('avatarGalleryOverlay');
    
    overlay.style.display = 'none';
    gallery.style.display = 'none';
    
    // Restore body scroll
    document.body.style.overflow = '';
}

function showAvatarCategory(category) {
    // Update tabs
    document.querySelectorAll('.avatar-tab').forEach(tab => tab.classList.remove('active'));
    event.target.classList.add('active');
    
    // Update sections
    document.querySelectorAll('.avatar-category-section').forEach(section => {
        section.style.display = 'none';
    });
    
    document.getElementById(category + '-avatars').style.display = 'block';
}

function populateAvatarGrids() {
    populateGrid('femaleGrid', femaleAvatars);
    populateGrid('maleGrid', maleAvatars);
    populateGrid('generalGrid', generalAvatars);
}

function populateGrid(gridId, avatars) {
    const grid = document.getElementById(gridId);
    grid.innerHTML = '';
    
    avatars.forEach(avatar => {
        const img = document.createElement('img');
        img.src = '/ll_images/' + avatar;
        img.className = 'avatar-option';
        img.setAttribute('data-avatar', avatar);
        img.onclick = () => selectAvatar(avatar);
        img.title = avatar.replace(/\.(jpg|png)$/, '').toUpperCase();
        
        // Handle broken images gracefully
        img.onerror = function() {
            this.style.display = 'none';
        };
        
        grid.appendChild(img);
    });
}

function selectAvatar(avatarName) {
    // Update preview
    document.getElementById('avatarPreview').src = '/ll_images/' + avatarName;
    
    // Clear file input
    document.getElementById('avatarInput').value = '';
    
    // Set selected avatar
    document.getElementById('selectedAvatar').value = avatarName;
    
    // Update visual selection in all grids
    document.querySelectorAll('.avatar-option').forEach(img => img.classList.remove('selected'));
    document.querySelectorAll(`[data-avatar="${avatarName}"]`).forEach(img => img.classList.add('selected'));
    
    // Hide gallery
    hideAvatarGallery();
}

// Camera functionality
let cameraStream = null;

function openCameraModal() {
    const modal = new bootstrap.Modal(document.getElementById('cameraModal'));
    modal.show();
    
    // Reset camera interface
    resetCameraInterface();
}

function openCameraModal() {
    const modal = new bootstrap.Modal(document.getElementById('cameraModal'));
    modal.show();
    
    // Reset camera interface
    resetCameraInterface();
}

function resetCameraInterface() {
    // Hide all elements initially
    document.getElementById('cameraVideo').style.display = 'none';
    document.getElementById('cameraCanvas').style.display = 'none';
    document.getElementById('cameraPreview').style.display = 'none';
    document.getElementById('cameraError').style.display = 'none';
    
    // Show/hide buttons
    document.getElementById('startCamera').style.display = 'inline-block';
    document.getElementById('capturePhoto').style.display = 'none';
    document.getElementById('retakePhoto').style.display = 'none';
    document.getElementById('usePhoto').style.display = 'none';
    
    // Stop any existing camera stream
    if (cameraStream) {
        cameraStream.getTracks().forEach(track => track.stop());
        cameraStream = null;
    }
}

async function startCamera() {
    try {
        // Request camera access with front camera preference for selfies
        const constraints = {
            video: {
                facingMode: 'user', // Front camera for selfies
                width: { ideal: 640 },
                height: { ideal: 480 }
            }
        };
        
        cameraStream = await navigator.mediaDevices.getUserMedia(constraints);
        
        const video = document.getElementById('cameraVideo');
        video.srcObject = cameraStream;
        video.style.display = 'block';
        
        // Hide error and start button, show capture button
        document.getElementById('cameraError').style.display = 'none';
        document.getElementById('startCamera').style.display = 'none';
        document.getElementById('capturePhoto').style.display = 'inline-block';
        document.getElementById('cropHint').style.display = 'inline';
        
    } catch (error) {
        console.error('Error accessing camera:', error);
        showCameraError('Unable to access camera. Please ensure camera permissions are granted.');
    }
}

function showCameraError(message) {
    document.getElementById('errorMessage').textContent = message;
    document.getElementById('cameraError').style.display = 'block';
    document.getElementById('startCamera').style.display = 'inline-block';
}

function capturePhoto() {
    const video = document.getElementById('cameraVideo');
    const canvas = document.getElementById('cameraCanvas');
    const ctx = canvas.getContext('2d');
    
    // Set canvas size to match video
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    // Draw the video frame to canvas
    ctx.drawImage(video, 0, 0);
    
    // Store original canvas dimensions for reference (removed - not needed)
    
    // Convert canvas to blob and display preview
    canvas.toBlob(blob => {
        const url = URL.createObjectURL(blob);
        const img = document.getElementById('capturedImage');
        img.src = url;
        
        // Store the blob for later use
        window.capturedSelfieBlob = blob;
        
        // Hide video, show preview and controls
        video.style.display = 'none';
        document.getElementById('cameraPreview').style.display = 'block';
        document.getElementById('capturePhoto').style.display = 'none';
        document.getElementById('cropHint').style.display = 'none';
        document.getElementById('retakePhoto').style.display = 'inline-block';
        document.getElementById('cropPhoto').style.display = 'inline-block';
        document.getElementById('usePhoto').style.display = 'inline-block';
        
        // Initialize crop area
        setupCropArea();
        
        // Stop camera stream
        if (cameraStream) {
            cameraStream.getTracks().forEach(track => track.stop());
            cameraStream = null;
        }
    }, 'image/jpeg', 0.8);
}

function retakePhoto() {
    // Reset to camera view
    document.getElementById('cameraPreview').style.display = 'none';
    document.getElementById('retakePhoto').style.display = 'none';
    document.getElementById('usePhoto').style.display = 'none';
    
    // Restart camera
    startCamera();
}

function usePhoto() {
    if (window.capturedSelfieBlob) {
        // Update avatar preview
        const url = URL.createObjectURL(window.capturedSelfieBlob);
        document.getElementById('avatarPreview').src = url;
        
        // Store blob globally for form submission (use consistent variable name)
        window.selfieForUpload = window.capturedSelfieBlob;
        
        // Clear selected predefined avatar
        document.getElementById('selectedAvatar').value = '';
        
        // Also add blob to file input as backup
        const file = new File([window.capturedSelfieBlob], 'selfie.jpg', { type: 'image/jpeg' });
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(file);
        document.getElementById('avatarInput').files = dataTransfer.files;
        
        // Debug logging
        console.log('Selfie blob stored:', window.selfieForUpload);
        console.log('Blob size:', window.selfieForUpload.size);
        
        // Close modal
        bootstrap.Modal.getInstance(document.getElementById('cameraModal')).hide();
    }
}

// Event listeners for camera controls
document.getElementById('startCamera').addEventListener('click', startCamera);
document.getElementById('capturePhoto').addEventListener('click', capturePhoto);
document.getElementById('retakePhoto').addEventListener('click', retakePhoto);
document.getElementById('cropPhoto').addEventListener('click', toggleCropMode);
document.getElementById('usePhoto').addEventListener('click', usePhoto);

// Crop functionality variables
let cropMode = false;
let cropData = { x: 0, y: 0, width: 200, height: 200 };

function setupCropArea() {
    const img = document.getElementById('capturedImage');
    const cropSelection = document.getElementById('cropSelection');
    
    // Wait for image to load or use current dimensions
    function initializeCrop() {
        const displayWidth = img.clientWidth;
        const displayHeight = img.clientHeight;
        
        // Make initial crop box smaller and centered
        const initialSize = Math.min(displayWidth, displayHeight) * 0.5; // 50% of smaller dimension
        const centerX = (displayWidth / 2) - (initialSize / 2);
        const centerY = (displayHeight / 2) - (initialSize / 2);
        
        cropData = {
            x: Math.max(0, centerX),
            y: Math.max(0, centerY),
            width: initialSize,
            height: initialSize
        };
        
        console.log('Setting up crop area:', cropData, 'Image dimensions:', displayWidth, displayHeight);
        updateCropDisplay();
    }
    
    if (img.complete && img.clientWidth > 0) {
        initializeCrop();
    } else {
        img.onload = initializeCrop;
    }
}

function toggleCropMode() {
    cropMode = !cropMode;
    const cropControls = document.getElementById('cropControls');
    const cropButton = document.getElementById('cropPhoto');
    
    if (cropMode) {
        cropControls.style.display = 'block';
        cropButton.innerHTML = '<i class="fas fa-check me-2"></i>Apply Crop';
        cropButton.className = 'btn btn-success me-2';
    } else {
        cropControls.style.display = 'none';
        cropButton.innerHTML = '<i class="fas fa-crop me-2"></i>Crop Face';
        cropButton.className = 'btn btn-info me-2';
        applyCrop();
    }
}

function updateCropDisplay() {
    const cropSelection = document.getElementById('cropSelection');
    cropSelection.style.left = cropData.x + 'px';
    cropSelection.style.top = cropData.y + 'px';
    cropSelection.style.width = cropData.width + 'px';
    cropSelection.style.height = cropData.height + 'px';
}

function applyCrop() {
    const canvas = document.getElementById('cameraCanvas');
    const img = document.getElementById('capturedImage');
    
    // Create temporary canvas to work with current canvas data
    const tempCanvas = document.createElement('canvas');
    tempCanvas.width = canvas.width;
    tempCanvas.height = canvas.height;
    const tempCtx = tempCanvas.getContext('2d');
    tempCtx.drawImage(canvas, 0, 0);
    
    // Create new canvas for cropped image
    const cropCanvas = document.createElement('canvas');
    const cropCtx = cropCanvas.getContext('2d');
    cropCanvas.width = 400;
    cropCanvas.height = 400;
    
    // Get scale factors
    const displayWidth = img.clientWidth;
    const displayHeight = img.clientHeight;
    const scaleX = canvas.width / displayWidth;
    const scaleY = canvas.height / displayHeight;
    
    // Calculate crop coordinates
    const sourceX = cropData.x * scaleX;
    const sourceY = cropData.y * scaleY;
    const sourceWidth = cropData.width * scaleX;
    const sourceHeight = cropData.height * scaleY;
    
    console.log('Crop application:', {
        cropData,
        displayDims: [displayWidth, displayHeight],
        canvasDims: [canvas.width, canvas.height],
        scale: [scaleX, scaleY],
        source: [sourceX, sourceY, sourceWidth, sourceHeight]
    });
    
    // Draw cropped portion from temp canvas to crop canvas
    cropCtx.drawImage(tempCanvas, 
        sourceX, sourceY, sourceWidth, sourceHeight,
        0, 0, 400, 400);
    
    // Update everything with the cropped result
    cropCanvas.toBlob(blob => {
        window.capturedSelfieBlob = blob;
        const url = URL.createObjectURL(blob);
        
        // Create new image to ensure proper loading
        const newImg = new Image();
        newImg.onload = function() {
            // Update displayed image
            img.src = url;
            
            // Update canvas
            canvas.width = 400;
            canvas.height = 400;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(newImg, 0, 0, 400, 400);
            
            // Calculate the new crop area position based on the original crop relative to the new 400x400 image
            setTimeout(() => {
                const newDisplayWidth = img.clientWidth;
                const newDisplayHeight = img.clientHeight;
                
                // Calculate what portion of the original crop area should be shown in the new image
                // Since we cropped a portion and it became the full 400x400, the center of that crop
                // should be the center of the new crop area
                const centerRatioX = 0.5; // Center of the cropped area
                const centerRatioY = 0.5; // Center of the cropped area
                
                // Create new crop area centered in the new image, but smaller
                const newSize = Math.min(newDisplayWidth, newDisplayHeight) * 0.4;
                
                cropData = {
                    x: (newDisplayWidth * centerRatioX) - (newSize / 2),
                    y: (newDisplayHeight * centerRatioY) - (newSize / 2),
                    width: newSize,
                    height: newSize
                };
                
                // Ensure crop area stays within bounds
                cropData.x = Math.max(0, Math.min(cropData.x, newDisplayWidth - cropData.width));
                cropData.y = Math.max(0, Math.min(cropData.y, newDisplayHeight - cropData.height));
                
                updateCropDisplay();
                console.log('New centered crop area:', cropData, 'for dimensions:', [newDisplayWidth, newDisplayHeight]);
            }, 100);
        };
        newImg.src = url;
    }, 'image/jpeg', 0.8);
}

// Help Modal System
function showHelpModal(element) {
    const helpText = element.getAttribute('data-help-text');
    
    // Create modal if it doesn't exist
    let modal = document.getElementById('helpModal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'helpModal';
        modal.innerHTML = `
            <div style="position: fixed; z-index: 10000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5);">
                <div style="background-color: white; margin: 15% auto; padding: 20px; border-radius: 8px; width: 80%; max-width: 400px; position: relative; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
                    <span onclick="closeHelpModal()" style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; position: absolute; right: 15px; top: 10px;">&times;</span>
                    <h5 style="margin-bottom: 15px;">Help</h5>
                    <p id="helpModalText">${helpText}</p>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    } else {
        const modalText = document.getElementById('helpModalText');
        if (modalText) {
            modalText.textContent = helpText;
        }
        modal.style.display = 'block';
    }
    
    modal.style.display = 'block';
}

function closeHelpModal() {
    const modal = document.getElementById('helpModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// Close modal when clicking outside
document.addEventListener('click', function(event) {
    const modal = document.getElementById('helpModal');
    if (modal && event.target === modal) {
        closeHelpModal();
    }
});

// Close modal with Escape key
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeHelpModal();
    }
});

// Initialize modal event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Close modal when clicking the X
    const closeBtn = document.querySelector('.help-modal-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', closeHelpModal);
    }
    
    // Close modal when clicking outside of it
    const modal = document.getElementById('helpModal');
    if (modal) {
        modal.addEventListener('click', function(event) {
            if (event.target === this) {
                closeHelpModal();
            }
        });
    }
    
    // Close modal with Escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeHelpModal();
        }
    });
});

// Add drag and resize functionality for crop area
document.addEventListener('DOMContentLoaded', function() {
    let isDragging = false;
    let isResizing = false;
    let dragStart = { x: 0, y: 0 };
    let resizeHandle = null;
    let initialCropData = {};
    
    document.addEventListener('mousedown', function(e) {
        if (!cropMode) return;
        
        // Check if clicking on a resize handle
        if (e.target.classList.contains('crop-handle')) {
            isResizing = true;
            resizeHandle = e.target.getAttribute('data-handle');
            initialCropData = { ...cropData };
            dragStart.x = e.clientX;
            dragStart.y = e.clientY;
            e.preventDefault();
            e.stopPropagation();
        }
        // Check if clicking on crop selection for dragging
        else if (e.target.id === 'cropSelection') {
            isDragging = true;
            dragStart.x = e.clientX - cropData.x;
            dragStart.y = e.clientY - cropData.y;
            e.preventDefault();
        }
    });
    
    document.addEventListener('mousemove', function(e) {
        if (!cropMode) return;
        
        const img = document.getElementById('capturedImage');
        const rect = img.getBoundingClientRect();
        
        if (isResizing && resizeHandle) {
            const deltaX = e.clientX - dragStart.x;
            const deltaY = e.clientY - dragStart.y;
            
            let newCropData = { ...initialCropData };
            
            // Handle corner resize directions to maintain square aspect ratio
            let sizeDelta = 0;
            switch (resizeHandle) {
                case 'nw':
                    sizeDelta = Math.max(deltaX, deltaY); // Use the larger delta to maintain square
                    newCropData.x = Math.max(0, initialCropData.x + sizeDelta);
                    newCropData.y = Math.max(0, initialCropData.y + sizeDelta);
                    newCropData.width = Math.max(50, initialCropData.width - sizeDelta);
                    newCropData.height = newCropData.width; // Force square
                    break;
                case 'ne':
                    sizeDelta = Math.max(-deltaX, deltaY); // Invert deltaX for NE corner
                    newCropData.y = Math.max(0, initialCropData.y + sizeDelta);
                    newCropData.width = Math.max(50, initialCropData.width - sizeDelta);
                    newCropData.height = newCropData.width; // Force square
                    break;
                case 'sw':
                    sizeDelta = Math.max(deltaX, -deltaY); // Invert deltaY for SW corner
                    newCropData.x = Math.max(0, initialCropData.x + sizeDelta);
                    newCropData.width = Math.max(50, initialCropData.width - sizeDelta);
                    newCropData.height = newCropData.width; // Force square
                    break;
                case 'se':
                    sizeDelta = Math.max(-deltaX, -deltaY); // Use negative deltas for growth
                    newCropData.width = Math.max(50, initialCropData.width - sizeDelta);
                    newCropData.height = newCropData.width; // Force square
                    break;
            }
            
            // Ensure crop area stays within image bounds
            newCropData.x = Math.max(0, Math.min(rect.width - newCropData.width, newCropData.x));
            newCropData.y = Math.max(0, Math.min(rect.height - newCropData.height, newCropData.y));
            newCropData.width = Math.min(rect.width - newCropData.x, newCropData.width);
            newCropData.height = Math.min(rect.height - newCropData.y, newCropData.height);
            
            cropData = newCropData;
            updateCropDisplay();
        }
        else if (isDragging) {
            cropData.x = Math.max(0, Math.min(rect.width - cropData.width, e.clientX - dragStart.x));
            cropData.y = Math.max(0, Math.min(rect.height - cropData.height, e.clientY - dragStart.y));
            
            updateCropDisplay();
        }
    });
    
    document.addEventListener('mouseup', function(e) {
        isDragging = false;
        isResizing = false;
        resizeHandle = null;
    });
});

// Clean up camera when modal is closed
document.getElementById('cameraModal').addEventListener('hidden.bs.modal', function() {
    if (cameraStream) {
        cameraStream.getTracks().forEach(track => track.stop());
        cameraStream = null;
    }
});

document.getElementById('editProfileForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    // If we have a selfie blob, ensure it's properly added to form data
    if (window.selfieForUpload && window.selfieForUpload.size > 0) {
        // Remove any existing avatar file data
        formData.delete('avatar');
        // Add the selfie blob with proper filename following Image Canon
        formData.append('avatar', window.selfieForUpload, 'selfie.jpg');
        // Clear selected avatar since we're using a selfie
        formData.delete('selectedAvatar');
        formData.set('selectedAvatar', '');
        console.log('Adding selfie to form data - size:', window.selfieForUpload.size, 'type:', window.selfieForUpload.type);
    } else {
        console.log('No valid selfie blob found for upload - selfieForUpload:', window.selfieForUpload);
        // Check if there's a file in the file input instead
        const fileInput = document.getElementById('avatarInput');
        if (fileInput.files && fileInput.files.length > 0) {
            console.log('Using file input instead:', fileInput.files[0]);
        }
    }
    
    // Show loading state
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
    submitBtn.disabled = true;
    
    fetch(this.action, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    title: 'Success!',
                    text: 'Your profile has been updated successfully.',
                    icon: 'success',
                    confirmButtonText: 'View Profile'
                }).then(() => {
                    window.location.href = '/profile/{{ user.id }}';
                });
            } else {
                LocalLendables.showToast('Success', 'Profile updated successfully!', 'success');
                setTimeout(() => window.location.href = '/profile/{{ user.id }}', 1500);
            }
        } else {
            throw new Error(data.message || 'Failed to update profile');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Error!',
                text: error.message || 'Failed to update profile. Please try again.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        } else {
            LocalLendables.showToast('Error', 'Error: ' + (error.message || 'Failed to update profile. Please try again.'), 'error');
        }
    })
    .finally(() => {
        // Reset button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// Load membership status and check if user can go inactive
async function loadMembershipStatus() {
    try {
        const response = await fetch(`/api/users/{{ user.id }}/membership-status`);
        const data = await response.json();
        
        const statusSection = document.getElementById('statusSection');
        
        if (data.canGoInactive) {
            statusSection.innerHTML = `
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="membershipActive" name="active" 
                           ${data.isActive ? 'checked' : ''}>
                    <label class="form-check-label" for="membershipActive">
                        <strong>Active Membership</strong>
                    </label>
                </div>
                <div class="form-text">
                    You can safely set your status to inactive since all your items have been returned.
                </div>
            `;
        } else {
            statusSection.innerHTML = `
                <div class="alert alert-warning mb-0">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Cannot go inactive:</strong> You have ${data.activeLoansCount} item(s) currently on loan.
                    All items must be returned before you can set your status to inactive.
                    ${data.activeLoansCount > 0 ? `
                        <div class="mt-2">
                            <a href="/my-items?tab=loaned" class="btn btn-sm btn-outline-primary">
                                View Items on Loan
                            </a>
                        </div>
                    ` : ''}
                </div>
            `;
        }
    } catch (error) {
        console.error('Error loading membership status:', error);
        document.getElementById('statusSection').innerHTML = `
            <div class="alert alert-danger mb-0">
                Error loading membership status. Please refresh the page.
            </div>
        `;
    }
}

// Populate avatar gallery with predefined options
function populateAvatarGallery() {
    // Avatar categories and files
    const avatarCategories = {
        female: ['f1.jpg', 'f2.jpg', 'f3.jpg', 'f4.jpg', 'f5.jpg', 'f6.jpg', 'f7.jpg', 'f8.jpg', 'f9.jpg', 'f10.jpg', 'f11.jpg', 'f12.jpg', 'f13.jpg', 'f14.jpg', 'f15.jpg', 'f16.jpg', 'f17.jpg', 'f18.jpg', 'f19.jpg', 'f20.jpg', 'f21.jpg', 'f22.jpg', 'f23.jpg', 'f24.jpg'],
        male: ['m1.jpg', 'm2.jpg', 'm3.jpg', 'm4.jpg', 'm5.jpg', 'm6.jpg', 'm7.jpg', 'm8.jpg', 'm9.jpg', 'm10.jpg', 'm11.jpg', 'm12.jpg', 'm13.jpg', 'm14.jpg', 'm15.jpg', 'm16.jpg', 'm17.jpg', 'm18.jpg', 'm19.jpg', 'm20.jpg', 'm21.jpg', 'm22.jpg', 'm23.jpg', 'm24.jpg'],
        general: ['g1.jpg', 'g2.jpg', 'g3.jpg', 'g4.jpg', 'g5.jpg', 'g6.jpg', 'g7.jpg', 'g8.jpg', 'g9.jpg', 'g10.jpg', 'g11.jpg', 'g12.jpg']
    };

    // Populate each category
    Object.keys(avatarCategories).forEach(category => {
        const grid = document.getElementById(category + 'Grid');
        if (grid) {
            grid.innerHTML = '';
            avatarCategories[category].forEach(avatar => {
                const img = document.createElement('img');
                img.src = `/ll_images/${avatar}`;
                img.className = 'avatar-option';
                img.onclick = () => selectAvatar(avatar);
                grid.appendChild(img);
            });
        }
    });
}

// Load notification preferences
async function loadNotificationPreferences() {
    try {
        const response = await fetch(`/api/users/{{ user.id }}/preferences`);
        const data = await response.json();
        
        if (data.success && data.preferences) {
            document.getElementById('smsNotifications').checked = data.preferences.smsNotifications || false;
            document.getElementById('instantEmailNotifications').checked = data.preferences.instantEmailNotifications || false;
        }
    } catch (error) {
        console.error('Error loading notification preferences:', error);
    }
}

// Avatar categories with 8x8 grids
const avatarCategories = {
    female: {
        title: 'Female Avatars',
        avatars: Array.from({length: 64}, (_, i) => `f${i + 1}.jpg`)
    },
    male: {
        title: 'Male Avatars', 
        avatars: Array.from({length: 64}, (_, i) => `m${i + 1}.jpg`)
    },
    generic: {
        title: 'Generic Avatars',
        avatars: Array.from({length: 64}, (_, i) => `g${i + 1}.jpg`)
    }
};

// Open avatar selection modal
function openAvatarModal() {
    const modal = new bootstrap.Modal(document.getElementById('avatarModal'));
    modal.show();
    // Default to female category
    showAvatarCategory('female');
}

// Show specific avatar category
function showAvatarCategory(category) {
    // Update button states
    document.querySelectorAll('#avatarModal .btn-group .btn').forEach(btn => {
        btn.classList.remove('btn-primary');
        btn.classList.add('btn-outline-primary');
    });
    document.getElementById(category + 'Btn').classList.remove('btn-outline-primary');
    document.getElementById(category + 'Btn').classList.add('btn-primary');

    // Populate grid
    const grid = document.getElementById('avatarModalGrid');
    const categoryData = avatarCategories[category];
    
    grid.innerHTML = '';
    
    categoryData.avatars.forEach(avatar => {
        const col = document.createElement('div');
        col.className = 'col-1 text-center';
        
        const img = document.createElement('img');
        img.src = `/ll_images/${avatar}`;
        img.alt = 'Avatar Option';
        img.className = 'rounded-circle border border-1 border-secondary';
        img.style = 'width: 50px; height: auto; object-fit: contain; cursor: pointer;';
        img.onclick = () => selectModalAvatar(avatar);
        
        // Handle missing images gracefully
        img.onerror = function() {
            this.style.display = 'none';
            col.style.display = 'none';
        };
        
        col.appendChild(img);
        grid.appendChild(col);
    });
}

// Select avatar from modal
function selectModalAvatar(avatarFilename) {
    document.getElementById('selectedAvatar').value = avatarFilename;
    document.getElementById('avatarPreview').src = '/ll_images/' + avatarFilename;
    document.getElementById('avatarPreview').style.border = '3px solid #28a745';
    
    // Clear any uploaded file
    const fileInput = document.getElementById('avatarInput');
    fileInput.value = '';
    window.selfieForUpload = null;
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('avatarModal'));
    modal.hide();
    
    console.log('Modal avatar selected:', avatarFilename);
}

// Open avatar selection modal
function openAvatarModal() {
    const modal = new bootstrap.Modal(document.getElementById('avatarModal'));
    modal.show();
    // Default to female category
    showAvatarCategory('female');
}

// Show specific avatar category
function showAvatarCategory(category) {
    // Update button states
    document.querySelectorAll('#avatarModal .btn-group .btn').forEach(btn => {
        btn.classList.remove('btn-primary');
        btn.classList.add('btn-outline-primary');
    });
    document.getElementById(category + 'Btn').classList.remove('btn-outline-primary');
    document.getElementById(category + 'Btn').classList.add('btn-primary');

    // Populate grid
    const grid = document.getElementById('avatarModalGrid');
    const avatarCategories = {
        female: Array.from({length: 64}, (_, i) => `f${i + 1}.jpg`),
        male: Array.from({length: 64}, (_, i) => `m${i + 1}.jpg`),
        generic: [
            ...Array.from({length: 20}, (_, i) => `na${i + 1}.jpg`),   // na1-na20 (jpg files)
            ...Array.from({length: 10}, (_, i) => `na${i + 200}.png`), // na200-na209 (png files)
            ...Array.from({length: 31}, (_, i) => `na${i + 300}.png`)  // na300-na330 (png files)
        ].filter(file => file) // Remove any undefined entries
    };
    
    const avatars = avatarCategories[category];
    grid.innerHTML = '';
    
    avatars.forEach(avatar => {
        const col = document.createElement('div');
        col.className = 'col-xl-1 col-lg-2 col-md-2 col-sm-3 col-4 text-center mb-2';
        
        const img = document.createElement('img');
        img.src = `/ll_images/${avatar}`;
        img.alt = 'Avatar Option';
        img.className = 'rounded-circle border border-1 border-secondary avatar-grid-option';
        img.style = 'width: 45px; height: auto; object-fit: contain; cursor: pointer; transition: all 0.2s;';
        img.onclick = () => selectModalAvatar(avatar);
        
        // Hover effects
        img.onmouseenter = function() {
            this.style.transform = 'scale(1.1)';
            this.style.borderColor = '#007bff';
            this.style.borderWidth = '2px';
            // Show preview
            document.getElementById('modalAvatarPreview').src = this.src;
            document.getElementById('avatarPreviewSection').style.display = 'block';
        };
        
        img.onmouseleave = function() {
            this.style.transform = 'scale(1)';
            this.style.borderColor = '#6c757d';
            this.style.borderWidth = '1px';
        };
        
        // Handle missing images gracefully
        img.onerror = function() {
            this.style.display = 'none';
            col.style.display = 'none';
        };
        
        col.appendChild(img);
        grid.appendChild(col);
    });
}

// Select avatar from modal
function selectModalAvatar(avatarFilename) {
    document.getElementById('selectedAvatar').value = avatarFilename;
    document.getElementById('avatarPreview').src = '/ll_images/' + avatarFilename;
    document.getElementById('avatarPreview').style.border = '3px solid #28a745';
    
    // Clear any uploaded file
    const fileInput = document.getElementById('avatarInput');
    fileInput.value = '';
    window.selfieForUpload = null;
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('avatarModal'));
    modal.hide();
    
    console.log('Modal avatar selected:', avatarFilename);
}

// Initialize form when page loads
document.addEventListener('DOMContentLoaded', function() {
    populateAvatarGallery();
    loadMembershipStatus();
    loadNotificationPreferences();
});
</script>

<!-- Avatar Selection Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" aria-labelledby="avatarModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="avatarModalLabel">Choose Avatar</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Category Selection -->
                <div class="text-center mb-4">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary" id="femaleBtn" onclick="showAvatarCategory('female')">
                            <i class="fas fa-female me-1"></i>Female
                        </button>
                        <button type="button" class="btn btn-outline-primary" id="maleBtn" onclick="showAvatarCategory('male')">
                            <i class="fas fa-male me-1"></i>Male
                        </button>
                        <button type="button" class="btn btn-outline-primary" id="genericBtn" onclick="showAvatarCategory('generic')">
                            <i class="fas fa-user-circle me-1"></i>Generic
                        </button>
                    </div>
                </div>

                <!-- Avatar Preview -->
                <div class="text-center mb-3" id="avatarPreviewSection" style="display: none;">
                    <img id="modalAvatarPreview" src="" alt="Preview" 
                         class="rounded-circle border border-2 border-success" 
                         style="width: 80px; height: auto; object-fit: contain;">
                    <div class="small text-success mt-1">Preview</div>
                </div>

                <!-- Avatar Grid -->
                <div id="avatarModalGrid" class="row g-1" style="max-height: 400px; overflow-y: auto;">
                    <!-- Grid will be populated by JavaScript -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}