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

<?= $this->section('content') ?>
<?php
$canManageOperations = ($isPlatformAdmin ?? false) || in_array($currentMembership['role'] ?? '', ['owner', 'admin', 'manager'], true);
$eventLabels = [
    'blockchain_anchor_confirmed' => 'Blockchain confirmada',
    'demo_interval_registered' => 'Intervalo registado',
    'demo_event_registered' => 'Evento registado',
];
?>

<style>
    .qb-blockchain-modal {
        position: fixed;
        inset: 0;
        display: none;
        align-items: center;
        justify-content: center;
        padding: 1.5rem;
        background: rgba(3, 10, 18, 0.78);
        backdrop-filter: blur(12px);
        z-index: 80;
    }

    .qb-blockchain-modal.is-open {
        display: flex;
    }

    .qb-blockchain-modal__panel {
        width: min(760px, 100%);
        padding: 1.5rem;
        border-radius: 28px;
        border: 1px solid rgba(148, 163, 184, 0.18);
        background: linear-gradient(180deg, rgba(11, 23, 37, 0.98), rgba(8, 19, 31, 0.98));
        box-shadow: 0 32px 80px rgba(0, 0, 0, 0.34);
    }

    html[data-theme="light"] .qb-blockchain-modal__panel {
        background: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(239, 246, 252, 0.98));
        border-color: rgba(148, 163, 184, 0.22);
        box-shadow: 0 28px 70px rgba(31, 41, 55, 0.14);
    }

    .qb-blockchain-modal__eyebrow {
        font-size: 0.72rem;
        font-weight: 700;
        letter-spacing: 0.18em;
        text-transform: uppercase;
        color: rgb(34 211 238);
    }

    .qb-blockchain-modal__title {
        margin-top: 0.75rem;
        font-size: clamp(1.7rem, 3vw, 2.35rem);
        font-weight: 600;
        color: white;
    }

    html[data-theme="light"] .qb-blockchain-modal__title {
        color: rgb(15 23 42);
    }

    .qb-blockchain-modal__body {
        margin-top: 0.85rem;
        max-width: 42rem;
        font-size: 0.97rem;
        line-height: 1.75;
        color: rgb(148 163 184);
    }

    html[data-theme="light"] .qb-blockchain-modal__body {
        color: rgb(71 85 105);
    }

    .qb-blockchain-progress {
        margin-top: 1.35rem;
        height: 14px;
        border-radius: 999px;
        overflow: hidden;
        background: rgba(255, 255, 255, 0.08);
    }

    html[data-theme="light"] .qb-blockchain-progress {
        background: rgba(148, 163, 184, 0.22);
    }

    .qb-blockchain-progress__bar {
        width: 0;
        height: 100%;
        border-radius: inherit;
        background: linear-gradient(90deg, #22d3ee, #2563eb);
        transition: width 0.45s ease;
    }

    .qb-blockchain-stages {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 0.9rem;
        margin-top: 1.2rem;
    }

    .qb-blockchain-stage {
        padding: 1rem;
        border-radius: 20px;
        border: 1px solid rgba(148, 163, 184, 0.14);
        background: rgba(255, 255, 255, 0.03);
    }

    html[data-theme="light"] .qb-blockchain-stage {
        background: rgba(255, 255, 255, 0.72);
        border-color: rgba(148, 163, 184, 0.18);
    }

    .qb-blockchain-stage.is-active {
        border-color: rgba(34, 211, 238, 0.28);
        box-shadow: inset 0 0 0 1px rgba(34, 211, 238, 0.18);
    }

    .qb-blockchain-stage.is-done {
        border-color: rgba(59, 130, 246, 0.3);
        background: rgba(37, 99, 235, 0.08);
    }

    html[data-theme="light"] .qb-blockchain-stage.is-done {
        background: rgba(37, 99, 235, 0.06);
    }

    .qb-blockchain-stage__top {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 0.8rem;
    }

    .qb-blockchain-stage__title {
        font-size: 0.98rem;
        font-weight: 600;
        color: white;
    }

    html[data-theme="light"] .qb-blockchain-stage__title {
        color: rgb(15 23 42);
    }

    .qb-blockchain-stage__body {
        margin-top: 0.5rem;
        font-size: 0.9rem;
        line-height: 1.65;
        color: rgb(148 163 184);
    }

    html[data-theme="light"] .qb-blockchain-stage__body {
        color: rgb(71 85 105);
    }

    .qb-blockchain-stage__badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 92px;
        padding: 0.45rem 0.7rem;
        border-radius: 999px;
        font-size: 0.72rem;
        font-weight: 700;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        background: rgba(148, 163, 184, 0.14);
        color: rgb(191 219 254);
    }

    html[data-theme="light"] .qb-blockchain-stage__badge {
        background: rgba(148, 163, 184, 0.16);
        color: rgb(51 65 85);
    }

    .qb-blockchain-stage.is-active .qb-blockchain-stage__badge {
        background: rgba(34, 211, 238, 0.16);
        color: rgb(165 243 252);
    }

    html[data-theme="light"] .qb-blockchain-stage.is-active .qb-blockchain-stage__badge {
        color: rgb(14 116 144);
    }

    .qb-blockchain-stage.is-done .qb-blockchain-stage__badge {
        background: rgba(59, 130, 246, 0.16);
        color: rgb(191 219 254);
    }

    html[data-theme="light"] .qb-blockchain-stage.is-done .qb-blockchain-stage__badge {
        color: rgb(29 78 216);
    }

    .qb-blockchain-modal__footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        margin-top: 1.25rem;
        flex-wrap: wrap;
    }

    .qb-blockchain-modal__status {
        font-size: 0.92rem;
        line-height: 1.7;
        color: rgb(191 219 254);
    }

    html[data-theme="light"] .qb-blockchain-modal__status {
        color: rgb(51 65 85);
    }

    .qb-blockchain-spinner {
        width: 18px;
        height: 18px;
        border: 2px solid rgba(255, 255, 255, 0.22);
        border-top-color: rgba(34, 211, 238, 0.96);
        border-radius: 999px;
        animation: qb-spin 0.8s linear infinite;
    }

    html[data-theme="light"] .qb-blockchain-spinner {
        border-color: rgba(148, 163, 184, 0.3);
        border-top-color: rgba(37, 99, 235, 0.96);
    }

    @keyframes qb-spin {
        to {
            transform: rotate(360deg);
        }
    }

    @media (max-width: 900px) {
        .qb-blockchain-stages {
            grid-template-columns: 1fr;
        }
    }
</style>

<section class="qb-page-hero">
    <div class="flex flex-col gap-6 xl:flex-row xl:items-end xl:justify-between">
        <div class="qb-page-hero-copy">
            <span class="qb-label">Intervencao tecnica</span>
            <h1 class="mt-5 text-white"><?= esc($intervention['intervention_code']) ?></h1>
            <p class="mt-3 text-lg text-slate-200"><?= esc($intervention['title']) ?></p>
            <p class="mt-4 text-sm leading-7 text-slate-300"><?= esc($intervention['description'] ?: 'Sem descricao adicional.') ?></p>
        </div>
        <div class="flex flex-wrap gap-3">
            <span class="qb-status-pill"><?= esc($intervention['status']) ?></span>
            <?php if ($canManageOperations && $transactions === []): ?>
                <form
                    action="<?= site_url('maintenance/' . rawurlencode($intervention['intervention_code']) . '/anchor-blockchain') ?>"
                    method="post"
                    data-blockchain-anchor-form
                    data-intervention-code="<?= esc($intervention['intervention_code']) ?>"
                    data-network="Polygon PoS"
                >
                    <?= csrf_field() ?>
                    <button type="submit" class="qb-button-primary" data-blockchain-anchor-trigger>Ancorar na blockchain</button>
                </form>
            <?php endif; ?>
            <a href="<?= site_url('maintenance/' . rawurlencode($intervention['intervention_code']) . '/edit') ?>" class="qb-button-secondary">Editar</a>
            <a href="<?= site_url('maintenance') ?>" class="qb-button-secondary">Voltar</a>
        </div>
    </div>
</section>

<section class="qb-detail-grid">
    <article class="qb-detail-item">
        <div class="qb-detail-item__label">Parque eolico</div>
        <div class="qb-detail-item__value"><?= esc($intervention['site_name'] ?? '-') ?></div>
    </article>
    <article class="qb-detail-item">
        <div class="qb-detail-item__label">Turbina</div>
        <div class="qb-detail-item__value"><?= esc($intervention['turbine_code'] ?? '-') ?></div>
    </article>
    <article class="qb-detail-item">
        <div class="qb-detail-item__label">Estado</div>
        <div class="qb-detail-item__value"><?= esc($intervention['status']) ?></div>
    </article>
    <article class="qb-detail-item">
        <div class="qb-detail-item__label">Responsavel</div>
        <div class="qb-detail-item__value"><?= esc($intervention['assigned_to_name'] ?? '-') ?></div>
    </article>
</section>

<section class="grid gap-4 xl:grid-cols-2">
    <article class="qb-page-card">
        <h2 class="qb-section-title">Tarefas</h2>
        <div class="qb-list-stack mt-4">
            <?php foreach ($tasks as $task): ?>
                <div class="qb-list-item">
                    <div class="flex items-center justify-between gap-3">
                        <div class="qb-list-item__title"><?= esc($task['sequence_no']) ?>. <?= esc($task['task_label']) ?></div>
                        <span class="qb-status-pill qb-status-pill--soft"><?= esc($task['status']) ?></span>
                    </div>
                    <p class="qb-list-item__body"><?= esc($task['notes'] ?: ($task['task_description_snapshot'] ?: '')) ?></p>
                </div>
            <?php endforeach; ?>
            <?php if ($tasks === []): ?>
                <div class="qb-empty-state">Sem tarefas associadas.</div>
            <?php endif; ?>
        </div>
    </article>
    <article class="qb-page-card">
        <h2 class="qb-section-title">Eventos</h2>
        <div class="qb-list-stack mt-4">
            <?php foreach ($events as $event): ?>
                <div class="qb-list-item">
                    <div class="flex items-center justify-between gap-3">
                        <div class="qb-list-item__title"><?= esc($eventLabels[$event['event_type']] ?? $event['event_type']) ?></div>
                        <div class="qb-list-item__meta"><?= esc($event['happened_at']) ?></div>
                    </div>
                    <p class="qb-list-item__body"><?= esc($event['event_message']) ?></p>
                </div>
            <?php endforeach; ?>
            <?php if ($events === []): ?>
                <div class="qb-empty-state">Sem eventos registados.</div>
            <?php endif; ?>
        </div>
    </article>
</section>

<section class="grid gap-4 xl:grid-cols-2">
    <article class="qb-page-card">
        <h2 class="qb-section-title">Ficheiros</h2>
        <div class="qb-list-stack mt-4">
            <?php foreach ($files as $file): ?>
                <div class="qb-list-item">
                    <div class="qb-list-item__title"><?= esc($file['original_name']) ?></div>
                    <p class="qb-list-item__body"><?= esc($file['description'] ?: $file['storage_path']) ?></p>
                </div>
            <?php endforeach; ?>
            <?php if ($files === []): ?>
                <div class="qb-empty-state">Sem ficheiros associados.</div>
            <?php endif; ?>
        </div>
    </article>
    <article class="qb-page-card">
        <h2 class="qb-section-title">Blockchain</h2>
        <div class="qb-list-stack mt-4">
            <?php foreach ($transactions as $transaction): ?>
                <div class="qb-list-item">
                    <div class="flex items-center justify-between gap-3">
                        <div class="qb-list-item__title"><?= esc($transaction['network']) ?> / <?= esc($transaction['status']) ?></div>
                        <span class="qb-chip qb-chip--soft"><?= esc($transaction['anchor_type'] ?? 'anchor') ?></span>
                    </div>
                    <p class="qb-list-item__body break-all"><?= esc($transaction['transaction_hash']) ?></p>
                    <p class="qb-list-item__body break-all">Hash ancorado: <?= esc($transaction['anchored_hash'] ?? '-') ?></p>
                </div>
            <?php endforeach; ?>
            <?php if ($transactions === []): ?>
                <div class="qb-empty-state">
                    Sem transacoes blockchain associadas.
                    <?php if ($canManageOperations): ?>
                        Usa "Ancorar na blockchain" para escrever esta intervencao no registo distribuido.
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </article>
</section>

<div class="qb-blockchain-modal" id="blockchainModal" aria-hidden="true">
    <section class="qb-blockchain-modal__panel" role="dialog" aria-modal="true" aria-labelledby="blockchainModalTitle">
        <div class="qb-blockchain-modal__eyebrow">Quantum Blockchain Write</div>
        <h2 class="qb-blockchain-modal__title" id="blockchainModalTitle">A preparar a ancoragem da intervencao</h2>
        <p class="qb-blockchain-modal__body" id="blockchainModalBody">
            O Quantum esta a consolidar o pacote tecnico da intervencao, gerar o hash de integridade e submeter a operacao para escrita na rede blockchain.
        </p>

        <div class="qb-blockchain-progress">
            <div class="qb-blockchain-progress__bar" id="blockchainProgressBar"></div>
        </div>

        <div class="qb-blockchain-stages" id="blockchainStageList"></div>

        <div class="qb-blockchain-modal__footer">
            <div class="qb-blockchain-modal__status" id="blockchainModalStatus">A iniciar o processo de ancoragem.</div>
            <div class="inline-flex items-center gap-3 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200">
                <span class="qb-blockchain-spinner" aria-hidden="true"></span>
                <span>Escrita em curso</span>
            </div>
        </div>
    </section>
</div>

<script>
    (() => {
        const form = document.querySelector('[data-blockchain-anchor-form]');
        const modal = document.getElementById('blockchainModal');
        const progressBar = document.getElementById('blockchainProgressBar');
        const stageList = document.getElementById('blockchainStageList');
        const modalTitle = document.getElementById('blockchainModalTitle');
        const modalBody = document.getElementById('blockchainModalBody');
        const modalStatus = document.getElementById('blockchainModalStatus');

        if (!form || !modal || !progressBar || !stageList || !modalTitle || !modalBody || !modalStatus) {
            return;
        }

        const stages = [
            {
                key: 'prepare',
                title: 'Preparar o payload tecnico',
                body: 'A intervencao e consolidada com identificadores, contexto do ativo e metadados operacionais.'
            },
            {
                key: 'hash',
                title: 'Gerar o hash de integridade',
                body: 'O Quantum calcula a impressao criptografica que representa o registo tecnico.'
            },
            {
                key: 'submit',
                title: 'Submeter para a rede',
                body: 'O pacote e encaminhado para o fluxo de escrita blockchain configurado para a plataforma.'
            },
            {
                key: 'confirm',
                title: 'Confirmar ancoragem',
                body: 'O backoffice prepara a resposta final com o identificador da transacao e o estado confirmado.'
            }
        ];

        const wait = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms));

        const renderStages = () => {
            stageList.innerHTML = '';
            stages.forEach((stage) => {
                const article = document.createElement('article');
                article.className = 'qb-blockchain-stage';
                article.dataset.stage = stage.key;
                article.innerHTML = `
                    <div class="qb-blockchain-stage__top">
                        <div>
                            <div class="qb-blockchain-stage__title">${stage.title}</div>
                            <p class="qb-blockchain-stage__body">${stage.body}</p>
                        </div>
                        <span class="qb-blockchain-stage__badge">Pendente</span>
                    </div>
                `;
                stageList.appendChild(article);
            });
        };

        const setStage = (key, state, label) => {
            const element = stageList.querySelector(`[data-stage="${key}"]`);
            if (!element) {
                return;
            }

            element.classList.remove('is-active', 'is-done');
            if (state === 'active') {
                element.classList.add('is-active');
            }
            if (state === 'done') {
                element.classList.add('is-done');
            }

            const badge = element.querySelector('.qb-blockchain-stage__badge');
            if (badge) {
                badge.textContent = label;
            }
        };

        const openModal = () => {
            modal.classList.add('is-open');
            modal.setAttribute('aria-hidden', 'false');
            document.body.style.overflow = 'hidden';
        };

        const setBusyButton = (busy) => {
            const button = form.querySelector('[data-blockchain-anchor-trigger]');
            if (!button) {
                return;
            }

            button.disabled = busy;
            button.textContent = busy ? 'A ancorar...' : 'Ancorar na blockchain';
        };

        form.addEventListener('submit', async (event) => {
            event.preventDefault();

            const interventionCode = form.dataset.interventionCode || 'Intervencao';
            const network = form.dataset.network || 'Blockchain';

            renderStages();
            progressBar.style.width = '0%';
            modalTitle.textContent = `A ancorar ${interventionCode} na blockchain`;
            modalBody.textContent = `O Quantum esta a preparar a escrita da intervencao ${interventionCode} na rede ${network}, com trilho tecnico, hash de integridade e confirmacao operacional.`;
            modalStatus.textContent = 'A iniciar a escrita do registo tecnico.';
            setBusyButton(true);
            openModal();

            for (let index = 0; index < stages.length; index += 1) {
                const stage = stages[index];
                setStage(stage.key, 'active', 'Em curso');
                progressBar.style.width = `${((index + 1) / stages.length) * 100}%`;

                if (stage.key === 'prepare') {
                    modalStatus.textContent = 'A consolidar o pacote tecnico da intervencao.';
                } else if (stage.key === 'hash') {
                    modalStatus.textContent = 'A gerar o hash criptografico para o registo.';
                } else if (stage.key === 'submit') {
                    modalStatus.textContent = `A submeter a operacao para ${network}.`;
                } else {
                    modalStatus.textContent = 'A validar a resposta e a preparar a confirmacao no backoffice.';
                }

                await wait(stage.key === 'submit' ? 1200 : 850);
                setStage(stage.key, 'done', 'Concluido');
            }

            modalStatus.textContent = 'A finalizar a operacao e a atualizar o registo da intervencao.';
            await wait(450);
            form.submit();
        });
    })();
</script>
<?= $this->endSection() ?>
