<div>
    {{-- Flash message --}}
    @if(session()->has('message'))
        <div class="mb-4 rounded-lg bg-green-50 p-3 text-sm text-green-700">
            {{ session('message') }}
        </div>
    @endif

    @if($editing)
        {{-- ====== EDIT MODE ====== --}}
        <div class="rounded-xl border border-primary-200 bg-white p-6">
            <h3 class="mb-4 text-lg font-semibold text-gray-900">Edit Tool</h3>

            <div class="space-y-4">
                <x-form-input wire:model="editName" label="Name" type="text"
                    :error="$errors->first('editName')" />

                <x-form-textarea wire:model="editDescription" label="Description" rows="2"
                    :error="$errors->first('editDescription')" />

                <x-form-input wire:model.number="editTimeout" label="Timeout (seconds)" type="number" min="1" max="300"
                    :error="$errors->first('editTimeout')" />

                <x-form-select wire:model="editRiskLevel" label="Risk Level" hint="Controls tool availability in Watcher mode projects">
                    <option value="">Not classified</option>
                    @foreach($riskLevels as $level)
                        <option value="{{ $level->value }}">{{ $level->label() }}</option>
                    @endforeach
                </x-form-select>
            </div>

            <div class="mt-6 flex gap-3">
                <button wire:click="save" class="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700">
                    Save Changes
                </button>
                <button wire:click="cancelEdit" class="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                    Cancel
                </button>
            </div>
        </div>
    @else
        {{-- ====== VIEW MODE ====== --}}
        {{-- Header --}}
        <div class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
            <div class="min-w-0">
                <div class="flex flex-wrap items-center gap-2">
                    <h2 class="text-xl font-bold text-gray-900">{{ $tool->name }}</h2>
                    @if($tool->isPlatformTool())
                        <span class="inline-flex items-center rounded-full bg-violet-100 px-2.5 py-0.5 text-xs font-medium text-violet-700">Platform</span>
                    @else
                        <x-status-badge :status="$tool->status->value" />
                    @endif
                    <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium
                        {{ match($tool->type->value) {
                            'mcp_stdio' => 'bg-blue-100 text-blue-800',
                            'mcp_http' => 'bg-cyan-100 text-cyan-800',
                            'mcp_bridge' => 'bg-purple-100 text-purple-800',
                            'built_in' => 'bg-amber-100 text-amber-800',
                            default => 'bg-gray-100 text-gray-800',
                        } }}">
                        {{ $tool->type->label() }}
                    </span>
                    @if($tool->risk_level)
                        <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {{ $tool->risk_level->color() }}">
                            {{ $tool->risk_level->label() }}
                        </span>
                    @endif
                </div>
                @if($tool->description)
                    <p class="mt-1 text-sm text-gray-500">{{ $tool->description }}</p>
                @endif
            </div>

            <div class="flex flex-wrap gap-2">
                @if($tool->isPlatformTool())
                    @php $isActivated = $activation?->isActive() ?? false; @endphp
                    <button wire:click="toggleStatus"
                        class="rounded-lg border px-3 py-1.5 text-sm font-medium transition
                            {{ $isActivated
                                ? 'border-gray-300 text-gray-700 hover:bg-gray-50'
                                : 'border-primary-500 bg-primary-600 text-white hover:bg-primary-700' }}">
                        {{ $isActivated ? 'Deactivate' : 'Activate' }}
                    </button>
                @else
                    <button wire:click="toggleStatus"
                        class="rounded-lg border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50">
                        {{ $tool->status === \App\Domain\Tool\Enums\ToolStatus::Active ? 'Disable' : 'Enable' }}
                    </button>
                    <button wire:click="startEdit"
                        class="rounded-lg border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50">
                        Edit
                    </button>
                    <button wire:click="deleteTool" wire:confirm="Are you sure you want to delete this tool?"
                        class="rounded-lg border border-red-300 px-3 py-1.5 text-sm font-medium text-red-700 hover:bg-red-50">
                        Delete
                    </button>
                @endif
            </div>
        </div>

        {{-- Tabs --}}
        @php
            $tabs = ['overview' => 'Overview', 'config' => 'Configuration', 'agents' => 'Agents', 'middleware' => 'Middleware'];
            if ($tool->isPlatformTool()) {
                $tabs['activation'] = 'Team Setup';
            }
        @endphp
        <div class="mb-6 border-b border-gray-200">
            <nav class="-mb-px flex gap-6 overflow-x-auto scrollbar-none">
                @foreach($tabs as $tab => $label)
                    <button wire:click="$set('activeTab', '{{ $tab }}')"
                        class="whitespace-nowrap border-b-2 pb-3 text-sm font-medium transition
                            {{ $activeTab === $tab
                                ? 'border-primary-600 text-primary-600'
                                : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700' }}">
                        {{ $label }}
                    </button>
                @endforeach
            </nav>
        </div>

        {{-- Tab: Overview --}}
        @if($activeTab === 'overview')
            <div class="grid gap-6 lg:grid-cols-2">
                <div class="rounded-xl border border-gray-200 bg-white p-5">
                    <h4 class="mb-3 text-sm font-semibold uppercase tracking-wider text-gray-400">Details</h4>
                    <dl class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Slug</dt>
                            <dd class="font-mono text-xs text-gray-700">{{ $tool->slug }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Functions</dt>
                            <dd class="text-gray-700">{{ $tool->functionCount() }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Risk Level</dt>
                            <dd>
                                @if($tool->risk_level)
                                    <span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium {{ $tool->risk_level->color() }}">
                                        {{ $tool->risk_level->label() }}
                                    </span>
                                @else
                                    <span class="text-gray-400">Not classified</span>
                                @endif
                            </dd>
                        </div>
                        @if(! $tool->isPlatformTool())
                            <div class="flex justify-between">
                                <dt class="text-gray-500">Credential</dt>
                                <dd>
                                    @if($linkedCredential)
                                        <a href="{{ route('credentials.show', $linkedCredential->id) }}" class="text-primary-600 hover:text-primary-800 text-xs font-medium">
                                            {{ $linkedCredential->name }}
                                            <span class="text-gray-400">({{ $linkedCredential->credential_type->label() }})</span>
                                        </a>
                                    @elseif(! empty($tool->credentials))
                                        <span class="text-xs text-gray-500">Inline key (encrypted)</span>
                                    @else
                                        <span class="text-xs text-gray-400">None</span>
                                    @endif
                                </dd>
                            </div>
                        @endif
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Timeout</dt>
                            <dd class="text-gray-700">{{ $tool->settings['timeout'] ?? 30 }}s</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Health</dt>
                            <dd class="text-gray-700">{{ $tool->health_status ?? 'Unknown' }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-gray-500">Created</dt>
                            <dd class="text-gray-700">{{ $tool->created_at->format('M j, Y H:i') }}</dd>
                        </div>
                        @if($tool->isPlatformTool())
                            <div class="flex justify-between">
                                <dt class="text-gray-500">Team Status</dt>
                                <dd>
                                    @if($activation?->isActive())
                                        <span class="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">Active for your team</span>
                                    @else
                                        <span class="inline-flex items-center rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-500">Not activated</span>
                                    @endif
                                </dd>
                            </div>
                        @endif
                    </dl>
                </div>

                @if(! $tool->isPlatformTool() && ($tool->transport_config['kind'] ?? '') === 'browser')
                    <div class="rounded-xl border border-gray-200 bg-white p-5">
                        <h4 class="mb-3 text-sm font-semibold uppercase tracking-wider text-gray-400">Proxy Configuration</h4>
                        <p class="mb-3 text-xs text-gray-500">Route browser traffic through a proxy for residential IP access. Only this tool uses the selected proxy.</p>
                        <div class="space-y-3">
                            <x-form-select wire:model="proxyCredentialId" label="Proxy Credential">
                                <option value="">None (direct connection)</option>
                                @foreach($proxyCredentials as $pc)
                                    <option value="{{ $pc->id }}">{{ $pc->name }} ({{ $pc->secret_data['protocol'] ?? 'socks5' }}://{{ $pc->secret_data['host'] ?? '?' }}:{{ $pc->secret_data['port'] ?? '?' }})</option>
                                @endforeach
                            </x-form-select>
                            <div class="flex items-center justify-between">
                                <a href="{{ route('credentials.create') }}" class="text-xs text-primary-600 hover:text-primary-800">+ Create proxy credential</a>
                                <button wire:click="saveProxyCredential" class="rounded-lg bg-primary-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-primary-700">
                                    Save Proxy
                                </button>
                            </div>
                        </div>
                    </div>
                @endif

                <div class="rounded-xl border border-gray-200 bg-white p-5">
                    <h4 class="mb-3 text-sm font-semibold uppercase tracking-wider text-gray-400">Tool Functions</h4>
                    @if($tool->tool_definitions)
                        <ul class="space-y-2 text-sm">
                            @foreach($tool->tool_definitions as $def)
                                <li class="rounded-lg bg-gray-50 px-3 py-2">
                                    <span class="font-mono text-xs font-medium text-gray-900">{{ $def['name'] ?? 'unnamed' }}</span>
                                    @if(isset($def['description']))
                                        <p class="mt-0.5 text-xs text-gray-500">{{ \Illuminate\Support\Str::limit($def['description'], 100) }}</p>
                                    @endif
                                </li>
                            @endforeach
                        </ul>
                    @elseif($tool->isBuiltIn())
                        <p class="text-sm text-gray-500">Built-in tool functions are generated at runtime.</p>
                    @else
                        <p class="text-sm text-gray-400">No tool definitions stored. Schema discovery needed.</p>
                    @endif
                </div>
            </div>
        @endif

        {{-- Tab: Configuration --}}
        @if($activeTab === 'config')
            <div class="rounded-xl border border-gray-200 bg-white p-5">
                <h4 class="mb-3 text-sm font-semibold uppercase tracking-wider text-gray-400">Transport Configuration</h4>
                <pre class="overflow-x-auto rounded-lg bg-gray-50 p-4 text-xs text-gray-700">{{ json_encode($tool->transport_config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) }}</pre>
            </div>

            @if($tool->settings)
                <div class="mt-4 rounded-xl border border-gray-200 bg-white p-5">
                    <h4 class="mb-3 text-sm font-semibold uppercase tracking-wider text-gray-400">Settings</h4>
                    <pre class="overflow-x-auto rounded-lg bg-gray-50 p-4 text-xs text-gray-700">{{ json_encode($tool->settings, JSON_PRETTY_PRINT) }}</pre>
                </div>
            @endif
        @endif

        {{-- Tab: Agents --}}
        @if($activeTab === 'agents')
            <div class="rounded-xl border border-gray-200 bg-white">
                @if($agents->isEmpty())
                    <div class="px-6 py-12 text-center text-sm text-gray-400">
                        No agents are using this tool yet.
                    </div>
                @else
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Agent</th>
                                <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Priority</th>
                                <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Status</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            @foreach($agents as $agent)
                                <tr class="transition hover:bg-gray-50">
                                    <td class="px-6 py-4">
                                        <a href="{{ route('agents.show', $agent) }}" class="font-medium text-primary-600 hover:text-primary-800">
                                            {{ $agent->name }}
                                        </a>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-500">{{ $agent->pivot->priority ?? 0 }}</td>
                                    <td class="px-6 py-4">
                                        <x-status-badge :status="$agent->status->value" />
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                @endif
            </div>
        @endif

        {{-- Tab: Middleware --}}
        @if($activeTab === 'middleware')
            <div class="space-y-4">
                <div class="rounded-xl border border-gray-200 bg-white p-5">
                    <h4 class="mb-3 text-sm font-semibold text-gray-900">Execution Middleware Pipeline</h4>
                    <p class="mb-4 text-sm text-gray-500">Middleware runs on every tool invocation. Built-in middleware is always active. Add custom middleware for additional controls.</p>

                    <div class="space-y-2">
                        <div class="flex items-center gap-3 rounded-lg bg-gray-50 px-3 py-2 text-sm">
                            <span class="inline-flex rounded bg-green-100 px-2 py-0.5 text-[10px] font-semibold text-green-700">Built-in</span>
                            <span class="font-medium text-gray-700">Rate Limit</span>
                            <span class="text-gray-400">- Throttles calls per team (configurable via tool config)</span>
                        </div>
                        <div class="flex items-center gap-3 rounded-lg bg-gray-50 px-3 py-2 text-sm">
                            <span class="inline-flex rounded bg-green-100 px-2 py-0.5 text-[10px] font-semibold text-green-700">Built-in</span>
                            <span class="font-medium text-gray-700">Input Validation</span>
                            <span class="text-gray-400">- Validates input size and blocked patterns</span>
                        </div>
                        <div class="flex items-center gap-3 rounded-lg bg-gray-50 px-3 py-2 text-sm">
                            <span class="inline-flex rounded bg-green-100 px-2 py-0.5 text-[10px] font-semibold text-green-700">Built-in</span>
                            <span class="font-medium text-gray-700">Audit Log</span>
                            <span class="text-gray-400">- Logs all tool invocations with timing</span>
                        </div>

                        @foreach($middlewareConfigs as $mw)
                            <div class="flex items-center justify-between rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm {{ $mw->enabled ? '' : 'opacity-50' }}">
                                <div class="flex items-center gap-3">
                                    <span class="inline-flex rounded bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700">Custom</span>
                                    <span class="font-medium text-gray-700">{{ $mw->label }}</span>
                                    <span class="text-xs text-gray-400">Priority: {{ $mw->priority }}</span>
                                </div>
                                <span class="text-xs {{ $mw->enabled ? 'text-green-600' : 'text-gray-400' }}">
                                    {{ $mw->enabled ? 'Active' : 'Disabled' }}
                                </span>
                            </div>
                        @endforeach

                        @if($middlewareConfigs->isEmpty())
                            <p class="mt-2 text-center text-xs text-gray-400">No custom middleware configured. Use MCP tools to add middleware.</p>
                        @endif
                    </div>
                </div>
            </div>
        @endif

        {{-- Tab: Team Setup (platform tools only) --}}
        @if($activeTab === 'activation' && $tool->isPlatformTool())
            <div class="space-y-6">
                {{-- Activation status card --}}
                <div class="rounded-xl border border-gray-200 bg-white p-5">
                    <div class="flex items-center justify-between">
                        <div>
                            <h4 class="text-sm font-semibold text-gray-900">Team Activation</h4>
                            <p class="mt-1 text-sm text-gray-500">
                                Enable this platform tool for your team. Your credentials are stored securely and never shared.
                            </p>
                        </div>
                        <div class="flex items-center gap-3">
                            @if($activation?->isActive())
                                <span class="inline-flex items-center rounded-full bg-green-100 px-3 py-1 text-sm font-medium text-green-700">Active</span>
                            @else
                                <span class="inline-flex items-center rounded-full bg-gray-100 px-3 py-1 text-sm font-medium text-gray-500">Inactive</span>
                            @endif
                            <button wire:click="toggleStatus"
                                class="rounded-lg border px-3 py-1.5 text-sm font-medium transition
                                    {{ $activation?->isActive()
                                        ? 'border-gray-300 text-gray-700 hover:bg-gray-50'
                                        : 'border-primary-500 bg-primary-600 text-white hover:bg-primary-700' }}">
                                {{ $activation?->isActive() ? 'Deactivate' : 'Activate' }}
                            </button>
                        </div>
                    </div>
                    @if($activation?->activated_at)
                        <p class="mt-3 text-xs text-gray-400">Activated {{ $activation->activated_at->diffForHumans() }}</p>
                    @endif
                </div>

                {{-- Credentials form --}}
                @php $envVars = array_keys($tool->transport_config['env'] ?? []); @endphp
                @if(count($envVars) > 0)
                    <div class="rounded-xl border border-gray-200 bg-white p-5">
                        <h4 class="mb-1 text-sm font-semibold text-gray-900">API Credentials</h4>
                        <p class="mb-4 text-sm text-gray-500">
                            Enter your API credentials for this tool. They will be encrypted and injected at runtime.
                        </p>

                        <div class="space-y-4">
                            @foreach($envVars as $key)
                                <div>
                                    <label class="mb-1 block text-xs font-medium text-gray-700">{{ $key }}</label>
                                    <input wire:model="credentialInputs.{{ $key }}"
                                        type="password"
                                        autocomplete="off"
                                        placeholder="Enter {{ $key }}..."
                                        class="block w-full rounded-lg border border-gray-300 px-3 py-2.5 font-mono text-sm focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500" />
                                </div>
                            @endforeach
                        </div>

                        <div class="mt-5">
                            <button wire:click="saveCredentials"
                                class="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700">
                                Save Credentials
                            </button>
                        </div>
                    </div>
                @else
                    <div class="rounded-xl border border-gray-200 bg-white p-5">
                        <p class="text-sm text-gray-500">This tool does not require any credentials. Simply activate it above.</p>
                    </div>
                @endif
            </div>
        @endif
    @endif
</div>
