<?= $this->extend('layouts/dashboard') ?>

<?= $this->section('content') ?>
<?php
$defaultSite = $sites[0] ?? null;
$defaultTurbine = $turbines[0] ?? null;
$defaultTask = $tasks[0] ?? null;
$exampleRequests = [
    [
        'label' => 'Listar sites',
        'method' => 'GET',
        'endpoint' => '/sites',
        'body' => '',
    ],
    [
        'label' => 'Criar site',
        'method' => 'POST',
        'endpoint' => '/sites',
        'body' => json_encode([
            'name' => 'Wind Farm API Demo',
            'site_code' => 'WF-API-' . date('His'),
            'site_type' => 'wind_farm',
            'country_code' => 'PT',
            'region' => 'Centro',
            'location' => 'Leiria, Portugal',
            'status' => 'active',
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
    ],
    [
        'label' => 'Listar turbinas',
        'method' => 'GET',
        'endpoint' => '/turbines' . ($defaultSite ? '?site_id=' . $defaultSite['id'] : ''),
        'body' => '',
    ],
    [
        'label' => 'Criar turbina',
        'method' => 'POST',
        'endpoint' => '/turbines',
        'body' => json_encode([
            'site_id' => (int) ($defaultSite['id'] ?? 1),
            'turbine_code' => 'WT-API-' . date('His'),
            'name' => 'Turbina Demo API',
            'manufacturer' => 'Vestas',
            'model' => 'V136',
            'rated_power_kw' => 4200,
            'status' => 'active',
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
    ],
    [
        'label' => 'Preview intervenção',
        'method' => 'POST',
        'endpoint' => '/maintenance/preview',
        'body' => json_encode([
            'site_id' => (int) ($defaultSite['id'] ?? 1),
            'turbine_id' => (int) ($defaultTurbine['id'] ?? 0),
            'title' => 'Inspecao de nacelle',
            'intervention_type' => 'inspection',
            'maintenance_mode' => 'scheduled',
            'priority' => 'medium',
            'status' => 'planned',
            'external_reference' => $defaultTask['task_code'] ?? 'TASK-API-DEMO',
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
    ],
    [
        'label' => 'Criar intervenção',
        'method' => 'POST',
        'endpoint' => '/maintenance',
        'body' => json_encode([
            'site_id' => (int) ($defaultSite['id'] ?? 1),
            'turbine_id' => (int) ($defaultTurbine['id'] ?? 0),
            'title' => 'Intervencao corretiva API',
            'description' => 'Criada a partir do playground Quantum.',
            'intervention_type' => 'corrective',
            'maintenance_mode' => 'corrective',
            'priority' => 'high',
            'status' => 'planned',
            'reported_at' => date('Y-m-d H:i:s'),
            'external_reference' => 'API-' . date('YmdHis'),
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
    ],
    [
        'label' => 'Auditar intervenção',
        'method' => 'GET',
        'endpoint' => '/audit?q=MI-' . date('Y') . '-0001',
        'body' => '',
    ],
    [
        'label' => 'Listar blockchain',
        'method' => 'GET',
        'endpoint' => '/blockchain',
        'body' => '',
    ],
];
?>
<section class="grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_380px]">
    <article class="rounded-[30px] border border-white/10 bg-gradient-to-br from-sky-500/18 via-slate-900 to-cyan-500/10 p-6 shadow-glow">
        <div class="inline-flex rounded-full border border-sky-400/30 bg-sky-400/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.24em] text-sky-100"><?= esc(lang('Backoffice.apiAreaBadge')) ?></div>
        <h1 class="mt-4 text-3xl font-semibold tracking-tight text-white sm:text-4xl"><?= esc(lang('Backoffice.apiPlaygroundHeading')) ?></h1>
        <p class="mt-4 max-w-3xl text-sm leading-7 text-slate-300">Playground Quantum para sites, turbinas, intervenções, auditoria pública e histórico blockchain.</p>
        <div class="mt-6 rounded-3xl border border-sky-400/20 bg-sky-400/10 p-5">
            <div class="text-xs uppercase tracking-[0.22em] text-sky-200">Base URL</div>
            <div class="mt-2 font-mono text-sm text-white"><?= esc($baseApiUrl) ?></div>
            <p class="mt-3 text-sm text-slate-300">Usa um Bearer token com scopes Quantum ou com aliases legados suportados.</p>
        </div>
    </article>

    <article class="rounded-[30px] border border-white/10 bg-white/5 p-6 backdrop-blur">
        <h2 class="text-xl font-semibold text-white">Examples</h2>
        <p class="mt-1 text-sm text-slate-400">Carrega um template, ajusta o token e envia o pedido.</p>
        <div class="mt-5 space-y-3">
            <?php foreach ($exampleRequests as $example): ?>
                <button
                    type="button"
                    class="playground-example flex w-full items-start justify-between rounded-2xl border border-white/10 bg-slate-950/40 px-4 py-3 text-left transition hover:border-sky-400/20 hover:bg-white/5"
                    data-method="<?= esc($example['method']) ?>"
                    data-endpoint="<?= esc($example['endpoint']) ?>"
                    data-body="<?= esc($example['body']) ?>"
                >
                    <span>
                        <span class="block font-semibold text-white"><?= esc($example['label']) ?></span>
                        <span class="mt-1 block text-xs text-slate-400"><?= esc($example['method']) ?> <?= esc($example['endpoint']) ?></span>
                    </span>
                    <span class="text-slate-500">/</span>
                </button>
            <?php endforeach; ?>
        </div>
    </article>
</section>

<section class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(340px,0.75fr)]">
    <article class="rounded-[30px] border border-white/10 bg-white/5 p-6 backdrop-blur">
        <div class="grid gap-5">
            <div>
                <label for="playgroundToken" class="mb-2 block text-sm font-semibold text-slate-200"><?= esc(lang('Backoffice.apiBearerToken')) ?></label>
                <input id="playgroundToken" type="password" autocomplete="off" spellcheck="false" class="block w-full rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 text-white" placeholder="<api_key>">
                <p class="mt-2 text-sm text-slate-400"><?= esc(lang('Backoffice.apiBearerTokenHint')) ?></p>
            </div>
            <div class="grid gap-4 md:grid-cols-[140px_minmax(0,1fr)]">
                <div>
                    <label for="playgroundMethod" class="mb-2 block text-sm font-semibold text-slate-200"><?= esc(lang('Backoffice.apiMethod')) ?></label>
                    <select id="playgroundMethod" class="block w-full rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 text-white">
                        <option>GET</option>
                        <option>POST</option>
                    </select>
                </div>
                <div>
                    <label for="playgroundEndpoint" class="mb-2 block text-sm font-semibold text-slate-200"><?= esc(lang('Backoffice.apiEndpoint')) ?></label>
                    <input id="playgroundEndpoint" type="text" class="block w-full rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 text-white" value="/sites">
                </div>
            </div>
            <div>
                <label for="playgroundBody" class="mb-2 block text-sm font-semibold text-slate-200"><?= esc(lang('Backoffice.apiRequestBody')) ?></label>
                <textarea id="playgroundBody" rows="14" class="block w-full rounded-[28px] border border-white/10 bg-slate-950/60 px-4 py-4 font-mono text-sm text-white"></textarea>
            </div>
            <div class="flex flex-wrap gap-3">
                <button id="playgroundSubmit" type="button" class="inline-flex items-center justify-center rounded-2xl bg-gradient-to-r from-sky-400 to-cyan-400 px-5 py-3 text-sm font-semibold text-slate-950 transition hover:opacity-90"><?= esc(lang('Backoffice.apiSendRequest')) ?></button>
                <a href="<?= site_url('api-docs') ?>" class="inline-flex items-center justify-center rounded-2xl border border-white/10 bg-white/5 px-5 py-3 text-sm font-medium text-slate-200 transition hover:bg-white/10"><?= esc(lang('Backoffice.menuApiDocs')) ?></a>
            </div>
        </div>
    </article>

    <article class="rounded-[30px] border border-white/10 bg-white/5 p-6 backdrop-blur">
        <h2 class="text-xl font-semibold text-white"><?= esc(lang('Backoffice.apiResponse')) ?></h2>
        <div class="mt-4 rounded-3xl border border-white/10 bg-slate-950/40 p-4">
            <div class="flex items-center justify-between gap-3">
                <div class="text-xs uppercase tracking-[0.22em] text-slate-500">HTTP</div>
                <div id="playgroundStatus" class="rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300">idle</div>
            </div>
            <pre id="playgroundResponse" class="mt-4 min-h-[420px] overflow-x-auto text-xs text-slate-200"><code>{
  "status": "idle",
  "message": "Choose an example or configure a request."
}</code></pre>
        </div>
    </article>
</section>

<script>
    (() => {
        const baseUrl = <?= json_encode($baseApiUrl, JSON_UNESCAPED_SLASHES) ?>;
        const methodInput = document.getElementById('playgroundMethod');
        const endpointInput = document.getElementById('playgroundEndpoint');
        const bodyInput = document.getElementById('playgroundBody');
        const tokenInput = document.getElementById('playgroundToken');
        const submitButton = document.getElementById('playgroundSubmit');
        const statusBadge = document.getElementById('playgroundStatus');
        const responseNode = document.getElementById('playgroundResponse');
        const exampleButtons = Array.from(document.querySelectorAll('.playground-example'));

        const setResponse = (status, payload, tone = 'neutral') => {
            statusBadge.textContent = status;
            statusBadge.className = 'rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] ';
            if (tone === 'success') {
                statusBadge.className += 'border-sky-400/20 bg-sky-400/10 text-sky-100';
            } else if (tone === 'error') {
                statusBadge.className += 'border-rose-400/20 bg-rose-400/10 text-rose-100';
            } else {
                statusBadge.className += 'border-white/10 bg-white/5 text-slate-300';
            }

            responseNode.textContent = typeof payload === 'string'
                ? payload
                : JSON.stringify(payload, null, 2);
        };

        const syncBodyState = () => {
            bodyInput.disabled = methodInput.value === 'GET';
            bodyInput.classList.toggle('opacity-60', bodyInput.disabled);
        };

        exampleButtons.forEach((button) => {
            button.addEventListener('click', () => {
                methodInput.value = button.dataset.method || 'GET';
                endpointInput.value = button.dataset.endpoint || '/sites';
                bodyInput.value = button.dataset.body || '';
                syncBodyState();
            });
        });

        methodInput.addEventListener('change', syncBodyState);

        submitButton.addEventListener('click', async () => {
            const endpoint = endpointInput.value.trim();
            const token = tokenInput.value.trim();
            const method = methodInput.value;

            if (!endpoint) {
                setResponse('invalid', { status: 'error', message: 'Endpoint is required.' }, 'error');
                return;
            }

            const headers = {
                Accept: 'application/json',
            };

            if (token) {
                headers.Authorization = `Bearer ${token}`;
            }

            const requestOptions = { method, headers };

            if (method !== 'GET') {
                headers['Content-Type'] = 'application/json';
                const rawBody = bodyInput.value.trim();

                if (rawBody !== '') {
                    try {
                        requestOptions.body = JSON.stringify(JSON.parse(rawBody));
                    } catch (error) {
                        setResponse('invalid-json', { status: 'error', message: 'JSON body is invalid.' }, 'error');
                        return;
                    }
                } else {
                    requestOptions.body = '{}';
                }
            }

            setResponse('loading', { status: 'pending', message: 'Sending request...' });

            try {
                const response = await fetch(baseUrl + endpoint, requestOptions);
                const contentType = response.headers.get('content-type') || '';
                const payload = contentType.includes('application/json')
                    ? await response.json()
                    : await response.text();

                setResponse(
                    String(response.status),
                    payload,
                    response.ok ? 'success' : 'error'
                );
            } catch (error) {
                setResponse('network-error', { status: 'error', message: error.message || 'Request failed.' }, 'error');
            }
        });

        syncBodyState();
    })();
</script>
<?= $this->endSection() ?>
