<!DOCTYPE html>
<html lang="<%= I18n.locale %>" class="<%= @current_website.auto_dark_mode? ? 'pwb-auto-dark' : '' %> <%= @current_website.dark_mode_html_class %>">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="index, follow">
    <title><%= yield(:page_title) %></title>
    <%= favicon_tags %>
    <%= verification_meta_tags %>
    <%= yield(:page_head) %>

    <%# Preload LCP image for faster Largest Contentful Paint %>
    <% if @lcp_image_url.present? %>
      <link rel="preload" href="<%= @lcp_image_url %>" as="image" fetchpriority="high">
    <% end %>

    <%# Preconnect for external resources - do this FIRST %>
    <link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
    <link rel="preconnect" href="https://seed-assets.propertywebbuilder.com" crossorigin>
    <link rel="dns-prefetch" href="//unpkg.com">
    <%= font_preconnect_tags %>

    <%# CRITICAL CSS - Inlined for fastest FCP %>
    <%# Palette CSS - dynamic variables or compiled static CSS %>
    <%# Font CSS - font-family variables and base styles %>
    <style><%= critical_css %><%= palette_css %><%= font_css_variables %><%= custom_styles "bologna" %></style>

    <%# Google Fonts - async loaded %>
    <%= google_fonts_preload_tag %>

    <%# Main CSS - async loaded to not block rendering %>
    <link rel="preload" href="<%= asset_path('tailwind-bologna.css') %>" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="preload" href="<%= asset_path('bologna_theme.css') %>" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript>
      <%= stylesheet_link_tag "tailwind-bologna", media: "all" %>
      <%= stylesheet_link_tag "bologna_theme", media: "all" %>
    </noscript>

    <%# Flowbite CSS - deferred %>
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript><link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.css" rel="stylesheet"></noscript>

    <%# Material Symbols - primary icon font %>
    <%= stylesheet_link_tag "material-icons", media: "all" %>

    <%# Font Awesome 6 Subset - legacy support for admin editor (to be removed) %>
    <%= stylesheet_link_tag "fontawesome-subset", media: "all" %>

    <%= csrf_meta_tags %>

    <%# PWA manifest and theme color - uses palette primary color %>
    <link rel="manifest" href="/manifest.json">
    <meta name="theme-color" content="<%= @current_website.style_variables["primary_color"] || "#c2410c" %>">
  </head>

  <body class="tnt-body bologna-theme <%= @current_website.body_style %> font-sans antialiased bg-warm-gray-50 text-warm-gray-900">
    <%# Brand icons SVG sprite - must be early in body for <use> references %>
    <%= render partial: '/pwb/brand_icons_sprite' %>

    <a href="#main-content" class="sr-only focus:not-sr-only focus:absolute focus:top-0 focus:left-0 focus:z-50 focus:p-4 focus:bg-white focus:text-terra-600">Skip to main content</a>

    <%# MAIN WRAPPER %>
    <div id="main-vue" class="body-wrap sticky-wrap <%= @current_website.body_style %> flex flex-col min-h-screen">

      <%# Minimal Header %>
      <%= render partial: '/pwb/header', locals: { not_devise: true } %>

      <%# Main Content %>
      <main id="main-content" class="sticky-body flex-grow" role="main">
        <%= render 'devise/shared/messages' %>
        <%= yield %>
      </main>

      <%# Modern Footer %>
      <%= render partial: '/pwb/footer', locals: {} %>

      <%# Back to Top Button %>
      <button id="back-to-top"
              aria-label="Back to top"
              class="fixed bottom-8 right-8 z-50 w-12 h-12 bg-terra-500 text-white rounded-full shadow-medium
                     opacity-0 invisible transition-all duration-300 hover:bg-terra-600 hover:shadow-elevated
                     flex items-center justify-center">
        <%= icon(:keyboard_arrow_up, size: :md, class: "") %>
      </button>

      <%# Analytics %>
      <%= render partial: '/pwb/analytics', locals: {} %>
    </div>

    <%# JavaScript loaded at end of body for best performance %>
    <%= javascript_include_tag "pwb/application", defer: true %>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.js" defer></script>
    <script src="https://unpkg.com/@phosphor-icons/web" defer></script>
    <%= javascript_importmap_tags %>

    <%# Deferred UI enhancements %>
    <script defer>
      document.addEventListener('DOMContentLoaded', function() {
        // Header shadow on scroll
        const header = document.querySelector('header');
        if (header) {
          window.addEventListener('scroll', function() {
            header.classList.toggle('shadow-medium', window.scrollY > 20);
          }, {passive: true});
        }
        // Back to top button
        const backToTop = document.getElementById('back-to-top');
        if (backToTop) {
          window.addEventListener('scroll', function() {
            const show = window.scrollY > 400;
            backToTop.classList.toggle('opacity-0', !show);
            backToTop.classList.toggle('invisible', !show);
            backToTop.classList.toggle('opacity-100', show);
            backToTop.classList.toggle('visible', show);
          }, {passive: true});
          backToTop.addEventListener('click', function() {
            window.scrollTo({top: 0, behavior: 'smooth'});
          });
        }
        // Scroll animations using IntersectionObserver
        const animatedElements = document.querySelectorAll('.animate-on-scroll');
        if (animatedElements.length > 0 && 'IntersectionObserver' in window) {
          const observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
              if (entry.isIntersecting) {
                entry.target.classList.add('visible');
                observer.unobserve(entry.target);
              }
            });
          }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });
          animatedElements.forEach(function(el) { observer.observe(el); });
        } else {
          // Fallback: make all elements visible immediately
          animatedElements.forEach(function(el) { el.classList.add('visible'); });
        }
        // Mobile menu & dropdown handled by Stimulus controllers
      });
    </script>

    <%= yield(:page_script) %>
    <% if params[:edit_mode] == 'true' %>
      <%= javascript_include_tag "pwb/editor_client" %>
    <% end %>

    <%# Service Worker registration for PWA/offline support %>
    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('/service-worker.js')
            .then(function(registration) {
              console.log('SW registered:', registration.scope);
            })
            .catch(function(error) {
              console.log('SW registration failed:', error);
            });
        });
      }
    </script>
  </body>
</html>
