@extends('backoffice.layouts.app')

@section('title', ' CRM')

@section('content')
<div class="container-fluid crm-page">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
                <div>
                    <h2 class="mb-1 d-flex align-items-center gap-2">
                        <i class="bi bi-person-lines-fill"></i>
                        <span> CRM</span>
                    </h2>
                    <p class="text-muted mb-0">Oyuncu detaylarını hızlı inceleyin.</p>
                </div>

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

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" action="{{ route('backoffice.crm.index') }}">
                <div class="row g-3 align-items-end">
                    <div class="col-lg-8">
                        <label class="form-label">Oyuncu Ara</label>
                        <input
                            type="text"
                            id="crmSearchInput"
                            name="q"
                            class="form-control"
                            value="{{ $search }}"
                            placeholder="UYE ADI VEYA IP"
                            autocomplete="off"
                            minlength="3"
                        >
                        <div class="form-text">Oyuncu adı ile arama için minimum 3 karakter girin. IP araması aynen çalışır.</div>
                    </div>
                    <div class="col-lg-4">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary flex-fill">
                                <i class="bi bi-search me-1"></i>Ara
                            </button>
                            <a href="{{ route('backoffice.crm.index') }}" class="btn btn-light border flex-fill">
                                <i class="bi bi-arrow-counterclockwise me-1"></i>Temizle
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    @if(($effectiveSearch ?? '') !== '')
        <div class="row g-4">
            <div class="col-xxl-4 col-xl-5">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Eşleşen Profiller</h5>
                        <span class="badge bg-light text-dark border">{{ $profiles->count() }}</span>
                    </div>
                    <div class="card-body p-0">
                        @if($profiles->isEmpty())
                            <div class="p-4 text-muted">Eşleşen profil bulunamadı.</div>
                        @else
                            <div class="crm-profile-list" data-load-more-list="profiles" data-load-more-size="8">
                                @foreach($profiles as $profile)
                                    @php
                                        $isActive = (string) request('profile_type') === (string) $profile['selector_type']
                                            && (string) request('profile_value') === (string) $profile['selector_value']
                                            && (string) request('profile_site_id') === (string) ($profile['site_id'] ?? '')
                                            && (string) request('profile_site_sid') === (string) ($profile['site_sid'] ?? '');
                                    @endphp
                                    <a
                                        href="{{ route('backoffice.crm.index', ['q' => $search, 'profile_type' => $profile['selector_type'], 'profile_value' => $profile['selector_value'], 'profile_site_id' => $profile['site_id'], 'profile_site_sid' => $profile['site_sid']]) }}"
                                        class="crm-profile-card {{ $isActive ? 'is-active' : '' }}"
                                        data-load-more-item
                                    >
                                        <div class="d-flex justify-content-between align-items-start gap-3">
                                            <div>
                                                <div class="fw-semibold">{{ $profile['display_name'] }}</div>
                                                @if(!empty($profile['names']) && $profile['display_name'] !== ($profile['names'][0] ?? null))
                                                    <div class="small text-muted">{{ $profile['names'][0] }}</div>
                                                @endif
                                            </div>
                                            <div class="crm-profile-meta">
                                                @if(!empty($profile['site_name']))
                                                    <span class="badge crm-site-badge">{{ $profile['site_name'] }}</span>
                                                @endif
                                            </div>
                                        </div>
                                        <div class="crm-profile-stats">
                                            <span class="crm-stat-chip success">Onaylı Yatırım: {{ number_format($profile['approved_deposit_total'], 2, ',', '.') }}</span>
                                            <span class="crm-stat-chip danger">Onaylı Çekim: {{ number_format($profile['approved_withdrawal_total'], 2, ',', '.') }}</span>
                                            <span class="crm-stat-chip neutral">Onaylı Auto Yatırım Sayısı: {{ $profile['approved_auto_deposit_count'] }}</span>
                                        </div>
                                    </a>
                                @endforeach
                            </div>
                            @if($profiles->count() > 8)
                                <div class="crm-load-more-wrap">
                                    <button type="button" class="btn crm-load-more-btn" data-load-more-button="profiles">
                                        <span class="crm-load-more-label">Daha Fazla</span>
                                        <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                                    </button>
                                </div>
                            @endif
                        @endif
                    </div>
                </div>
            </div>

            <div class="col-xxl-8 col-xl-7">
                @if(empty($profileDetails))
                    <div class="card border-0 shadow-sm h-100">
                        <div class="card-body d-flex align-items-center justify-content-center text-center text-muted min-vh-25">
                            Soldan bir profil seçerek detayları görüntüleyin.
                        </div>
                    </div>
                @else
                    <div class="d-grid gap-4">
                        <div class="card border-0 shadow-sm">
                            <div class="card-header bg-white d-flex justify-content-between align-items-start flex-wrap gap-3">
                                <div>
                                    <h5 class="mb-1">{{ $profileDetails['display_name'] }}</h5>
                                    <div class="small text-muted">
                                        @if($profileDetails['customer_player_ids']->isNotEmpty())
                                            Oyuncu ID: {{ $profileDetails['customer_player_ids']->implode(', ') }}
                                        @else
                                            Profil: {{ $profileDetails['selector_value'] }}
                                        @endif
                                    </div>
                                </div>
                                <div class="small text-muted text-end">
                                    <div>İlk işlem: {{ optional($profileDetails['first_transaction_at'])->format('d.m.Y H:i') ?: '-' }}</div>
                                    <div>Son işlem: {{ optional($profileDetails['last_transaction_at'])->format('d.m.Y H:i') ?: '-' }}</div>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row g-3 crm-summary-grid">
                                    <div class="col-md-6 col-xl-4">
                                        <div class="crm-summary-card">
                                            <div class="crm-summary-head">
                                                <div class="crm-summary-icon neutral">
                                                    <i class="bi bi-bar-chart-line-fill"></i>
                                                </div>
                                                <div class="crm-summary-label">Toplam İşlem (Tüm Durumlar)</div>
                                            </div>
                                            <div class="crm-summary-value">{{ $profileDetails['total_transactions'] }}</div>
                                            <div class="crm-summary-divider"></div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-arrow-down-circle-fill text-success"></i>
                                                <span>Yatırım: <strong>{{ $profileDetails['deposit_count'] }}</strong> / Auto: <strong>{{ $profileDetails['deposit_auto_count'] }}</strong> / Manuel: <strong>{{ $profileDetails['deposit_manual_count'] }}</strong></span>
                                            </div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-arrow-up-circle-fill text-danger"></i>
                                                <span>Çekim: <strong>{{ $profileDetails['withdrawal_count'] }}</strong> / Auto: <strong>{{ $profileDetails['withdrawal_auto_count'] }}</strong> / Manuel: <strong>{{ $profileDetails['withdrawal_manual_count'] }}</strong></span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-xl-4">
                                        <div class="crm-summary-card success">
                                            <div class="crm-summary-head">
                                                <div class="crm-summary-icon success">
                                                    <i class="bi bi-arrow-down-left-circle-fill"></i>
                                                </div>
                                                <div class="crm-summary-label">Yatırım Toplamı (Tüm Durumlar)</div>
                                            </div>
                                            <div class="crm-summary-value">{{ number_format($profileDetails['deposit_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</div>
                                            <div class="crm-summary-divider"></div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-collection-fill text-primary"></i>
                                                <span>Toplam işlem: <strong>{{ $profileDetails['deposit_count'] }}</strong></span>
                                            </div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-check-circle-fill text-success"></i>
                                                <span>Onaylı: <strong>{{ $profileDetails['deposit_approved_count'] }}</strong> / <strong>{{ number_format($profileDetails['approved_deposit_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</strong></span>
                                            </div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-x-circle-fill text-danger"></i>
                                                <span>Reddedildi: <strong>{{ $profileDetails['deposit_declined_count'] }}</strong> / <strong>{{ number_format($profileDetails['deposit_declined_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</strong></span>
                                            </div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-clock-fill text-warning"></i>
                                                <span>Beklemede: <strong>{{ $profileDetails['deposit_pending_count'] }}</strong> / <strong>{{ number_format($profileDetails['deposit_pending_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</strong></span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6 col-xl-4">
                                        <div class="crm-summary-card danger">
                                            <div class="crm-summary-head">
                                                <div class="crm-summary-icon danger">
                                                    <i class="bi bi-arrow-up-right-circle-fill"></i>
                                                </div>
                                                <div class="crm-summary-label">Çekim Toplamı (Tüm Durumlar)</div>
                                            </div>
                                            <div class="crm-summary-value">{{ number_format($profileDetails['withdrawal_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</div>
                                            <div class="crm-summary-divider"></div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-collection-fill text-primary"></i>
                                                <span>Toplam işlem: <strong>{{ $profileDetails['withdrawal_count'] }}</strong></span>
                                            </div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-check-circle-fill text-success"></i>
                                                <span>Onaylı: <strong>{{ $profileDetails['withdrawal_approved_count'] }}</strong> / <strong>{{ number_format($profileDetails['approved_withdrawal_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</strong></span>
                                            </div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-x-circle-fill text-danger"></i>
                                                <span>Reddedildi: <strong>{{ $profileDetails['withdrawal_declined_count'] }}</strong> / <strong>{{ number_format($profileDetails['withdrawal_declined_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</strong></span>
                                            </div>
                                            <div class="crm-summary-sub">
                                                <i class="bi bi-clock-fill text-warning"></i>
                                                <span>Beklemede: <strong>{{ $profileDetails['withdrawal_pending_count'] }}</strong> / <strong>{{ number_format($profileDetails['withdrawal_pending_total'], 2, ',', '.') }} {{ $profileDetails['currency'] }}</strong></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <div class="row g-4">
                            <div class="col-xl-8">
                                <div class="card border-0 shadow-sm h-100 crm-history-card">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0">Son 20 Yatırım</h5>
                                    </div>
                                    <div class="card-body p-0 crm-scroll-panel crm-history-panel">
                                        <div class="table-responsive">
                                            <table class="table table-sm align-middle mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Tarih</th>
                                                        <th>Kaynak</th>
                                                        <th>Durum</th>
                                                        <th>Tutar</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @forelse($profileDetails['recent_deposits'] as $transaction)
                                                        @php($statusMeta = \App\Http\Controllers\Backoffice\CrmController::crmStatusMeta($transaction->status))
                                                        <tr class="{{ $statusMeta['row_class'] }}">
                                                            <td>{{ optional($transaction->created_at)->format('d.m.Y H:i') }}</td>
                                                            <td>{{ $transaction->source === 'auto' ? 'Auto' : 'Manuel' }}</td>
                                                            <td>{{ $statusMeta['label'] }}</td>
                                                            <td>{{ number_format((float) $transaction->amount, 2, ',', '.') }} {{ $transaction->currency }}</td>
                                                        </tr>
                                                    @empty
                                                        <tr><td colspan="4" class="text-center text-muted py-4">Yatırım bulunmuyor.</td></tr>
                                                    @endforelse
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-4">
                                <div class="card border-0 shadow-sm h-100">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0">IP Adresleri</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="crm-ip-list" data-load-more-list="ips" data-load-more-size="6">
                                            @forelse($profileDetails['ip_breakdown'] as $ip)
                                                <div class="crm-ip-item" data-load-more-item>
                                                    <div class="d-flex justify-content-between gap-3">
                                                        <div>
                                                            <div class="fw-semibold">{{ $ip['ip_address'] }}</div>
                                                            <div class="small text-muted mt-1">
                                                                @if(!empty($ip['country_code2']))
                                                                    <img
                                                                        src="https://flagcdn.com/20x15/{{ strtolower($ip['country_code2']) }}.png"
                                                                        alt="{{ $ip['country_code2'] }}"
                                                                        class="crm-country-flag"
                                                                        loading="lazy"
                                                                    >
                                                                @endif
                                                                {{ $ip['country_name'] ?: 'Ülke bilgisi alınamadı' }}
                                                            </div>
                                                        </div>
                                                        <span class="badge bg-light text-dark border">{{ $ip['count'] }}</span>
                                                    </div>
                                                </div>
                                            @empty
                                                <div class="text-muted">IP kaydı bulunmuyor.</div>
                                            @endforelse
                                        </div>
                                        @if($profileDetails['ip_breakdown']->count() > 6)
                                            <div class="crm-load-more-wrap crm-load-more-wrap-tight">
                                                <button type="button" class="btn crm-load-more-btn" data-load-more-button="ips">
                                                    <span class="crm-load-more-label">Daha Fazla</span>
                                                    <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                                                </button>
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endif
            </div>
        </div>
    @endif
</div>
@endsection

@push('styles')
<style>
    #crmSearchInput {
        text-transform: uppercase;
    }
    .crm-profile-list {
        display: grid;
        gap: 1px;
        background: #eef2f7;
    }
    .crm-profile-card {
        display: block;
        padding: 1rem 1.1rem;
        background: #fff;
        color: inherit;
        text-decoration: none;
        transition: background 0.15s ease, border-color 0.15s ease;
        border-left: 3px solid transparent;
    }
    .crm-profile-card:hover {
        background: #f8fbff;
        border-left-color: #0d6efd;
    }
    .crm-profile-card.is-active {
        background: #eef6ff;
        border-left-color: #0d6efd;
    }
    .crm-profile-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 0.4rem;
        flex-shrink: 0;
    }
    .crm-site-badge {
        max-width: 140px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        background: #e9f2ff;
        color: #1d4ed8;
        border: 1px solid #bfdbfe;
    }
    .crm-profile-stats {
        display: flex;
        flex-wrap: wrap;
        gap: 0.45rem;
        margin-top: 0.85rem;
    }
    .crm-stat-chip,
    .crm-tag {
        display: inline-flex;
        align-items: center;
        border-radius: 999px;
        padding: 0.28rem 0.65rem;
        font-size: 0.78rem;
        font-weight: 600;
    }
    .crm-stat-chip.success,
    .crm-tag {
        background: #e8f7ef;
        color: #166534;
    }
    .crm-stat-chip.danger {
        background: #fdecec;
        color: #b91c1c;
    }
    .crm-stat-chip.neutral,
    .crm-tag.crm-tag-alt {
        background: #eef2f7;
        color: #334155;
    }
    .crm-summary-card {
        height: 100%;
        border: 1px solid #dbe4f0;
        border-radius: 16px;
        padding: 1.1rem 1.15rem;
        background: #fff;
        box-shadow: 0 12px 30px rgba(15, 23, 42, 0.06);
    }
    .crm-summary-note {
        margin-bottom: 0.9rem;
        padding: 0.7rem 0.85rem;
        border: 1px solid #dbe4f0;
        border-radius: 12px;
        background: #f8fbff;
        color: #475569;
        font-size: 0.84rem;
    }
    .crm-summary-card.success {
        border: 2px solid #86efac;
    }
    .crm-summary-card.danger {
        border: 2px solid #fca5a5;
    }
    .crm-summary-head {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 0.75rem;
    }
    .crm-summary-icon {
        width: 2.4rem;
        height: 2.4rem;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        font-size: 1.1rem;
        background: #f8fafc;
        color: #475569;
        border: 1px solid #e2e8f0;
    }
    .crm-summary-icon.success {
        background: #ecfdf3;
        color: #15803d;
        border-color: #86efac;
    }
    .crm-summary-icon.danger {
        background: #fff1f2;
        color: #dc2626;
        border-color: #fca5a5;
    }
    .crm-summary-icon.neutral {
        background: #eff6ff;
        color: #2563eb;
        border-color: #bfdbfe;
    }
    .crm-summary-label {
        font-size: 0.86rem;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        color: #64748b;
        margin-bottom: 0;
        font-weight: 700;
    }
    .crm-summary-value {
        font-size: 1.5rem;
        font-weight: 800;
        color: #0f172a;
        line-height: 1.15;
    }
    .crm-summary-divider {
        height: 1px;
        margin: 0.85rem 0 0.65rem;
        border: 0;
        background: linear-gradient(90deg, rgba(148, 163, 184, 0.08) 0%, rgba(148, 163, 184, 0.65) 18%, rgba(148, 163, 184, 0.65) 82%, rgba(148, 163, 184, 0.08) 100%);
    }
    .crm-summary-card.success .crm-summary-divider {
        background: linear-gradient(90deg, rgba(34, 197, 94, 0.08) 0%, rgba(34, 197, 94, 0.5) 18%, rgba(34, 197, 94, 0.5) 82%, rgba(34, 197, 94, 0.08) 100%);
    }
    .crm-summary-card.danger .crm-summary-divider {
        background: linear-gradient(90deg, rgba(239, 68, 68, 0.08) 0%, rgba(239, 68, 68, 0.5) 18%, rgba(239, 68, 68, 0.5) 82%, rgba(239, 68, 68, 0.08) 100%);
    }
    .crm-summary-sub {
        margin-top: 0.45rem;
        font-size: 0.95rem;
        color: #334155;
        display: flex;
        align-items: flex-start;
        gap: 0.55rem;
        font-weight: 600;
    }
    .crm-summary-sub i {
        font-size: 0.95rem;
        margin-top: 0.12rem;
        flex-shrink: 0;
    }
    .crm-summary-sub strong {
        font-weight: 800;
        color: #0f172a;
    }
    .crm-ip-list {
        display: grid;
        gap: 0.75rem;
    }
    .crm-ip-item {
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        padding: 0.8rem 0.9rem;
        background: #fff;
    }
    .crm-country-flag {
        display: inline-block;
        margin-right: 0.35rem;
        width: 20px;
        height: 15px;
        object-fit: cover;
        border-radius: 2px;
        vertical-align: -0.18em;
        box-shadow: 0 0 0 1px rgba(148, 163, 184, 0.25);
    }
    .crm-scroll-panel {
        overflow: auto;
        scrollbar-width: thin;
        scrollbar-color: #94a3b8 #eff6ff;
        min-height: 0;
    }
    .crm-history-card {
        min-height: 100%;
    }
    .crm-history-panel {
        flex: 1 1 auto;
        min-height: 0;
        overflow: auto;
    }
    .crm-history-panel .table-responsive {
        min-height: 100%;
    }
    .crm-scroll-panel::-webkit-scrollbar {
        width: 10px;
        height: 10px;
    }
    .crm-scroll-panel::-webkit-scrollbar-track {
        background: #eff6ff;
    }
    .crm-scroll-panel::-webkit-scrollbar-thumb {
        background: linear-gradient(180deg, #93c5fd 0%, #60a5fa 100%);
        border-radius: 999px;
        border: 2px solid #eff6ff;
    }
    .crm-scroll-panel::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(180deg, #60a5fa 0%, #2563eb 100%);
    }
    .crm-scroll-panel .table {
        margin-bottom: 0;
    }
    .crm-scroll-panel .table tbody tr:nth-child(even):not(.is-approved):not(.is-declined) > td {
        background: #fafcff;
    }
    .crm-scroll-panel .table tbody tr.is-approved > td {
        background: #eefaf3;
    }
    .crm-scroll-panel .table tbody tr.is-declined > td {
        background: #fff1f1;
    }
    .crm-scroll-panel .table tbody tr td {
        border-color: #e5e7eb;
    }
    [data-load-more-item].is-hidden {
        display: none;
    }
    .crm-load-more-wrap {
        padding: 1rem 1.1rem 1.15rem;
        border-top: 1px solid #eef2f7;
        background: linear-gradient(180deg, rgba(248,250,252,0) 0%, #f8fafc 100%);
    }
    .crm-load-more-wrap-tight {
        padding: 1rem 0 0;
        border-top: 0;
        background: transparent;
    }
    .crm-load-more-btn {
        width: 100%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 0.6rem;
        border-radius: 999px;
        border: 1px solid #dbe4f0;
        background: #fff;
        color: #0f172a;
        font-weight: 600;
        padding: 0.72rem 1rem;
        box-shadow: 0 8px 20px rgba(15, 23, 42, 0.06);
    }
    .crm-load-more-btn:hover {
        background: #f8fbff;
        border-color: #bfd5ff;
        color: #0d6efd;
    }
    .crm-load-more-btn.is-loading {
        pointer-events: none;
    }
    .min-vh-25 {
        min-height: 25vh;
    }
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('crmSearchInput');

    function normalizeCrmSearchValue(value) {
        return String(value || '')
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^A-Za-z0-9.\s]/g, '')
            .replace(/\s+/g, ' ')
            .trimStart()
            .toUpperCase();
    }

    function syncSearchValue() {
        const normalized = normalizeCrmSearchValue(searchInput.value);
        if (searchInput.value !== normalized) {
            const end = normalized.length;
            searchInput.value = normalized;
            searchInput.setSelectionRange(end, end);
        }
    }

    if (searchInput) {
        searchInput.addEventListener('input', syncSearchValue);
        searchInput.addEventListener('paste', function () {
            requestAnimationFrame(syncSearchValue);
        });
        syncSearchValue();
    }

    document.querySelectorAll('[data-load-more-list]').forEach(function (list) {
        const listId = list.getAttribute('data-load-more-list');
        const pageSize = Number(list.getAttribute('data-load-more-size') || 6);
        const items = Array.from(list.querySelectorAll('[data-load-more-item]'));
        const button = document.querySelector('[data-load-more-button="' + listId + '"]');
        let visibleCount = pageSize;

        if (!items.length) {
            if (button) {
                button.closest('.crm-load-more-wrap')?.classList.add('d-none');
            }
            return;
        }

        function renderItems() {
            items.forEach(function (item, index) {
                item.classList.toggle('is-hidden', index >= visibleCount);
            });

            if (!button) {
                return;
            }

            const remaining = items.length - visibleCount;
            const wrapper = button.closest('.crm-load-more-wrap');

            if (remaining <= 0) {
                wrapper?.classList.add('d-none');
                return;
            }

            wrapper?.classList.remove('d-none');
            const label = button.querySelector('.crm-load-more-label');
            if (label) {
                label.textContent = 'Daha Fazla (' + remaining + ')';
            }
        }

        renderItems();

        if (!button) {
            return;
        }

        button.addEventListener('click', function () {
            const spinner = button.querySelector('.spinner-border');
            button.classList.add('is-loading');
            spinner?.classList.remove('d-none');

            window.setTimeout(function () {
                visibleCount += pageSize;
                renderItems();
                spinner?.classList.add('d-none');
                button.classList.remove('is-loading');
            }, 280);
        });
    });
});
</script>
@endpush
