@props([
    'research' => [],
    'modalId' => 'catalog-research-modal',
    'buttonClass' => 'mb-btn-ghost',
    'buttonLabel' => 'View ranking & JSON',
])

@php
    $products = is_array($research['products'] ?? null) ? array_values($research['products']) : [];
    $ranking = is_array($research['ranking'] ?? null) ? $research['ranking'] : [];
    $json = json_encode($research, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '{}';
    $hasResearch = $products !== [] || $research !== [];
@endphp

@if ($hasResearch)
    <button type="button" class="{{ $buttonClass }}" data-bs-toggle="modal" data-bs-target="#{{ $modalId }}">
        {{ $buttonLabel }}
    </button>

    <div class="modal fade" id="{{ $modalId }}" tabindex="-1" aria-labelledby="{{ $modalId }}-label" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="{{ $modalId }}-label">Catalog research & ranking</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body">
                    @if ($ranking !== [])
                        <dl class="row small mb-3">
                            @if (isset($ranking['source']))
                                <dt class="col-sm-3">Ranker</dt>
                                <dd class="col-sm-9">{{ $ranking['source'] }}</dd>
                            @endif
                            @if (isset($ranking['selected_count']))
                                <dt class="col-sm-3">Selected</dt>
                                <dd class="col-sm-9">{{ $ranking['selected_count'] }} of {{ $research['candidate_count'] ?? '?' }} candidates</dd>
                            @endif
                            @if (isset($ranking['keywords_enabled']))
                                <dt class="col-sm-3">Keywords</dt>
                                <dd class="col-sm-9">{{ ($ranking['keywords_enabled'] ?? false) ? 'Enabled' : 'Disabled' }}</dd>
                            @endif
                            @if (filled($research['user_keyword_seeds'] ?? null))
                                <dt class="col-sm-3">User seeds</dt>
                                <dd class="col-sm-9">{{ implode(', ', $research['user_keyword_seeds']) }}</dd>
                            @endif
                            @if (filled($research['ai_keyword_seeds'] ?? null))
                                <dt class="col-sm-3">AI seeds</dt>
                                <dd class="col-sm-9">{{ implode(', ', $research['ai_keyword_seeds']) }}</dd>
                            @endif
                            @if (filled($research['keyword_seeds'] ?? null))
                                <dt class="col-sm-3">Research seeds</dt>
                                <dd class="col-sm-9">{{ count($research['keyword_seeds']) }} merged seed{{ count($research['keyword_seeds']) === 1 ? '' : 's' }}</dd>
                            @endif
                            @if (filled($research['keyword_ideas_fetched'] ?? null))
                                <dt class="col-sm-3">Keyword ideas</dt>
                                <dd class="col-sm-9">
                                    {{ $research['keyword_ideas_curated_count'] ?? count($research['keywords'] ?? []) }} relevant
                                    @if ((int) ($research['keyword_ideas_fetched'] ?? 0) > (int) ($research['keyword_ideas_curated_count'] ?? count($research['keywords'] ?? [])))
                                        <span class="text-muted">(filtered from {{ $research['keyword_ideas_fetched'] }} fetched)</span>
                                    @endif
                                </dd>
                            @endif
                        </dl>
                    @endif

                    <ul class="nav nav-tabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="{{ $modalId }}-ranking-tab" data-bs-toggle="tab" data-bs-target="#{{ $modalId }}-ranking-pane" type="button" role="tab">
                                Ranking ({{ count($products) }})
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="{{ $modalId }}-json-tab" data-bs-toggle="tab" data-bs-target="#{{ $modalId }}-json-pane" type="button" role="tab">
                                Research JSON
                            </button>
                        </li>
                    </ul>

                    <div class="tab-content border border-top-0 rounded-bottom p-3 bg-white">
                        <div class="tab-pane fade show active" id="{{ $modalId }}-ranking-pane" role="tabpanel">
                            @if ($products === [])
                                <p class="text-muted mb-0">No ranked products saved yet.</p>
                            @else
                                <div class="vstack gap-3">
                                    @foreach ($products as $product)
                                        <div class="border rounded-3 p-3">
                                            <div class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-2">
                                                <div>
                                                    <span class="badge bg-primary me-2">#{{ $product['rank'] ?? '?' }}</span>
                                                    <strong>{{ $product['name'] ?? $product['url'] ?? 'Product' }}</strong>
                                                    @if (filled($product['best_for'] ?? null))
                                                        <span class="badge bg-success ms-2">{{ $product['best_for'] }}</span>
                                                    @endif
                                                </div>
                                                @if (filled($product['ranking_source'] ?? null))
                                                    <span class="badge bg-secondary">{{ $product['ranking_source'] }}</span>
                                                @endif
                                            </div>

                                            @if (filled($product['url'] ?? null))
                                                <div class="small mb-2">
                                                    <a href="{{ $product['url'] }}" target="_blank" rel="noopener">{{ $product['url'] }}</a>
                                                </div>
                                            @endif

                                            <dl class="row small mb-0">
                                                @if (filled($product['rating'] ?? null) || filled($product['review_count'] ?? null))
                                                    <dt class="col-sm-3">Listing signals</dt>
                                                    <dd class="col-sm-9">
                                                        @if (filled($product['rating'] ?? null))
                                                            {{ $product['rating'] }} stars
                                                        @endif
                                                        @if (filled($product['review_count'] ?? null))
                                                            · {{ $product['review_count'] }} reviews
                                                        @endif
                                                        @if (filled($product['price'] ?? null))
                                                            · {{ $product['price'] }}
                                                        @endif
                                                    </dd>
                                                @endif

                                                @if (filled($product['product_keywords']['primary'] ?? null) || filled($product['keywords']['primary'] ?? null))
                                                    <dt class="col-sm-3">Imported keywords</dt>
                                                    <dd class="col-sm-9">
                                                        {{ $product['product_keywords']['primary'] ?? $product['keywords']['primary'] }}
                                                        @php
                                                            $related = $product['product_keywords']['related'] ?? $product['keywords']['related'] ?? [];
                                                        @endphp
                                                        @if (is_array($related) && $related !== [])
                                                            <div class="text-muted">Related: {{ implode(', ', $related) }}</div>
                                                        @endif
                                                    </dd>
                                                @endif

                                                @php
                                                    $generatedSeeds = $product['keyword_seeds_generated']
                                                        ?? $product['keyword_research']['generated_seeds']
                                                        ?? null;
                                                @endphp
                                                @if (is_array($generatedSeeds))
                                                    @if (filled($generatedSeeds['user'] ?? null))
                                                        <dt class="col-sm-3">User seeds</dt>
                                                        <dd class="col-sm-9">{{ implode(', ', $generatedSeeds['user']) }}</dd>
                                                    @endif
                                                    @if (filled($generatedSeeds['ai'] ?? null))
                                                        <dt class="col-sm-3">AI seeds</dt>
                                                        <dd class="col-sm-9">{{ implode(', ', $generatedSeeds['ai']) }}</dd>
                                                    @endif
                                                    @if (filled($generatedSeeds['heuristic'] ?? null))
                                                        <dt class="col-sm-3">Heuristic seeds</dt>
                                                        <dd class="col-sm-9">{{ implode(', ', $generatedSeeds['heuristic']) }}</dd>
                                                    @endif
                                                @endif

                                                @if (filled($product['matched_keyword'] ?? null))
                                                    <dt class="col-sm-3">Keyword</dt>
                                                    <dd class="col-sm-9">
                                                        {{ $product['matched_keyword'] }}
                                                        @if (filled($product['keyword_search_volume'] ?? null))
                                                            · {{ number_format((int) $product['keyword_search_volume']) }} monthly searches
                                                        @endif
                                                        @if (filled($product['keyword_competition'] ?? null))
                                                            · {{ $product['keyword_competition'] }} competition
                                                        @endif
                                                    </dd>
                                                @endif

                                                @if (filled($product['keyword_match_reason'] ?? null))
                                                    <dt class="col-sm-3">Keyword match</dt>
                                                    <dd class="col-sm-9">
                                                        @if (filled($product['keyword_match_source'] ?? null))
                                                            <span class="text-uppercase">{{ $product['keyword_match_source'] }}</span>:
                                                        @endif
                                                        {{ $product['keyword_match_reason'] }}
                                                    </dd>
                                                @endif

                                                @if (filled($product['selection_reason'] ?? null))
                                                    <dt class="col-sm-3">Selection</dt>
                                                    <dd class="col-sm-9">{{ $product['selection_reason'] }}</dd>
                                                @endif

                                                @if (filled($product['ranking_reason'] ?? null))
                                                    <dt class="col-sm-3">Ranked above next</dt>
                                                    <dd class="col-sm-9">{{ $product['ranking_reason'] }}</dd>
                                                @endif
                                            </dl>
                                        </div>
                                    @endforeach
                                </div>
                            @endif
                        </div>

                        <div class="tab-pane fade" id="{{ $modalId }}-json-pane" role="tabpanel">
                            <div class="d-flex justify-content-end mb-2">
                                <button type="button" class="mb-btn-ghost" data-copy-json="{{ $modalId }}-json">
                                    Copy JSON
                                </button>
                            </div>
                            <pre id="{{ $modalId }}-json" class="small bg-light border rounded p-3 mb-0" style="max-height: 420px; overflow: auto;"><code>{{ $json }}</code></pre>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="mb-btn-ghost" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    @once
        @push('scripts')
            <script>
                document.addEventListener('click', (event) => {
                    const button = event.target.closest('[data-copy-json]');

                    if (!button) {
                        return;
                    }

                    const target = document.getElementById(button.dataset.copyJson);

                    if (!target) {
                        return;
                    }

                    navigator.clipboard.writeText(target.textContent.trim()).then(() => {
                        const original = button.textContent;
                        button.textContent = 'Copied';
                        setTimeout(() => {
                            button.textContent = original;
                        }, 1500);
                    });
                });
            </script>
        @endpush
    @endonce
@endif
