/* global React */
const { useState, useEffect, useRef } = React;

// ───────────────────────────────────────────────────────────
// Blason — vrai logo de l'EAN (extrait du site officiel)
// `compact` (défaut: true) = juste l'écusson tripartite, sans texte ARQUEBUSE 1474
// `compact={false}` = blason complet avec texte (utile pour le hero histoire)
// ───────────────────────────────────────────────────────────
function Blason({ size = 48, compact = true }) {
  const src = compact
    ? "assets/images/logo-small.png"
    : "assets/images/logo.png";
  // ratio approximatif : compact ~1:1, full ~1.05 (avec texte sous l'écu)
  const ratio = compact ? 1 : 1.05;
  return (
    <img
      src={src}
      alt="Blason de l'Arquebuse Genève · 1474"
      width={size}
      height={size * ratio}
      style={{
        flexShrink: 0,
        height: size * ratio,
        width: "auto",
        display: "block",
        objectFit: "contain",
      }}
    />
  );
}

// ───────────────────────────────────────────────────────────
// Bannière DÉMO — avertit que c'est une maquette de prévisualisation
// ───────────────────────────────────────────────────────────
function DemoBanner() {
  const [closed, setClosed] = useState(false);
  if (closed) return null;
  // Palette Eljadi WORKS — eljadiworks.com
  const ELJADI = {
    ink: "#3d2416", // brun foncé (texte / fond principal)
    accent: "#f0b42e", // jaune doré (signature)
    accentHover: "#d9a229",
    cream: "#fef9f3", // crème (texte sur fond foncé)
    inkSoft: "#5a4438", // brun moyen
  };
  return (
    <div
      role="alert"
      style={{
        background: ELJADI.ink,
        backgroundImage: `linear-gradient(90deg, ${ELJADI.ink} 0%, ${ELJADI.inkSoft} 50%, ${ELJADI.ink} 100%)`,
        color: ELJADI.cream,
        padding: "10px 48px 10px 16px",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        gap: 16,
        fontFamily: "Inter, var(--sans)",
        fontSize: 12,
        letterSpacing: "0.04em",
        position: "relative",
        textAlign: "center",
        flexWrap: "wrap",
        borderBottom: `2px solid ${ELJADI.accent}`,
      }}
    >
      <span
        style={{
          background: ELJADI.accent,
          color: ELJADI.ink,
          padding: "3px 10px",
          fontWeight: 700,
          fontSize: 10,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          flexShrink: 0,
        }}
      >
        Démo
      </span>
      <span style={{ flex: "0 1 auto" }}>
        <strong style={{ fontWeight: 600 }}>
          Maquette de prévisualisation
        </strong>
        <span
          style={{ opacity: 0.75, marginLeft: 10, fontSize: 11.5 }}
          className="hide-mobile"
        >
          · Le site officiel reste{" "}
          <a
            href="https://www.arquebuse.ch"
            target="_blank"
            rel="noopener"
            style={{
              color: ELJADI.accent,
              textDecoration: "underline",
              textUnderlineOffset: 2,
            }}
          >
            arquebuse.ch
          </a>
        </span>
      </span>
      <span
        style={{
          marginLeft: "auto",
          fontSize: 11,
          letterSpacing: "0.06em",
          opacity: 0.85,
          display: "inline-flex",
          alignItems: "center",
          gap: 8,
        }}
        className="hide-mobile"
      >
        <span style={{ opacity: 0.6 }}>Proposition par</span>
        <a
          href="https://eljadiworks.com"
          target="_blank"
          rel="noopener"
          style={{
            color: ELJADI.cream,
            textDecoration: "none",
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            fontWeight: 600,
            letterSpacing: "0.02em",
          }}
        >
          <img
            src="assets/images/eljadi-logo.svg"
            alt="Eljadi WORKS"
            style={{
              height: 16,
              width: "auto",
              filter: "brightness(0) invert(1)",
              opacity: 0.95,
            }}
          />
        </a>
      </span>
      <button
        onClick={() => setClosed(true)}
        aria-label="Fermer la bannière"
        style={{
          position: "absolute",
          right: 12,
          top: "50%",
          transform: "translateY(-50%)",
          background: "transparent",
          border: 0,
          color: ELJADI.cream,
          cursor: "pointer",
          fontSize: 16,
          lineHeight: 1,
          padding: "4px 8px",
          opacity: 0.6,
        }}
      >
        ✕
      </button>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Top-bar institutionnelle
// ───────────────────────────────────────────────────────────
function TopBar() {
  return (
    <div
      style={{
        background: "var(--ink)",
        color: "var(--paper-2)",
        borderBottom: "1px solid rgba(184,137,61,0.25)",
      }}
    >
      <div
        className="container-wide"
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          padding: "10px 32px",
          fontFamily: "var(--mono)",
          fontSize: 11,
          letterSpacing: "0.14em",
          textTransform: "uppercase",
        }}
      >
        <span style={{ opacity: 0.85 }}>
          Exercices de l'Arquebuse et de la Navigation · Genève · MCDLXXIV
        </span>
        <span style={{ display: "flex", gap: 24, alignItems: "center" }}>
          <span style={{ opacity: 0.7 }}>FR</span>
          <span
            style={{
              width: 1,
              height: 12,
              background: "rgba(246,242,232,0.25)",
            }}
          ></span>
          <a
            href="#"
            style={{
              color: "var(--accent-soft)",
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
            }}
          >
            Espace membre <span>→</span>
          </a>
        </span>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Header / Nav
// ───────────────────────────────────────────────────────────
function Header({ current, onNav }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const items = [
    { id: "accueil", label: "Accueil" },
    { id: "stand", label: "Stand" },
    { id: "calendrier", label: "Calendrier" },
    { id: "resultats", label: "Résultats" },
    { id: "acces", label: "Accès" },
    { id: "histoire", label: "Histoire" },
    { id: "boutique", label: "Bourse" },
  ];

  return (
    <>
      <DemoBanner />
      <TopBar />
      <header
        style={{
          background: "var(--bg)",
          borderBottom: "1px solid var(--hairline)",
          position: "sticky",
          top: 0,
          zIndex: 50,
          backdropFilter: scrolled ? "blur(8px)" : "none",
          backgroundColor: scrolled ? "rgba(246,242,232,0.92)" : "var(--bg)",
          transition: "background-color .25s ease",
        }}
      >
        <div
          className="container-wide"
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "14px 32px",
            gap: 16,
          }}
        >
          {/* logo block */}
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              onNav("accueil");
            }}
            style={{ display: "flex", alignItems: "center", gap: 14 }}
          >
            <Blason size={42} />
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                lineHeight: 1,
              }}
            >
              <span
                style={{
                  fontFamily: "var(--display)",
                  fontSize: 26,
                  fontWeight: 500,
                  letterSpacing: "-0.01em",
                }}
              >
                Arquebuse
              </span>
              <span className="tag-mono" style={{ marginTop: 4, fontSize: 10 }}>
                Genève · MCDLXXIV
              </span>
            </div>
          </a>

          {/* nav */}
          <nav
            className="hide-mobile main-nav"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 2,
              marginLeft: 24,
            }}
          >
            {items.map((item) => (
              <a
                key={item.id}
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  onNav(item.id);
                }}
                style={{
                  padding: "10px 11px",
                  fontSize: 13,
                  whiteSpace: "nowrap",
                  color: current === item.id ? "var(--ink)" : "var(--gray)",
                  position: "relative",
                  transition: "color .2s",
                }}
                onMouseEnter={(e) =>
                  (e.currentTarget.style.color = "var(--ink)")
                }
                onMouseLeave={(e) =>
                  (e.currentTarget.style.color =
                    current === item.id ? "var(--ink)" : "var(--gray)")
                }
              >
                {item.label}
                {current === item.id && (
                  <span
                    style={{
                      position: "absolute",
                      left: 11,
                      right: 11,
                      bottom: 2,
                      height: 1,
                      background: "var(--accent)",
                    }}
                  />
                )}
              </a>
            ))}
            <button
              className="btn btn-primary"
              style={{
                marginLeft: 12,
                padding: "10px 16px",
                fontSize: 12,
                whiteSpace: "nowrap",
              }}
            >
              Membres <span>→</span>
            </button>
          </nav>

          {/* mobile burger */}
          <button
            className="show-mobile"
            onClick={() => setMobileOpen(!mobileOpen)}
            style={{
              background: "transparent",
              border: "1px solid var(--hairline-strong)",
              padding: "10px 14px",
              cursor: "pointer",
              fontFamily: "var(--mono)",
              fontSize: 11,
              letterSpacing: "0.1em",
              textTransform: "uppercase",
            }}
          >
            {mobileOpen ? "Fermer" : "Menu"}
          </button>
        </div>

        {/* mobile drawer */}
        {mobileOpen && (
          <div
            className="show-mobile"
            style={{
              borderTop: "1px solid var(--hairline)",
              padding: "12px 20px 24px",
            }}
          >
            {items.map((item) => (
              <a
                key={item.id}
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  onNav(item.id);
                  setMobileOpen(false);
                }}
                style={{
                  display: "block",
                  padding: "14px 0",
                  fontSize: 18,
                  fontFamily: "var(--display)",
                  borderBottom: "1px dashed var(--hairline)",
                  color:
                    current === item.id ? "var(--accent-deep)" : "var(--ink)",
                }}
              >
                {item.label}
              </a>
            ))}
            <button
              className="btn btn-primary"
              style={{ marginTop: 20, width: "100%", justifyContent: "center" }}
            >
              Espace membres →
            </button>
          </div>
        )}
      </header>
    </>
  );
}

// ───────────────────────────────────────────────────────────
// Footer
// ───────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer
      style={{
        background: "var(--paper-3)",
        borderTop: "1px solid var(--hairline)",
        marginTop: 80,
      }}
    >
      <div className="container-wide" style={{ padding: "64px 32px 32px" }}>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "auto 1fr 1fr 1fr",
            gap: 64,
            alignItems: "start",
          }}
          className="footer-grid"
        >
          <div style={{ display: "flex", alignItems: "flex-start", gap: 16 }}>
            <Blason size={64} />
            <div>
              <div
                style={{
                  fontFamily: "var(--display)",
                  fontSize: 22,
                  lineHeight: 1.1,
                }}
              >
                Arquebuse
                <br />
                Genève
              </div>
              <div className="tag-mono" style={{ marginTop: 10, fontSize: 10 }}>
                MCDLXXIV
              </div>
            </div>
          </div>

          <div>
            <div className="tag-mono" style={{ marginBottom: 16 }}>
              — Adresse
            </div>
            <div style={{ fontSize: 14, lineHeight: 1.8 }}>
              Stand de tir de Saint-Georges
              <br />
              8, route du Pont-Butin
              <br />
              1213 Petit-Lancy · Genève
              <br />
              <span
                className="mono"
                style={{ fontSize: 13, color: "var(--gray)" }}
              >
                +41 22 792 29 21
              </span>
              <br />
              <a
                href="mailto:tir@arquebuse.ch"
                style={{ color: "var(--accent-deep)" }}
              >
                tir@arquebuse.ch
              </a>
            </div>
          </div>

          <div>
            <div className="tag-mono" style={{ marginBottom: 16 }}>
              — Liens
            </div>
            <ul
              style={{
                listStyle: "none",
                padding: 0,
                margin: 0,
                fontSize: 14,
                lineHeight: 2,
              }}
            >
              <li>
                <a
                  href="#"
                  style={{ borderBottom: "1px solid transparent" }}
                  onMouseEnter={(e) =>
                    (e.currentTarget.style.borderBottomColor = "var(--accent)")
                  }
                  onMouseLeave={(e) =>
                    (e.currentTarget.style.borderBottomColor = "transparent")
                  }
                >
                  EAN officiel
                </a>
              </li>
              <li>
                <a href="#">Boutique du stand</a>
              </li>
              <li>
                <a href="#">Bourse EAN</a>
              </li>
              <li>
                <a href="#">Hôtel de l'Arquebuse</a>
              </li>
              <li>
                <a href="#">Liens partenaires</a>
              </li>
            </ul>
          </div>

          <div>
            <div className="tag-mono" style={{ marginBottom: 16 }}>
              — Newsletter
            </div>
            <div
              style={{
                fontSize: 13,
                color: "var(--gray)",
                marginBottom: 14,
                lineHeight: 1.6,
              }}
            >
              Calendrier, résultats et nouvelles, une fois par mois.
            </div>
            <div
              style={{ display: "flex", borderBottom: "1px solid var(--ink)" }}
            >
              <input
                type="email"
                placeholder="vous@email.ch"
                style={{
                  flex: 1,
                  border: 0,
                  background: "transparent",
                  padding: "10px 0",
                  fontSize: 14,
                  fontFamily: "var(--sans)",
                  outline: "none",
                }}
              />
              <button
                style={{
                  border: 0,
                  background: "transparent",
                  cursor: "pointer",
                  padding: "10px 8px",
                  fontFamily: "var(--mono)",
                  fontSize: 11,
                  letterSpacing: "0.1em",
                }}
              >
                S'INSCRIRE →
              </button>
            </div>
          </div>
        </div>

        <hr className="hr-fine" style={{ margin: "48px 0 20px" }} />

        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            flexWrap: "wrap",
            gap: 12,
            fontFamily: "var(--mono)",
            fontSize: 11,
            letterSpacing: "0.12em",
            textTransform: "uppercase",
            color: "var(--gray)",
          }}
        >
          <span>MCDLXXIV — MMXXVI · 552 ans</span>
          <span style={{ display: "flex", gap: 24 }}>
            <a href="#">Mentions légales</a>
            <a href="#">Confidentialité</a>
            <a href="#">© 2026 EAN</a>
          </span>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .footer-grid { grid-template-columns: 1fr !important; gap: 40px !important; }
        }
      `}</style>
    </footer>
  );
}

// ───────────────────────────────────────────────────────────
// PageHeader (utilisé par les sous-pages)
// ───────────────────────────────────────────────────────────
function PageHeader({ eyebrow, title, italic, subtitle, align = "left" }) {
  return (
    <div style={{ textAlign: align, padding: "64px 0 40px" }}>
      {eyebrow && (
        <div className="tag-gold" style={{ marginBottom: 18 }}>
          — {eyebrow} —
        </div>
      )}
      <h1
        style={{
          fontFamily: "var(--display)",
          fontWeight: 500,
          fontSize: "clamp(40px, 6vw, 72px)",
          lineHeight: 1.05,
          margin: 0,
          letterSpacing: "-0.015em",
        }}
      >
        {title}
        {italic && (
          <em
            style={{
              color: "var(--accent-deep)",
              fontWeight: 500,
              display: "block",
            }}
          >
            {italic}
          </em>
        )}
      </h1>
      {subtitle && (
        <div
          style={{
            marginTop: 20,
            color: "var(--gray)",
            fontSize: 16,
            maxWidth: 640,
            lineHeight: 1.55,
            marginLeft: align === "center" ? "auto" : 0,
            marginRight: align === "center" ? "auto" : 0,
          }}
        >
          {subtitle}
        </div>
      )}
      <div
        style={{
          width: 60,
          height: 1,
          background: "var(--accent)",
          margin: align === "center" ? "28px auto 0" : "28px 0 0",
        }}
      />
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Photo (image réelle si src fourni, sinon placeholder design)
// ───────────────────────────────────────────────────────────
function PhotoPH({
  ratio = "4/3",
  label = "PHOTO TBD",
  height,
  style = {},
  src,
  alt,
  objectPosition,
}) {
  const wrapStyle = height
    ? { height, ...style }
    : { aspectRatio: ratio, ...style };
  if (src) {
    return (
      <div
        style={{
          ...wrapStyle,
          overflow: "hidden",
          position: "relative",
          background: "var(--paper-3)",
        }}
      >
        <img
          src={src}
          alt={alt || label}
          loading="lazy"
          decoding="async"
          style={{
            width: "100%",
            height: "100%",
            objectFit: "cover",
            objectPosition: objectPosition || "center",
            display: "block",
          }}
        />
      </div>
    );
  }
  return (
    <div className="placeholder-photo" style={wrapStyle}>
      <span>{label}</span>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Roman numeral helper
// ───────────────────────────────────────────────────────────
function toRoman(n) {
  const map = [
    ["M", 1000],
    ["CM", 900],
    ["D", 500],
    ["CD", 400],
    ["C", 100],
    ["XC", 90],
    ["L", 50],
    ["XL", 40],
    ["X", 10],
    ["IX", 9],
    ["V", 5],
    ["IV", 4],
    ["I", 1],
  ];
  let s = "",
    k = n;
  for (const [r, v] of map) {
    while (k >= v) {
      s += r;
      k -= v;
    }
  }
  return s;
}

// ───────────────────────────────────────────────────────────
// Fade-up wrapper (intersection observer)
// ───────────────────────────────────────────────────────────
function FadeUp({ children, delay = 0, style = {} }) {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          setTimeout(() => setVis(true), delay);
          obs.disconnect();
        }
      },
      { threshold: 0.12 },
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return (
    <div ref={ref} className={"fade-up" + (vis ? " in" : "")} style={style}>
      {children}
    </div>
  );
}

// expose to global
Object.assign(window, {
  Blason,
  DemoBanner,
  TopBar,
  Header,
  Footer,
  PageHeader,
  PhotoPH,
  toRoman,
  FadeUp,
});
