{% extends 'expat_life/base.html' %}
{% load static %}

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

{% block content %}

<style>
    /* =========================================================
       MY PROFILE PAGE - PREMIUM LIVE IN SRI LANKA THEME
    ========================================================= */

    :root {
        --lis-deep: #07131c;
        --lis-navy: #0b2638;
        --lis-blue: #0d6efd;
        --lis-blue-dark: #0b3d91;
        --lis-teal: #0f766e;
        --lis-teal-bright: #20c997;
        --lis-gold: #ffc107;
        --lis-gold-light: #ffd45f;
        --lis-soft-blue: #f5f9ff;
        --lis-sand: #fff8ed;
        --lis-white: #ffffff;
        --lis-text: #102033;
        --lis-muted: #64748b;
        --lis-border: rgba(15, 42, 64, 0.10);
        --lis-shadow: 0 18px 45px rgba(15, 23, 42, 0.08);
        --lis-shadow-strong: 0 28px 70px rgba(15, 23, 42, 0.16);
    }

    .profile-page-section {
        position: relative;
        overflow: hidden;
        min-height: 88vh;
        background:
            radial-gradient(circle at 10% 12%, rgba(255, 193, 7, 0.13), transparent 28%),
            radial-gradient(circle at 88% 14%, rgba(13, 110, 253, 0.10), transparent 30%),
            radial-gradient(circle at 82% 86%, rgba(15, 118, 110, 0.12), transparent 32%),
            linear-gradient(180deg, #f5f9ff 0%, #ffffff 100%);
        padding: 90px 0;
    }

    .profile-page-section::before {
        content: "";
        position: absolute;
        width: 420px;
        height: 420px;
        right: -190px;
        top: -190px;
        border-radius: 50%;
        background: rgba(255, 193, 7, 0.12);
        pointer-events: none;
    }

    .profile-page-section::after {
        content: "";
        position: absolute;
        width: 360px;
        height: 360px;
        left: -170px;
        bottom: -180px;
        border-radius: 50%;
        background: rgba(13, 110, 253, 0.08);
        pointer-events: none;
    }

    .profile-page-wrap {
        position: relative;
        z-index: 2;
    }

    .profile-main-card {
        position: relative;
        overflow: hidden;
        border: 1px solid rgba(15, 42, 64, 0.08);
        border-radius: 36px;
        background:
            radial-gradient(circle at 92% 8%, rgba(255, 193, 7, 0.14), transparent 32%),
            linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
        box-shadow: var(--lis-shadow-strong);
    }

    .profile-main-card::before {
        content: "";
        position: absolute;
        inset: 0 0 auto 0;
        height: 6px;
        background: linear-gradient(90deg, var(--lis-gold), var(--lis-teal), var(--lis-blue));
        z-index: 2;
    }

    .profile-main-card::after {
        content: "";
        position: absolute;
        width: 260px;
        height: 260px;
        right: -130px;
        bottom: -130px;
        border-radius: 50%;
        background: rgba(15, 118, 110, 0.08);
        pointer-events: none;
    }

    .profile-main-card-body {
        position: relative;
        z-index: 3;
        padding: 3rem;
    }

    .profile-hero {
        text-align: center;
        margin-bottom: 2.4rem;
    }

    .profile-image-shell {
        position: relative;
        display: inline-block;
        padding: 9px;
        border-radius: 50%;
        background:
            linear-gradient(135deg, rgba(255, 193, 7, 0.95), rgba(15, 118, 110, 0.75), rgba(13, 110, 253, 0.75));
        box-shadow:
            0 20px 44px rgba(15, 23, 42, 0.16),
            0 0 0 12px rgba(255, 193, 7, 0.08);
    }

    .profile-image-shell::after {
        content: "\F4DA";
        font-family: "bootstrap-icons";
        position: absolute;
        right: 10px;
        bottom: 13px;
        width: 42px;
        height: 42px;
        border-radius: 50%;
        background: linear-gradient(135deg, var(--lis-deep), var(--lis-blue));
        color: #ffffff;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 1.05rem;
        border: 3px solid #ffffff;
        box-shadow: 0 10px 22px rgba(13, 110, 253, 0.24);
        pointer-events: none;
    }

    .profile-preview-image {
        width: 160px;
        height: 160px;
        object-fit: cover;
        cursor: pointer;
        border-radius: 50%;
        border: 5px solid #ffffff;
        box-shadow: 0 14px 30px rgba(15, 23, 42, 0.16);
        transition: all 0.24s ease;
    }

    .profile-preview-image:hover {
        transform: scale(1.025);
        filter: brightness(1.03);
    }

    .profile-upload-hint {
        margin-top: 1rem;
        color: var(--lis-muted);
        font-size: 0.9rem;
        line-height: 1.6;
    }

    .profile-upload-hint i {
        color: var(--lis-teal);
    }

    .section-mini-title {
        display: inline-flex;
        align-items: center;
        gap: 0.45rem;
        padding: 7px 15px;
        border-radius: 999px;
        background: rgba(15, 118, 110, 0.09);
        border: 1px solid rgba(15, 118, 110, 0.14);
        color: var(--lis-teal);
        font-size: 0.78rem;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.075em;
        margin-bottom: 14px;
    }

    .section-mini-title::before {
        content: "";
        width: 7px;
        height: 7px;
        border-radius: 50%;
        background: var(--lis-gold);
        box-shadow: 0 0 0 5px rgba(255, 193, 7, 0.14);
    }

    .profile-title {
        color: var(--lis-text);
        font-weight: 950;
        letter-spacing: -0.035em;
        line-height: 1.12;
        font-size: clamp(2rem, 3.4vw, 2.9rem);
        margin-bottom: 0.65rem;
    }

    .profile-subtitle {
        max-width: 720px;
        margin: 0 auto;
        color: var(--lis-muted);
        line-height: 1.75;
    }

    .profile-action-row {
        display: flex;
        flex-wrap: wrap;
        gap: 0.85rem;
        justify-content: center;
        margin-bottom: 2.3rem;
    }

    .profile-action-row .btn {
        border-radius: 999px;
        padding: 0.82rem 1.45rem;
        font-weight: 850;
        letter-spacing: 0.01em;
        transition: all 0.22s ease;
    }

    .btn-profile-primary {
        background: linear-gradient(135deg, var(--lis-deep), var(--lis-blue));
        border: none;
        color: #ffffff;
        box-shadow: 0 16px 32px rgba(13, 110, 253, 0.20);
    }

    .btn-profile-primary:hover {
        background: linear-gradient(135deg, var(--lis-deep), var(--lis-teal));
        color: #ffffff;
        transform: translateY(-2px);
        box-shadow: 0 20px 38px rgba(15, 118, 110, 0.24);
    }

    .btn-profile-outline {
        color: var(--lis-deep);
        border: 1px solid rgba(7, 19, 28, 0.20);
        background: #ffffff;
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.06);
    }

    .btn-profile-outline:hover {
        background: var(--lis-deep);
        border-color: var(--lis-deep);
        color: #ffffff;
        transform: translateY(-2px);
    }

    .profile-divider {
        border-color: rgba(15, 42, 64, 0.10);
        opacity: 1;
        margin: 2rem 0;
    }

    .profile-section-heading {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 1.3rem;
    }

    .profile-section-icon {
        width: 44px;
        height: 44px;
        border-radius: 16px;
        background:
            linear-gradient(135deg, rgba(255, 193, 7, 0.20), rgba(15, 118, 110, 0.10));
        color: var(--lis-teal);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 1.15rem;
        flex-shrink: 0;
        box-shadow: 0 12px 24px rgba(15, 118, 110, 0.08);
    }

    .profile-section-heading h4,
    .profile-section-heading h5 {
        color: var(--lis-text);
        font-weight: 950;
        letter-spacing: -0.025em;
        margin-bottom: 0;
    }

    .profile-detail-grid {
        margin-top: 0.5rem;
    }

    .profile-detail-item {
        height: 100%;
        padding: 1rem 1.05rem;
        border-radius: 20px;
        background:
            radial-gradient(circle at 92% 10%, rgba(255, 193, 7, 0.08), transparent 30%),
            linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
        border: 1px solid rgba(15, 42, 64, 0.08);
        box-shadow: 0 12px 26px rgba(15, 23, 42, 0.045);
    }

    .profile-detail-label {
        display: block;
        color: var(--lis-muted);
        font-size: 0.78rem;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.055em;
        margin-bottom: 0.35rem;
    }

    .profile-detail-value {
        color: var(--lis-text);
        font-weight: 750;
        line-height: 1.55;
        word-break: break-word;
    }

    .profile-message-box {
        padding: 1.1rem 1.2rem;
        border-radius: 22px;
        background:
            linear-gradient(135deg, rgba(255, 193, 7, 0.11), rgba(15, 118, 110, 0.06));
        border: 1px solid rgba(255, 193, 7, 0.18);
        color: #475569;
        line-height: 1.7;
    }

    .profile-status-pill {
        display: inline-flex;
        align-items: center;
        gap: 0.42rem;
        padding: 0.42rem 0.78rem;
        border-radius: 999px;
        font-size: 0.82rem;
        font-weight: 900;
        border: 1px solid transparent;
    }

    .profile-status-pill.success {
        background: rgba(15, 118, 110, 0.09);
        color: var(--lis-teal);
        border-color: rgba(15, 118, 110, 0.14);
    }

    .profile-status-pill.warning {
        background: rgba(255, 193, 7, 0.14);
        color: #8a5a00;
        border-color: rgba(255, 193, 7, 0.22);
    }

    .profile-permission-card {
        height: 100%;
        position: relative;
        overflow: hidden;
        padding: 1.2rem;
        border-radius: 24px;
        border: 1px solid rgba(15, 42, 64, 0.08);
        background:
            radial-gradient(circle at 92% 10%, rgba(13, 110, 253, 0.08), transparent 32%),
            linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
        box-shadow: var(--lis-shadow);
    }

    .profile-permission-card::before {
        content: "";
        position: absolute;
        inset: 0 0 auto 0;
        height: 4px;
        background: linear-gradient(90deg, var(--lis-gold), var(--lis-teal), var(--lis-blue));
    }

    .profile-permission-card > * {
        position: relative;
        z-index: 2;
    }

    .profile-permission-title {
        display: block;
        color: var(--lis-text);
        font-weight: 950;
        letter-spacing: -0.015em;
        margin-bottom: 0.75rem;
        line-height: 1.35;
    }

    .profile-activity-box {
        position: relative;
        overflow: hidden;
        padding: 1.3rem 1.4rem;
        border-radius: 24px;
        background:
            radial-gradient(circle at 92% 10%, rgba(255, 193, 7, 0.13), transparent 34%),
            linear-gradient(135deg, #fff8ed 0%, #ffffff 100%);
        border: 1px solid rgba(255, 193, 7, 0.20);
        color: var(--lis-muted);
        line-height: 1.7;
    }

    .profile-activity-box strong {
        color: var(--lis-text);
    }

    .profile-activity-box i {
        color: #8a5a00;
    }

    #uploadStatus .alert {
        border-radius: 16px;
        border: none;
        font-weight: 700;
        max-width: 520px;
        margin-left: auto;
        margin-right: auto;
    }

    #uploadStatus .alert-success {
        background: rgba(15, 118, 110, 0.10);
        color: var(--lis-teal);
    }

    #uploadStatus .alert-info {
        background: rgba(13, 110, 253, 0.10);
        color: var(--lis-blue-dark);
    }

    #uploadStatus .alert-danger {
        background: rgba(180, 35, 24, 0.08);
        color: #b42318;
    }

    /* =========================================================
       CROP MODAL - PREMIUM TOUCH
    ========================================================= */

    .profile-crop-modal .modal-content {
        border: 0;
        border-radius: 28px;
        overflow: hidden;
        box-shadow: 0 30px 80px rgba(15, 23, 42, 0.24);
        background:
            radial-gradient(circle at 92% 8%, rgba(255, 193, 7, 0.12), transparent 32%),
            linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
    }

    .profile-crop-modal .modal-header {
        border-bottom: 1px solid rgba(15, 42, 64, 0.08);
        padding: 1.25rem 1.4rem;
    }

    .profile-crop-modal .modal-title {
        color: var(--lis-text);
        font-weight: 950;
        letter-spacing: -0.02em;
    }

    .profile-crop-modal .modal-body {
        padding: 1.4rem;
    }

    .profile-crop-area {
        width: 100%;
        max-height: 500px;
        overflow: hidden;
        border-radius: 22px;
        background: #f8fbff;
        border: 1px solid rgba(15, 42, 64, 0.08);
    }

    .profile-crop-modal .modal-footer {
        border-top: 1px solid rgba(15, 42, 64, 0.08);
        padding: 1.1rem 1.4rem;
    }

    .profile-crop-modal .btn {
        border-radius: 999px;
        font-weight: 850;
        padding: 0.75rem 1.35rem;
    }

    .profile-crop-modal .btn-secondary {
        background: #ffffff;
        color: var(--lis-deep);
        border: 1px solid rgba(7, 19, 28, 0.20);
    }

    .profile-crop-modal .btn-secondary:hover {
        background: var(--lis-deep);
        border-color: var(--lis-deep);
        color: #ffffff;
    }

    .profile-crop-modal .btn-primary {
        background: linear-gradient(135deg, var(--lis-deep), var(--lis-blue));
        border: none;
        box-shadow: 0 14px 28px rgba(13, 110, 253, 0.18);
    }

    .profile-crop-modal .btn-primary:hover {
        background: linear-gradient(135deg, var(--lis-deep), var(--lis-teal));
    }

    @media (max-width: 767.98px) {
        .profile-page-section {
            padding: 60px 0;
            min-height: auto;
        }

        .profile-main-card {
            border-radius: 28px;
        }

        .profile-main-card-body {
            padding: 2rem 1.35rem;
        }

        .profile-preview-image {
            width: 138px;
            height: 138px;
        }

        .profile-action-row {
            flex-direction: column;
        }

        .profile-action-row .btn {
            width: 100%;
        }

        .profile-section-heading {
            align-items: flex-start;
        }
    }
</style>

<section class="profile-page-section">
    <div class="container profile-page-wrap">
        <div class="row justify-content-center">
            <div class="col-lg-10">

                <div class="profile-main-card">
                    <div class="profile-main-card-body">

                        <div class="profile-hero">
                            <div class="profile-image-shell">
                                <img
                                    id="profilePreview"
                                    src="{% if profile.profile_image %}{{ profile.profile_image.url }}{% else %}{% static default_profile_image %}{% endif %}"
                                    alt="Profile Image"
                                    class="profile-preview-image"
                                    title="Click to change profile image"
                                >
                                <input type="file" id="profileImageInput" accept=".jpg,.jpeg,.png,.webp" hidden>
                            </div>

                            <p class="profile-upload-hint mb-0">
                                <i class="bi bi-camera-fill me-1"></i>
                                Click the image to upload a new profile photo
                            </p>

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

                            <div class="mt-4">
                                <span class="section-mini-title">Guest Profile</span>
                                <h1 class="profile-title">My Profile</h1>
                                <p class="profile-subtitle">
                                    Manage your Live in Sri Lanka account details, profile image, access permissions,
                                    and guest information in one secure place.
                                </p>
                            </div>
                        </div>

                        <div class="profile-action-row">
                            <a href="{% url 'expat_life:edit_foreigner_profile' %}" class="btn btn-profile-primary">
                                <i class="bi bi-pencil-square me-2"></i>
                                Edit Profile
                            </a>

                            <a href="{% url 'expat_life:change_foreigner_username' %}" class="btn btn-profile-outline">
                                <i class="bi bi-person-badge me-2"></i>
                                Change Username
                            </a>

                            <a href="{% url 'expat_life:change_foreigner_password' %}" class="btn btn-profile-outline">
                                <i class="bi bi-shield-lock me-2"></i>
                                Change Password
                            </a>
                        </div>

                        <hr class="profile-divider">

                        <div class="profile-section-heading">
                            <div class="profile-section-icon">
                                <i class="bi bi-person-lines-fill"></i>
                            </div>
                            <div>
                                <h4>Profile Details</h4>
                            </div>
                        </div>

                        <div class="row g-3 profile-detail-grid">
                            <div class="col-md-6">
                                <div class="profile-detail-item">
                                    <span class="profile-detail-label">Username</span>
                                    <div class="profile-detail-value">{{ request.user.username }}</div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="profile-detail-item">
                                    <span class="profile-detail-label">Email</span>
                                    <div class="profile-detail-value">{{ request.user.email }}</div>
                                </div>
                            </div>

                            {% if lead %}
                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Full Name</span>
                                        <div class="profile-detail-value">{{ lead.full_name }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">WhatsApp</span>
                                        <div class="profile-detail-value">{{ lead.whatsapp_number|default:"-" }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Country</span>
                                        <div class="profile-detail-value">{{ lead.country }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Nationality</span>
                                        <div class="profile-detail-value">{{ lead.nationality|default:"-" }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Gender</span>
                                        <div class="profile-detail-value">{{ lead.get_gender_display|default:"-" }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Expected Arrival Date</span>
                                        <div class="profile-detail-value">{{ lead.expected_arrival_date|default:"-" }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Duration of Stay</span>
                                        <div class="profile-detail-value">{{ lead.duration_of_stay|default:"-" }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Monthly Budget</span>
                                        <div class="profile-detail-value">{{ lead.get_monthly_budget_display }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="profile-detail-item">
                                        <span class="profile-detail-label">Remote Worker</span>
                                        <div class="profile-detail-value">
                                            {% if lead.remote_worker %}
                                                <span class="profile-status-pill success">
                                                    <i class="bi bi-check-circle"></i>
                                                    Yes
                                                </span>
                                            {% else %}
                                                <span class="profile-status-pill warning">
                                                    <i class="bi bi-dash-circle"></i>
                                                    No
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>

                                <div class="col-12">
                                    <div class="profile-message-box">
                                        <span class="profile-detail-label">Message</span>
                                        {{ lead.message|default:"-" }}
                                    </div>
                                </div>
                            {% endif %}

                            <div class="col-md-6">
                                <div class="profile-detail-item">
                                    <span class="profile-detail-label">Confirmed</span>
                                    <div class="profile-detail-value">
                                        {% if profile.is_confirmed %}
                                            <span class="profile-status-pill success">
                                                <i class="bi bi-check-circle"></i>
                                                Yes
                                            </span>
                                        {% else %}
                                            <span class="profile-status-pill warning">
                                                <i class="bi bi-clock-history"></i>
                                                Pending
                                            </span>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="profile-detail-item">
                                    <span class="profile-detail-label">Joined At</span>
                                    <div class="profile-detail-value">{{ profile.joined_at }}</div>
                                </div>
                            </div>
                        </div>

                        <hr class="profile-divider">

                        <div class="profile-section-heading">
                            <div class="profile-section-icon">
                                <i class="bi bi-shield-check"></i>
                            </div>
                            <div>
                                <h5>Access & Permissions</h5>
                            </div>
                        </div>

                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="profile-permission-card">
                                    <span class="profile-permission-title">Can View Private Listings</span>
                                    {% if profile.can_view_private_listings %}
                                        <span class="profile-status-pill success">
                                            <i class="bi bi-check-circle"></i>
                                            Yes
                                        </span>
                                    {% else %}
                                        <span class="profile-status-pill warning">
                                            <i class="bi bi-lock"></i>
                                            No
                                        </span>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="profile-permission-card">
                                    <span class="profile-permission-title">Can Book Arrangements</span>
                                    {% if profile.can_book_arrangements %}
                                        <span class="profile-status-pill success">
                                            <i class="bi bi-check-circle"></i>
                                            Yes
                                        </span>
                                    {% else %}
                                        <span class="profile-status-pill warning">
                                            <i class="bi bi-lock"></i>
                                            No
                                        </span>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="profile-permission-card">
                                    <span class="profile-permission-title">Account Status</span>
                                    {% if profile.is_confirmed %}
                                        <span class="profile-status-pill success">
                                            <i class="bi bi-check-circle"></i>
                                            Active
                                        </span>
                                    {% else %}
                                        <span class="profile-status-pill warning">
                                            <i class="bi bi-clock-history"></i>
                                            Pending Review
                                        </span>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <hr class="profile-divider">

                        <div class="profile-section-heading">
                            <div class="profile-section-icon">
                                <i class="bi bi-credit-card"></i>
                            </div>
                            <div>
                                <h5>Payments & Related Activity</h5>
                            </div>
                        </div>

                        <div class="profile-activity-box">
                            <p class="mb-0">
                                <i class="bi bi-info-circle me-2"></i>
                                <strong>Coming next:</strong>
                                Here you can later show consultation payments, confirmation payments, package orders,
                                and related history.
                            </p>
                        </div>

                    </div>
                </div>

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

<!-- Crop Area -->
<div class="modal fade profile-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">
                    <i class="bi bi-crop me-2"></i>
                    Adjust Profile Image
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div class="profile-crop-area">
                    <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">
                    <i class="bi bi-x-circle me-2"></i>
                    Cancel
                </button>

                <button type="button" id="cropAndUploadBtn" class="btn btn-primary">
                    <i class="bi bi-cloud-arrow-up me-2"></i>
                    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;
        }

        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 formData = new FormData();
            formData.append('profile_image', blob, 'profile.jpg');
            formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

            fetch("{% url 'expat_life:upload_foreigner_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(function(error) {
                console.error(error);
                statusBox.innerHTML = '<div class="alert alert-danger py-2">Something went wrong while uploading.</div>';
            });

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

{% endblock %}