{% extends 'base/base.html' %}
{% block title %}Dashboard - CryptoSignals Pro{% endblock %}
{% block extra_css %}
<style>
    .telegram-cta-card {
        background:
            radial-gradient(circle at top right, rgba(0, 212, 255, 0.18), transparent 35%),
            linear-gradient(135deg, rgba(15, 23, 42, 0.96) 0%, rgba(24, 24, 56, 0.96) 45%, rgba(123, 47, 247, 0.2) 100%);
        border: 1px solid rgba(0, 212, 255, 0.22);
        overflow: hidden;
        position: relative;
    }

    .telegram-cta-card::before {
        content: '';
        position: absolute;
        inset: 0;
        background: linear-gradient(90deg, rgba(0, 212, 255, 0.06), transparent 40%, rgba(123, 47, 247, 0.08));
        pointer-events: none;
    }

    .telegram-cta-icon {
        width: 64px;
        height: 64px;
        border-radius: 20px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background: rgba(0, 212, 255, 0.14);
        color: var(--accent-cyan);
        font-size: 1.8rem;
        box-shadow: inset 0 0 0 1px rgba(0, 212, 255, 0.12);
    }

    .telegram-cta-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        justify-content: flex-end;
        align-items: center;
    }

    .telegram-direct-meta {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 0.65rem;
        margin-top: 0.9rem;
    }

    .telegram-direct-chip {
        display: inline-flex;
        align-items: center;
        gap: 0.45rem;
        padding: 0.45rem 0.8rem;
        border-radius: 999px;
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(0, 212, 255, 0.18);
        color: var(--accent-cyan);
        font-weight: 600;
        text-decoration: none;
    }

    .telegram-direct-chip:hover {
        color: var(--accent-cyan);
        background: rgba(0, 212, 255, 0.12);
    }

    .dashboard-market-card .card-body {
        padding: 0;
    }

    .dashboard-market-list {
        max-height: 430px;
        overflow-y: auto;
        border-right: 1px solid var(--border-color);
    }

    .dashboard-market-coin-row {
        cursor: pointer;
        padding: 1rem 1.1rem;
        border-bottom: 1px solid var(--border-color);
        transition: all 0.25s ease;
    }

    .dashboard-market-coin-row:hover,
    .dashboard-market-coin-row.active {
        background: rgba(0, 212, 255, 0.10);
    }

    .dashboard-market-coin-row.active {
        box-shadow: inset 3px 0 0 var(--accent-cyan);
    }

    .dashboard-market-coin-icon,
    .dashboard-market-mini-icon {
        border-radius: 50%;
        object-fit: cover;
    }

    .dashboard-market-coin-icon {
        width: 42px;
        height: 42px;
    }

    .dashboard-market-mini-icon {
        width: 34px;
        height: 34px;
    }

    .dashboard-market-chart-wrap {
        padding: 1.5rem;
    }

    .dashboard-market-chart-box {
        position: relative;
        height: 320px;
    }

    .dashboard-market-timeframe {
        background: transparent;
        border: 1px solid var(--border-color);
        color: var(--text-secondary);
        border-radius: 10px;
        padding: 0.4rem 0.75rem;
        font-size: 0.8rem;
        font-weight: 600;
        transition: all 0.2s ease;
    }

    .dashboard-market-timeframe.active,
    .dashboard-market-timeframe:hover {
        background: rgba(0, 212, 255, 0.16);
        color: var(--accent-cyan);
        border-color: rgba(0, 212, 255, 0.28);
    }

    .dashboard-market-side {
        padding: 1.5rem;
        border-left: 1px solid var(--border-color);
        background: linear-gradient(180deg, rgba(0, 212, 255, 0.06), transparent 32%);
    }

    .dashboard-market-stat {
        display: flex;
        justify-content: space-between;
        gap: 1rem;
        padding: 0.45rem 0;
        border-bottom: 1px solid rgba(148, 163, 184, 0.08);
    }

    .dashboard-market-stat:last-child {
        border-bottom: 0;
    }

    .dashboard-signal-badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 0.55rem 1rem;
        border-radius: 999px;
        font-size: 0.78rem;
        font-weight: 700;
        letter-spacing: 0.04em;
        text-transform: uppercase;
    }

    .dashboard-signal-buy {
        background: rgba(16, 185, 129, 0.18);
        color: var(--success);
    }

    .dashboard-signal-sell {
        background: rgba(239, 68, 68, 0.18);
        color: var(--danger);
    }

    .dashboard-signal-neutral {
        background: rgba(245, 158, 11, 0.18);
        color: var(--warning);
    }

    .dashboard-live-signal-card {
        background: rgba(255, 255, 255, 0.02);
        border: 1px solid rgba(148, 163, 184, 0.12);
        border-radius: 14px;
        padding: 1rem;
    }

    @media (max-width: 991.98px) {
        .telegram-cta-actions {
            justify-content: flex-start;
        }

        .dashboard-market-list {
            max-height: 280px;
            border-right: 0;
            border-bottom: 1px solid var(--border-color);
        }

        .dashboard-market-side {
            border-left: 0;
            border-top: 1px solid var(--border-color);
        }

        .dashboard-market-chart-box {
            height: 260px;
        }
    }

    @media (max-width: 575.98px) {
        .container-fluid {
            padding-top: 0.5rem;
        }

        .page-title {
            margin-top: 0.35rem;
            margin-bottom: 1.25rem;
            line-height: 1.15;
        }

        .dashboard-stats-row {
            margin-left: 0.1rem;
            margin-right: 0.1rem;
            margin-bottom: 1rem !important;
        }

        .dashboard-stats-col {
            padding-left: 0.45rem;
            padding-right: 0.45rem;
            margin-bottom: 0.7rem;
        }

        .dashboard-stats-col:last-child {
            margin-bottom: 0;
        }

        .telegram-cta-icon {
            width: 56px;
            height: 56px;
            border-radius: 18px;
            font-size: 1.5rem;
        }

        .telegram-cta-card .card-body {
            padding: 1rem;
        }

        .dashboard-market-chart-wrap,
        .dashboard-market-side {
            padding: 1rem;
        }

        .dashboard-market-timeframe {
            flex: 1 1 0;
            text-align: center;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <h1 class="page-title">Welcome back, {{ user.get_full_name|default:user.username }}! 👋</h1>
    
    <!-- Statistics Cards -->
    <div class="row mb-4 dashboard-stats-row">
        <div class="col-md-3 animate-fade-in animate-delay-1 dashboard-stats-col">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 custom-text-muted">Wallet Balance</p>
                            <h3 class="mb-0 custom-text-white">${{ wallet.balance|default:"0.00" }}</h3>
                        </div>
                        <div class="icon cyan">
                            <i class="bi bi-wallet2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 animate-fade-in animate-delay-2 dashboard-stats-col">
            <div class="card stat-card earnings">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 custom-text-muted">Total Earnings</p>
                            <h3 class="mb-0 custom-text-success">${{ user.total_earnings|default:"0.00" }}</h3>
                        </div>
                        <div class="icon green">
                            <i class="bi bi-graph-up-arrow"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 animate-fade-in animate-delay-3 dashboard-stats-col">
            <div class="card stat-card referrals">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 custom-text-muted">Referrals</p>
                            <h3 class="mb-0 custom-text-white">{{ total_referrals }}</h3>
                            {% if referral_current_level %}
                            <small class="custom-text-warning d-block mt-2">Current Level: {{ referral_current_level }}</small>
                            {% else %}
                            <small class="custom-text-muted d-block mt-2">Current Level: 0</small>
                            {% endif %}
                        </div>
                        <div class="icon orange">
                            <i class="bi bi-people-fill"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 animate-fade-in animate-delay-4 dashboard-stats-col">
            <div class="card stat-card signals">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 custom-text-muted">Active Signals</p>
                            <h3 class="mb-0 custom-text-white">{{ recent_signals.count }}</h3>
                        </div>
                        <div class="icon purple">
                            <i class="bi bi-lightning-charge-fill"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {% with dashboard_settings=automated_signal_dashboard.settings %}
    {% if dashboard_settings.telegram_channel_enabled %}
    {% if dashboard_settings.telegram_channel_url or dashboard_settings.telegram_contact_username %}
    <div class="card telegram-cta-card mb-4">
        <div class="card-body position-relative">
            <div class="row align-items-center g-4">
                <div class="col-lg-8">
                    <div class="d-flex align-items-start gap-3">
                        <div class="telegram-cta-icon">
                            <i class="bi bi-telegram"></i>
                        </div>
                        <div>
                            <span class="badge badge-active mb-3">Community Channel</span>
                            <h3 class="custom-text-white mb-2">{{ dashboard_settings.telegram_channel_title }}</h3>
                            <p class="custom-text-muted mb-0">
                                {{ dashboard_settings.telegram_channel_description|default:"Get market updates, alerts, and announcements directly on Telegram." }}
                            </p>
                            {% if dashboard_settings.telegram_contact_username %}
                            <div class="telegram-direct-meta">
                                <span class="custom-text-muted">Direct connect:</span>
                                <a href="https://t.me/{{ dashboard_settings.telegram_contact_username|cut:'@' }}" target="_blank" rel="noopener noreferrer" class="telegram-direct-chip">
                                    <i class="bi bi-at"></i>@{{ dashboard_settings.telegram_contact_username|cut:'@' }}
                                </a>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
                <div class="col-lg-4 text-lg-end">
                    <div class="telegram-cta-actions">
                        {% if dashboard_settings.telegram_channel_url %}
                        <a href="{{ dashboard_settings.telegram_channel_url }}" target="_blank" rel="noopener noreferrer" class="btn btn-primary btn-lg">
                            <i class="bi bi-send-fill me-2"></i>{{ dashboard_settings.telegram_button_text|default:"Open Telegram" }}
                        </a>
                        {% endif %}
                        {% if dashboard_settings.telegram_contact_username %}
                        <a href="https://t.me/{{ dashboard_settings.telegram_contact_username|cut:'@' }}" target="_blank" rel="noopener noreferrer" class="btn btn-outline-primary">
                            <i class="bi bi-chat-dots-fill me-2"></i>Message @{{ dashboard_settings.telegram_contact_username|cut:'@' }}
                        </a>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    {% endif %}
    {% endwith %}

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0 custom-text-white">Today's Automated Profit Signal</h5>
            {% if automated_signal_dashboard.state == 'available' %}
            <span class="badge badge-pending">Live Now</span>
            {% elif automated_signal_dashboard.state == 'accepted' %}
            <span class="badge badge-approved">Accepted</span>
            {% elif automated_signal_dashboard.state == 'expired' %}
            <span class="badge badge-rejected">Missed Today</span>
            {% elif automated_signal_dashboard.state == 'disabled' %}
            <span class="badge badge-rejected">Disabled</span>
            {% else %}
            <span class="badge badge-active">Scheduled</span>
            {% endif %}
        </div>
        <div class="card-body">
            {% if automated_signal_dashboard.test_mode_enabled %}
            <p class="custom-text-warning mb-3">
                Test mode is enabled. Auto signals are cycling every {{ automated_signal_dashboard.test_interval_minutes }} minute(s).
            </p>
            {% endif %}
            {% with auto_signal=automated_signal_dashboard.representative_signal %}
                {% if automated_signal_dashboard.state == 'available' %}
                <div class="row align-items-center g-4">
                    <div class="col-lg-8">
                        <p class="custom-text-muted mb-2">
                            Signal amount based on current wallet balance:
                            <span class="custom-text-white">${{ automated_signal_dashboard.wallet_signal_amount|floatformat:2 }}</span>
                        </p>
                        <p class="custom-text-muted mb-2">
                            Active approved plan(s): <span class="custom-text-white">{{ automated_signal_dashboard.active_plan_count }}</span>
                        </p>
                        <h3 class="custom-text-white mb-2">
                            Today's profit:
                            <span class="custom-text-success">${{ automated_signal_dashboard.profit_amount|floatformat:2 }}</span>
                        </h3>
                        <div class="d-flex flex-wrap gap-3 mb-3">
                            {% if auto_signal and auto_signal.coin %}
                            <span class="custom-text-muted">
                                Coin:
                                <span class="custom-text-white">{{ auto_signal.coin.name }} ({{ auto_signal.coin.symbol }})</span>
                            </span>
                            {% endif %}
                            {% if auto_signal %}
                            <span class="custom-text-muted">
                                Type:
                                <span class="badge {% if auto_signal.signal_type == 'BUY' %}badge-buy{% else %}badge-sell{% endif %}">
                                    {{ auto_signal.signal_type }}
                                </span>
                            </span>
                            <span class="custom-text-muted">Entry: <span class="custom-text-white">${{ auto_signal.entry_price|floatformat:8 }}</span></span>
                            <span class="custom-text-muted">Target: <span class="custom-text-success">${{ auto_signal.target_price|floatformat:8 }}</span></span>
                            {% endif %}
                        </div>
                        <p class="custom-text-muted mb-0">
                            Window closes in
                            <span
                                id="autoSignalCountdown"
                                class="custom-text-warning fw-semibold"
                                data-expires-at="{{ automated_signal_dashboard.current_expires_at|date:'c' }}"
                            >
                                calculating...
                            </span>.
                            If you skip this signal, your plan moves to the next day and completion gets delayed.
                        </p>
                    </div>
                    <div class="col-lg-4">
                        <form method="post" action="{% url 'accept_daily_signal' %}" class="d-grid gap-3">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="bi bi-check2-circle me-2"></i>Accept Signal
                            </button>
                            <div class="small custom-text-muted">
                                Program target: {{ automated_signal_dashboard.target_multiplier|floatformat:2 }}x in
                                {{ automated_signal_dashboard.completion_days }} accepted signal day(s).
                            </div>
                        </form>
                    </div>
                </div>
                {% elif automated_signal_dashboard.state == 'accepted' %}
                <h3 class="custom-text-white mb-2">
                    Profit credited:
                    <span class="custom-text-success">${{ automated_signal_dashboard.profit_amount|floatformat:2 }}</span>
                </h3>
                {% if automated_signal_dashboard.has_future_signals %}
                <p class="custom-text-muted mb-0">
                    Today's automated signal has already been accepted. Your next signal will be available on
                    <span class="custom-text-white">{{ automated_signal_dashboard.next_release_at|date:"M d, Y g:i A" }}</span>.
                </p>
                {% else %}
                <p class="custom-text-muted mb-0">
                    Today's automated signal has been accepted and your current deposit cycle has completed successfully.
                </p>
                {% endif %}
                {% elif automated_signal_dashboard.state == 'expired' %}
                <h3 class="custom-text-white mb-2">Today's signal window has ended</h3>
                <p class="custom-text-muted mb-0">
                    You did not accept the 10-minute signal window today, so your completion shifts forward.
                    Next signal time:
                    <span class="custom-text-white">{{ automated_signal_dashboard.next_release_at|date:"M d, Y g:i A" }}</span>.
                </p>
                {% elif automated_signal_dashboard.state == 'no_balance' %}
                <h3 class="custom-text-white mb-2">Wallet balance required for signal delivery</h3>
                <p class="custom-text-muted mb-0">
                    Your automated plan exists, but signal dispatch only works when your current wallet balance is greater than $0.00.
                </p>
                {% elif automated_signal_dashboard.state == 'inactive' %}
                <h3 class="custom-text-white mb-2">No active automated signal plan yet</h3>
                <p class="custom-text-muted mb-0">
                    Once your deposit is approved, your automated signal program starts and daily signals appear here at
                    <span class="custom-text-white">{{ automated_signal_dashboard.settings.daily_signal_time|time:"g:i A" }}</span>.
                </p>
                {% elif automated_signal_dashboard.state == 'disabled' %}
                <h3 class="custom-text-white mb-2">Automated signal program is currently paused</h3>
                <p class="custom-text-muted mb-0">
                    The admin has temporarily disabled automated user signals. Your approved plans remain saved and can resume later.
                </p>
                {% else %}
                <h3 class="custom-text-white mb-2">Next automated signal is scheduled</h3>
                <p class="custom-text-muted mb-0">
                    Your next signal will appear on
                    <span class="custom-text-white">{{ automated_signal_dashboard.next_release_at|date:"M d, Y g:i A" }}</span>.
                    Current wallet-based signal amount:
                    <span class="custom-text-white">${{ automated_signal_dashboard.wallet_signal_amount|floatformat:2 }}</span>.
                    The target for new approved deposits is {{ automated_signal_dashboard.target_multiplier|floatformat:2 }}x in
                    {{ automated_signal_dashboard.completion_days }} accepted signal day(s).
                </p>
                {% endif %}
            {% endwith %}
        </div>
    </div>

    {% with dashboard_settings=automated_signal_dashboard.settings %}
    {% if dashboard_settings.show_dashboard_market_overview %}
    <div class="card dashboard-market-card mb-4" id="dashboardMarketSection">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0 custom-text-white">{{ dashboard_settings.dashboard_market_title|default:"Trading Markets" }}</h5>
            <a href="{% url 'coins' %}" class="btn btn-sm btn-outline-primary">Open Full Market</a>
        </div>
        <div class="card-body">
            <div class="row g-0">
                <div class="col-lg-3">
                    <div class="dashboard-market-list" id="dashboardMarketCoinList">
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary"></div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="dashboard-market-chart-wrap">
                        <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
                            <div class="d-flex align-items-center gap-3">
                                <img src="" alt="" class="dashboard-market-coin-icon" id="dashboardMarketFeaturedIcon" style="display:none;">
                                <div>
                                    <h4 class="mb-1 custom-text-white" id="dashboardMarketFeaturedName">Loading market data...</h4>
                                    <small class="custom-text-muted" id="dashboardMarketFeaturedSymbol">Preparing live chart</small>
                                </div>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="dashboard-market-timeframe" data-timeframe="1H">1H</button>
                                <button type="button" class="dashboard-market-timeframe active" data-timeframe="24H">24H</button>
                                <button type="button" class="dashboard-market-timeframe" data-timeframe="7D">7D</button>
                            </div>
                        </div>
                        <div class="d-flex justify-content-between align-items-start mb-3 flex-wrap gap-3">
                            <div>
                                <h2 class="custom-text-white mb-1" id="dashboardMarketFeaturedPrice">$--</h2>
                                <span class="custom-text-muted" id="dashboardMarketFeaturedChange">--</span>
                            </div>
                            <span class="dashboard-signal-badge dashboard-signal-neutral" id="dashboardMarketSignalPill">HOLD</span>
                        </div>
                        <div class="dashboard-market-chart-box">
                            <canvas id="dashboardMarketChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3">
                    <div class="dashboard-market-side">
                        <h5 class="custom-text-white mb-3">Coin Stats</h5>
                        <div class="dashboard-market-stat">
                            <span class="custom-text-muted">24h High</span>
                            <span class="custom-text-white" id="dashboardMarketHigh">$--</span>
                        </div>
                        <div class="dashboard-market-stat">
                            <span class="custom-text-muted">24h Low</span>
                            <span class="custom-text-white" id="dashboardMarketLow">$--</span>
                        </div>
                        <div class="dashboard-market-stat">
                            <span class="custom-text-muted">24h Volume</span>
                            <span class="custom-text-white" id="dashboardMarketVolume">$--</span>
                        </div>
                        <div class="dashboard-market-stat mb-4">
                            <span class="custom-text-muted">RSI (14)</span>
                            <span class="custom-text-white" id="dashboardMarketRsi">--</span>
                        </div>
                        <div class="dashboard-live-signal-card">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h6 class="custom-text-white mb-0">Trading Signal</h6>
                                <span class="badge badge-active">Live</span>
                            </div>
                            <div class="mb-3">
                                <span class="dashboard-signal-badge dashboard-signal-neutral" id="dashboardMarketSignalCard">HOLD</span>
                            </div>
                            <p class="custom-text-muted small mb-0" id="dashboardMarketSignalReason">Based on RSI and price action analysis.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    {% endwith %}
    
    <div class="row">
        <!-- Recent Signals -->
        <div class="col-lg-8 mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 custom-text-white">Latest Trading Signals</h5>
                    <a href="{% url 'signals' %}" class="btn btn-sm btn-primary">View All</a>
                </div>
                <div class="card-body p-0">
                    {% if recent_signals %}
                    <div class="table-responsive">
                        <table class="table mb-0">
                            <thead>
                                <tr>
                                    <th class="custom-text-muted">Coin</th>
                                    <th class="custom-text-muted">Type</th>
                                    <th class="custom-text-muted">Entry</th>
                                    <th class="custom-text-muted">Target</th>
                                    <th class="custom-text-muted">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for signal in recent_signals %}
                                <tr>
                                    <td>
                                        <strong class="custom-text-muted">{{ signal.coin.name }}</strong>
                                        <small class="d-block custom-text-muted">{{ signal.coin.symbol }}</small>
                                    </td>
                                    <td>
                                        <span class="badge {% if signal.signal_type == 'BUY' %}badge-buy{% else %}badge-sell{% endif %}">
                                            {{ signal.signal_type }}
                                        </span>
                                    </td>
                                    <td class="custom-text-muted">${{ signal.entry_price|floatformat:2 }}</td>
                                    <td class="custom-text-muted">${{ signal.target_price|floatformat:2 }}</td>
                                    <td>
                                        <span class="badge badge-{{ signal.status|lower }}">{{ signal.status }}</span>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% else %}
                    <div class="text-center py-5">
                        <i class="bi bi-lightning-charge" style="font-size: 3rem; color: #64748b;"></i>
                        <p class="mt-3 custom-text-muted">No active signals at the moment.</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <!-- Quick Actions & Referral -->
        <div class="col-lg-4 mb-4">
            <!-- Quick Actions -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0 custom-text-white">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="{% url 'deposit_request' %}" class="btn btn-primary">
                            <i class="bi bi-plus-circle me-2"></i>Make Deposit
                        </a>
                        {% if user.is_verified %}
                        <a href="{% url 'withdraw_request' %}" class="btn btn-outline-primary">
                            <i class="bi bi-arrow-up-circle me-2"></i>Withdraw Funds
                        </a>
                        {% else %}
                        <a href="{% url 'identity_verification' %}" class="btn btn-outline-primary">
                            <i class="bi bi-person-badge me-2"></i>Verify ID to Withdraw
                        </a>
                        {% endif %}
                        <a href="{% url 'signals' %}" class="btn btn-outline-primary">
                            <i class="bi bi-lightning-charge me-2"></i>View Signals
                        </a>
                        <a href="{% url 'referral_dashboard' %}" class="btn btn-outline-primary">
                            <i class="bi bi-people me-2"></i>Refer Friends
                        </a>
                    </div>
                    <p class="custom-text-muted mt-3 mb-0">
                        {% if user.verification_status == 'VERIFIED' %}
                        Your ID is verified. Withdrawals are enabled.
                        {% elif user.verification_status == 'PENDING' %}
                        Your verification is under review. Withdrawals will unlock after approval.
                        {% else %}
                        Upload your ID card and selfie to unlock withdrawals.
                        {% endif %}
                    </p>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 custom-text-white">Referral Level</h5>
                    <a href="{% url 'referral_dashboard' %}" class="btn btn-sm btn-outline-primary">View Details</a>
                </div>
                <div class="card-body">
                    {% if referral_current_level %}
                    <h4 class="custom-text-white mb-2">Level {{ referral_current_level }} unlocked</h4>
                    {% if referral_current_level_detail %}
                    <p class="custom-text-muted mb-2">
                        Current team bonus:
                        <span class="custom-text-success">${{ referral_current_level_detail.bonus_amount|floatformat:2 }}</span>
                    </p>
                    {% endif %}
                    {% if referral_latest_team_bonus %}
                    <p class="custom-text-success mb-0">
                        Latest credited bonus: ${{ referral_latest_team_bonus.amount|floatformat:2 }} for Level {{ referral_latest_team_bonus.level_achieved }}.
                    </p>
                    {% endif %}
                    {% else %}
                    <h4 class="custom-text-white mb-2">Level 0</h4>
                    <p class="custom-text-muted mb-0">
                        Build your qualified direct team to unlock your first team bonus.
                    </p>
                    {% endif %}
                </div>
            </div>
            
            <!-- Recent Deposits -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 custom-text-white">Recent Deposits</h5>
                    <a href="{% url 'deposit_history' %}" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body p-0">
                    {% if recent_deposits %}
                    <ul class="list-group list-group-flush">
                        {% for deposit in recent_deposits %}
                        <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent" style="border-color: var(--border-color);">
                            <div>
                                <strong class="d-block custom-text-white">${{ deposit.amount }}</strong>
                                <span class="badge badge-{{ deposit.status|lower }}">{{ deposit.get_status_display }}</span>
                            </div>
                            <small class="custom-text-muted">{{ deposit.created_at|date:"M d" }}</small>
                        </li>
                        {% endfor %}
                    </ul>
                    {% else %}
                    <div class="text-center py-4">
                        <p class="custom-text-muted">No deposits yet.</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
{% if automated_signal_dashboard.settings.show_dashboard_market_overview %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{% endif %}
{% if automated_signal_dashboard.state == 'available' %}
<script>
(function () {
    const countdown = document.getElementById('autoSignalCountdown');
    if (!countdown) {
        return;
    }

    const expiresAt = new Date(countdown.dataset.expiresAt).getTime();

    function updateCountdown() {
        const remaining = expiresAt - Date.now();
        if (remaining <= 0) {
            countdown.textContent = '0m 0s';
            return;
        }

        const minutes = Math.floor(remaining / 60000);
        const seconds = Math.floor((remaining % 60000) / 1000);
        countdown.textContent = `${minutes}m ${seconds}s`;
    }

    updateCountdown();
    setInterval(updateCountdown, 1000);
})();
</script>
{% endif %}
{% if automated_signal_dashboard.settings.show_dashboard_market_overview %}
<script>
(function () {
    const marketSection = document.getElementById('dashboardMarketSection');
    if (!marketSection) {
        return;
    }

    const apiUrl = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin,ethereum,binancecoin,solana,ripple,dogecoin&order=market_cap_desc&sparkline=true&price_change_percentage=1h,24h,7d';
    const coinList = document.getElementById('dashboardMarketCoinList');
    const timeframeButtons = Array.from(document.querySelectorAll('.dashboard-market-timeframe'));
    let dashboardMarketCoins = [];
    let dashboardMarketSelectedCoinId = 'bitcoin';
    let dashboardMarketTimeframe = '24H';
    let dashboardMarketChart = null;

    function getSignalClass(signalLabel) {
        if (signalLabel.indexOf('BUY') !== -1) {
            return 'dashboard-signal-buy';
        }
        if (signalLabel.indexOf('SELL') !== -1) {
            return 'dashboard-signal-sell';
        }
        return 'dashboard-signal-neutral';
    }

    function calculateRsi(prices) {
        if (!prices || prices.length < 14) {
            return 50;
        }

        let gains = 0;
        let losses = 0;
        for (let index = prices.length - 13; index < prices.length; index += 1) {
            const change = prices[index] - prices[index - 1];
            if (change > 0) {
                gains += change;
            } else {
                losses -= change;
            }
        }

        const avgGain = gains / 14;
        const avgLoss = losses / 14;
        if (avgLoss === 0) {
            return 100;
        }

        const rs = avgGain / avgLoss;
        return 100 - (100 / (1 + rs));
    }

    function generateSignal(change, rsi) {
        if (rsi < 30 && change > 0) {
            return { label: 'STRONG BUY', reason: 'Oversold market with upward momentum.' };
        }
        if (rsi < 35 && change > 0) {
            return { label: 'BUY', reason: 'Near oversold zone with improving momentum.' };
        }
        if (rsi > 70 && change < 0) {
            return { label: 'STRONG SELL', reason: 'Overbought market with downside pressure.' };
        }
        if (rsi > 65 && change < 0) {
            return { label: 'SELL', reason: 'Near overbought zone with weakening momentum.' };
        }
        if (change > 3) {
            return { label: 'BUY', reason: 'Strong daily momentum remains positive.' };
        }
        if (change < -3) {
            return { label: 'SELL', reason: 'Price weakness is dominating the session.' };
        }
        return { label: 'HOLD', reason: 'Neutral structure based on RSI and price action.' };
    }

    function formatCompactNumber(value) {
        if (value >= 1000000000) {
            return `$${(value / 1000000000).toFixed(2)}B`;
        }
        if (value >= 1000000) {
            return `$${(value / 1000000).toFixed(2)}M`;
        }
        return `$${Number(value || 0).toLocaleString()}`;
    }

    function renderCoinList() {
        coinList.innerHTML = dashboardMarketCoins.map((coin) => {
            const isActive = coin.id === dashboardMarketSelectedCoinId ? 'active' : '';
            const change = Number(coin.price_change_percentage_24h || 0);
            const changeClass = change >= 0 ? 'custom-text-success' : 'custom-text-danger';

            return `
                <div class="dashboard-market-coin-row ${isActive}" data-coin-id="${coin.id}">
                    <div class="d-flex justify-content-between align-items-center gap-3">
                        <div class="d-flex align-items-center gap-3">
                            <img src="${coin.image}" alt="${coin.symbol}" class="dashboard-market-mini-icon">
                            <div>
                                <strong class="custom-text-white d-block">${coin.symbol.toUpperCase()}</strong>
                                <small class="custom-text-muted">${coin.name}</small>
                            </div>
                        </div>
                        <div class="text-end">
                            <div class="custom-text-white">$${Number(coin.current_price || 0).toLocaleString()}</div>
                            <small class="${changeClass}">${change >= 0 ? '+' : ''}${change.toFixed(2)}%</small>
                        </div>
                    </div>
                </div>
            `;
        }).join('');

        coinList.querySelectorAll('.dashboard-market-coin-row').forEach((row) => {
            row.addEventListener('click', function () {
                dashboardMarketSelectedCoinId = this.dataset.coinId;
                renderCoinList();
                updateMarketCard();
            });
        });
    }

    function getChartData(prices) {
        if (!prices || !prices.length) {
            return [];
        }
        if (dashboardMarketTimeframe === '1H') {
            return prices.slice(-24);
        }
        return prices;
    }

    function updateSignalBadges(signalInfo) {
        const signalPill = document.getElementById('dashboardMarketSignalPill');
        const signalCard = document.getElementById('dashboardMarketSignalCard');
        const className = getSignalClass(signalInfo.label);

        signalPill.className = `dashboard-signal-badge ${className}`;
        signalPill.textContent = signalInfo.label;
        signalCard.className = `dashboard-signal-badge ${className}`;
        signalCard.textContent = signalInfo.label;
        document.getElementById('dashboardMarketSignalReason').textContent = signalInfo.reason;
    }

    function updateMarketCard() {
        const coin = dashboardMarketCoins.find((item) => item.id === dashboardMarketSelectedCoinId) || dashboardMarketCoins[0];
        if (!coin) {
            return;
        }

        const prices = coin.sparkline_in_7d ? coin.sparkline_in_7d.price : [];
        const change = Number(coin.price_change_percentage_24h || 0);
        const rsi = calculateRsi(prices);
        const signalInfo = generateSignal(change, rsi);
        const icon = document.getElementById('dashboardMarketFeaturedIcon');

        icon.src = coin.image;
        icon.alt = coin.symbol;
        icon.style.display = 'block';
        document.getElementById('dashboardMarketFeaturedName').textContent = coin.name;
        document.getElementById('dashboardMarketFeaturedSymbol').textContent = `${coin.symbol.toUpperCase()}/USDT`;
        document.getElementById('dashboardMarketFeaturedPrice').textContent = `$${Number(coin.current_price || 0).toLocaleString()}`;

        const changeElement = document.getElementById('dashboardMarketFeaturedChange');
        changeElement.textContent = `${change >= 0 ? '+' : ''}${change.toFixed(2)}% (24h)`;
        changeElement.className = change >= 0 ? 'custom-text-success' : 'custom-text-danger';

        document.getElementById('dashboardMarketHigh').textContent = `$${Number(coin.high_24h || 0).toLocaleString()}`;
        document.getElementById('dashboardMarketLow').textContent = `$${Number(coin.low_24h || 0).toLocaleString()}`;
        document.getElementById('dashboardMarketVolume').textContent = formatCompactNumber(Number(coin.total_volume || 0));
        document.getElementById('dashboardMarketRsi').textContent = rsi.toFixed(0);
        updateSignalBadges(signalInfo);

        const chartData = getChartData(prices);
        const ctx = document.getElementById('dashboardMarketChart').getContext('2d');
        const color = change >= 0 ? '#10b981' : '#ef4444';
        const gradient = ctx.createLinearGradient(0, 0, 0, 320);
        gradient.addColorStop(0, change >= 0 ? 'rgba(16, 185, 129, 0.25)' : 'rgba(239, 68, 68, 0.25)');
        gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');

        if (dashboardMarketChart) {
            dashboardMarketChart.destroy();
        }

        dashboardMarketChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: chartData.map((_, index) => index + 1),
                datasets: [{
                    data: chartData,
                    borderColor: color,
                    backgroundColor: gradient,
                    borderWidth: 2.5,
                    fill: true,
                    pointRadius: 0,
                    tension: 0.35,
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                },
                scales: {
                    x: {
                        display: false,
                    },
                    y: {
                        grid: {
                            color: 'rgba(148, 163, 184, 0.08)',
                        },
                        ticks: {
                            color: '#64748b',
                        },
                    },
                },
            },
        });
    }

    timeframeButtons.forEach((button) => {
        button.addEventListener('click', function () {
            dashboardMarketTimeframe = this.dataset.timeframe;
            timeframeButtons.forEach((item) => item.classList.remove('active'));
            this.classList.add('active');
            updateMarketCard();
        });
    });

    fetch(apiUrl)
        .then((response) => {
            if (!response.ok) {
                throw new Error('Failed to fetch market data.');
            }
            return response.json();
        })
        .then((data) => {
            dashboardMarketCoins = data;
            renderCoinList();
            updateMarketCard();
        })
        .catch(() => {
            coinList.innerHTML = `
                <div class="text-center py-5">
                    <i class="bi bi-exclamation-circle custom-text-warning" style="font-size: 2rem;"></i>
                    <p class="custom-text-muted mt-3 mb-0">Live market data is temporarily unavailable.</p>
                </div>
            `;
            document.getElementById('dashboardMarketFeaturedName').textContent = 'Market data unavailable';
            document.getElementById('dashboardMarketFeaturedSymbol').textContent = 'Please refresh again later';
        });
})();
</script>
{% endif %}
{% endblock %}
