<div class="space-y-6">
    {{-- Header --}}
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <h1 class="text-2xl font-bold text-ink">{{ __('Knowledge Agent Insights') }}</h1>
            <p class="text-sm text-muted mt-0.5">
                {{ __('See what your AI is answering, where it gets stuck, and which sources are doing the work.') }}
            </p>
        </div>
        <div class="flex items-center gap-2">
            <a href="{{ route('knowledge-base') }}"
               class="text-sm text-muted hover:text-ink inline-flex items-center gap-1.5">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
                {{ __('Back to library') }}
            </a>
        </div>
    </div>

    {{-- Empty state shown when the workspace hasn't added any KB content
         yet. Without this every chart is zero-filled which makes the page
         look broken on a fresh install. --}}
    @if(!$this->hasKbContent)
        <div class="panel p-8 text-center border-2 border-dashed border-border">
            <div class="w-12 h-12 bg-primary-50 dark:bg-primary-900/20 rounded-xl flex items-center justify-center mx-auto mb-3">
                <svg class="w-6 h-6 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/></svg>
            </div>
            <p class="text-sm font-semibold text-ink">{{ __('No knowledge base content yet') }}</p>
            <p class="text-xs text-muted mt-1 max-w-md mx-auto">
                {{ __('Add documents, websites, or Q&A pairs to your knowledge base and your AI will start answering customer questions automatically. Come back here to see how it’s performing.') }}
            </p>
            <a href="{{ route('knowledge-base') }}"
               class="btn-primary text-sm inline-flex items-center gap-2 mt-4">
                {{ __('Add knowledge') }}
            </a>
        </div>
    @endif

    {{-- Range + channel filters --}}
    <div class="flex flex-wrap items-center gap-2">
        <span class="text-xs text-muted uppercase tracking-wide font-medium mr-1">{{ __('Range') }}:</span>
        @foreach([7 => '7d', 30 => '30d', 90 => '90d'] as $days => $label)
            <button wire:click="setRange({{ $days }})"
                    class="px-3 py-1 text-xs font-medium rounded-lg border transition-colors {{ $rangeDays === $days ? 'bg-primary-600 text-white border-primary-600' : 'bg-surface-2 text-muted border-border hover:text-ink' }}">
                {{ $label }}
            </button>
        @endforeach

        @if(count($this->availableChannels) > 0)
            <span class="text-xs text-muted uppercase tracking-wide font-medium ml-3 mr-1">{{ __('Channel') }}:</span>
            <button wire:click="setChannel(null)"
                    class="px-3 py-1 text-xs font-medium rounded-lg border transition-colors {{ $channelFilter === null ? 'bg-primary-600 text-white border-primary-600' : 'bg-surface-2 text-muted border-border hover:text-ink' }}">
                {{ __('All') }}
            </button>
            @foreach($this->availableChannels as $channel)
                <button wire:click="setChannel('{{ $channel }}')"
                        class="px-3 py-1 text-xs font-medium rounded-lg border transition-colors {{ $channelFilter === $channel ? 'bg-primary-600 text-white border-primary-600' : 'bg-surface-2 text-muted border-border hover:text-ink' }}">
                    {{ ucfirst($channel) }}
                </button>
            @endforeach
        @endif
    </div>

    {{-- KPI cards. Deflection rate is the headline number — the one
         marketing screenshots will lead with. --}}
    <div class="grid grid-cols-2 lg:grid-cols-5 gap-4">
        <div class="bg-surface-2 rounded-xl border border-border p-4">
            <p class="text-xs text-muted font-medium uppercase tracking-wide">{{ __('Deflection Rate') }}</p>
            <p class="text-2xl font-bold text-ink mt-1">{{ $this->stats['deflection_rate'] }}%</p>
            <p class="text-[11px] text-muted mt-0.5">{{ $this->stats['answered'] }} {{ __('answered') }} / {{ $this->stats['total'] }} {{ __('total') }}</p>
        </div>
        <div class="bg-surface-2 rounded-xl border border-border p-4">
            <p class="text-xs text-muted font-medium uppercase tracking-wide">{{ __('Questions Answered') }}</p>
            <p class="text-2xl font-bold text-ink mt-1">{{ number_format($this->stats['total']) }}</p>
            <p class="text-[11px] text-muted mt-0.5">{{ __('last') }} {{ $rangeDays }}d</p>
        </div>
        <div class="bg-surface-2 rounded-xl border border-border p-4">
            <p class="text-xs text-muted font-medium uppercase tracking-wide">{{ __('Avg Confidence') }}</p>
            <p class="text-2xl font-bold text-ink mt-1">{{ $this->stats['avg_confidence'] }}</p>
            <p class="text-[11px] text-muted mt-0.5">{{ __('out of 100') }}</p>
        </div>
        <div class="bg-surface-2 rounded-xl border border-border p-4">
            <p class="text-xs text-muted font-medium uppercase tracking-wide">{{ __('Hours Saved') }}</p>
            <p class="text-2xl font-bold text-ink mt-1">{{ $this->stats['hours_saved'] }}</p>
            <p class="text-[11px] text-muted mt-0.5">{{ __('vs human-answered') }}</p>
        </div>
        <div class="bg-surface-2 rounded-xl border border-border p-4">
            <p class="text-xs text-muted font-medium uppercase tracking-wide">{{ __('Total AI Cost') }}</p>
            <p class="text-2xl font-bold text-ink mt-1">${{ number_format($this->stats['total_cost'], 2) }}</p>
            <p class="text-[11px] text-muted mt-0.5">${{ number_format($this->stats['avg_cost'], 4) }} / {{ __('answer') }}</p>
        </div>
    </div>

    {{-- Most-asked questions row. Clustered semantically so 15 phrasings
         of "what's your refund policy?" surface as one entry with a
         count of 15 — turning a flat answer log into something the team
         can actually act on. --}}
    @if(!empty($this->topAskedQuestions) || !empty($this->clusteredGaps))
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div class="panel p-0 overflow-hidden">
                <div class="px-5 py-4 border-b border-border">
                    <p class="panel-heading">{{ __('Most-Asked Questions') }}</p>
                    <p class="text-xs text-muted mt-0.5">
                        {{ __('Topics customers keep asking about — clustered so similar phrasings count as one.') }}
                    </p>
                </div>
                @if(empty($this->topAskedQuestions))
                    <div class="px-5 py-10 text-center">
                        <p class="text-sm text-muted">{{ __('No answered questions in this window.') }}</p>
                    </div>
                @else
                    <div class="divide-y divide-border">
                        @foreach($this->topAskedQuestions as $cluster)
                            <div class="px-5 py-3 flex items-center gap-3">
                                <span class="px-2 py-0.5 rounded-full text-xs font-bold bg-primary-600/10 text-primary-600 shrink-0">
                                    ×{{ $cluster['count'] }}
                                </span>
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm text-ink line-clamp-1">{{ $cluster['representative'] }}</p>
                                    <p class="text-[11px] text-muted mt-0.5">
                                        {{ __('Last asked') }} {{ \Carbon\Carbon::parse($cluster['last_asked'])->diffForHumans() }}
                                    </p>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif
            </div>

            <div class="panel p-0 overflow-hidden">
                <div class="px-5 py-4 border-b border-border">
                    <p class="panel-heading">{{ __('Top Gap Clusters') }}</p>
                    <p class="text-xs text-muted mt-0.5">
                        {{ __('Recurring questions the agent could not answer — fix the biggest one first.') }}
                    </p>
                </div>
                @if(empty($this->clusteredGaps))
                    <div class="px-5 py-10 text-center">
                        <p class="text-sm text-muted">{{ __('No recurring gaps — your KB covers what customers ask.') }}</p>
                    </div>
                @else
                    <div class="divide-y divide-border">
                        @foreach($this->clusteredGaps as $cluster)
                            <div class="px-5 py-3 flex items-center gap-3">
                                <span class="px-2 py-0.5 rounded-full text-xs font-bold bg-warning/10 text-warning shrink-0">
                                    ×{{ $cluster['count'] }}
                                </span>
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm text-ink line-clamp-1">{{ $cluster['representative'] }}</p>
                                    <p class="text-[11px] text-muted mt-0.5">
                                        {{ __('Last asked') }} {{ \Carbon\Carbon::parse($cluster['last_asked'])->diffForHumans() }}
                                    </p>
                                </div>
                                <a href="{{ route('knowledge-base') }}?addQa={{ urlencode($cluster['representative']) }}"
                                   class="shrink-0 inline-flex items-center gap-1 px-2 py-1 text-[11px] font-medium rounded-lg bg-primary-600/10 text-primary-600 hover:bg-primary-600/20">
                                    {{ __('Fix') }}
                                </a>
                            </div>
                        @endforeach
                    </div>
                @endif
            </div>
        </div>
    @endif

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {{-- Knowledge gaps — left 2/3. These are the most-actionable items
             on the whole page: questions the agent failed to answer well
             because nothing in the KB matched. --}}
        <div class="lg:col-span-2 panel p-0 overflow-hidden">
            <div class="px-5 py-4 border-b border-border flex items-center justify-between">
                <div>
                    <p class="panel-heading">{{ __('Knowledge Gaps') }}</p>
                    <p class="text-xs text-muted mt-0.5">
                        {{ __('Customer questions your AI could not answer. Each one is a candidate Q&A to add.') }}
                    </p>
                </div>
                <span class="px-2 py-0.5 rounded-full text-[11px] font-semibold bg-warning/10 text-warning">
                    {{ $this->stats['fallbacks'] }} {{ __('total') }}
                </span>
            </div>
            @if($this->knowledgeGaps->isEmpty())
                <div class="px-5 py-10 text-center">
                    <p class="text-sm text-muted">
                        {{ $this->stats['total'] > 0 ? __('No gaps in this window — your AI answered every question with confidence.') : __('No questions logged yet in this window.') }}
                    </p>
                </div>
            @else
                <div class="divide-y divide-border">
                    @foreach($this->knowledgeGaps as $gap)
                        <div class="px-5 py-4 hover:bg-surface-2/40 transition-colors">
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm font-medium text-ink line-clamp-2">{{ $gap->question }}</p>
                                    <div class="flex flex-wrap items-center gap-3 mt-1.5 text-[11px] text-muted">
                                        @if($gap->channel)
                                            <span class="inline-flex items-center gap-1">
                                                <span class="w-1.5 h-1.5 rounded-full bg-muted/60"></span>
                                                {{ ucfirst($gap->channel) }}
                                            </span>
                                        @endif
                                        <span>{{ __('Confidence') }}: {{ $gap->confidence }}</span>
                                        <span>{{ $gap->created_at->diffForHumans() }}</span>
                                    </div>
                                </div>
                                {{-- "Add to KB" pre-fills a Q&A on the document
                                     manager with this question as the Q field.
                                     Wired via query string the doc manager
                                     already reads. --}}
                                <a href="{{ route('knowledge-base') }}?addQa={{ urlencode($gap->question) }}"
                                   class="shrink-0 inline-flex items-center gap-1.5 px-2.5 py-1 text-[11px] font-medium rounded-lg bg-primary-600/10 text-primary-600 hover:bg-primary-600/20 transition-colors">
                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                                    {{ __('Add to KB') }}
                                </a>
                            </div>
                        </div>
                    @endforeach
                </div>
            @endif
        </div>

        {{-- Top sources — right 1/3. Lets admin see which documents are
             pulling weight and which are dead. --}}
        <div class="panel p-0 overflow-hidden">
            <div class="px-5 py-4 border-b border-border">
                <p class="panel-heading">{{ __('Top Sources') }}</p>
                <p class="text-xs text-muted mt-0.5">
                    {{ __('Most-cited knowledge base documents.') }}
                </p>
            </div>
            @if(empty($this->topSources))
                <div class="px-5 py-10 text-center">
                    <p class="text-sm text-muted">{{ __('No citations yet in this window.') }}</p>
                </div>
            @else
                <div class="divide-y divide-border">
                    @foreach($this->topSources as $source)
                        <div class="px-5 py-3 flex items-center gap-3">
                            <div class="w-8 h-8 rounded-lg bg-primary-50 dark:bg-primary-900/20 flex items-center justify-center shrink-0">
                                @if($source['type'] === 'website')
                                    <svg class="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9"/></svg>
                                @elseif($source['type'] === 'qa')
                                    <svg class="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                @else
                                    <svg class="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                                @endif
                            </div>
                            <div class="min-w-0 flex-1">
                                @if($source['source_url'])
                                    <a href="{{ $source['source_url'] }}" target="_blank" rel="noopener"
                                       class="text-sm text-ink hover:text-primary-600 truncate block">{{ $source['title'] }}</a>
                                @else
                                    <p class="text-sm text-ink truncate">{{ $source['title'] }}</p>
                                @endif
                            </div>
                            <span class="text-xs font-semibold text-muted shrink-0">{{ $source['citations'] }}</span>
                        </div>
                    @endforeach
                </div>
            @endif
        </div>
    </div>

    {{-- Recent answers feed. Admin can mark answers helpful/unhelpful
         from here as a tuning signal — customer-facing thumbs go in the
         widget/email channels in Phase 1 and update the same column. --}}
    <div class="panel p-0 overflow-hidden">
        <div class="px-5 py-4 border-b border-border flex items-center justify-between gap-3">
            <div>
                <p class="panel-heading">{{ __('Recent Answers') }}</p>
                <p class="text-xs text-muted mt-0.5">
                    {{ __('A live tail of what your AI has been saying. Mark answers helpful or unhelpful to tune.') }}
                </p>
            </div>
            <button wire:click="toggleOnlyGaps"
                    class="px-3 py-1 text-xs font-medium rounded-lg border transition-colors {{ $onlyGaps ? 'bg-warning/15 text-warning border-warning/30' : 'bg-surface-2 text-muted border-border hover:text-ink' }}">
                {{ $onlyGaps ? __('Showing gaps only') : __('Show only gaps') }}
            </button>
        </div>
        @if($this->recentLogs->isEmpty())
            <div class="px-5 py-10 text-center">
                <p class="text-sm text-muted">{{ __('No replies in this window yet.') }}</p>
            </div>
        @else
            <div class="divide-y divide-border">
                @foreach($this->recentLogs as $log)
                    <div class="px-5 py-4">
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0 flex-1">
                                <p class="text-sm font-medium text-ink line-clamp-2">{{ $log->question }}</p>
                                <p class="text-xs text-muted mt-1 line-clamp-3 whitespace-pre-line">{{ $log->answer }}</p>
                                <div class="flex flex-wrap items-center gap-3 mt-2 text-[11px] text-muted">
                                    @if($log->channel)
                                        <span>{{ ucfirst($log->channel) }}</span>
                                    @endif
                                    <span>{{ __('Confidence') }}: {{ $log->confidence }}</span>
                                    @if($log->was_fallback)
                                        <span class="px-1.5 py-0.5 rounded-full bg-warning/10 text-warning font-medium">{{ __('Fallback') }}</span>
                                    @endif
                                    @if(!empty($log->cited_chunk_ids))
                                        <span>{{ count($log->cited_chunk_ids) }} {{ __('sources') }}</span>
                                    @endif
                                    <span>{{ $log->created_at->diffForHumans() }}</span>
                                </div>
                            </div>
                            <div class="flex items-center gap-1 shrink-0">
                                <button wire:click="markHelpful({{ $log->id }}, true)"
                                        title="{{ __('Mark helpful') }}"
                                        class="p-1.5 rounded-lg transition-colors {{ $log->was_helpful === true ? 'bg-success/15 text-success' : 'text-muted hover:bg-surface hover:text-ink' }}">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"/></svg>
                                </button>
                                <button wire:click="markHelpful({{ $log->id }}, false)"
                                        title="{{ __('Mark unhelpful') }}"
                                        class="p-1.5 rounded-lg transition-colors {{ $log->was_helpful === false ? 'bg-danger/15 text-danger' : 'text-muted hover:bg-surface hover:text-ink' }}">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06L17 4m-7 10v5a2 2 0 002 2h.095c.5 0 .905-.405.905-.905 0-.714.211-1.412.608-2.006L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5"/></svg>
                                </button>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        @endif
    </div>
</div>
