@extends('layouts.admin')

@section('admin-content')
    <div class="container-fluid">
        <div class="row mb-4">
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <h1 class="h3 mb-1 text-dark">
                                <i class="fas fa-arrow-trend-up text-primary me-2"></i>
                                {{ trans('app.Client Updates') }}
                            </h1>
                            <p class="text-muted mb-0">{{ trans('app.Latest available updates for your clients') }}</p>
                        </div>
                        <a href="{{ route('admin.product-versions.index') }}" class="btn btn-outline-primary">
                            {{ trans('app.View All Versions') }}
                        </a>
                    </div>
                </div>
            </div>
        </div>

        {{-- Controls: Click "View Changelog" to open all changelogs for the product --}}

        <div class="table-responsive">
            <table class="table table-hover table-bordered align-middle">
                <thead>
                    <tr>

                        <th>{{ trans('app.Client') }}</th>
                        <th>{{ trans('app.Current') }}</th>
                        <th>{{ trans('app.Latest') }}</th>
                        <th>{{ trans('app.Status') }}</th>
                        <th>{{ trans('app.Release Type') }}</th>
                        <th style="width:220px">{{ trans('app.Actions') }}</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($productsWithUpdates as $row)
                        @php
                            $product = $row['product'];
                            $current = $row['current'];
                            $latest = $row['latest'];
                            $shouldUpdate = $row['should_update'];
                        @endphp
                        <tr
                            @if ($latest) data-product-id="{{ $product->id }}" data-latest-version="{{ $latest->version }}" data-latest-changelog="{{ base64_encode($latest->changelog ?? '') }}" data-product-name="{{ e($product->name) }}" @endif>

                            <td>
                                <div class="fw-semibold">{{ $product->name }}</div>
                                <div class="small text-muted">Base: {{ $product->category->name ?? '' }}</div>
                            </td>
                            <td class="align-middle">{{ $current?->version ?? '-' }}</td>
                            <td class="align-middle">
                                @if ($latest)
                                    {{ $latest->version }}
                                @else
                                    -
                                @endif
                            </td>
                            <td class="align-middle"><span
                                    class="text-muted">{{ $latest?->status ? ucfirst($latest->status) : '-' }}</span></td>
                            <td class="align-middle">
                                @if ($latest)
                                    <span
                                        class="badge bg-secondary text-uppercase">{{ $latest->release_type ?? 'minor' }}</span>
                                @endif
                            </td>
                            <td class="align-middle">
                                <div class="btn-group btn-group-sm" role="group">
                                    <button type="button" class="btn btn-outline-primary btn-sm view-changelog"
                                        data-product-id="{{ $product->id }}"
                                        data-latest-version="{{ $latest?->version ?? '' }}"
                                        data-name="{{ e($product->name) }}">{{ trans('app.View Changelog') }}</button>
                                    <a href="{{ route('admin.product-versions.categoryVersions', $product->category) }}"
                                        class="btn btn-outline-primary btn-sm">{{ trans('app.View Versions') }}</a>
                                    <a href="{{ route('admin.products.edit', $product) }}"
                                        class="btn btn-outline-primary btn-sm">{{ trans('app.Update Client') }}</a>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6">{{ trans('app.No updates available right now.') }}</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div class="d-flex justify-content-center mt-3">
            {{ $productsWithUpdates->links() }}
        </div>

        <!-- Changelog Modal -->
        <div class="modal fade" id="changelogModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title text-primary" id="changelogModalLabel"></h5>
                        <div class="ms-2">
                            <button type="button" class="btn btn-outline-secondary btn-sm me-2" id="copyAllChangelogs"
                                disabled>{{ trans('app.Copy All') }}</button>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" id="changelogModalBody">
                    </div>
                </div>
            </div>
        </div>



        <script>
            (function() {

                // Fetch and show all changelogs for a product in the modal and enable copy-all
                document.querySelectorAll('.view-changelog').forEach(btn => {
                    btn.addEventListener('click', async (e) => {
                        const productId = btn.dataset.productId;
                        const latestVersion = btn.dataset.latestVersion || '';
                        const name = btn.dataset.name || '';
                        const modalEl = document.getElementById('changelogModal');
                        const modal = new bootstrap.Modal(modalEl);
                        document.getElementById('changelogModalLabel').textContent =
                            `${name} — {{ trans('app.Changelogs') }}`;
                        const body = document.getElementById('changelogModalBody');
                        body.innerHTML = '<p class="text-muted">{{ trans('app.Loading...') }}</p>';
                        const copyBtn = document.getElementById('copyAllChangelogs');
                        copyBtn.disabled = true;
                        try {
                            const res = await fetch(
                                `{{ url('/admin/products') }}/${productId}/changelogs`, {
                                    credentials: 'same-origin'
                                });
                            if (!res.ok) throw new Error('Network response was not ok');
                            const json = await res.json();
                            const versions = json.versions || [];
                            const current = json.product?.current_version || null;
                            if (versions.length === 0) {
                                body.innerHTML =
                                    '<p class="text-muted">{{ trans('app.No changelog provided.') }}</p>';
                            } else {
                                let html = '<div class="list-group">';
                                versions.forEach(v => {
                                    const isCurrent = current && (v.version === current);
                                    const isLatest = latestVersion && (v.version ===
                                        latestVersion);
                                    html +=
                                        `<div class="list-group-item ${isLatest ? ' bg-warning bg-opacity-5' : ''}">`;
                                    html +=
                                        `<div class="d-flex justify-content-between align-items-start">`;
                                    html +=
                                        `<div><strong>${v.version} ${isCurrent && isLatest ? '(Current & Latest)' : isCurrent ? '(Current)' : isLatest ? '(Latest)' : ''}</strong> <span class="badge bg-secondary text-uppercase ms-2">${v.release_type ?? 'minor'}</span> <small class="text-muted ms-2">${v.status ?? ''}</small></div>`;
                                    html +=
                                        `<div class="small text-muted">${new Date(v.created_at).toLocaleString()}</div>`;
                                    html += `</div>`;
                                    html +=
                                        `<div class="mt-2 changelog-content">${v.changelog ? v.changelog : '<p class="text-muted">{{ trans('app.No changelog provided.') }}</p>'}</div>`;
                                    html += `</div>`;
                                });
                                html += '</div>';
                                body.innerHTML = html;
                                copyBtn.disabled = false;
                                copyBtn.onclick = () => {
                                    const nodes = body.querySelectorAll('.changelog-content');
                                    const texts = Array.from(nodes).map(n => n.innerText.trim())
                                        .filter(Boolean);
                                    const allText = texts.join('\n\n---\n\n');
                                    navigator.clipboard.writeText(allText).then(() => {
                                        const orig = copyBtn.textContent;
                                        copyBtn.textContent = '{{ trans('app.Copied!') }}';
                                        setTimeout(() => copyBtn.textContent = orig, 1500);
                                    }).catch(() => {
                                        alert(
                                            '{{ trans('app.Failed to copy to clipboard') }}'
                                        );
                                    });
                                };
                            }
                        } catch (err) {
                            body.innerHTML =
                                `<p class="text-danger">{{ trans('app.Error fetching changelogs:') }} ${err.message}</p>`;
                            copyBtn.disabled = true;
                        }
                        modal.show();
                    });
                });

            })();
        </script>
    </div>
@endsection
