<!DOCTYPE html>
<html lang="{{ current_language|default('it') }}"
      :class="{ 'dark': $store.theme.dark }"
      class="h-full">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="TieMeasureFlow - Sistema di gestione misurazioni industriali">
  <meta name="csrf-token" content="{{ csrf_token() }}">

  <title>{% block title %}TieMeasureFlow{% endblock %}</title>

  <!-- Favicon -->
  <link rel="icon" type="image/svg+xml" href="{{ url_for('static', filename='img/tmflow-icon.svg') }}">

  <!-- Google Fonts: Inter + JetBrains Mono -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">

  <!-- TailwindCSS (compiled) -->
  <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">

  <!-- Theme CSS Variables -->
  <link rel="stylesheet" href="{{ url_for('static', filename='css/themes.css') }}">

  <!-- Authoritative per-user theme from the server session (empty when anonymous) -->
  <script>window.__SERVER_THEME = "{{ current_theme if current_user else '' }}";</script>

  <!-- Alpine.js Theme Init (before Alpine loads) -->
  <script src="{{ url_for('static', filename='js/alpine-init.js') }}"></script>

  {% block extra_head %}{% endblock %}
</head>

<body class="{% block body_class %}h-full{% endblock %} bg-[var(--bg-primary)] text-[var(--text-primary)] font-sans antialiased transition-colors duration-300">

  <!-- Alpine.js App Wrapper -->
  <div x-data class="{% block wrapper_class %}min-h-full{% endblock %} flex flex-col">

    <!-- Navbar -->
    {% include "components/navbar.html" %}

    <!-- Flash Messages -->
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        <div class="fixed top-16 right-4 z-50 flex flex-col gap-2 max-w-md w-full"
             x-data
             x-init="setTimeout(() => { $el.remove() }, 8000)">
          {% for category, message in messages %}
            <div x-data="{ show: true }"
                 x-show="show"
                 x-transition:enter="transition ease-out duration-300"
                 x-transition:enter-start="opacity-0 translate-x-4"
                 x-transition:enter-end="opacity-100 translate-x-0"
                 x-transition:leave="transition ease-in duration-200"
                 x-transition:leave-start="opacity-100 translate-x-0"
                 x-transition:leave-end="opacity-0 translate-x-4"
                 class="flex items-center gap-3 px-4 py-3 rounded-lg shadow-lg border
                   {% if category == 'success' %}
                     bg-emerald-50 dark:bg-emerald-900/30 border-emerald-200 dark:border-emerald-800 text-emerald-800 dark:text-emerald-200
                   {% elif category == 'error' %}
                     bg-red-50 dark:bg-red-900/30 border-red-200 dark:border-red-800 text-red-800 dark:text-red-200
                   {% elif category == 'warning' %}
                     bg-amber-50 dark:bg-amber-900/30 border-amber-200 dark:border-amber-800 text-amber-800 dark:text-amber-200
                   {% else %}
                     bg-blue-50 dark:bg-blue-900/30 border-blue-200 dark:border-blue-800 text-blue-800 dark:text-blue-200
                   {% endif %}">

              <!-- Icon -->
              {% if category == 'success' %}
                <svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
              {% elif category == 'error' %}
                <svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
              {% elif category == 'warning' %}
                <svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"/>
                </svg>
              {% else %}
                <svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
              {% endif %}

              <span class="text-sm font-medium flex-1">{{ message }}</span>

              <!-- Dismiss -->
              <button @click="show = false" class="shrink-0 hover:opacity-70 transition-opacity touch-target">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
              </button>
            </div>
          {% endfor %}
        </div>
      {% endif %}
    {% endwith %}

    <!-- Main Content -->
    <main class="{% block main_class %}flex-1{% endblock %}">
      {% block content %}{% endblock %}
    </main>

    {% block footer %}
    <!-- Footer -->
    <footer class="py-4 text-center border-t border-[var(--border-color)] transition-colors duration-300">
      <p class="text-xs text-steel dark:text-steel-light tracking-wide">
        Powered by <span class="font-semibold">TieMeasureFlow</span> &mdash; Tielogic
      </p>
    </footer>
    {% endblock %}

  </div>

  {% block extra_js %}{% endblock %}

  {% if current_user and auto_logout_minutes %}
  <script>
  function inactivityTimer() {
    var timeoutMs = {{ auto_logout_minutes }} * 60 * 1000;
    var warningMs = 60 * 1000;
    return {
      lastActivity: Date.now(),
      showWarning: false,
      remainingSeconds: 60,
      _interval: null,
      init() {
        var self = this;
        this._interval = setInterval(function() { self._check(); }, 5000);
        var lastUpdate = 0;
        var handler = function() {
          var now = Date.now();
          if (now - lastUpdate > 3000) {
            lastUpdate = now;
            self.lastActivity = now;
            self.showWarning = false;
          }
        };
        ['mousemove','mousedown','keypress','touchstart','scroll'].forEach(function(evt) {
          window.addEventListener(evt, handler, { passive: true });
        });
      },
      resetTimer() {
        this.lastActivity = Date.now();
        this.showWarning = false;
      },
      _check() {
        var elapsed = Date.now() - this.lastActivity;
        var remaining = timeoutMs - elapsed;
        if (remaining <= 0) {
          clearInterval(this._interval);
          window.location.href = '{{ url_for("auth.logout") }}';
        } else if (remaining <= warningMs) {
          this.showWarning = true;
          this.remainingSeconds = Math.ceil(remaining / 1000);
        }
      }
    };
  }
  </script>
  <div x-data="inactivityTimer()" class="contents">
    <template x-if="showWarning">
      <div class="fixed inset-0 z-[100] flex items-center justify-center bg-black/50" @click.self="resetTimer()">
        <div class="bg-[var(--bg-primary)] rounded-xl p-6 shadow-2xl max-w-sm mx-4 border border-[var(--border-color)]">
          <div class="flex items-center gap-3 mb-4">
            <div class="w-10 h-10 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
              <svg class="w-5 h-5 text-amber-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
            </div>
            <h3 class="text-lg font-semibold text-[var(--text-primary)]">{{ _('Sessione in scadenza') }}</h3>
          </div>
          <p class="text-sm text-[var(--text-secondary)] mb-5">
            {{ _('Sarai disconnesso tra') }} <span class="font-mono font-bold text-amber-600" x-text="remainingSeconds"></span> {{ _('secondi per inattività.') }}
          </p>
          <button @click="resetTimer()" class="btn btn-primary w-full">
            {{ _('Continua a lavorare') }}
          </button>
        </div>
      </div>
    </template>
  </div>
  {% endif %}

  <!-- Alpine.js CDN (defer) - must load AFTER extra_js so component functions are defined -->
  <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</body>
</html>
