---
import { Image } from "astro:assets";
import type { ImageMetadata } from "astro";
import Markdown from "../../islands/Markdown.jsx";

const { section, index } = Astro.props;

const hasImage = !!section.image;
const reverse = index % 2 === 1;

const sectionImages = import.meta.glob<{ default: ImageMetadata }>(
  "/src/assets/sections/**/*.{png,jpg,jpeg,webp,avif}",
  { eager: true },
);

let sectionImage: ImageMetadata | null = null;

if (section.image) {
  const path = `/src/assets/sections/${section.image}`;
  const mod = sectionImages[path];
  if (mod) sectionImage = mod.default;
}

const isAboveFold = index === 0; // możesz zmienić warunek jak chcesz
---

<section class="f-section">
  <div
    class={`f-section-grid ${hasImage ? "md:grid-cols-2" : "md:grid-cols-1"}`}
  >
    {
      sectionImage && (
        <Image
          src={sectionImage}
          alt={section.title}
          class={`f-section-image ${reverse ? "md:order-1" : "md:order-2"} ${section.dimmed ? "f-image-dimmed" : ""}`}
          loading={isAboveFold ? "eager" : "lazy"}
          fetchpriority={isAboveFold ? "high" : "auto"}
          decoding="async"
          format="webp"
          widths={[480, 768, 1024, 1440]}
          sizes="(min-width: 768px) 50vw, 100vw"
        />
      )
    }

    <div class={`${hasImage ? (reverse ? "md:order-2" : "md:order-1") : ""}`}>
      {section.title && <h2 class="f-section-title">{section.title}</h2>}
      <Markdown text={section.content} />

      {
        section.button && (
          <div class="f-section-nav">
            <a
              href={section.button.url}
              class="btn btn-primary"
              title={section.button.title}
            >
              {section.button.text}
            </a>
          </div>
        )
      }
    </div>
  </div>
</section>
