{% load static %}
<!doctype html>
<html lang="pt-PT">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Estado do sistema · Kreate4Web</title>
  <link rel="icon" href="{% static 'branding/kreate4web-favicon.png' %}">
  <link rel="stylesheet" href="{% static 'unfold/fonts/inter/styles.css' %}">
  <link rel="stylesheet" href="{% static 'unfold/fonts/material-symbols/styles.css' %}">
  <link rel="stylesheet" href="{% static 'css/client-portal.css' %}?v=9.4.0">
</head>
<body class="k4w-health-page">
<header class="k4w-health-topbar">
  <a href="{% url 'home' %}"><img src="{% static 'branding/kreate4web-logo-horizontal.png' %}" alt="Kreate4Web"></a>
  <div><span>Portal v{{ report.version }}</span><b>{{ report.environment }}</b></div>
</header>
<main class="k4w-health-main">
  <section class="k4w-health-hero is-{{ report.status }}">
    <div>
      <span class="k4w-health-eyebrow">DIAGNÓSTICO EM TEMPO REAL</span>
      <h1>Estado do Portal Kreate4Web</h1>
      <p>Verificação segura dos componentes essenciais. O teste não altera dados de clientes nem executa operações destrutivas.</p>
      <div class="k4w-health-actions">
        <button id="health-run" type="button"><span class="material-symbols-outlined">monitor_heart</span> Executar testes agora</button>
        {% if request.user.is_staff %}<a href="{% url 'admin:index' %}">Voltar ao backoffice</a>{% else %}<a href="{% url 'security:login' %}">Entrar no portal</a>{% endif %}
      </div>
    </div>
    <aside>
      <div class="k4w-health-pulse"><span></span><strong id="overall-label">{% if report.status == 'ok' %}Operacional{% elif report.status == 'warning' %}Com avisos{% else %}Intervenção necessária{% endif %}</strong></div>
      <small>Última verificação</small>
      <time id="checked-at">{{ report.checked_at }}</time>
    </aside>
  </section>

  <section class="k4w-health-summary">
    <article><span class="material-symbols-outlined">task_alt</span><div><small>Operacionais</small><strong id="sum-ok">{{ report.summary.ok }}</strong></div></article>
    <article><span class="material-symbols-outlined">warning</span><div><small>Avisos</small><strong id="sum-warning">{{ report.summary.warning }}</strong></div></article>
    <article><span class="material-symbols-outlined">error</span><div><small>Erros</small><strong id="sum-error">{{ report.summary.error }}</strong></div></article>
    <article><span class="material-symbols-outlined">speed</span><div><small>Testes</small><strong>{{ report.summary.total }}</strong></div></article>
  </section>

  <section class="k4w-health-panel">
    <header><div><span>COMPONENTES</span><h2>Resultados técnicos</h2></div><p id="health-progress">Teste concluído</p></header>
    <div class="k4w-health-grid" id="health-grid">
      {% for item in report.checks %}
      <article class="is-{{ item.status }}" data-key="{{ item.key }}">
        <span class="k4w-health-status-icon material-symbols-outlined">{% if item.status == 'ok' %}check_circle{% elif item.status == 'warning' %}warning{% else %}cancel{% endif %}</span>
        <div><h3>{{ item.label }}</h3><p>{{ item.message }}</p>{% if item.detail %}<small>{{ item.detail }}</small>{% endif %}</div>
        <b>{{ item.duration_ms }} ms</b>
      </article>
      {% endfor %}
    </div>
  </section>

  <section class="k4w-health-note">
    <span class="material-symbols-outlined">shield</span><div><strong>Informação protegida</strong><p>Detalhes de infraestrutura só são apresentados a utilizadores administrativos autenticados. Redis ou SMTP indisponíveis em desenvolvimento são classificados como aviso, não como falha do portal web.</p></div>
  </section>
</main>
<footer class="k4w-global-footer"><span>© {% now "Y" %} Kreate4Web · K4W</span><span>Portal v{{ report.version }} · {{ report.environment }}</span><span><a href="https://www.kreate4web.com/" target="_blank" rel="noopener">kreate4web.com</a></span></footer>
<script>
(function(){
  const button=document.getElementById('health-run');
  const grid=document.getElementById('health-grid');
  const progress=document.getElementById('health-progress');
  const csrf='{{ csrf_token }}';
  const icon=(s)=>s==='ok'?'check_circle':(s==='warning'?'warning':'cancel');
  async function run(){
    button.disabled=true;button.classList.add('is-running');progress.textContent='A executar testes…';
    grid.querySelectorAll('article').forEach((el,i)=>setTimeout(()=>el.classList.add('is-testing'),i*70));
    try{
      const response=await fetch('{% url "health_run" %}',{method:'POST',headers:{'X-CSRFToken':csrf,'X-Requested-With':'XMLHttpRequest'}});
      const data=await response.json();
      data.checks.forEach(item=>{
        const row=grid.querySelector(`[data-key="${item.key}"]`); if(!row)return;
        row.className=`is-${item.status}`;
        row.querySelector('.k4w-health-status-icon').textContent=icon(item.status);
        row.querySelector('p').textContent=item.message;
        const old=row.querySelector('small'); if(old)old.remove();
        if(item.detail){const small=document.createElement('small');small.textContent=item.detail;row.querySelector('div').appendChild(small)}
        row.querySelector('b').textContent=`${item.duration_ms} ms`;
      });
      document.getElementById('sum-ok').textContent=data.summary.ok;
      document.getElementById('sum-warning').textContent=data.summary.warning;
      document.getElementById('sum-error').textContent=data.summary.error;
      document.getElementById('checked-at').textContent=new Date(data.checked_at).toLocaleString('pt-PT');
      document.getElementById('overall-label').textContent=data.status==='ok'?'Operacional':(data.status==='warning'?'Com avisos':'Intervenção necessária');
      progress.textContent='Teste concluído agora';
    }catch(error){progress.textContent='Não foi possível concluir o teste';}
    finally{button.disabled=false;button.classList.remove('is-running')}
  }
  button.addEventListener('click',run);
  document.getElementById('checked-at').textContent=new Date('{{ report.checked_at }}').toLocaleString('pt-PT');
})();
</script>
</body>
</html>
