{% extends "base.html" %}
{% block title %}{{ gateway_name }} — Shoreguard{% endblock %}

{% block breadcrumbs %}
<ol class="breadcrumb mb-0">
    <li class="breadcrumb-item"><a href="/gateways">Gateways</a></li>
    <li class="breadcrumb-item active">{{ gateway_name }}</li>
</ol>
{% endblock %}

{% block content %}
<div x-data='gatewayDetail({{ gateway_name | tojson }})' x-init="load()">
    <!-- Loading -->
    <div x-show="loading" class="text-center text-muted py-5">
        <div class="spinner-border spinner-border-sm me-2"></div>Loading gateway...
    </div>

    <!-- Error -->
    <div x-show="error" x-cloak class="alert alert-danger" x-text="error"></div>

    <!-- Not found -->
    <div x-show="!loading && !error && !gw" x-cloak class="alert alert-warning">
        Gateway "<span x-text="name"></span>" not found.
    </div>

    <!-- Gateway detail -->
    <div x-show="!loading && !error && gw" x-cloak>
        <!-- Status bar -->
        <div class="d-flex align-items-center justify-content-between mb-4 pb-3 border-bottom" style="border-color:var(--sg-border)!important">
            <div class="d-flex align-items-center gap-3">
                <span class="badge" :class="SG.badges.gateway[gw?.status] || 'text-bg-secondary'">
                    <i class="bi me-1" :class="'bi-' + statusIcon(gw?.status)"></i>
                    <span x-text="statusLabel(gw?.status)"></span>
                </span>
                <span x-show="gw?.version" class="text-muted" x-text="'v' + (gw?.version || '')"></span>
            </div>
            <div class="d-flex gap-2">
                <button x-show="$store.auth.localMode && $store.auth.hasRole('admin') && gw?.status !== 'connected'" x-cloak
                        class="btn btn-outline-success btn-sm" :disabled="acting" @click="startGateway()">
                    <template x-if="acting"><span class="spinner-border spinner-border-sm me-1"></span></template>
                    <i x-show="!acting" class="bi bi-play-fill me-1"></i>Start
                </button>
                <button x-show="$store.auth.localMode && $store.auth.hasRole('admin') && gw?.status === 'connected'" x-cloak
                        class="btn btn-outline-danger btn-sm" :disabled="acting" @click="stopGateway()">
                    <template x-if="acting"><span class="spinner-border spinner-border-sm me-1"></span></template>
                    <i x-show="!acting" class="bi bi-stop-fill me-1"></i>Stop
                </button>
                <button x-show="$store.auth.localMode && $store.auth.hasRole('admin') && gw?.status === 'connected'" x-cloak
                        class="btn btn-outline-warning btn-sm" :disabled="acting" @click="restartGateway()">
                    <template x-if="acting"><span class="spinner-border spinner-border-sm me-1"></span></template>
                    <i x-show="!acting" class="bi bi-arrow-repeat me-1"></i>Restart
                </button>
                <button x-show="$store.auth.hasRole('admin')" x-cloak
                        class="btn btn-outline-primary btn-sm" @click="testConnection()">
                    <i class="bi bi-plug me-1"></i>Test Connection
                </button>
                <button x-show="$store.auth.hasRole('admin')" x-cloak
                        class="btn btn-outline-danger btn-sm" @click="unregister()" title="Unregister">
                    <i class="bi bi-trash"></i>
                </button>
                <button class="btn btn-outline-secondary btn-sm" @click="load()" title="Refresh">
                    <i class="bi bi-arrow-clockwise"></i>
                </button>
            </div>
        </div>

        <!-- Action output -->
        <div x-show="actionOutput" x-cloak class="mb-3">
            <div class="log-output small">
                <div class="log-line" :class="actionClass" x-html="actionOutput"></div>
            </div>
        </div>

        <!-- Quick links -->
        <div class="row g-3 mb-4">
            <div class="col">
                <a :href="gw?.status === 'connected' ? gwUrl('/sandboxes') : null"
                   class="btn btn-outline-secondary w-100 py-3"
                   :class="{ 'disabled': gw?.status !== 'connected' }">
                    <i class="bi bi-grid me-2"></i>Sandboxes
                </a>
            </div>
            <div class="col">
                <a :href="gw?.status === 'connected' ? gwUrl('/providers') : null"
                   class="btn btn-outline-secondary w-100 py-3"
                   :class="{ 'disabled': gw?.status !== 'connected' }">
                    <i class="bi bi-key me-2"></i>Providers
                </a>
            </div>
            <div class="col">
                <a :href="gw?.status === 'connected' ? gwUrl('/wizard') : null"
                   class="btn btn-outline-success w-100 py-3"
                   :class="{ 'disabled': gw?.status !== 'connected' }">
                    <i class="bi bi-plus-circle me-2"></i>New Sandbox
                </a>
            </div>
        </div>

        <!-- Gateway details card -->
        <div class="card sg-card-themed mb-4">
            <div class="card-body">
                <!-- ── Metadata ── -->
                <fieldset class="sg-fieldset mb-3">
                    <legend class="sg-legend">Metadata</legend>
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label small text-muted"><i class="bi bi-card-text me-1"></i>Description</label>
                            <template x-if="$store.auth.hasRole('admin')">
                                <input type="text" class="form-control form-control-sm" x-model="metaForm.description"
                                       placeholder="e.g. Production EU-West for ML team" maxlength="1000">
                            </template>
                            <template x-if="!$store.auth.hasRole('admin')">
                                <div class="form-control-plaintext small" x-text="gw?.description || '—'"></div>
                            </template>
                        </div>
                        <div class="col-12">
                            <label class="form-label small text-muted"><i class="bi bi-tags me-1"></i>Labels</label>
                            <div x-show="metaLabels.length > 0" class="mb-2 d-flex flex-wrap gap-1">
                                <template x-for="lbl in metaLabels" :key="lbl.key">
                                    <span class="badge text-bg-light border d-inline-flex align-items-center gap-1">
                                        <span class="font-monospace" x-text="lbl.key"></span>
                                        <span class="text-muted">=</span>
                                        <span x-text="lbl.val"></span>
                                        <button x-show="$store.auth.hasRole('admin')" type="button"
                                                class="btn-close btn-close-sm ms-1" style="font-size:.55rem"
                                                @click="removeMetaLabel(lbl.key)"></button>
                                    </span>
                                </template>
                            </div>
                            <div x-show="$store.auth.hasRole('admin') && metaLabels.length < 20"
                                 class="input-group input-group-sm" style="max-width:400px">
                                <input type="text" class="form-control font-monospace" x-model="newMetaKey"
                                       placeholder="key" @keydown.enter.prevent="addMetaLabel()">
                                <span class="input-group-text">=</span>
                                <input type="text" class="form-control" x-model="newMetaVal"
                                       placeholder="value" @keydown.enter.prevent="addMetaLabel()">
                                <button class="btn btn-outline-success" type="button" @click="addMetaLabel()"
                                        :disabled="!newMetaKey.trim()">
                                    <i class="bi bi-plus"></i>
                                </button>
                            </div>
                            <span x-show="!$store.auth.hasRole('admin') && metaLabels.length === 0"
                                  class="text-muted fst-italic small">No labels</span>
                        </div>
                    </div>
                </fieldset>

                <!-- ── Connection ── -->
                <fieldset class="sg-fieldset mb-3">
                    <legend class="sg-legend">Connection</legend>
                    <table class="table table-sm table-borderless mb-0 align-middle">
                        <tbody>
                            <tr>
                                <td class="text-muted" style="width:120px"><i class="bi bi-globe me-2"></i>URL</td>
                                <td>
                                    <span class="endpoint-badge px-2 py-1" x-text="(gw?.scheme || 'https') + '://' + (gw?.endpoint || '\u2014')"></span>
                                </td>
                            </tr>
                            <template x-if="gw?.auth_mode">
                                <tr>
                                    <td class="text-muted"><i class="bi bi-shield-check me-2"></i>Auth</td>
                                    <td x-text="gw.auth_mode"></td>
                                </tr>
                            </template>
                            <template x-if="gw?.registered_at">
                                <tr>
                                    <td class="text-muted"><i class="bi bi-calendar-plus me-2"></i>Registered</td>
                                    <td>
                                        <span x-text="formatTimeAgo(gw.registered_at)"></span>
                                        <span class="text-muted small ms-1" x-text="'(' + new Date(gw.registered_at).toLocaleDateString(undefined, { year:'numeric', month:'short', day:'numeric' }) + ')'"></span>
                                    </td>
                                </tr>
                            </template>
                            <template x-if="gw?.last_seen">
                                <tr>
                                    <td class="text-muted"><i class="bi bi-clock-history me-2"></i>Last Seen</td>
                                    <td>
                                        <span x-text="formatTimeAgo(gw.last_seen)"></span>
                                        <span class="text-muted small ms-1" x-text="'(' + new Date(gw.last_seen).toLocaleDateString(undefined, { year:'numeric', month:'short', day:'numeric' }) + ')'"></span>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </fieldset>

                <!-- ── Inference (only when connected) ── -->
                <fieldset x-show="gw?.connected" x-cloak class="sg-fieldset mb-3"
                          x-data="inferenceConfig()" x-effect="if (gw?.connected && !loaded) load()">
                    <legend class="sg-legend">Inference</legend>
                    <div x-show="loading" class="text-muted small">
                        <div class="spinner-border spinner-border-sm me-2"></div>Loading provider config...
                    </div>
                    <div x-show="!loading" x-cloak>
                        <div class="row g-3 align-items-end">
                            <div class="col-md-4">
                                <label class="form-label small text-muted">Provider</label>
                                <select class="form-select form-select-sm" x-model="provider" @change="onProviderChange()">
                                    <option value="">— Select —</option>
                                    <template x-for="p in providers" :key="p.name">
                                        <option :value="p.name" x-text="p.label" :selected="p.name === provider"></option>
                                    </template>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label small text-muted">Model ID</label>
                                <input type="text" class="form-control form-control-sm" x-model="modelId"
                                       :placeholder="placeholder">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label small text-muted">Timeout (s)</label>
                                <input type="number" class="form-control form-control-sm"
                                       x-model.number="timeoutSecs" placeholder="0" min="0">
                            </div>
                        </div>
                        <div x-show="provider" class="mt-2 small text-muted">
                            <i class="bi bi-info-circle me-1"></i>
                            API key must be set as environment variable
                            <template x-if="currentProvider?.env_var">
                                <code x-text="currentProvider.env_var"></code>
                            </template>
                            on the gateway host.
                        </div>
                        <div x-show="!provider" class="mt-2 small text-warning">
                            <i class="bi bi-exclamation-triangle me-1"></i>
                            No inference provider configured. Sandboxes need a provider to run agents.
                        </div>
                    </div>
                </fieldset>

                <!-- ── Single Save button ── -->
                <div x-show="$store.auth.hasRole('admin')" x-cloak class="d-flex align-items-center gap-2 pt-2">
                    <button class="btn btn-primary btn-sm" @click="saveAll()" :disabled="saving">
                        <template x-if="saving"><span class="spinner-border spinner-border-sm me-1"></span></template>
                        <i x-show="!saving" class="bi bi-check-lg me-1"></i>Save
                    </button>
                    <span x-show="saveOutput" class="small" x-html="saveOutput"></span>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="/static/js/gateway.js"></script>
{% endblock %}
