{% extends 'affiliates_app/base_affiliate.html' %}
{% load static %}

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

{% block content %}
<style>
    .affiliate-profile-section {
        background:
            radial-gradient(circle at top left, rgba(25, 135, 84, 0.12), transparent 28%),
            radial-gradient(circle at bottom right, rgba(13, 110, 253, 0.08), transparent 30%),
            linear-gradient(135deg, #f8fafc 0%, #eefaf4 100%);
        min-height: 100vh;
    }
    .profile-image-box img {
        width: 160px;
        height: 160px;
        object-fit: cover;
        cursor: pointer;
    }

    .affiliate-section-title {
        font-weight: 700;
        color: #064e3b;
        margin-bottom: 1rem;
    }

    .profile-detail-item {
        margin-bottom: 1rem;
        word-break: break-word;
    }

    .profile-detail-item strong {
        color: #111827;
        font-weight: 700;
    }

    .profile-detail-value {
        color: #374151;
        margin-top: 0.15rem;
    }

    .status-badge {
        display: inline-block;
        border-radius: 50rem;
        padding: 0.4rem 0.8rem;
        font-size: 0.85rem;
        font-weight: 600;
    }

    .status-approved {
        background: #dcfce7;
        color: #166534;
    }

    .status-pending {
        background: #fef3c7;
        color: #92400e;
    }

    .status-rejected {
        background: #fee2e2;
        color: #991b1b;
    }

    .status-inactive {
        background: #e5e7eb;
        color: #374151;
    }

    .earnings-summary-box {
        border: 1px solid #e5e7eb;
        background: #f9fafb;
        border-radius: 1rem;
        padding: 1rem;
        height: 100%;
        text-align: center;
    }

    .earnings-summary-box strong {
        display: block;
        color: #374151;
        margin-bottom: 0.35rem;
    }

    .earnings-summary-box span {
        display: block;
        font-size: 1.5rem;
        font-weight: 800;
        color: #047857;
    }

    .affiliate-code-box {
        display: inline-block;
        background: #f3f4f6;
        border: 1px solid #e5e7eb;
        border-radius: 0.5rem;
        padding: 0.45rem 0.7rem;
        font-weight: 700;
        color: #064e3b;
    }

    .affiliate-link-input {
        border-radius: 0.75rem;
    }

    .copy-btn {
        border-radius: 0.75rem;
    }

    #uploadStatus .alert {
        display: inline-block;
        padding: 0.45rem 0.8rem;
        font-size: 0.85rem;
        margin-bottom: 0;
    }

    @media (max-width: 575.98px) {
        .card-body {
            padding: 1.25rem !important;
        }

        .profile-image-box img {
            width: 135px;
            height: 135px;
        }

        .profile-actions .btn {
            width: 100%;
        }

        .earnings-summary-box span {
            font-size: 1.25rem;
        }

        .input-group.affiliate-link-group {
            display: block;
        }

        .input-group.affiliate-link-group .form-control {
            width: 100%;
            margin-bottom: 0.5rem;
        }

        .input-group.affiliate-link-group .btn {
            width: 100%;
            border-radius: 0.75rem !important;
        }
    }

    .affiliate-profile-card {
        border-radius: 28px;
        overflow: hidden;
        background: #ffffff;
        box-shadow: 0 20px 55px rgba(15, 23, 42, 0.10);
    }

    .affiliate-profile-header {
        background: linear-gradient(135deg, #064e3b 0%, #047857 58%, #0f766e 100%);
        padding: 2rem 2.2rem;
        color: #ffffff;
        position: relative;
        overflow: hidden;
    }

    .affiliate-profile-header::after {
        content: "";
        position: absolute;
        width: 210px;
        height: 210px;
        border-radius: 50%;
        right: -80px;
        top: -80px;
        background: rgba(255, 255, 255, 0.12);
    }

    .affiliate-profile-header-content {
        position: relative;
        z-index: 2;
    }

    .affiliate-profile-kicker {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        background: rgba(255, 255, 255, 0.15);
        border: 1px solid rgba(255, 255, 255, 0.18);
        color: rgba(255, 255, 255, 0.92);
        padding: 7px 13px;
        border-radius: 50rem;
        font-size: 0.82rem;
        font-weight: 700;
        margin-bottom: 0.9rem;
    }

    .affiliate-profile-header h2 {
        font-weight: 800;
        letter-spacing: -0.03em;
        margin-bottom: 0.45rem;
    }

    .affiliate-profile-header p {
        margin-bottom: 0;
        color: rgba(255, 255, 255, 0.82);
    }
</style>

<section class="affiliate-profile-section py-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-10">

                <div class="card border-0 affiliate-profile-card">
                    <div class="affiliate-profile-header">
                        <div class="affiliate-profile-header-content">
                            <span class="affiliate-profile-kicker">
                                <i class="bi bi-person-badge-fill"></i>
                                Affiliate Partner Account
                            </span>
                            <h2>My Affiliate Profile</h2>
                            <p>View your personal details, payout information, affiliate tools, and earnings summary.</p>
                        </div>
                    </div>
                    <div class="card-body p-4 p-lg-5">

                        <!-- Profile Image -->
                        <div class="text-center mb-4">
                            <div class="position-relative d-inline-block profile-image-box">
                                <img
                                    id="profilePreview"
                                    src="{% if profile.profile_photo %}{{ profile.profile_photo.url }}{% else %}{% static 'expat_life/images/default-profile-neutral.png' %}{% endif %}"
                                    alt="Profile Photo"
                                    class="rounded-circle border shadow-sm"
                                    style="width: 160px; height: 160px; object-fit: cover; cursor: pointer;"
                                    title="Click to change profile image"
                                >
                                <input type="file" id="profileImageInput" accept=".jpg,.jpeg,.png,.webp" hidden>
                            </div>

                            <h4 class="fw-bold mt-3 mb-1">
                                {{ profile.full_name|default:user.username }}
                            </h4>

                            <p class="mt-2 text-muted small mb-0">
                                Click the image to upload a new profile photo
                            </p>

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

                        <!-- Actions -->
                        <div class="d-flex flex-wrap gap-2 justify-content-center profile-actions mb-4">
                            <a href="{% url 'affiliates_app:affiliate_edit_profile' %}" class="btn btn-primary">
                                <i class="bi bi-pencil-square me-1"></i> Edit Profile
                            </a>

                            <a href="{% url 'affiliates_app:affiliate_change_username' %}" class="btn btn-outline-secondary">
                                <i class="bi bi-person-circle me-1"></i> Change Username
                            </a>

                            <a href="{% url 'affiliates_app:affiliate_change_password' %}" class="btn btn-outline-dark">
                                <i class="bi bi-key me-1"></i> Change Password
                            </a>
                        </div>

                        <hr>

                        <!-- Profile Details -->
                        <h4 class="affiliate-section-title">Profile Details</h4>

                        <div class="row g-3">
                            <div class="col-md-6 profile-detail-item">
                                <strong>Username:</strong><br>
                                <div class="profile-detail-value">{{ user.username }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Email:</strong><br>
                                <div class="profile-detail-value">{{ user.email }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Full Name:</strong><br>
                                <div class="profile-detail-value">{{ profile.full_name }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Phone Number:</strong><br>
                                <div class="profile-detail-value">{{ profile.phone|default:"-" }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>WhatsApp:</strong><br>
                                <div class="profile-detail-value">{{ profile.whatsapp|default:"-" }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Country:</strong><br>
                                <div class="profile-detail-value">{{ profile.country|default:"-" }}</div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <!-- Earnings Summary -->
                        <h5 class="affiliate-section-title">Earnings Summary</h5>

                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="earnings-summary-box">
                                    <strong>Total Earned</strong>
                                    <span>${{ profile.total_earned_usd|floatformat:2 }}</span>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="earnings-summary-box">
                                    <strong>Total Paid</strong>
                                    <span>${{ profile.total_paid_usd|floatformat:2 }}</span>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="earnings-summary-box">
                                    <strong>Available Balance</strong>
                                    <span>${{ profile.available_balance_usd|floatformat:2 }}</span>
                                </div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <!-- Bank & Payout Details -->
                        <h5 class="affiliate-section-title">Bank & Payout Details</h5>

                        <div class="row g-3">
                            <div class="col-md-6 profile-detail-item">
                                <strong>Bank Name:</strong><br>
                                <div class="profile-detail-value">{{ profile.bank_name|default:"-" }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Bank Branch:</strong><br>
                                <div class="profile-detail-value">{{ profile.bank_branch|default:"-" }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Account Holder:</strong><br>
                                <div class="profile-detail-value">{{ profile.bank_account_name|default:"-" }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Account Number:</strong><br>
                                <div class="profile-detail-value">{{ profile.bank_account_number|default:"-" }}</div>
                            </div>

                            <div class="col-12 profile-detail-item">
                                <strong>Payout Notes:</strong><br>
                                <div class="profile-detail-value">
                                    {{ profile.payout_notes|default:"No notes"|linebreaks }}
                                </div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <!-- Affiliate Tools -->
                        <h5 class="affiliate-section-title">Affiliate Tools</h5>

                        <div class="row g-3">
                            <div class="col-md-6 profile-detail-item">
                                <strong>Affiliate Code:</strong><br>
                                <div class="profile-detail-value mt-2">
                                    <span class="affiliate-code-box">{{ profile.affiliate_code }}</span>
                                </div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Affiliate Link:</strong><br>

                                <div class="input-group affiliate-link-group mt-2">
                                    <input
                                        type="text"
                                        readonly
                                        value="{{ profile.get_affiliate_link }}"
                                        class="form-control affiliate-link-input"
                                        id="affiliateLinkInput"
                                    >
                                    <button class="btn btn-outline-secondary copy-btn" type="button" onclick="copyAffiliateLink()">
                                        <i class="bi bi-files me-1"></i> Copy
                                    </button>
                                </div>

                                <small class="text-muted d-block mt-2">
                                    Share this link through WhatsApp, email, social media, QR code, or printed materials.
                                </small>
                            </div>
                        </div>

                        <hr class="my-4">

                        <!-- Status & Preferences -->
                        <h5 class="affiliate-section-title">Status & Preferences</h5>

                        <div class="row g-3">
                            <div class="col-md-4 profile-detail-item">
                                <strong>Status:</strong><br>
                                <div class="profile-detail-value">
                                    <span class="status-badge {% if profile.status == 'approved' %}status-approved{% elif profile.status == 'pending' %}status-pending{% elif profile.status == 'rejected' %}status-rejected{% else %}status-inactive{% endif %}">
                                        {{ profile.get_status_display }}
                                    </span>
                                </div>
                            </div>

                            <div class="col-md-4 profile-detail-item">
                                <strong>Active Account:</strong><br>
                                <div class="profile-detail-value">
                                    {% if profile.is_active %}
                                        <span class="status-badge status-approved">Yes</span>
                                    {% else %}
                                        <span class="status-badge status-inactive">No</span>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="col-md-4 profile-detail-item">
                                <strong>Affiliate Code:</strong><br>
                                <div class="profile-detail-value">{{ profile.affiliate_code }}</div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <!-- System Info -->
                        <h5 class="affiliate-section-title">System Info</h5>

                        <div class="row g-3">
                            <div class="col-md-6 profile-detail-item">
                                <strong>Joined On:</strong><br>
                                <div class="profile-detail-value">{{ profile.created_at|date:"F j, Y" }}</div>
                            </div>

                            <div class="col-md-6 profile-detail-item">
                                <strong>Last Updated:</strong><br>
                                <div class="profile-detail-value">{{ profile.updated_at|date:"F j, Y" }}</div>
                            </div>
                        </div>

                    </div>
                </div>

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

<!-- Crop Image Modal -->
<div class="modal fade" 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 fw-bold" 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>
{% endblock %}

{% block extra_js %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>

<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_photo', croppedFile);
            formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

            fetch("{% url 'affiliates_app:affiliate_upload_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">Profile image updated successfully.</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);
    });
});

function copyAffiliateLink() {
    const copyText = document.getElementById('affiliateLinkInput');

    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(copyText.value).then(function () {
            alert('Affiliate link copied to clipboard!');
        });
    } else {
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        document.execCommand('copy');
        alert('Affiliate link copied to clipboard!');
    }
}
</script>
{% endblock %}