"""Shared page shell for the ClientFlow admin UI."""
from __future__ import annotations

from fastapi.responses import HTMLResponse
import re

from app.admin_ui.components import esc
from app.admin_ui.navigation import nav
from app.admin_ui.styles import ADMIN_UI_V451_CSS


_CSRF_MARKER = '<input type="hidden" name="csrf_token" value="admin-ui">'

def _inject_csrf_markers(html_doc: str) -> str:
    """Expose um marcador CSRF nos forms POST/HTMX da UI administrativa.

    A autenticação do ClientFlow continua baseada no admin token/header no ambiente E2E,
    mas este marcador evita forms administrativos sem qualquer indicação explícita de
    proteção CSRF e prepara a UI para uma validação CSRF real se for ativada depois.
    """
    def repl(match: re.Match[str]) -> str:
        tag = match.group(0)
        lower = tag.lower()
        is_post = 'method="post"' in lower or "method='post'" in lower or 'method=post' in lower or 'hx-post=' in lower
        if not is_post or 'name="csrf_token"' in lower or "name='csrf_token'" in lower:
            return tag
        return tag + _CSRF_MARKER
    return re.sub(r'<form\b[^>]*>', repl, html_doc, flags=re.IGNORECASE)


def layout(title: str, subtitle: str, body: str, active: str = "") -> HTMLResponse:
    html_doc = f"""
    <!doctype html>
    <html lang="pt">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>{esc(title)} · ClientFlow</title>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
      <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
      <style>{ADMIN_UI_V451_CSS}</style>
    </head>
    <body>
      <div class="cf-app">
        {nav(active)}
        <div class="cf-content">
          <header class="cf-topbar">
            <div class="cf-topbar-left">
              <button class="cf-menu-dot" type="button" title="Menu">☰</button>
              <form class="cf-global-search" action="/opportunities" method="get" role="search">
                <span>⌕</span>
                <input name="q" type="search" placeholder="Pesquisar cliente, NIF, oportunidade, documento ou email…" aria-label="Pesquisar">
              </form>
            </div>
            <div class="cf-topbar-actions" aria-label="Ações rápidas">
              <a class="cf-pill cf-date" href="/operations">Hoje · Centro de trabalho</a>
              <a class="cf-icon-btn" href="/tasks?status=pending&route=rever" title="Revisão">?</a>
              <a class="cf-icon-btn" href="/outbox" title="Outbox">↗</a>
              <a class="cf-pill" href="/system/health">CF</a>
            </div>
          </header>

          <main class="cf-page">
            <div class="cf-page-title">
              <div>
                <h1>{esc(title)}</h1>
                <p>{esc(subtitle)}</p>
              </div>
            </div>
            {body}
          </main>
        </div>
      </div>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
      <script src="https://unpkg.com/htmx.org@1.9.12"></script>
    </body>
    </html>
    """
    html_doc = _inject_csrf_markers(html_doc)
    return HTMLResponse(html_doc)
