/* ================================================================
   PERFORMANCE OPTIMIZATIONS
   Core Web Vitals improvements for better page speed and UX
   ================================================================ */

/* ================================================================
   CRITICAL IMAGE PRELOADING HINTS
   ================================================================ */

/*
  Add these <link> preload tags to your <head> section for critical images:

  <!-- Hero images -->
  <link rel="preload" as="image" href="/images/hero-defcon.webp" type="image/webp">
  <link rel="preload" as="image" href="/images/logo.webp" type="image/webp">

  <!-- Critical icons -->
  <link rel="preload" as="image" href="/images/icons/alert.svg" type="image/svg+xml">

  <!-- Use fetchpriority="high" for above-fold images -->
  <img src="/hero.webp" alt="Hero" fetchpriority="high">

  <!-- Use loading="lazy" for below-fold images -->
  <img src="/below-fold.webp" alt="Content" loading="lazy">
*/

/* ================================================================
   IMAGE DIMENSION HINTS (Prevent CLS - Cumulative Layout Shift)
   ================================================================ */

/* Always set explicit dimensions on images to prevent layout shift */
img {
  max-width: 100%;
  height: auto;
  display: block;
  content-visibility: auto;
}

/* Aspect ratio preservation for responsive images */
.img-wrapper,
.image-container {
  position: relative;
  overflow: hidden;
}

/* Common aspect ratios */
.aspect-16-9 {
  aspect-ratio: 16 / 9;
}

.aspect-4-3 {
  aspect-ratio: 4 / 3;
}

.aspect-1-1 {
  aspect-ratio: 1 / 1;
}

.aspect-21-9 {
  aspect-ratio: 21 / 9;
}

.aspect-3-2 {
  aspect-ratio: 3 / 2;
}

/* Responsive image inside aspect ratio container */
.aspect-16-9 img,
.aspect-4-3 img,
.aspect-1-1 img,
.aspect-21-9 img,
.aspect-3-2 img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* ================================================================
   FONT LOADING OPTIMIZATION (FOUT Prevention)
   ================================================================ */

/*
  Add font-display: swap to your @font-face declarations:

  @font-face {
    font-family: 'YourFont';
    src: url('/fonts/yourfont.woff2') format('woff2');
    font-display: swap;
    font-weight: 400;
    font-style: normal;
  }
*/

/* Optional: Use system font stack as fallback for instant rendering */
.text-instant {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
}

/* ================================================================
   WILL-CHANGE HINTS FOR ANIMATIONS (GPU Acceleration)
   ================================================================ */

/* Apply will-change to elements that will animate */
/* WARNING: Use sparingly - overuse can hurt performance */

.nav--mobile,
.modal,
.dropdown__menu,
.tooltip {
  will-change: transform;
}

.fade-in,
.fade-out {
  will-change: opacity;
}

/* Scrolling containers */
.scroll-container {
  will-change: scroll-position;
}

/* Remove will-change after animation completes */
@media (prefers-reduced-motion: no-preference) {
  .animated {
    will-change: transform, opacity;
  }

  .animated.animation-complete {
    will-change: auto;
  }
}

/* ================================================================
   CSS CONTAINMENT FOR PERFORMANCE
   ================================================================ */

/* Contain layout changes to improve rendering performance */

/* Cards - contain layout and paint */
.card,
.article-card,
.panel {
  contain: layout paint;
}

/* List items */
.card-grid > *,
.list > * {
  contain: layout;
}

/* Comments section */
.comments,
.comment-list {
  contain: layout;
}

/* Sidebars and asides */
aside,
.sidebar {
  contain: layout paint;
}

/* Footer sections */
footer section {
  contain: layout;
}

/* ================================================================
   CONTENT-VISIBILITY FOR LAZY RENDERING
   ================================================================ */

/* Defer rendering of off-screen content */
/* Significantly improves initial page load time */

/* Below-fold sections */
.below-fold,
.lazy-section {
  content-visibility: auto;
  contain-intrinsic-size: auto 500px; /* Estimated height to prevent layout shift */
}

/* Comment sections */
.comments {
  content-visibility: auto;
  contain-intrinsic-size: auto 800px;
}

/* Footer (usually below fold) */
footer {
  content-visibility: auto;
  contain-intrinsic-size: auto 400px;
}

/* Long article content sections */
.article__content section:not(:first-child) {
  content-visibility: auto;
  contain-intrinsic-size: auto 600px;
}

/* Archive pages with many items */
.archive-list,
.article-list {
  content-visibility: auto;
  contain-intrinsic-size: auto 1000px;
}

/* Large tables */
.large-table,
table.data-table {
  content-visibility: auto;
  contain-intrinsic-size: auto 800px;
}

/* ================================================================
   ASPECT RATIO BOXES (Prevent CLS for Videos & Iframes)
   ================================================================ */

/* Responsive video container */
.video-wrapper,
.iframe-wrapper,
.embed-responsive {
  position: relative;
  width: 100%;
  overflow: hidden;
}

/* 16:9 videos (YouTube, Vimeo) */
.video-16-9,
.embed-16-9 {
  aspect-ratio: 16 / 9;
}

/* 4:3 videos */
.video-4-3,
.embed-4-3 {
  aspect-ratio: 4 / 3;
}

/* 21:9 ultrawide */
.video-21-9,
.embed-21-9 {
  aspect-ratio: 21 / 9;
}

/* Responsive iframe/video inside container */
.video-wrapper iframe,
.video-wrapper video,
.iframe-wrapper iframe,
.embed-responsive iframe,
.embed-responsive video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}

/* ================================================================
   OPTIMIZE REPAINTS AND REFLOWS
   ================================================================ */

/* Use transform instead of top/left for animations */
.slide-in {
  transform: translateX(0);
  transition: transform 0.3s ease;
}

.slide-in--from-left {
  transform: translateX(-100%);
}

.slide-in--from-right {
  transform: translateX(100%);
}

/* Use transform for scaling */
.scale-on-hover {
  transition: transform 0.2s ease;
}

.scale-on-hover:hover {
  transform: scale(1.05);
}

/* Fade animations using opacity (GPU accelerated) */
.fade {
  transition: opacity 0.3s ease;
}

.fade--out {
  opacity: 0;
}

.fade--in {
  opacity: 1;
}

/* ================================================================
   REDUCE LAYOUT THRASHING
   ================================================================ */

/* Fixed heights for header/footer to prevent reflow */
.site-footer {
  min-height: 400px;
}

/* Breadcrumbs containment */
.breadcrumbs {
  will-change: auto;
  contain: layout style;
}

/* Reserve space for navigation */
.nav-spacer {
  height: 60px;
}

/* ================================================================
   OPTIMIZE SCROLLING PERFORMANCE
   ================================================================ */

/* Smooth scrolling with GPU acceleration */
html {
  scroll-behavior: smooth;
}

/* Optimize fixed elements */
.header--fixed,
.navbar--fixed,
.sidebar--sticky {
  position: fixed;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  transform: translateZ(0);
}

/* Optimize sticky positioning */
.sticky {
  position: sticky;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

/* Optimize scrollable containers */
.scroll-container,
.overflow-auto,
.overflow-scroll {
  -webkit-overflow-scrolling: touch;
  overflow-y: auto;
  overscroll-behavior: contain;
}

/* ================================================================
   CRITICAL CSS LOADING STRATEGY
   ================================================================ */

/*
  Inline critical CSS in <head> for above-fold content:

  <style>
    /* Critical CSS here - reset, layout, hero section */
  </style>

  Load non-critical CSS asynchronously:

  <link rel="preload" href="/css/style.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <noscript><link rel="stylesheet" href="/css/style.css"></noscript>
*/

/* ================================================================
   LAZY LOADING IMAGES
   ================================================================ */

/* Native lazy loading with fallback styling */
img[loading="lazy"] {
  background: var(--bg-tertiary, #162032);
  min-height: 200px; /* Prevent layout shift while loading */
}

/* Blur-up placeholder effect */
.img-lazy {
  filter: blur(10px);
  transition: filter 0.3s ease;
}

.img-lazy.loaded {
  filter: blur(0);
}

/* Progressive JPEG or WebP loading */
.img-progressive {
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
}

/* ================================================================
   MINIMIZE RENDER-BLOCKING RESOURCES
   ================================================================ */

/*
  Defer non-critical CSS:

  <link rel="stylesheet" href="/css/non-critical.css" media="print" onload="this.media='all'">

  Preconnect to third-party domains:

  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://www.google-analytics.com">

  DNS prefetch for external resources:

  <link rel="dns-prefetch" href="https://cdn.example.com">
*/

/* ================================================================
   OPTIMIZE ANIMATIONS (60 FPS)
   ================================================================ */

/* Only animate transform and opacity for smooth 60fps */
.animate-transform {
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.animate-opacity {
  transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* Avoid animating expensive properties */
/* BAD: width, height, top, left, margin, padding */
/* GOOD: transform, opacity */

/* Hardware acceleration for 3D transforms */
.hw-accelerate {
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  will-change: transform;
}

/* ================================================================
   REDUCE UNUSED CSS (Use PurgeCSS or Similar)
   ================================================================ */

/*
  Run PurgeCSS in production to remove unused styles:

  npm install -D @fullhuman/postcss-purgecss

  Add to postcss.config.js:

  module.exports = {
    plugins: [
      require('@fullhuman/postcss-purgecss')({
        content: ['./views/**/*.php', './public/**/*.html'],
        defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
      })
    ]
  }
*/

/* ================================================================
   OPTIMIZE THIRD-PARTY SCRIPTS
   ================================================================ */

/*
  Load third-party scripts asynchronously:

  <script src="analytics.js" async></script>
  <script src="non-critical.js" defer></script>

  Use facades for heavy embeds (YouTube, Twitter):

  <div class="youtube-facade" data-id="VIDEO_ID">
    <img src="thumbnail.jpg" loading="lazy">
    <button class="play-button">Play</button>
  </div>
*/

/* YouTube embed facade */
.youtube-facade {
  position: relative;
  aspect-ratio: 16 / 9;
  cursor: pointer;
  background: #000;
}

.youtube-facade img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.youtube-facade::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 68px;
  height: 48px;
  background: rgba(255, 0, 0, 0.8);
  border-radius: 8px;
  pointer-events: none;
}

.youtube-facade::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-40%, -50%);
  width: 0;
  height: 0;
  border-left: 20px solid white;
  border-top: 12px solid transparent;
  border-bottom: 12px solid transparent;
  pointer-events: none;
}

/* ================================================================
   RESOURCE HINTS
   ================================================================ */

/*
  Add to <head>:

  <!-- Preconnect to critical origins -->
  <link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="preconnect" href="https://cdn.example.com" crossorigin>

  <!-- DNS prefetch for third-party domains -->
  <link rel="dns-prefetch" href="https://www.google-analytics.com">

  <!-- Preload critical assets -->
  <link rel="preload" href="/fonts/font.woff2" as="font" type="font/woff2" crossorigin>
  <link rel="preload" href="/css/critical.css" as="style">

  <!-- Prefetch next page resources -->
  <link rel="prefetch" href="/next-page.html">
*/

/* ================================================================
   MINIMIZE MAIN THREAD WORK
   ================================================================ */

/* Offload animations to GPU */
@media (prefers-reduced-motion: no-preference) {
  .gpu-animation {
    transform: translateZ(0);
    backface-visibility: hidden;
    perspective: 1000px;
  }
}

/* Use requestAnimationFrame for JS animations */
/* Use Intersection Observer for lazy loading */
/* Use Web Workers for heavy computations */

/* ================================================================
   OPTIMIZE WEB FONTS
   ================================================================ */

/*
  Use font subsetting to reduce file size:

  @font-face {
    font-family: 'CustomFont';
    src: url('/fonts/custom-subset.woff2') format('woff2');
    font-display: swap;
    unicode-range: U+0020-007F; // Basic Latin only
  }

  Use variable fonts when possible (single file for multiple weights):

  @font-face {
    font-family: 'InterVariable';
    src: url('/fonts/inter-var.woff2') format('woff2');
    font-display: swap;
    font-weight: 100 900;
  }
*/

/* ================================================================
   REDUCE SERVER RESPONSE TIME
   ================================================================ */

/*
  Server-side optimizations:

  - Enable HTTP/2 or HTTP/3
  - Use a CDN for static assets
  - Enable Gzip/Brotli compression
  - Set proper cache headers
  - Use server-side caching (Redis, Memcached)
  - Optimize database queries
  - Use lazy loading for data

  Example Nginx config:

  gzip on;
  gzip_comp_level 6;
  gzip_types text/plain text/css application/json application/javascript text/xml;

  brotli on;
  brotli_comp_level 6;
*/

/* ================================================================
   MINIMIZE CUMULATIVE LAYOUT SHIFT (CLS)
   ================================================================ */

/* Reserve space for ads */
.ad-slot {
  min-height: 250px;
  background: var(--bg-tertiary, #162032);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Reserve space for dynamic content */
.skeleton-loader {
  background: linear-gradient(
    90deg,
    var(--bg-tertiary, #162032) 25%,
    var(--bg-card, #1a2536) 50%,
    var(--bg-tertiary, #162032) 75%
  );
  background-size: 200% 100%;
  animation: loading 1.5s ease-in-out infinite;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* Set minimum heights for dynamic sections */
.dynamic-content {
  min-height: 300px;
}

/* ================================================================
   OPTIMIZE FIRST INPUT DELAY (FID)
   ================================================================ */

/* Ensure interactive elements are keyboard accessible */
button,
a,
input,
select {
  cursor: pointer;
  user-select: none;
  -webkit-tap-highlight-color: rgba(14, 165, 233, 0.1);
}

textarea {
  cursor: text;
  -webkit-tap-highlight-color: rgba(14, 165, 233, 0.1);
}

/* Reduce input delay on mobile */
@media (hover: none) and (pointer: coarse) {
  button,
  a,
  input {
    touch-action: manipulation;
  }
}

/* ================================================================
   REDUCE JAVASCRIPT EXECUTION TIME
   ================================================================ */

/*
  Code splitting strategies:

  - Split vendor code from app code
  - Lazy load route-specific code
  - Defer non-critical scripts
  - Use dynamic imports
  - Minimize main thread work

  Example:

  // Lazy load module
  const module = await import('./heavy-module.js');

  // Defer execution
  setTimeout(() => {
    // Non-critical code
  }, 0);
*/

/* ================================================================
   RESPECT REDUCED MOTION & DATA PREFERENCES
   ================================================================ */

/* Disable animations if user prefers reduced motion */
@media (prefers-reduced-motion: reduce) {
  *,
  *::before,
  *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }

  .video-wrapper video {
    animation: none !important;
  }
}

/* Optimize for users on slow connections */
@media (prefers-reduced-data: reduce) {
  /* Reduce video loading on slow connections (handled by HTML preload attr) */
  video {
    content-visibility: auto;
  }

  /* Use lower quality images */
  img {
    image-rendering: auto;
  }

  /* Disable background images */
  .bg-image {
    background-image: none !important;
  }
}

/* ================================================================
   MONITORING & DEBUGGING
   ================================================================ */

/*
  Use Performance API to measure:

  // Largest Contentful Paint
  new PerformanceObserver((list) => {
    const entries = list.getEntries();
    const lastEntry = entries[entries.length - 1];
    console.log('LCP:', lastEntry.renderTime || lastEntry.loadTime);
  }).observe({ entryTypes: ['largest-contentful-paint'] });

  // First Input Delay
  new PerformanceObserver((list) => {
    list.getEntries().forEach((entry) => {
      console.log('FID:', entry.processingStart - entry.startTime);
    });
  }).observe({ entryTypes: ['first-input'] });

  // Cumulative Layout Shift
  let clsScore = 0;
  new PerformanceObserver((list) => {
    list.getEntries().forEach((entry) => {
      if (!entry.hadRecentInput) {
        clsScore += entry.value;
        console.log('CLS:', clsScore);
      }
    });
  }).observe({ entryTypes: ['layout-shift'] });
*/
