{% extends 'affiliates_app/base_affiliate.html' %}
{% load static %}
{% load expat_extras %}
{% block title %}Affiliate Dashboard{% endblock %}

{% block content %}
<style>
    .marketing-training-card {
        border-radius: 24px;
        overflow: hidden;
        background: #ffffff;
    }

    .marketing-training-header {
        background:
            linear-gradient(135deg, rgba(14, 26, 34, 0.96), rgba(21, 94, 117, 0.92));
        color: #fff;
        padding: 1.5rem 1.75rem;
        border-bottom: none;
    }

    .marketing-training-header .section-mini-title {
        color: #ffc107;
        font-size: .76rem;
        font-weight: 800;
        text-transform: uppercase;
        letter-spacing: .1em;
    }

    .marketing-training-header h3 {
        font-weight: 800;
    }

    .marketing-training-header p {
        color: rgba(255, 255, 255, .78);
        max-width: 760px;
    }

    .training-guide-box,
    .training-media-box {
        background: #f8fafc;
        border: 1px solid #e5e7eb;
        border-radius: 20px;
        padding: 1.35rem;
    }

    .training-icon {
        width: 52px;
        height: 52px;
        border-radius: 18px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background: #0e1a22;
        color: #ffc107;
        font-size: 1.45rem;
        flex-shrink: 0;
    }

    .training-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .training-list li {
        display: flex;
        gap: .65rem;
        margin-bottom: .75rem;
        color: #475569;
        line-height: 1.55;
    }

    .training-list li i {
        color: #16a34a;
        margin-top: .18rem;
        flex-shrink: 0;
    }

    .training-video-wrapper {
        position: relative;
        width: 100%;
        padding-top: 56.25%;
        border-radius: 16px;
        overflow: hidden;
        background: #0e1a22;
    }

    .training-video-wrapper iframe {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        border: 0;
    }

    .training-media-box audio {
        height: 40px;
    }

    .training-language-tabs {
        display: flex;
        flex-wrap: wrap;
        gap: .75rem;
        padding: .75rem;
        background: #f8fafc;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
    }

    .training-lang-btn {
        border: 1px solid #d1d5db;
        background: #fff;
        color: #0e1a22;
        border-radius: 999px;
        padding: .55rem 1.15rem;
        font-weight: 700;
        font-size: .9rem;
        display: inline-flex;
        align-items: center;
        gap: .45rem;
        transition: all .2s ease;
    }

    .training-lang-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 8px 18px rgba(15, 23, 42, .08);
    }

    .training-lang-btn.active {
        background: #0e1a22;
        border-color: #0e1a22;
        color: #fff;
        box-shadow: 0 10px 22px rgba(15, 23, 42, .18);
    }

    .training-language-panel {
        display: none;
    }

    .training-language-panel.active {
        display: block;
    }

    /* =========================================================
   CONNECTED ENSOLANKA ACCESS
    ========================================================= */

    .affiliate-access-panel {
        border-radius: 36px;
        border: 1px solid rgba(226, 232, 240, 0.95);
        background: rgba(255, 255, 255, 0.98);
        box-shadow: 0 22px 52px rgba(15, 23, 42, 0.10);
        padding: 1.8rem;
    }

    .affiliate-access-kicker {
        display: inline-flex;
        align-items: center;
        gap: 0.45rem;
        color: #0f766e;
        font-size: 0.83rem;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
    }

    .affiliate-access-card {
        position: relative;
        overflow: hidden;
        border-radius: 30px;
        border: 1px solid rgba(226, 232, 240, 0.95);
        background: rgba(255, 255, 255, 0.98);
        box-shadow: 0 18px 42px rgba(15, 23, 42, 0.08);
        padding: 1.55rem 1.4rem;
        display: flex;
        flex-direction: column;
        transition: all 0.22s ease;
    }

    .affiliate-access-card::after {
        content: "";
        position: absolute;
        top: -75px;
        right: -75px;
        width: 155px;
        height: 155px;
        border-radius: 50%;
        background: rgba(15, 118, 110, 0.06);
        pointer-events: none;
    }

    .affiliate-access-card:hover {
        transform: translateY(-3px);
        border-color: rgba(15, 118, 110, 0.22);
        box-shadow: 0 28px 58px rgba(15, 23, 42, 0.12);
    }

    .affiliate-access-card > * {
        position: relative;
        z-index: 2;
    }

    .affiliate-access-icon {
        width: 62px;
        height: 62px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 22px;
        font-size: 1.55rem;
        color: #0f766e;
        background: #ecfdf5;
    }

    .affiliate-access-icon.gold {
        color: #b45309;
        background: #fef3c7;
    }

    .affiliate-access-card h5 {
        color: #0f172a;
        font-weight: 900;
    }

    .affiliate-access-card p {
        color: #64748b;
        line-height: 1.68;
        flex-grow: 1;
    }

    .affiliate-access-card form {
        margin-top: auto;
    }

    @media (max-width: 767.98px) {
        .affiliate-access-panel {
            border-radius: 28px;
            padding: 1.35rem;
        }
    }

    .training-language-image-tabs {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        padding: 0.75rem;
        background: #f8fafc;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
    }

    .training-lang-image-btn {
        border: 2px solid transparent;
        background: transparent;
        padding: 0;
        border-radius: 999px;
        line-height: 1;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        opacity: 0.72;
        transition: all 0.22s ease;
    }

    .training-lang-image-btn img {
        width: 150px;
        max-width: 100%;
        height: auto;
        display: block;
    }

    .training-lang-image-btn:hover {
        opacity: 1;
        transform: translateY(-2px);
        filter: drop-shadow(0 10px 18px rgba(15, 23, 42, 0.18));
    }

    .training-lang-image-btn.active {
        opacity: 1;
        transform: translateY(-2px);
        filter: drop-shadow(0 12px 22px rgba(15, 23, 42, 0.22));
    }

    @media (max-width: 767.98px) {
        .training-language-image-tabs {
            justify-content: center;
        }

        .training-lang-image-btn img {
            width: 120px;
        }
    }

    @media (max-width: 420px) {
        .training-lang-image-btn img {
            width: 96px;
        }
    }
</style>
<section class="affiliate-dashboard-hero py-5">
    <div class="container">

        {% if just_signed_up %}
        <div class="row justify-content-center mb-4">
            <div class="col-12 col-lg-10">
                <div class="alert affiliate-welcome-alert shadow-sm border-0 rounded-4 p-3 p-md-4">
                    <div class="d-flex flex-column flex-md-row align-items-start gap-3">
                        <div class="affiliate-welcome-icon flex-shrink-0">
                            <i class="bi bi-check-circle-fill"></i>
                        </div>

                        <div class="w-100">
                            <h4 class="fw-bold mb-2">Welcome! Your affiliate account has been created successfully.</h4>

                            <p class="mb-3 text-muted">
                                You are now signed in to your affiliate dashboard. Please keep your login details safe.
                                You can start sharing your affiliate link after your account is ready.
                            </p>

                            {% if account_role or new_account_email or username or password %}
                            <div class="bg-white border rounded-4 p-3 affiliate-login-details">
                                <div class="row g-2">

                                    {% if account_role %}
                                    <div class="col-12">
                                        <div class="d-flex flex-column flex-sm-row">
                                            <strong class="me-sm-2 text-dark affiliate-login-label">Account Type:</strong>
                                            <span class="text-break">{{ account_role }}</span>
                                        </div>
                                    </div>
                                    {% endif %}

                                    {% if new_account_email %}
                                    <div class="col-12">
                                        <div class="d-flex flex-column flex-sm-row">
                                            <strong class="me-sm-2 text-dark affiliate-login-label">Email:</strong>
                                            <span class="text-break">{{ new_account_email }}</span>
                                        </div>
                                    </div>
                                    {% endif %}

                                    {% if username %}
                                    <div class="col-12">
                                        <div class="d-flex flex-column flex-sm-row">
                                            <strong class="me-sm-2 text-dark affiliate-login-label">Username:</strong>
                                            <span class="text-break">{{ username }}</span>
                                        </div>
                                    </div>
                                    {% endif %}

                                    {% if password %}
                                    <div class="col-12">
                                        <div class="d-flex flex-column flex-sm-row">
                                            <strong class="me-sm-2 text-dark affiliate-login-label">Temporary Password:</strong>
                                            <span class="text-break">{{ password }}</span>
                                        </div>
                                    </div>
                                    {% endif %}

                                </div>

                                <hr class="my-3">

                                <p class="mb-0 small text-muted">
                                    For better security, please change your password after your first login.
                                    Your affiliate link and affiliate code are available at the top of this dashboard.
                                </p>
                            </div>
                            {% endif %}

                            <div class="d-flex flex-column flex-sm-row gap-2 mt-3">
                                <button type="button" class="btn btn-success btn-sm px-3" onclick="copyAffiliateLink()">
                                    <i class="bi bi-link-45deg me-1"></i>
                                    Copy My Affiliate Link
                                </button>

                                <a href="{% url 'affiliates_app:home_affiliates' %}" class="btn btn-outline-dark btn-sm px-3">
                                    <i class="bi bi-megaphone me-1"></i>
                                    View Affiliate Program Page
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}

        <div class="row align-items-center g-4">
            <div class="col-lg-8">
                <span class="section-mini-title">Affiliate Partner Center</span>
                <h1 class="fw-bold mb-3">Welcome, {{ affiliate.full_name }}</h1>
                <p class="lead text-muted mb-4">
                    Track your referred guests, monitor your possible future earnings,
                    download marketing resources, and request payouts from your affiliate wallet.
                </p>

                <div class="affiliate-link-box">
                    <small>Your Affiliate Link</small>
                    <div class="d-flex flex-column flex-md-row gap-2 mt-2">
                        <input
                            type="text"
                            class="form-control"
                            value="{{ request.scheme }}://{{ request.get_host }}/?ref={{ affiliate.affiliate_code }}"
                            readonly
                        >
                        <button class="btn btn-dark" onclick="copyAffiliateLink()">Copy Link</button>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="affiliate-code-card text-center">
                    <span>Affiliate Code</span>
                    <h2 style="color: #ffc107; text-shadow: 0 0 5px rgba(0,0,0,0.4);">{{ affiliate.affiliate_code }}</h2>
                    <p class="mb-0">Share this code or QR link with potential guests.</p>
                </div>

                <!-- Scroll button -->
                <div class="text-center mt-4">
                    <button onclick="smoothScrollTo('marketing-training')" 
                            class="btn w-100 py-2 shadow-sm" 
                            style="background: linear-gradient(135deg, #f3f4f6, #d1d5db); color: #111827; border: 1px solid #cbd5e1; font-weight: 700;">
                        <i class="bi bi-mortarboard-fill me-1"></i> Marketing Training
                    </button>
                </div>
                <div class="text-center mt-4">
                    <button onclick="smoothScrollTo('marketing-resources')" class="btn w-100 py-2" style="background-color: #ffc107; color: #000; border: none; font-weight: 500;">
                        <i class="bi bi-arrow-down-circle"></i> Marketing Resources
                    </button>
                </div>
                <div class="text-center mt-4">
                    <button onclick="smoothScrollTo('business-card')" class="btn w-100 py-2" style="background-color: #ffc107; color: #000; border: none; font-weight: 500;">
                        <i class="bi bi-arrow-down-circle"></i> Get Your Business Card
                    </button>
                </div>
            </div>
        </div>
    </div>
</section>


<section class="py-5">
    <div class="container">

        <div class="row g-4 mb-5">
            <div class="col-md-6 col-xl-3">
                <div class="affiliate-stat-card">
                    <span>Possible Future Earnings</span>
                    <h3>${{ possible_future_earnings }}</h3>
                    <p>Based on referred guest package interests.</p>
                </div>
            </div>

            <div class="col-md-6 col-xl-3">
                <div class="affiliate-stat-card">
                    <span>Pending Commission</span>
                    <h3>${{ pending_commission_total }}</h3>
                    <p>Commissions waiting for guest payment confirmation.</p>
                </div>
            </div>

            <div class="col-md-6 col-xl-3">
                <div class="affiliate-stat-card">
                    <span>Earned Commission</span>
                    <h3>${{ earned_commission_total }}</h3>
                    <p>Confirmed earnings ready for payout process.</p>
                </div>
            </div>

            <div class="col-md-6 col-xl-3">
                <div class="affiliate-stat-card">
                    <span>Available Balance</span>
                    <h3>${{ affiliate.available_balance_usd }}</h3>
                    <p>Available amount after completed payouts.</p>
                </div>
            </div>
        </div>


        <div class="row g-4 mb-5">
            <div class="col-lg-8">
                <div class="affiliate-panel">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <h4 class="fw-bold mb-1">Referred Guests</h4>
                            <p class="text-muted mb-0">
                                Guests who signed up using your affiliate link.
                            </p>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table align-middle">
                            <thead>
                                <tr>
                                    <th>Guest</th>
                                    <th>Contact</th>
                                    <th>Package</th>
                                    <th>Possible Commission</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for referral in referrals %}
                                    <tr>
                                        <td>
                                            <strong>{{ referral.guest_name|default:"Guest" }}</strong><br>
                                            <small class="text-muted">{{ referral.guest_country }}</small>
                                        </td>
                                        <td>
                                            <small>{{ referral.guest_email }}</small><br>
                                            <small>{{ referral.guest_phone }}</small>
                                        </td>
                                        <td>
                                            {{ referral.selected_package_name|default:"Not selected" }}
                                        </td>
                                        <td>
                                            <strong>${{ referral.total_possible_commission_usd }}</strong>
                                        </td>
                                        <td>
                                            <span class="badge bg-dark">{{ referral.get_status_display }}</span>
                                        </td>
                                    </tr>
                                {% empty %}
                                    <tr>
                                        <td colspan="5" class="text-center text-muted py-4">
                                            No referred guests yet.
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>


            <div class="col-lg-4">
                <div class="affiliate-panel mb-4">
                    <h4 class="fw-bold mb-3">Request Payout</h4>

                    <p class="text-muted">
                        Available balance:
                        <strong>${{ affiliate.available_balance_usd }}</strong>
                    </p>

                    <form method="post" action="{% url 'affiliates_app:request_affiliate_payout' %}">
                        {% csrf_token %}
                        <div class="mb-3">
                            <label class="form-label">Amount USD</label>
                            <input type="number" step="0.01" min="1" name="amount_usd" class="form-control" required>
                        </div>

                        <button type="submit" class="btn btn-dark w-100">
                            Submit Payout Request
                        </button>
                    </form>
                </div>

                <div class="affiliate-panel">
                    <h4 class="fw-bold mb-3">Client Status</h4>

                    <div class="d-flex justify-content-between border-bottom py-2">
                        <span>Pending Clients</span>
                        <strong>{{ pending_clients_count }}</strong>
                    </div>

                    <div class="d-flex justify-content-between border-bottom py-2">
                        <span>Completed Clients</span>
                        <strong>{{ completed_clients_count }}</strong>
                    </div>

                    <div class="d-flex justify-content-between py-2">
                        <span>Total Referrals</span>
                        <strong>{{ referrals.count }}</strong>
                    </div>
                </div>


            </div>

        </div>

        <div class="row g-4">

 
            <div class="col-md-6 col-xl-3">
                <div class="dashboard-link-card h-100 text-center">
                    <i class="bi bi-hourglass-split fs-2 text-secondary"></i>
                    <div class="display-6 fw-bold mt-2">{{ pending_clients_count }}</div>
                    <p class="text-muted small text-uppercase mb-0" style="letter-spacing:.05em;">Pending</p>
                    <h5 class="fw-bold mt-2">Pending Referrals</h5>
                    <p class="small">Referrals who have signed up but are not yet confirmed.</p>
                    <a href="{% url 'affiliates_app:affiliate_referral_list' %}?status=signed_up" class="btn btn-outline-dark">View list</a>
                </div>
            </div>


            <div class="col-md-6 col-xl-3">
                <div class="dashboard-link-card h-100 text-center">
                    <i class="bi bi-patch-check-fill fs-2 text-success"></i>
                    <div class="display-6 fw-bold mt-2 text-success">
                        {{ confirmed_count }}
                    </div>
                    <p class="text-muted small text-uppercase mb-0" style="letter-spacing:.05em;">Confirmed</p>
                    <h5 class="fw-bold mt-2">Confirmed</h5>
                    <p class="small">Referrals who paid the confirmation fee — commission earned.</p>
                    <a href="{% url 'affiliates_app:affiliate_referral_list' %}?status=confirmed" class="btn btn-outline-success">View list</a>
                </div>
            </div>


            <div class="col-md-6 col-xl-3">
                <div class="dashboard-link-card h-100 text-center">
                    <i class="bi bi-credit-card-fill fs-2 text-info"></i>
                    <div class="display-6 fw-bold mt-2 text-info">{{ completed_clients_count }}</div>
                    <p class="text-muted small text-uppercase mb-0" style="letter-spacing:.05em;">Paid / Completed</p>
                    <h5 class="fw-bold mt-2">Service Fee Paid</h5>
                    <p class="small">Referrals who paid the service fee or completed the full journey.</p>
                    <a href="{% url 'affiliates_app:affiliate_referral_list' %}?status=paid_completed" class="btn btn-outline-info">View list</a>
                </div>
            </div>


            <div class="col-md-6 col-xl-3">
                <div class="dashboard-link-card h-100 text-center">
                    <img src="{% if affiliate.profile_photo %}{{ affiliate.profile_photo.url }}{% else %}{% static default_profile_image %}{% endif %}"
                        alt="Profile Image"
                        style="width: 70px; height: 70px; object-fit: cover; border-radius: 50%; border: 1.5px solid #ccc;">
                    <h5 class="fw-bold mt-3">My Profile</h5>
                    <p class="small">View and edit your personal info, bank details, and account settings.</p>
                    <a href="{% url 'affiliates_app:affiliate_profile' %}" class="btn btn-outline-dark">
                        Open profile
                    </a>
                </div>
            </div>

        </div>
        <!-- Section: Marketing Training / Guidance -->
        <div id="marketing-training" class="card mt-4 border-0 shadow-sm marketing-training-card">
            <div class="card-header marketing-training-header">
                <div>
                    <span class="section-mini-title d-block mb-1">Affiliate Training</span>
                    <h3 class="mb-1">Marketing Guidance &amp; Training</h3>
                    <p class="mb-0">
                        Learn how to confidently promote Sri Lanka living opportunities and represent Ensolanka as a trusted global ambassador.
                    </p>
                </div>
            </div>

            <div class="card-body p-4">

                {% if training_resources %}

                    <!-- Language Image Buttons -->
                    <div class="training-language-image-tabs mb-4">

                        <button type="button"
                                class="training-lang-btn training-lang-image-btn active"
                                data-training-lang="en"
                                aria-label="Show English training resources">
                            <img src="{% static 'expat_life/images/english.png' %}"
                                alt="English">
                        </button>

                        <button type="button"
                                class="training-lang-btn training-lang-image-btn"
                                data-training-lang="si"
                                aria-label="Show Sinhala training resources">
                            <img src="{% static 'expat_life/images/sinhala.png' %}"
                                alt="Sinhala">
                        </button>

                        <button type="button"
                                class="training-lang-btn training-lang-image-btn"
                                data-training-lang="ta"
                                aria-label="Show Tamil training resources">
                            <img src="{% static 'expat_life/images/tamil.png' %}"
                                alt="Tamil">
                        </button>

                    </div>

                    <!-- Training Content Panels -->
                    {% for training in training_resources %}
                    <div class="training-language-panel {% if training.language == 'en' %}active{% endif %}"
                        data-training-panel="{{ training.language }}">

                        <div class="row g-4 align-items-start">

                            <!-- Left: Training Guide Details -->
                            <div class="col-lg-7">
                                <div class="training-guide-box h-100">

                                    <div class="d-flex align-items-start gap-3 mb-3">
                                        <div class="training-icon">
                                            <i class="bi bi-journal-richtext"></i>
                                        </div>

                                        <div>
                                            <span class="badge rounded-pill bg-warning text-dark mb-2">
                                                {{ training.get_language_display }}
                                            </span>

                                            <h4 class="fw-bold mb-1">
                                                {{ training.title }}
                                            </h4>

                                            {% if training.description %}
                                            <p class="text-muted mb-0">
                                                {{ training.description|linebreaksbr }}
                                            </p>
                                            {% else %}
                                            <p class="text-muted mb-0">
                                                Complete training materials to help affiliates promote Sri Lanka living opportunities with confidence.
                                            </p>
                                            {% endif %}
                                        </div>
                                    </div>

                                    <div class="playbook-summary mt-4">
                                        <h5 class="fw-bold mb-3">Training Materials</h5>

                                        <ul class="training-list">
                                            <li>
                                                <i class="bi bi-check-circle-fill"></i>
                                                Read the complete ambassador playbook for this language.
                                            </li>
                                            <li>
                                                <i class="bi bi-check-circle-fill"></i>
                                                Download the summary overview for quick revision.
                                            </li>
                                            <li>
                                                <i class="bi bi-check-circle-fill"></i>
                                                Listen to the audio guide to improve your explanation flow.
                                            </li>
                                            <li>
                                                <i class="bi bi-check-circle-fill"></i>
                                                Watch the video training before promoting to potential guests.
                                            </li>
                                        </ul>
                                    </div>

                                    <div class="d-flex flex-column flex-md-row flex-wrap gap-2 mt-4">

                                        {% if training.full_playbook_pdf %}
                                        <a href="{{ training.full_playbook_pdf.url }}"
                                        class="btn btn-dark rounded-pill px-4"
                                        target="_blank">
                                            <i class="bi bi-file-earmark-pdf me-1"></i>
                                            View Full Playbook
                                        </a>

                                        <a href="{{ training.full_playbook_pdf.url }}"
                                        class="btn btn-outline-dark rounded-pill px-4"
                                        download>
                                            <i class="bi bi-download me-1"></i>
                                            Download Full Playbook
                                        </a>
                                        {% endif %}

                                        {% if training.summary_overview_pdf %}
                                        <a href="{{ training.summary_overview_pdf.url }}"
                                        class="btn btn-outline-primary rounded-pill px-4"
                                        download>
                                            <i class="bi bi-file-earmark-text me-1"></i>
                                            Download Summary Overview
                                        </a>
                                        {% endif %}

                                    </div>

                                    {% if not training.full_playbook_pdf and not training.summary_overview_pdf %}
                                    <p class="text-muted small mt-4 mb-0">
                                        Document files for this language will be available soon.
                                    </p>
                                    {% endif %}

                                </div>
                            </div>

                            <!-- Right: Audio + Video -->
                            <div class="col-lg-5">

                                <!-- Audio Training -->
                                <div class="training-media-box mb-4">
                                    <h5 class="fw-bold mb-2">
                                        <i class="bi bi-headphones me-1"></i>
                                        Audio Training Guide
                                    </h5>

                                    {% if training.audio_guide_file %}
                                    <audio controls preload="metadata" class="w-100 mb-3">
                                        <source src="{{ training.audio_guide_file.url }}" type="audio/mpeg">
                                        Your browser does not support the audio element.
                                    </audio>

                                    <a href="{{ training.audio_guide_file.url }}"
                                    class="btn btn-outline-secondary btn-sm rounded-pill"
                                    download>
                                        <i class="bi bi-download me-1"></i>
                                        Download Audio File
                                    </a>
                                    {% else %}
                                    <p class="text-muted small mb-0">
                                        Audio guide for this language will be available soon.
                                    </p>
                                    {% endif %}
                                </div>

                                <!-- Video Training -->
                                <div class="training-media-box">
                                    <h5 class="fw-bold mb-2">
                                        <i class="bi bi-play-circle-fill me-1"></i>
                                        Video Training
                                    </h5>

                                    {% if training.youtube_video_link %}
                                        {% with training.youtube_video_link|video_embed_url as embed_url %}
                                            {% if embed_url %}
                                            <div class="training-video-wrapper">
                                                <iframe
                                                    src="{{ embed_url }}"
                                                    title="{{ training.title }} Video Training"
                                                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                                    referrerpolicy="strict-origin-when-cross-origin"
                                                    allowfullscreen
                                                    loading="lazy">
                                                </iframe>
                                            </div>
                                            {% endif %}
                                        {% endwith %}
                                    {% else %}
                                    <p class="text-muted small mb-0">
                                        Video training for this language will be available soon.
                                    </p>
                                    {% endif %}
                                </div>

                            </div>

                        </div>

                    </div>
                    {% endfor %}

                {% else %}
                    <div class="text-center py-4">
                        <i class="bi bi-journal-x" style="font-size:2rem; color:#94a3b8;"></i>
                        <h5 class="fw-bold mt-3">Training resources are not available yet</h5>
                        <p class="text-muted mb-0">
                            The Ensolanka Global Ambassador Playbook, summary, audio guide, and video training will appear here once published.
                        </p>
                    </div>
                {% endif %}

            </div>
        </div>

        <div id="business-card"></div>
        <!-- New Section: Business Card Generator -->
        <div class="card mt-4">
            <div class="card-header">
                <h3>Create a Promotional Business Card</h3>
            </div>
            <div class="card-body">
                <form method="post" action="{% url 'affiliates_app:generate_business_card' %}">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="promo_link">Choose the page you want to promote:</label>
                        <select name="promo_link" id="promo_link" class="form-control" required>
                            <option value="">-- Select a link --</option>
                            {% for link in promotional_links %}
                            <option value="{{ link.url_name }}">{{ link.display_name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary mt-3">Generate Business Card</button>
                </form>
            </div>
        </div>

        <!-- Section: Existing Business Cards -->
        <div class="card mt-4">
            <div class="card-header">
                <h3>Your Generated Business Cards</h3>
            </div>
             <div class="card-body" id="cards-container">
                {% include 'affiliates_app/_cards_section.html' with existing_cards=existing_cards now=now %}
            </div>
        </div>
        <div id="marketing-resources" ></div>
        <!-- Section: General Marketing Resources -->
        <div class="card mt-4 border-0 shadow-sm general-marketing-card">
            <div class="card-body d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-3">
                <div>
                    <span class="section-mini-title d-block mb-1">Marketing Library</span>
                    <h3 class="fw-bold mb-2">General Marketing Resources</h3>
                    <p class="text-muted mb-0">
                        Access ready-to-use brochures, presentations, audio guides, and video resources in different languages
                        to support your affiliate promotions.
                    </p>
                </div>

                <div class="text-md-end">
                    <a href="{% url 'affiliates_app:marketing_resources' %}" class="btn btn-dark rounded-pill px-4">
                        <i class="bi bi-folder2-open me-2"></i>
                        Open Resources
                    </a>
                </div>
            </div>
        </div>
        <!-- Section: Request Custom Marketing Resources -->
        <div class="card mt-4">
            <div class="card-header">
                <h3>Request Custom Marketing Materials</h3>
            </div>
            <div class="card-body">
                <p class="text-muted mb-3">
                    Need brochures or slide decks in additional languages, personalized with your own contact details and QR code? 
                    Select the languages below and submit a request. We'll prepare them for you and notify you when ready.
                </p>
                
                <form method="post">
                    {% csrf_token %}
                    <input type="hidden" name="request_resources" value="1">
                    <div class="mb-3">
                        {{ resource_request_form.requested_languages.label_tag }}
                        <div class="row">
                            {% for checkbox in resource_request_form.requested_languages %}
                                <div class="col-md-3 col-sm-6">
                                    <div class="form-check">
                                        {{ checkbox.tag }}
                                        <label class="form-check-label" for="{{ checkbox.id_for_label }}">
                                            {{ checkbox.choice_label }}
                                        </label>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit Request</button>
                </form>
                
                {% if pending_requests %}
                    <hr>
                    <h5>Your Pending Requests</h5>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Request Date</th>
                                    <th>Languages</th>
                                    <th>Status</th>
                                    <th>Response</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for req in pending_requests %}
                                <tr>
                                    <td>{{ req.request_date|date:"Y-m-d" }}</td>
                                    <td>{{ req.requested_languages|join:", " }}</td>
                                    <td>
                                        {% if req.status == 'pending' %}
                                            <span class="badge bg-warning text-dark">Pending</span>
                                        {% elif req.status == 'in_progress' %}
                                            <span class="badge bg-info">In Progress</span>
                                        {% else %}
                                            <span class="badge bg-secondary">{{ req.get_status_display }}</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ req.response_message|default:"—" }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% endif %}
            </div>
        </div>

        <div class="affiliate-panel">
            <div class="mb-4">
                <h4 class="fw-bold mb-1">Your Custom Marketing Resources</h4>
                <p class="text-muted mb-0">
                    These brochures and slide decks are generated on request, personalized with your contact details, 
                    unique QR code, and referral link. Need another language or format? 
                    <a href="#request-resources" class="text-decoration-none">Request new materials</a> – we’ll prepare them for you.
                </p>
            </div>

            <div class="row g-3">
                {% for resource in resources %}
                <div class="col-md-6 col-xl-3">
                    <div class="resource-card h-100">
                        <div class="resource-icon">
                            <i class="bi bi-folder2-open"></i>
                        </div>

                        <h6 class="fw-bold">{{ resource.title }}</h6>

                        <p class="text-muted small mb-3">
                            Custom Resource / {{ resource.get_language_display }}
                        </p>

                        {% if resource.description %}
                        <p class="text-muted small mb-3">
                            {{ resource.description|truncatewords:18 }}
                        </p>
                        {% endif %}

                        <div class="d-flex flex-column gap-2">

                            {% if resource.full_pdf_file %}
                            <a href="{{ resource.full_pdf_file.url }}" class="btn btn-outline-dark btn-sm" download>
                                <i class="bi bi-file-earmark-pdf"></i>
                                Full Brochure
                            </a>
                            {% endif %}

                            {% if resource.summary_overview_pdf %}
                            <a href="{{ resource.summary_overview_pdf.url }}" class="btn btn-outline-primary btn-sm" download>
                                <i class="bi bi-file-earmark-text"></i>
                                Summary Overview
                            </a>
                            {% endif %}

                            {% if resource.presentation_pdf %}
                            <a href="{{ resource.presentation_pdf.url }}" class="btn btn-outline-secondary btn-sm" download>
                                <i class="bi bi-easel"></i>
                                Presentation
                            </a>
                            {% endif %}

                            {% if not resource.full_pdf_file and not resource.summary_overview_pdf and not resource.presentation_pdf %}
                            <button class="btn btn-outline-secondary btn-sm" disabled>
                                <i class="bi bi-clock-history"></i>
                                Files coming soon
                            </button>
                            {% endif %}

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

                {% empty %}
                <div class="col-12">
                    <p class="text-muted mb-0">
                        No customized materials are available yet.
                        <a href="#request-resources">Request your personalized brochures, summaries, and presentations</a>
                        in your preferred languages, and we will deliver them here as soon as they’re ready.
                    </p>
                </div>
                {% endfor %}
            </div>
        </div>

    </div>
</section>
<!-- =====================================================
     CONNECTED ENSOLANKA ACCESS
====================================================== -->
<section class="affiliate-connected-access py-4">
    <div class="container">

        <div class="affiliate-access-panel">

            <div class="affiliate-access-header mb-4">
                <span class="affiliate-access-kicker">
                    <i class="bi bi-link-45deg"></i>
                    Connected Ensolanka Access
                </span>

                <h2 class="fw-bold mb-2">
                    Expand Your Account
                </h2>

                <p class="text-muted mb-0">
                    Use your existing Affiliate Partner account to activate related Ensolanka services
                    without creating another login.
                </p>
            </div>

            <div class="row g-4">

                <!-- Property Care Access -->
                <div class="col-lg-6">
                    <div class="affiliate-access-card h-100">

                        <span class="affiliate-access-icon">
                            <i class="bi bi-house-gear-fill"></i>
                        </span>

                        <h5 class="fw-bold mt-3">
                            Property Care Access
                        </h5>

                        {% if has_property_manager_profile %}
                            <p>
                                Your Property Care profile is already active.
                                Open the Property Care Dashboard to register properties,
                                request maintenance support, and review care plans.
                            </p>

                            <a href="{% url 'property_manager_app:property_manager_dashboard' %}"
                               class="btn btn-outline-dark rounded-pill fw-bold">
                                <i class="bi bi-arrow-right-circle-fill me-2"></i>
                                Open Property Care Dashboard
                            </a>
                        {% else %}
                            <p>
                                Activate Property Care access using your existing Affiliate account details.
                                This is useful if you own or manage property in Sri Lanka.
                            </p>

                            <form method="post"
                                  action="{% url 'affiliates_app:activate_property_manager_from_affiliate' %}">
                                {% csrf_token %}

                                <button type="submit"
                                        class="btn btn-dark rounded-pill fw-bold">
                                    <i class="bi bi-person-plus-fill me-2"></i>
                                    Activate Property Care Access
                                </button>
                            </form>
                        {% endif %}

                    </div>
                </div>


                <!-- Rental Owner Access -->
                <div class="col-lg-6">
                    <div class="affiliate-access-card h-100">

                        <span class="affiliate-access-icon gold">
                            <i class="bi bi-buildings-fill"></i>
                        </span>

                        <h5 class="fw-bold mt-3">
                            Rental Owner Access
                        </h5>

                        {% if has_rental_owner_profile %}
                            <p>
                                Your Rental Owner profile is already active.
                                Open your Rental Dashboard to create and manage guest-facing rental listings.
                            </p>

                            <a href="{% url 'rental_app:rental_owner_dashboard' %}"
                               class="btn btn-outline-dark rounded-pill fw-bold">
                                <i class="bi bi-arrow-right-circle-fill me-2"></i>
                                Open Rental Dashboard
                            </a>
                        {% else %}
                            <p>
                                Activate Rental Owner access using your existing Affiliate account details
                                and start building rental listings for international guests.
                            </p>

                            <form method="post"
                                  action="{% url 'affiliates_app:activate_rental_owner_from_affiliate' %}">
                                {% csrf_token %}

                                <button type="submit"
                                        class="btn btn-dark rounded-pill fw-bold">
                                    <i class="bi bi-person-plus-fill me-2"></i>
                                    Activate Rental Owner Access
                                </button>
                            </form>
                        {% endif %}

                    </div>
                </div>

            </div>
        </div>

    </div>
</section>

<style>
    .affiliate-dashboard-hero {
        background:
            linear-gradient(135deg, rgba(8, 15, 31, 0.92), rgba(20, 35, 58, 0.82)),
            url("{% static 'expat_life/images/affiliates_hero.webp' %}");
        background-size: cover;
        background-position: center;
        color: #fff;
    }

    .affiliate-dashboard-hero .text-muted,
    .affiliate-dashboard-hero .lead {
        color: rgba(255,255,255,0.78) !important;
    }

    .affiliate-link-box {
        background: rgba(255,255,255,0.12);
        border: 1px solid rgba(255,255,255,0.18);
        backdrop-filter: blur(12px);
        padding: 18px;
        border-radius: 20px;
    }

    .affiliate-link-box small {
        color: rgba(255,255,255,0.75);
        font-weight: 600;
        letter-spacing: 0.04em;
        text-transform: uppercase;
    }

    .affiliate-code-card {
        background: rgba(255,255,255,0.14);
        border: 1px solid rgba(255,255,255,0.2);
        backdrop-filter: blur(14px);
        border-radius: 28px;
        padding: 36px 24px;
        box-shadow: 0 24px 70px rgba(0,0,0,0.25);
    }

    .affiliate-code-card span {
        font-size: 0.8rem;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        color: rgba(255,255,255,0.7);
    }

    .affiliate-code-card h2 {
        font-weight: 800;
        margin: 12px 0;
        letter-spacing: 0.04em;
    }

    .affiliate-stat-card,
    .affiliate-panel,
    .resource-card {
        background: #fff;
        border: 1px solid rgba(0,0,0,0.06);
        border-radius: 24px;
        box-shadow: 0 16px 45px rgba(15, 23, 42, 0.06);
    }

    .affiliate-stat-card {
        padding: 24px;
        height: 100%;
    }

    .affiliate-stat-card span {
        color: #6c757d;
        font-size: 0.85rem;
        font-weight: 600;
    }

    .affiliate-stat-card h3 {
        font-weight: 800;
        margin: 10px 0;
    }

    .affiliate-stat-card p {
        color: #6c757d;
        margin-bottom: 0;
        font-size: 0.9rem;
    }

    .affiliate-panel {
        padding: 26px;
    }

    .resource-card {
        padding: 22px;
        transition: 0.25s ease;
    }

    .resource-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 55px rgba(15, 23, 42, 0.10);
    }

    .resource-icon {
        width: 48px;
        height: 48px;
        border-radius: 16px;
        background: #f1f3f5;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.4rem;
        margin-bottom: 16px;
    }

    /* ========== WELCOME ALERT STYLES (fix white-on-white) ========== */
    .affiliate-welcome-alert {
        background: #eaf7ed !important;      /* light green background */
        border-left: 6px solid #2c7a4d !important;
        color: #1e2a3e !important;
    }

    .affiliate-welcome-alert h4,
    .affiliate-welcome-alert .fw-bold {
        color: #0b2b1f !important;
    }

    .affiliate-welcome-alert .text-muted {
        color: #2c4b3e !important;  /* darker muted text for readability */
        opacity: 1;
    }

    .affiliate-welcome-alert .affiliate-welcome-icon i {
        font-size: 2.8rem;
        color: #2c7a4d;
    }

    /* login details box inside welcome alert */
    .affiliate-welcome-alert .affiliate-login-details {
        background: #ffffff !important;
        border: 1px solid #dce5dc;
        border-radius: 1rem;
        box-shadow: 0 4px 12px rgba(0,0,0,0.04);
    }

    .affiliate-welcome-alert .affiliate-login-details .affiliate-login-label {
        color: #1f3b2c !important;
        font-weight: 700;
        min-width: 140px;
    }

    .affiliate-welcome-alert .affiliate-login-details span:not(.affiliate-login-label) {
        color: #1a2c24 !important;
        font-weight: 500;
    }

    .affiliate-welcome-alert .affiliate-login-details hr {
        background-color: #e2e8f0;
    }

    /* buttons inside welcome alert */
    .affiliate-welcome-alert .btn-success {
        background-color: #2c7a4d;
        border-color: #1f5a38;
    }

    .affiliate-welcome-alert .btn-outline-dark {
        color: #1a3b2c;
        border-color: #bdd3c2;
    }
    .affiliate-welcome-alert .btn-outline-dark:hover {
        background-color: #eef4ea;
        color: #0a2b1f;
    }

    @media (max-width: 767px) {
        .affiliate-panel {
            padding: 18px;
        }

        .affiliate-dashboard-hero {
            text-align: center;
        }

        .affiliate-code-card {
            padding: 26px 18px;
        }
    }


</style>


<script>
    function copyAffiliateLink() {
        const input = document.querySelector('.affiliate-link-box input');
        input.select();
        input.setSelectionRange(0, 99999);
        document.execCommand('copy');
        alert('Affiliate link copied!');
    }
</script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.querySelector('form[action*="generate_business_card"]');
        if (!form) return;
        
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(form);
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerText;
            submitBtn.disabled = true;
            submitBtn.innerText = 'Generating...';
            
            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (response.redirected) {
                    // If server redirects, follow and then refresh cards
                    return fetch(response.url);
                }
                return response;
            })
            .then(() => {
                // Refresh the cards section with cache-buster
                refreshCards();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Something went wrong. Please try again.');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerText = originalText;
            });
        });
        
        function refreshCards() {
            fetch("{% url 'affiliates_app:get_affiliate_cards' %}")
            .then(response => response.json())
            .then(data => {
                if (data.html) {
                    document.getElementById('cards-container').innerHTML = data.html;
                    // Re-attach download links? Not needed, they are static.
                }
            })
            .catch(error => console.error('Refresh error:', error));
        }
    });
</script>
<script>
    function smoothScrollTo(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.scrollIntoView({
                behavior: 'smooth',
                block: 'start',
            });
        }
    }
</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const buttons = document.querySelectorAll('.training-lang-btn');
        const panels = document.querySelectorAll('.training-language-panel');

        buttons.forEach(function (button) {
            button.addEventListener('click', function () {
                const selectedLang = this.getAttribute('data-training-lang');

                buttons.forEach(function (btn) {
                    btn.classList.remove('active');
                });

                panels.forEach(function (panel) {
                    panel.classList.remove('active');
                });

                this.classList.add('active');

                const activePanel = document.querySelector(
                    '.training-language-panel[data-training-panel="' + selectedLang + '"]'
                );

                if (activePanel) {
                    activePanel.classList.add('active');
                }
            });
        });
    });
</script>
{% endblock %}