/* =========================================================
   RENFECHT — Shared visual components + Values context
   ========================================================= */

/* ---------- Values context ---------- */

const ValuesContext = React.createContext(null);
const useValues = () => React.useContext(ValuesContext);

/* ---------- Heraldic crest ---------- */
function Crest({ size = 120, withBanner = true, className = "" }) {
  const v = useValues();
  const yearRoman = (v && v.event && v.event.yearRoman) || "MMXXVI";
  const w = size;
  const h = size * 1.18;
  return (
    <svg className={"crest " + className} viewBox="0 0 200 236" width={w} height={h} aria-label="RenFecht crest" role="img">
      <defs>
        <linearGradient id="crestPaper" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="currentColor" stopOpacity="0.06" />
          <stop offset="1" stopColor="currentColor" stopOpacity="0.18" />
        </linearGradient>
      </defs>
      <g fill="currentColor" opacity="0.7">
        <circle cx="100" cy="6" r="1.6" /><circle cx="20" cy="40" r="1.2" /><circle cx="180" cy="40" r="1.2" />
      </g>
      <path d="M30 28 L170 28 L170 110 Q170 170 100 200 Q30 170 30 110 Z" fill="url(#crestPaper)" stroke="currentColor" strokeWidth="1.5" />
      <path d="M38 36 L162 36 L162 110 Q162 164 100 192 Q38 164 38 110 Z" fill="none" stroke="currentColor" strokeWidth="0.6" opacity="0.6" />
      <path d="M38 36 L162 36 L162 56 L38 56 Z" fill="currentColor" opacity="0.12" />
      <line x1="38" y1="56" x2="162" y2="56" stroke="currentColor" strokeWidth="0.6" />
      <g stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round">
        <line x1="48" y1="68" x2="152" y2="172" />
        <line x1="42" y1="62" x2="54" y2="74" strokeWidth="1.6" />
        <line x1="40" y1="60" x2="48" y2="68" strokeWidth="1.6" />
        <line x1="38" y1="78" x2="68" y2="58" strokeWidth="1.4" />
        <circle cx="40" cy="60" r="3" fill="currentColor" />
        <line x1="152" y1="68" x2="48" y2="172" />
        <line x1="158" y1="62" x2="146" y2="74" strokeWidth="1.6" />
        <line x1="160" y1="60" x2="152" y2="68" strokeWidth="1.6" />
        <line x1="162" y1="78" x2="132" y2="58" strokeWidth="1.4" />
        <circle cx="160" cy="60" r="3" fill="currentColor" />
      </g>
      <g fill="currentColor">
        <circle cx="100" cy="120" r="14" opacity="0.14" />
        <circle cx="100" cy="120" r="10" fill="none" stroke="currentColor" strokeWidth="0.8" />
        <circle cx="100" cy="120" r="2.4" />
      </g>
      <text x="100" y="51" textAnchor="middle" fontFamily="Cinzel, serif" fontSize="14" letterSpacing="2" fill="currentColor" style={{ fontWeight: 600 }}>R · F</text>
      {withBanner && (
        <g>
          <path d="M22 198 Q60 188 100 198 Q140 188 178 198 L172 218 Q140 208 100 218 Q60 208 28 218 Z" fill="currentColor" opacity="0.92" />
          <text x="100" y="213" textAnchor="middle" fontFamily="Cinzel, serif" fontSize="9" letterSpacing="3.6" fill="var(--paper, #fcc5a4)">TEXAS · {yearRoman}</text>
        </g>
      )}
    </svg>
  );
}

/* ---------- Ornaments ---------- */

function FleurDivider({ width = 180, className = "" }) {
  return (
    <svg className={"fleur-div flourish " + className} viewBox="0 0 180 28" width={width} height={width * 28/180} aria-hidden="true">
      <g stroke="currentColor" strokeWidth="0.9" fill="none">
        <line x1="0" y1="14" x2="62" y2="14" />
        <line x1="118" y1="14" x2="180" y2="14" />
        <line x1="0" y1="11" x2="62" y2="11" opacity="0.5" />
        <line x1="118" y1="11" x2="180" y2="11" opacity="0.5" />
      </g>
      <g fill="currentColor">
        <circle cx="62" cy="14" r="1.6" /><circle cx="118" cy="14" r="1.6" />
      </g>
      <g transform="translate(90 14)" stroke="currentColor" strokeWidth="0.9" fill="none">
        <path d="M0 -10 Q-3 -4 -6 -2 Q-3 -2 0 0 Q3 -2 6 -2 Q3 -4 0 -10 Z" fill="currentColor" />
        <path d="M0 0 L0 8 M-7 4 L0 8 L7 4" />
        <circle cx="0" cy="-12" r="1.4" fill="currentColor" />
      </g>
    </svg>
  );
}

function CrossedSwordsIcon({ size = 28, className = "" }) {
  return (
    <svg className={className} viewBox="0 0 28 28" width={size} height={size} aria-hidden="true">
      <g stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round">
        <line x1="4" y1="4" x2="24" y2="24" />
        <line x1="24" y1="4" x2="4" y2="24" />
        <line x1="2" y1="7" x2="7" y2="2" strokeWidth="1.6" />
        <line x1="26" y1="7" x2="21" y2="2" strokeWidth="1.6" />
        <line x1="2" y1="21" x2="7" y2="26" strokeWidth="1.6" />
        <line x1="26" y1="21" x2="21" y2="26" strokeWidth="1.6" />
      </g>
      <circle cx="3" cy="3" r="1.5" fill="currentColor" /><circle cx="25" cy="3" r="1.5" fill="currentColor" />
    </svg>
  );
}

function Manicule({ size = 22, className = "" }) {
  return (
    <svg className={className} viewBox="0 0 24 24" width={size} height={size} aria-hidden="true" fill="currentColor">
      <path d="M3 12 L11 12 L11 10 L9 10 L9 7 Q9 5 11 5 Q13 5 13 7 L13 11 L15 9 Q16 8 17 9 L20 12 L20 16 Q20 19 17 19 L10 19 Q7 19 5 17 L3 14 Z" />
    </svg>
  );
}

function CornerDots() {
  return (<><span className="corner bl" /><span className="corner br" /></>);
}

function OrnatedDivider({ label }) {
  return (
    <div className="divider" role="presentation">
      <CrossedSwordsIcon size={22} className="flourish" />
      {label && <span className="eyebrow">{label}</span>}
      <CrossedSwordsIcon size={22} className="flourish" />
    </div>
  );
}

/* ---------- SectionHeader — unified section title ---------- */

function SectionHeader({ eyebrow, title, sub, align = "center", divider = true }) {
  return (
    <div style={{ textAlign: align, marginBottom: "var(--space-7)" }}>
      {eyebrow && <span className="eyebrow">{eyebrow}</span>}
      {title && <h2 style={{ marginTop: 10 }}>{title}</h2>}
      {sub && <p className="lede" style={{ maxWidth: "44ch", margin: align === "center" ? "1rem auto 0" : "1rem 0 0" }}>{sub}</p>}
      {divider && <div className="flourish"><FleurDivider width={120} className="text-accent" /></div>}
    </div>
  );
}

/* ---------- Page banner ---------- */

function PageBanner({ eyebrow, title, lead }) {
  return (
    <section className="page-banner">
      <div className="wrap">
        <span className="eyebrow">{eyebrow}</span>
        <h1>{title}</h1>
        {lead && <p className="lede" style={{ maxWidth: "60ch", margin: "1.4rem auto 0" }}>{lead}</p>}
        <div style={{ marginTop: 28 }} className="flourish">
          <FleurDivider width={120} />
        </div>
      </div>
    </section>
  );
}

/* ---------- Site header ---------- */

function SiteHeader({ active, onNavigate, tweaks, setTweak }) {
  const v = useValues();
  const mode = tweaks?.mode || "light";
  const a11y = tweaks?.a11y || "off";
  return (
    <header className="site-header">
      <div className="site-header-inner">
        <a href="#home" className="brand-link" onClick={(e) => { e.preventDefault(); onNavigate("home"); }}>
          <span className="brand-mark"><img src="./favicon.svg" alt="" /></span>
          <span className="brand-word">{v.event.name}</span>
        </a>
        <nav className="nav">
          {v.nav.map(item => (
            <a key={item.id}
               href={"#" + item.id}
               className={(active === item.id ? "active" : "") + (item.secondary ? " nav-secondary" : "")}
               onClick={(e) => { e.preventDefault(); onNavigate(item.id); }}>
              {item.label}
            </a>
          ))}
          <a href="#register"
             className="btn btn-accent"
             style={{ marginLeft: 6, padding: "9px 16px", fontSize: "0.72rem" }}
             onClick={(e) => { e.preventDefault(); onNavigate("register"); }}>
            Register
          </a>
        </nav>
        <div className="header-actions" aria-label="Display settings">
          <button
            type="button"
            className="icon-toggle"
            aria-label={mode === "dark" ? "Switch to light mode" : "Switch to dark mode"}
            title={mode === "dark" ? "Light mode" : "Dark mode"}
            aria-pressed={mode === "dark"}
            onClick={() => setTweak && setTweak("mode", mode === "dark" ? "light" : "dark")}
          >
            {mode === "dark" ? "SUN" : "MOON"}
          </button>
          <button
            type="button"
            className="icon-toggle"
            aria-label={a11y === "on" ? "Disable reading mode" : "Enable reading mode"}
            title={a11y === "on" ? "Disable reading mode" : "Enable reading mode"}
            aria-pressed={a11y === "on"}
            onClick={() => setTweak && setTweak("a11y", a11y === "on" ? "off" : "on")}
          >
            {a11y === "on" ? "Scripture" : "Reader"}
          </button>
        </div>
      </div>
    </header>
  );
}

/* ---------- Site footer ---------- */

function SiteFooter({ onNavigate }) {
  const v = useValues();
  const f = v.footer;
  return (
    <footer className="site-footer">
      <div className="wrap">
        <div className="footer-inner">
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--ink)" }}>
              <img src="./favicon.svg" alt="" style={{ width: 48, height: 57 }} />
              <div>
                <div className="logotype" style={{ fontSize: "1.6rem", color: "var(--accent)" }}>{v.event.name}</div>
                <div className="eyebrow" style={{ marginTop: 4 }}>TEXAS · {v.event.year}</div>
              </div>
            </div>
            <p style={{ marginTop: 16, fontSize: "0.95rem", color: "var(--ink-soft)", maxWidth: "32ch" }}>
              {f.tagline}
            </p>
          </div>
          {f.columns.map(col => (
            <div key={col.title}>
              <h4>{col.title}</h4>
              {col.links.map(link => (
                <a key={link.label}
                   href={link.href || ("#" + link.page)}
                   target={link.href && link.href.startsWith("http") ? "_blank" : undefined}
                   onClick={(e) => {
                     if (link.page) { e.preventDefault(); onNavigate(link.page); }
                     else if (link.href === "#") { e.preventDefault(); }
                   }}>
                  {link.label}
                </a>
              ))}
            </div>
          ))}
        </div>
        <div className="rule" style={{ marginTop: 48 }} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <div className="mono" style={{ fontSize: "0.78rem", letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
            {f.imprint}
          </div>
          {f.imprintRightHref ? (
            <a className="mono" href={f.imprintRightHref} target="_blank" rel="noopener noreferrer" style={{ fontSize: "0.78rem", letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-mute)", borderBottom: "1px solid var(--rule)" }}>
              {f.imprintRight}
            </a>
          ) : (
            <div className="mono" style={{ fontSize: "0.78rem", letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
              {f.imprintRight}
            </div>
          )}
        </div>
      </div>
    </footer>
  );
}

/* ---------- Placeholder helper ---------- */

function Placeholder({ label, ratio = "4 / 3", style = {}, children }) {
  return (
    <div className="placeholder" style={{ aspectRatio: ratio, ...style }}>
      {children || <span className="ph-label">{label}</span>}
    </div>
  );
}

/* ---------- Scroll-reveal hook ---------- */

function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    if (!("IntersectionObserver" in window)) { els.forEach(el => el.classList.add("in")); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

/* ---------- Closing CTA — unified (small/big variants) ---------- */

function ClosingCTA({ eyebrow, title, cta, target, onNavigate, variant = "small" }) {
  const v = useValues();
  if (variant === "small") {
    return (
      <section className="section-tight" style={{ borderTop: "1px solid var(--rule)" }}>
        <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 24 }}>
          <div>
            <span className="eyebrow">{eyebrow}</span>
            <h2 style={{ marginTop: 6, fontSize: "var(--scale-6)" }}>{title}</h2>
          </div>
          <a href={"#" + target} className="btn btn-accent" onClick={(e) => { e.preventDefault(); onNavigate(target); }}>
            {cta} →
          </a>
        </div>
      </section>
    );
  }
  // big variant — for home page closing
  return (
    <section className="section" style={{ background: "var(--ink)", color: "var(--paper)", position: "relative", overflow: "hidden" }}>
      <div aria-hidden="true" className="flourish" style={{ position: "absolute", right: -120, top: "50%", transform: "translateY(-50%)", color: "var(--paper)", opacity: 0.08, pointerEvents: "none" }}>
        <Crest size={520} withBanner={false} />
      </div>
      <div className="wrap" style={{ position: "relative" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: "var(--space-7)", alignItems: "center" }} className="cta-grid">
          <div>
            <span className="eyebrow" style={{ color: "color-mix(in oklab, var(--paper) 70%, transparent)" }}>{eyebrow}</span>
            <h2 style={{ color: "var(--paper)", fontSize: "clamp(2.4rem, 5vw, 4rem)", marginTop: 18 }}>
              Tournament entries close <span className="logotype" style={{ color: "var(--accent-soft)" }}>{v.event.deadline}</span>.
            </h2>
            <p style={{ color: "color-mix(in oklab, var(--paper) 80%, transparent)", maxWidth: "48ch", marginTop: 18, fontSize: "1.1rem" }}>
              Tickets for Spectators will always be available, fighters must register in advance, capacity is 60 for longsword, 30 for Harness/Mixed Steel.
            </p>
            <div style={{ marginTop: 28, display: "flex", gap: 14, flexWrap: "wrap" }}>
              <a href={"#" + target} className="btn btn-accent" onClick={(e) => { e.preventDefault(); onNavigate(target); }}>{cta} →</a>
              <a href="#event" className="btn" onClick={(e) => { e.preventDefault(); onNavigate("event"); }} style={{ background: "transparent", color: "var(--paper)", borderColor: "var(--paper)" }}>Event Details</a>
            </div>
          </div>
          <div style={{ borderLeft: "1px solid color-mix(in oklab, var(--paper) 30%, transparent)", paddingLeft: "var(--space-6)" }}>
            <dl style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "10px 24px", margin: 0 }}>
              <Dt>DATE</Dt><Dd>{v.event.dateRange}</Dd>
              <Dt>VENUE</Dt><Dd>{v.event.venue.toUpperCase()}</Dd>
              <Dt>FEE</Dt><Dd>{v.event.feeDisplay}</Dd>
              <Dt>FORMAT</Dt><Dd>{v.event.format.toUpperCase()}</Dd>
            </dl>
          </div>
        </div>
        <style>{`@media (max-width: 740px) { .cta-grid { grid-template-columns: 1fr !important; } }`}</style>
      </div>
    </section>
  );
}
function Dt({ children }) { return <dt className="mono" style={{ color: "color-mix(in oklab, var(--paper) 60%, transparent)", fontSize: "0.78rem", letterSpacing: "0.22em" }}>{children}</dt>; }
function Dd({ children }) { return <dd style={{ margin: 0, fontFamily: "var(--font-display)", letterSpacing: "0.06em" }}>{children}</dd>; }

/* ---------- Exports ---------- */

Object.assign(window, {
  ValuesContext, useValues,
  Crest, FleurDivider, CrossedSwordsIcon, Manicule, CornerDots,
  OrnatedDivider, SectionHeader, PageBanner, SiteHeader, SiteFooter, Placeholder,
  useReveal, ClosingCTA,
});
