@extends('layouts.admin')

@section('admin-content')
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h1 class="h3 mb-1">{{ trans('app.Base Solution') }}</h1>
                                <p class="text-muted mb-0">{{ trans('app.manage_client_categories') }}</p>
                            </div>
                            <div>
                                <a href="{{ route('admin.product-categories.create') }}" class="btn btn-primary">
                                    <i class="fas fa-plus me-2"></i>
                                    {{ trans('app.new_category') }}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label for="search" class="form-label">{{ trans('app.Search') }}</label>
                                <input type="text" class="form-control" id="search"
                                    placeholder="{{ trans('app.search_categories') }}">
                            </div>
                            <div class="col-md-3">
                                <label for="status" class="form-label">{{ trans('app.Status') }}</label>
                                <select class="form-select" id="status">
                                    <option value="">{{ trans('app.All Status') }}</option>
                                    <option value="active">{{ trans('app.Active') }}</option>
                                    <option value="inactive">{{ trans('app.Inactive') }}</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="sort" class="form-label">{{ trans('app.Sort By') }}</label>
                                <select class="form-select" id="sort">
                                    <option value="name">{{ trans('app.Name') }}</option>
                                    <option value="products">{{ trans('app.Products Count') }}</option>
                                    <option value="sort_order">{{ trans('app.sort_order') }}</option>
                                    <option value="created_at">{{ trans('app.Created Date') }}</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-grid">
                                    <button type="button" class="btn btn-outline-secondary" id="reset-filters-btn">
                                        <i class="fas fa-refresh me-1"></i>
                                        {{ trans('app.Reset') }}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Categories Table -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-light">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-folder me-3 text-primary"></i>
                                <div>
                                    <h5 class="card-title mb-0">{{ trans('app.all_categories') }}</h5>
                                    <small class="text-muted">{{ trans('app.Manage your client categories') }}</small>
                                </div>
                            </div>
                            <div>
                                <span class="badge bg-info fs-6">{{ $categories->count() }}
                                    {{ trans('app.Categories') }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        @if ($categories->count() > 0)
                            <div class="table-responsive">
                                <table class="table table-hover mb-0 product-categories-table">
                                    <thead class="table-light">
                                        <tr>
                                            <th class="text-center">{{ trans('app.Image') }}</th>
                                            <th>{{ trans('app.Name') }}</th>
                                            <th>{{ trans('app.Slug') }}</th>
                                            <th class="text-center">{{ trans('app.Clients') }}</th>
                                            <th class="text-center">{{ trans('app.Status') }}</th>
                                            <th class="text-center">{{ trans('app.sort_order') }}</th>
                                            <th class="text-center">{{ trans('app.Actions') }}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($categories as $category)
                                            <tr>
                                                <td class="text-center">
                                                    @if ($category->image)
                                                        <img src="{{ asset('storage/' . $category->image) }}"
                                                            alt="{{ $category->name }}" class="rounded category-image">
                                                    @else
                                                        <div
                                                            class="bg-light rounded d-flex align-items-center justify-content-center category-avatar">
                                                            <span
                                                                class="text-muted small fw-bold">{{ substr($category->name, 0, 1) }}</span>
                                                        </div>
                                                    @endif
                                                </td>
                                                <td>
                                                    <div class="fw-semibold text-dark">{{ $category->name }}</div>
                                                    <small class="text-muted">{{ $category->slug }}</small>
                                                </td>
                                                <td>
                                                    <span class="text-muted">{{ $category->slug }}</span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="badge bg-info">{{ $category->products->count() }}</span>
                                                </td>
                                                <td class="text-center">
                                                    <div class="d-flex flex-wrap gap-1 justify-content-center">
                                                        <span
                                                            class="badge {{ $category->is_active ? 'bg-success' : 'bg-secondary' }}">
                                                            {{ $category->is_active ? trans('app.Active') : trans('app.Inactive') }}
                                                        </span>
                                                        @if ($category->is_featured)
                                                            <span
                                                                class="badge bg-warning text-dark">{{ trans('app.Featured') }}</span>
                                                        @endif
                                                        @if ($category->show_in_menu)
                                                            <span class="badge bg-info">{{ trans('app.In Menu') }}</span>
                                                        @endif
                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <span class="text-muted">{{ $category->sort_order ?? '—' }}</span>
                                                </td>
                                                <td class="text-center">
                                                    <div class="btn-group-vertical btn-group-sm" role="group">

                                                        <button type="button"
                                                            class="btn btn-outline-secondary btn-sm js-show-versions"
                                                            data-category-id="{{ $category->id }}"
                                                            data-category-name="{{ $category->name }}">
                                                            <i class="fas fa-list me-1"></i>
                                                            {{ __('Versions') }}
                                                        </button>

                                                        <button type="button"
                                                            class="btn btn-outline-secondary btn-sm js-show-client-versions"
                                                            data-category-id="{{ $category->id }}"
                                                            data-category-name="{{ $category->name }}">
                                                            <i class="fas fa-puzzle-piece me-1"></i>
                                                            {{ __('Customization & Addons') }}
                                                        </button>

                                                        <a href="{{ route('admin.product-categories.edit', $category) }}"
                                                            class="btn btn-outline-primary btn-sm">
                                                            <i class="fas fa-edit me-1"></i>
                                                            {{ trans('app.Edit') }}
                                                        </a>

                                                        <form
                                                            action="{{ route('admin.product-categories.destroy', $category) }}"
                                                            method="POST" class="d-inline"
                                                            data-confirm="delete-category">
                                                            @csrf
                                                            @method('DELETE')
                                                            <button type="submit"
                                                                class="btn btn-outline-danger btn-sm w-100">
                                                                <i class="fas fa-trash me-1"></i>
                                                                {{ trans('app.Delete') }}
                                                            </button>
                                                        </form>
                                                    </div>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <div class="text-center py-5">
                                <div class="mb-4">
                                    <i class="fas fa-folder-open text-muted empty-state-icon"></i>
                                </div>
                                <h4 class="text-muted">{{ trans('app.No Categories Found') }}</h4>
                                <p class="text-muted mb-4">
                                    {{ trans('app.Create your first client category to get started') }}</p>
                                <a href="{{ route('admin.product-categories.create') }}" class="btn btn-primary">
                                    <i class="fas fa-plus me-2"></i>
                                    {{ trans('app.Create Category') }}
                                </a>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Pagination -->
        @if ($categories->hasPages())
            <div class="row mt-4">
                <div class="col-12">
                    <div class="d-flex justify-content-center">
                        {{ $categories->links() }}
                    </div>
                </div>
            </div>
        @endif
    </div>

    <!-- Versions Modal -->
    <div class="modal fade" id="versionsModal" 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="versionsModalLabel">{{ __('Versions') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="versions-list list-group"></div>
                </div>
                <div class="modal-footer">
                    <button type="button"
                        class="btn btn-outline-secondary btn-sm js-copy-versions">{{ __('Copy All') }}</button>
                    <button type="button" class="btn btn-secondary btn-sm"
                        data-bs-dismiss="modal">{{ __('Close') }}</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Customization & Addons Modal -->
    <div class="modal fade" id="clientVersionsModal" 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="clientVersionsModalLabel">{{ __('Customization & Addons') }}
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="client-versions-list list-group"></div>
                </div>
                <div class="modal-footer">
                    <button type="button"
                        class="btn btn-outline-secondary btn-sm js-copy-client-versions">{{ __('Copy All') }}</button>
                    <button type="button" class="btn btn-secondary btn-sm"
                        data-bs-dismiss="modal">{{ __('Close') }}</button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript is now handled by admin-categories.js -->

    @push('scripts')
        <script>
            (function() {
                function formatDate(dt) {
                    return dt ? new Date(dt).toLocaleString() : '';
                }

                // Versions modal logic
                const versionsModalEl = document.getElementById('versionsModal');
                const versionsModal = new bootstrap.Modal(versionsModalEl);
                const versionsList = versionsModalEl.querySelector('.versions-list');
                const versionsTitle = versionsModalEl.querySelector('.modal-title');

                // Client Versions modal logic
                const clientModalEl = document.getElementById('clientVersionsModal');
                const clientModal = new bootstrap.Modal(clientModalEl);
                const clientList = clientModalEl.querySelector('.client-versions-list');
                const clientTitle = clientModalEl.querySelector('.modal-title');

                async function fetchAndShowVersions(categoryId, categoryName) {
                    versionsTitle.textContent = `Versions — ${categoryName}`;
                    versionsList.innerHTML = '<div class="text-center py-3 text-muted">Loading…</div>';
                    versionsModal.show();
                    try {
                        const res = await fetch(`/admin/product-versions/${categoryId}/versions-json`, {
                            credentials: 'same-origin'
                        });
                        if (!res.ok) throw new Error('Network response was not ok');
                        const json = await res.json();
                        if (!json.success) throw new Error('Failed to load data');
                        if (!json.versions.length) {
                            versionsList.innerHTML = '<div class="text-center py-3 text-muted">No versions found</div>';
                            return;
                        }
                        versionsList.innerHTML = '';
                        json.versions.forEach(v => {
                            const item = document.createElement('div');
                            item.className = 'list-group-item';
                            item.innerHTML = `
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <div class="fw-semibold">${escapeHtml(v.version)}</div>
                            <small class="text-muted">Note: ${escapeHtml(v.note || '')}</small>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-secondary me-1">${escapeHtml(v.release_type || '')}</span>
                            <span class="badge ${v.status === 'published' ? 'bg-success' : 'bg-secondary'}">${escapeHtml(v.status)}</span>
                            <div><small class="text-muted">${formatDate(v.created_at)}</small></div>
                        </div>
                    </div>
                    <hr/>
                    <div class="changelog">
                        <span class="fw-semibold d-block">Changelog:</span><br/>
                        ${v.changelog || ''}
                        </div>
                `;
                            versionsList.appendChild(item);
                        });
                    } catch (err) {
                        versionsList.innerHTML =
                            `<div class="text-danger py-3">Error loading versions: ${escapeHtml(err.message)}</div>`;
                    }
                }

                async function fetchAndShowClientVersions(categoryId, categoryName) {
                    clientTitle.textContent = `Customization & Addons — ${categoryName}`;
                    clientList.innerHTML = '<div class="text-center py-3 text-muted">Loading…</div>';
                    clientModal.show();
                    try {
                        const res = await fetch(`/admin/product-versions/${categoryId}/client-versions-json`, {
                            credentials: 'same-origin'
                        });
                        if (!res.ok) throw new Error('Network response was not ok');
                        const json = await res.json();
                        if (!json.success) throw new Error('Failed to load data');
                        if (!json.items.length) {
                            clientList.innerHTML =
                                '<div class="text-center py-3 text-muted">No customizations or addons found</div>';
                            return;
                        }
                        clientList.innerHTML = '';
                        json.items.forEach(it => {
                            const item = document.createElement('div');
                            item.className = 'list-group-item';
                            item.innerHTML = `
                    <div class="d-flex justify-content-between align-items-start ">
                        <div>
                            <div class="fw-semibold">${escapeHtml(it.title)} <span class="badge bg-secondary text-uppercase ms-2">${escapeHtml(it.tag || '')}</span><span class="badge rounded-pill bg-info text-dark">${escapeHtml(it.product ? it.product.name : '-')} • v${escapeHtml(it.version)}</span></div>
                        </div>
                        <div class="text-end"><small class="text-muted">${formatDate(it.created_at)}</small></div>
                    </div>
                    <div class="description mb-2"><small class="text-muted d-block">Description: </small>${escapeHtml(it.description || '')}</div>
                    <div class="note small text-muted"> <small class="text-muted d-block">Note: </small>${escapeHtml(it.note || '')}</div>
                    <div class="mt-2"><strong>Cost:</strong> $${escapeHtml(it.cost ?? '-') } &nbsp; <strong>Timeline:</strong> ${escapeHtml(it.timeline ?? '-')}</div>
                `;
                            clientList.appendChild(item);
                        });
                    } catch (err) {
                        clientList.innerHTML =
                            `<div class="text-danger py-3">Error loading items: ${escapeHtml(err.message)}</div>`;
                    }
                }

                // Event delegation for buttons
                document.addEventListener('click', function(e) {
                    const btn = e.target.closest('.js-show-versions, .js-show-client-versions');
                    if (!btn) return;
                    const categoryId = btn.getAttribute('data-category-id');
                    const categoryName = btn.getAttribute('data-category-name');
                    if (btn.classList.contains('js-show-versions')) {
                        fetchAndShowVersions(categoryId, categoryName);
                    } else if (btn.classList.contains('js-show-client-versions')) {
                        fetchAndShowClientVersions(categoryId, categoryName);
                    }
                });

                // Copy all handlers
                document.querySelector('.js-copy-versions').addEventListener('click', function() {
                    const parts = Array.from(versionsList.querySelectorAll('.list-group-item .changelog')).map(el =>
                        el.innerText.trim()).filter(Boolean);
                    const text = parts.join('\n\n---\n\n');
                    if (!text) return;
                    navigator.clipboard.writeText(text);
                    this.textContent = 'Copied';
                    setTimeout(() => this.textContent = '{{ __('Copy All') }}', 1500);
                });

                document.querySelector('.js-copy-client-versions').addEventListener('click', function() {
                    const parts = Array.from(clientList.querySelectorAll('.list-group-item')).map(el => el.innerText
                        .trim()).filter(Boolean);
                    const text = parts.join('\n\n---\n\n');
                    if (!text) return;
                    navigator.clipboard.writeText(text);
                    this.textContent = 'Copied';
                    setTimeout(() => this.textContent = '{{ __('Copy All') }}', 1500);
                });

                // Small helper to escape text when injecting into HTML attributes
                function escapeHtml(unsafe) {
                    if (unsafe === null || unsafe === undefined) return '';
                    return String(unsafe)
                        .replace(/&/g, '&amp;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;')
                        .replace(/"/g, '&quot;')
                        .replace(/'/g, '&#039;');
                }
            })();
        </script>
    @endpush
@endsection
