{% extends 'rental_app/base_rental.html' %}
{% load static %}

{% block title %}My Rental Owner Profile{% endblock %}

{% block content %}

<style>
    /* =========================================================
       RENTAL OWNER PROFILE PAGE — PREMIUM
    ========================================================= */

    .rental-profile-page {
        min-height: 100vh;
        background:
            radial-gradient(circle at top left, rgba(251, 191, 36, 0.10), transparent 28%),
            radial-gradient(circle at top right, rgba(14, 116, 144, 0.10), transparent 32%),
            linear-gradient(180deg, #f8fafc 0%, #eff6ff 45%, #ffffff 100%);
        padding: 4rem 0 5rem;
    }

    .rental-profile-hero {
        position: relative;
        overflow: hidden;
        border-radius: 40px;
        padding: 2.7rem 2.5rem;
        background:
            radial-gradient(circle at top right, rgba(251, 191, 36, 0.20), transparent 32%),
            linear-gradient(135deg, #082f49 0%, #0e7490 55%, #0f766e 100%);
        color: #ffffff;
        box-shadow: 0 32px 72px rgba(15, 23, 42, 0.20);
        margin-bottom: 2rem;
    }

    .rental-profile-hero::before {
        content: "";
        position: absolute;
        top: -120px;
        right: -90px;
        width: 320px;
        height: 320px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.07);
        pointer-events: none;
    }

    .rental-profile-hero::after {
        content: "";
        position: absolute;
        bottom: -160px;
        left: -120px;
        width: 380px;
        height: 380px;
        border-radius: 50%;
        background: rgba(251, 191, 36, 0.08);
        pointer-events: none;
    }

    .rental-profile-hero-inner {
        position: relative;
        z-index: 2;
    }

    .rental-profile-kicker {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.52rem 1rem;
        border-radius: 999px;
        background: rgba(255, 255, 255, 0.14);
        border: 1px solid rgba(255, 255, 255, 0.22);
        color: #fef3c7;
        font-size: 0.84rem;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 1rem;
    }

    .rental-profile-hero h1 {
        font-size: clamp(2.2rem, 4vw, 3.6rem);
        font-weight: 950;
        letter-spacing: -0.045em;
        line-height: 1.1;
        margin-bottom: 0.8rem;
    }

    .rental-profile-hero p {
        color: rgba(255, 255, 255, 0.88);
        line-height: 1.8;
        max-width: 850px;
        margin-bottom: 0;
        font-size: 1.05rem;
    }

    .rental-profile-shell {
        border-radius: 38px;
        background: rgba(255, 255, 255, 0.98);
        border: 1px solid rgba(226, 232, 240, 0.95);
        box-shadow: 0 24px 58px rgba(15, 23, 42, 0.10);
        overflow: hidden;
    }

    .rental-profile-top {
        padding: 2rem;
        background:
            radial-gradient(circle at top right, rgba(14, 116, 144, 0.06), transparent 30%),
            linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
        border-bottom: 1px solid #e2e8f0;
    }

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

    .rental-profile-avatar {
        width: 176px;
        height: 176px;
        border-radius: 50%;
        object-fit: cover;
        cursor: pointer;
        border: 6px solid rgba(255, 255, 255, 0.95);
        box-shadow: 0 24px 48px rgba(15, 23, 42, 0.18);
        transition: transform 0.25s ease, box-shadow 0.25s ease;
    }

    .rental-profile-avatar:hover {
        transform: translateY(-3px);
        box-shadow: 0 30px 58px rgba(15, 23, 42, 0.22);
    }

    .rental-avatar-camera {
        position: absolute;
        right: 10px;
        bottom: 12px;
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: linear-gradient(135deg, #0f172a, #0e7490);
        color: #fff;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: 4px solid #fff;
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.18);
        pointer-events: none;
        font-size: 1rem;
    }

    .rental-upload-helper {
        color: #64748b;
        font-size: 0.92rem;
        margin-top: 1rem;
        margin-bottom: 0;
    }

    .rental-profile-name {
        color: #0f172a;
        font-weight: 950;
        font-size: clamp(1.65rem, 3vw, 2.2rem);
        margin-bottom: 0.35rem;
    }

    .rental-profile-subtitle {
        color: #64748b;
        line-height: 1.7;
        margin-bottom: 1rem;
    }

    .rental-inline-statuses {
        display: flex;
        flex-wrap: wrap;
        gap: 0.65rem;
    }

    .rental-status-pill {
        display: inline-flex;
        align-items: center;
        gap: 0.42rem;
        border-radius: 999px;
        padding: 0.48rem 0.86rem;
        font-size: 0.82rem;
        font-weight: 900;
    }

    .rental-status-pill.success {
        background: #dcfce7;
        color: #166534;
    }

    .rental-status-pill.warning {
        background: #fef3c7;
        color: #92400e;
    }

    .rental-status-pill.muted {
        background: #e2e8f0;
        color: #475569;
    }

    .rental-action-toolbar {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        margin-top: 1.5rem;
    }

    .rental-action-toolbar .btn {
        border-radius: 999px;
        font-weight: 850;
        padding: 0.72rem 1.15rem;
    }

    .rental-btn-primary {
        color: #fff;
        border: none;
        background: linear-gradient(135deg, #0f172a, #0e7490);
    }

    .rental-btn-primary:hover {
        color: #fff;
    }

    .rental-profile-body {
        padding: 2rem;
    }

    .rental-section-card {
        border-radius: 30px;
        border: 1px solid #e2e8f0;
        background: #ffffff;
        box-shadow: 0 16px 36px rgba(15, 23, 42, 0.06);
        overflow: hidden;
        margin-bottom: 1.5rem;
    }

    .rental-section-header {
        padding: 1.45rem 1.6rem 1rem;
        border-bottom: 1px solid #e2e8f0;
        background:
            radial-gradient(circle at top right, rgba(14, 116, 144, 0.05), transparent 28%),
            #ffffff;
    }

    .rental-section-kicker {
        display: inline-flex;
        align-items: center;
        gap: 0.45rem;
        color: #0e7490;
        font-size: 0.8rem;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.35rem;
    }

    .rental-section-header h3 {
        color: #0f172a;
        font-weight: 950;
        margin-bottom: 0.35rem;
    }

    .rental-section-header p {
        color: #64748b;
        line-height: 1.65;
        margin-bottom: 0;
    }

    .rental-section-body {
        padding: 1.6rem;
    }

    .rental-detail-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
    }

    .rental-detail-item {
        border-radius: 22px;
        border: 1px solid #e2e8f0;
        background: #f8fafc;
        padding: 1rem 1.05rem;
        min-height: 92px;
    }

    .rental-detail-item.full {
        grid-column: 1 / -1;
    }

    .rental-detail-label {
        display: block;
        color: #64748b;
        font-size: 0.8rem;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.045em;
        margin-bottom: 0.35rem;
    }

    .rental-detail-value {
        color: #0f172a;
        font-weight: 850;
        line-height: 1.6;
        word-break: break-word;
    }

    .rental-access-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 1rem;
    }

    .rental-access-box {
        border-radius: 22px;
        border: 1px solid #e2e8f0;
        background: #f8fafc;
        padding: 1.15rem;
    }

    .rental-access-box strong {
        display: block;
        color: #64748b;
        font-size: 0.8rem;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.045em;
        margin-bottom: 0.45rem;
    }

    .rental-access-value {
        color: #0f172a;
        font-weight: 950;
        font-size: 1rem;
    }

    .rental-banking-panel {
        border-radius: 28px;
        border: 1px solid #e2e8f0;
        background:
            radial-gradient(circle at top right, rgba(16, 185, 129, 0.08), transparent 30%),
            #f8fafc;
        padding: 1.25rem;
        height: 100%;
    }

    .rental-banking-side {
        border-radius: 28px;
        border: 1px solid #e2e8f0;
        background: #ffffff;
        padding: 1.25rem;
        height: 100%;
    }

    .rental-banking-side h6 {
        color: #0f172a;
        font-weight: 950;
    }

    .rental-banking-side p {
        color: #64748b;
        line-height: 1.68;
    }

    .rental-banking-side .btn {
        border-radius: 999px;
        font-weight: 850;
        min-height: 48px;
    }

    .rental-empty-note {
        color: #64748b;
        line-height: 1.72;
    }

    .rental-system-strip {
        border-radius: 28px;
        border: 1px dashed rgba(14, 116, 144, 0.28);
        background:
            radial-gradient(circle at top right, rgba(251, 191, 36, 0.08), transparent 30%),
            #f8fafc;
        padding: 1.3rem;
    }

    #uploadStatus .alert {
        border-radius: 18px;
        margin-bottom: 0;
    }

    /* Crop modal */
    .rental-crop-modal .modal-content {
        border-radius: 30px;
        overflow: hidden;
        border: none;
        box-shadow: 0 30px 70px rgba(15, 23, 42, 0.24);
    }

    .rental-crop-modal .modal-header {
        background: linear-gradient(135deg, #082f49, #0e7490);
        color: #fff;
        border-bottom: 0;
    }

    .rental-crop-modal .btn-close {
        filter: invert(1);
    }

    .rental-crop-modal .modal-footer {
        border-top: 1px solid #e2e8f0;
    }

    .rental-crop-modal .btn {
        border-radius: 999px;
        font-weight: 850;
    }

    @media (max-width: 991.98px) {
        .rental-profile-hero {
            padding: 2rem 1.5rem;
            border-radius: 32px;
        }

        .rental-detail-grid,
        .rental-access-grid {
            grid-template-columns: 1fr;
        }

        .rental-profile-top,
        .rental-profile-body {
            padding: 1.45rem;
        }
    }

    @media (max-width: 767.98px) {
        .rental-profile-page {
            padding-top: 2.5rem;
        }

        .rental-profile-avatar {
            width: 150px;
            height: 150px;
        }

        .rental-action-toolbar {
            flex-direction: column;
            align-items: stretch;
        }

        .rental-action-toolbar .btn {
            width: 100%;
        }
    }
</style>


<section class="rental-profile-page">
    <div class="container">

        <!-- =====================================================
             HERO
        ====================================================== -->
        <div class="rental-profile-hero">
            <div class="rental-profile-hero-inner">
                <span class="rental-profile-kicker">
                    <i class="bi bi-person-badge-fill"></i>
                    Rental Owner Account
                </span>

                <h1>My Rental Owner Profile</h1>

                <p>
                    Manage your personal account details, owner status, payout readiness,
                    profile image, username, and password from one premium profile center.
                </p>
            </div>
        </div>


        <!-- =====================================================
             PROFILE SHELL
        ====================================================== -->
        <div class="rental-profile-shell">

            <!-- TOP PROFILE STRIP -->
            <div class="rental-profile-top">
                <div class="row align-items-center g-4">

                    <div class="col-lg-3 text-center">
                        <div class="rental-avatar-wrap">
                            <img
                                id="profilePreview"
                                src="{% if owner.profile_image %}{{ owner.profile_image.url }}{% else %}{% static default_profile_image %}{% endif %}"
                                alt="Profile Image"
                                class="rental-profile-avatar"
                                title="Click to change profile image"
                            >

                            <div class="rental-avatar-camera">
                                <i class="bi bi-camera-fill"></i>
                            </div>

                            <input
                                type="file"
                                id="profileImageInput"
                                accept="image/jpeg,image/png,image/webp"
                                hidden
                            >
                        </div>

                        <p class="rental-upload-helper">
                            Click the image to upload a new profile photo.
                        </p>

                        <div id="uploadStatus" class="mt-3"></div>
                    </div>


                    <div class="col-lg-9">
                        <h2 class="rental-profile-name">
                            {{ owner.full_name }}
                        </h2>

                        <p class="rental-profile-subtitle">
                            {{ owner.get_owner_type_display }} Rental Owner
                            {% if owner.business_name %}
                                · {{ owner.business_name }}
                            {% endif %}
                        </p>

                        <div class="rental-inline-statuses">
                            {% if owner.is_identity_verified %}
                                <span class="rental-status-pill success">
                                    <i class="bi bi-patch-check-fill"></i>
                                    Identity Verified
                                </span>
                            {% else %}
                                <span class="rental-status-pill warning">
                                    <i class="bi bi-shield-exclamation"></i>
                                    Identity Pending
                                </span>
                            {% endif %}

                            {% if owner.is_approved %}
                                <span class="rental-status-pill success">
                                    <i class="bi bi-check-circle-fill"></i>
                                    Approved
                                </span>
                            {% else %}
                                <span class="rental-status-pill warning">
                                    <i class="bi bi-hourglass-split"></i>
                                    Approval Pending
                                </span>
                            {% endif %}

                            {% if owner.can_submit_listings %}
                                <span class="rental-status-pill success">
                                    <i class="bi bi-house-add-fill"></i>
                                    Can Submit Listings
                                </span>
                            {% else %}
                                <span class="rental-status-pill muted">
                                    <i class="bi bi-dash-circle-fill"></i>
                                    Listing Access Limited
                                </span>
                            {% endif %}
                        </div>

                        <div class="rental-action-toolbar">
                            <a href="{% url 'rental_app:edit_rental_owner_profile' %}"
                               class="btn rental-btn-primary">
                                <i class="bi bi-pencil-square me-2"></i>
                                Edit Profile
                            </a>

                            <a href="{% url 'rental_app:change_rental_owner_username' %}"
                               class="btn btn-outline-secondary">
                                <i class="bi bi-person-gear me-2"></i>
                                Change Username
                            </a>

                            <a href="{% url 'rental_app:change_rental_owner_password' %}"
                               class="btn btn-outline-dark">
                                <i class="bi bi-key-fill me-2"></i>
                                Change Password
                            </a>

                            <a href="{% url 'rental_app:rental_owner_banking_details' %}"
                               class="btn btn-outline-success">
                                <i class="bi bi-bank2 me-2"></i>
                                Banking Details
                            </a>
                        </div>
                    </div>

                </div>
            </div>


            <!-- PROFILE BODY -->
            <div class="rental-profile-body">

                <!-- PROFILE DETAILS -->
                <div class="rental-section-card">
                    <div class="rental-section-header">
                        <span class="rental-section-kicker">
                            <i class="bi bi-person-lines-fill"></i>
                            Profile Information
                        </span>

                        <h3>Profile Details</h3>

                        <p>
                            Core personal, contact, business, and property partner account information.
                        </p>
                    </div>

                    <div class="rental-section-body">
                        <div class="rental-detail-grid">

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">Username</span>
                                <div class="rental-detail-value">
                                    {{ request.user.username }}
                                </div>
                            </div>

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">Email</span>
                                <div class="rental-detail-value">
                                    {{ owner.email }}
                                </div>
                            </div>

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">Full Name</span>
                                <div class="rental-detail-value">
                                    {{ owner.full_name }}
                                </div>
                            </div>

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">Owner Type</span>
                                <div class="rental-detail-value">
                                    {{ owner.get_owner_type_display }}
                                </div>
                            </div>

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">Business Name</span>
                                <div class="rental-detail-value">
                                    {{ owner.business_name|default:"-" }}
                                </div>
                            </div>

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">City</span>
                                <div class="rental-detail-value">
                                    {{ owner.city|default:"-" }}
                                </div>
                            </div>

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">Phone Number</span>
                                <div class="rental-detail-value">
                                    {{ owner.phone_number|default:"-" }}
                                </div>
                            </div>

                            <div class="rental-detail-item">
                                <span class="rental-detail-label">WhatsApp</span>
                                <div class="rental-detail-value">
                                    {{ owner.whatsapp_number|default:"-" }}
                                </div>
                            </div>

                            <div class="rental-detail-item full">
                                <span class="rental-detail-label">Address</span>
                                <div class="rental-detail-value">
                                    {{ owner.address|default:"-" }}
                                </div>
                            </div>

                        </div>
                    </div>
                </div>


                <!-- ACCESS STATUS -->
                <div class="rental-section-card">
                    <div class="rental-section-header">
                        <span class="rental-section-kicker">
                            <i class="bi bi-shield-check"></i>
                            Owner Access
                        </span>

                        <h3>Approval & Listing Access</h3>

                        <p>
                            Review the status that controls profile trust, platform approval, and rental listing creation.
                        </p>
                    </div>

                    <div class="rental-section-body">
                        <div class="rental-access-grid">

                            <div class="rental-access-box">
                                <strong>Identity Verified</strong>
                                <div class="rental-access-value">
                                    {% if owner.is_identity_verified %}
                                        Yes
                                    {% else %}
                                        No
                                    {% endif %}
                                </div>
                            </div>

                            <div class="rental-access-box">
                                <strong>Approved</strong>
                                <div class="rental-access-value">
                                    {% if owner.is_approved %}
                                        Yes
                                    {% else %}
                                        No
                                    {% endif %}
                                </div>
                            </div>

                            <div class="rental-access-box">
                                <strong>Can Submit Listings</strong>
                                <div class="rental-access-value">
                                    {% if owner.can_submit_listings %}
                                        Yes
                                    {% else %}
                                        No
                                    {% endif %}
                                </div>
                            </div>

                        </div>
                    </div>
                </div>


                <!-- BANKING & PAYOUT -->
                <div class="rental-section-card">
                    <div class="rental-section-header">
                        <span class="rental-section-kicker">
                            <i class="bi bi-bank2"></i>
                            Payment Readiness
                        </span>

                        <h3>Banking & Payout Details</h3>

                        <p>
                            Keep payout details ready so rental-owner payments can be processed smoothly.
                        </p>
                    </div>

                    <div class="rental-section-body">
                        <div class="row g-4 align-items-stretch">

                            <div class="col-lg-8">
                                <div class="rental-banking-panel">
                                    {% if owner.banking_details %}
                                        <div class="rental-detail-grid">

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">Account Holder</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.account_holder_name|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">Bank Name</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.bank_name|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">Branch Name</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.branch_name|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">Bank Country</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.bank_country|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">Account Number</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.account_number|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">SWIFT Code</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.swift_code|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">IBAN</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.iban|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item">
                                                <span class="rental-detail-label">Verified</span>
                                                <div class="rental-detail-value">
                                                    {% if owner.banking_details.is_verified %}
                                                        Yes
                                                    {% else %}
                                                        No
                                                    {% endif %}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item full">
                                                <span class="rental-detail-label">Bank Address</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.bank_address|default:"-" }}
                                                </div>
                                            </div>

                                            <div class="rental-detail-item full">
                                                <span class="rental-detail-label">Payment Notes</span>
                                                <div class="rental-detail-value">
                                                    {{ owner.banking_details.payment_notes|default:"-" }}
                                                </div>
                                            </div>

                                        </div>
                                    {% else %}
                                        <div class="rental-empty-note">
                                            <p class="mb-2 fw-bold text-dark">
                                                No banking details added yet.
                                            </p>

                                            <p class="mb-0">
                                                Add your banking details so rental payments can be transferred
                                                after any applicable commission deductions.
                                            </p>
                                        </div>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <div class="rental-banking-side">
                                    <h6 class="mb-2">
                                        Payout Setup
                                    </h6>

                                    <p class="small mb-4">
                                        Keep your banking information updated to receive rental payouts smoothly
                                        and avoid unnecessary payment delays.
                                    </p>

                                    <a href="{% url 'rental_app:rental_owner_banking_details' %}"
                                       class="btn btn-success w-100">
                                        {% if owner.banking_details %}
                                            Update Banking Details
                                        {% else %}
                                            Add Banking Details
                                        {% endif %}
                                    </a>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>


                <!-- SYSTEM INFO -->
                <div class="rental-system-strip">
                    <div class="rental-detail-grid">

                        <div class="rental-detail-item">
                            <span class="rental-detail-label">Created At</span>
                            <div class="rental-detail-value">
                                {{ owner.created_at }}
                            </div>
                        </div>

                        <div class="rental-detail-item">
                            <span class="rental-detail-label">Linked Account</span>
                            <div class="rental-detail-value">
                                {% if owner.user %}
                                    {{ owner.user.username }}
                                {% else %}
                                    -
                                {% endif %}
                            </div>
                        </div>

                    </div>
                </div>

            </div>
        </div>

    </div>
</section>


<!-- =====================================================
     CROP IMAGE MODAL
====================================================== -->
<div class="modal fade rental-crop-modal"
     id="cropImageModal"
     tabindex="-1"
     aria-labelledby="cropImageModalLabel"
     aria-hidden="true">

    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title" id="cropImageModalLabel">
                    Adjust Profile Image
                </h5>

                <button type="button"
                        class="btn-close"
                        data-bs-dismiss="modal"
                        aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div style="width: 100%; max-height: 500px; overflow: hidden;">
                    <img id="cropperImage"
                         src=""
                         alt="Crop Image"
                         style="max-width: 100%; display: block;">
                </div>
            </div>

            <div class="modal-footer">
                <button type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal">
                    Cancel
                </button>

                <button type="button"
                        id="cropAndUploadBtn"
                        class="btn btn-primary">
                    Crop & Upload
                </button>
            </div>

        </div>
    </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', function () {
    const preview = document.getElementById('profilePreview');
    const input = document.getElementById('profileImageInput');
    const statusBox = document.getElementById('uploadStatus');

    const cropModalEl = document.getElementById('cropImageModal');
    const cropImage = document.getElementById('cropperImage');
    const cropAndUploadBtn = document.getElementById('cropAndUploadBtn');

    let cropper = null;
    let selectedFile = null;
    const cropModal = new bootstrap.Modal(cropModalEl);

    preview.addEventListener('click', function () {
        input.click();
    });

    input.addEventListener('change', function () {
        const file = this.files[0];
        if (!file) return;

        const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (!allowedTypes.includes(file.type)) {
            statusBox.innerHTML = '<div class="alert alert-danger py-2">Only JPG, PNG, or WEBP images are allowed.</div>';
            input.value = '';
            return;
        }

        if (file.size > 2 * 1024 * 1024) {
            statusBox.innerHTML = '<div class="alert alert-warning py-2">Large image detected. It will be optimized after cropping.</div>';
        } else {
            statusBox.innerHTML = '';
        }

        selectedFile = file;

        const reader = new FileReader();
        reader.onload = function (e) {
            cropImage.src = e.target.result;
            cropModal.show();
        };
        reader.readAsDataURL(file);
    });

    cropModalEl.addEventListener('shown.bs.modal', function () {
        if (cropper) {
            cropper.destroy();
        }

        cropper = new Cropper(cropImage, {
            aspectRatio: 1,
            viewMode: 1,
            dragMode: 'move',
            autoCropArea: 1,
            responsive: true,
            background: false,
            movable: true,
            zoomable: true,
            rotatable: false,
            scalable: false,
            cropBoxMovable: true,
            cropBoxResizable: true,
        });
    });

    cropModalEl.addEventListener('hidden.bs.modal', function () {
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
    });

    cropAndUploadBtn.addEventListener('click', function () {
        if (!cropper) {
            statusBox.innerHTML = '<div class="alert alert-danger py-2">Cropper is not ready.</div>';
            return;
        }

        statusBox.innerHTML = '<div class="alert alert-info py-2">Processing image...</div>';

        const canvas = cropper.getCroppedCanvas({
            width: 600,
            height: 600,
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high'
        });

        if (!canvas) {
            statusBox.innerHTML = '<div class="alert alert-danger py-2">Could not crop image.</div>';
            return;
        }

        canvas.toBlob(function(blob) {
            if (!blob) {
                statusBox.innerHTML = '<div class="alert alert-danger py-2">Failed to create cropped image.</div>';
                return;
            }

            const fileName = selectedFile ? selectedFile.name : 'profile.jpg';
            const croppedFile = new File([blob], fileName, { type: 'image/jpeg' });

            const formData = new FormData();
            formData.append('profile_image', croppedFile);
            formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

            fetch("{% url 'rental_app:upload_rental_owner_profile_image' %}", {
                method: 'POST',
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    preview.src = data.image_url + '?t=' + new Date().getTime();
                    statusBox.innerHTML = '<div class="alert alert-success py-2">' + data.message + '</div>';
                    cropModal.hide();
                    input.value = '';
                } else {
                    statusBox.innerHTML = '<div class="alert alert-danger py-2">' + (data.error || 'Upload failed.') + '</div>';
                }
            })
            .catch(() => {
                statusBox.innerHTML = '<div class="alert alert-danger py-2">Something went wrong while uploading.</div>';
            });

        }, 'image/jpeg', 0.85);
    });
});
</script>

{% endblock %}