// Reusable components: Navbar, Hero, Sections, Footer, etc.
const { useState, useEffect, useRef } = React;

// ---- IntersectionObserver hook for scroll reveal ----
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -60px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// ---- Navbar ----
function Navbar({ t, lang, setLang, onCta }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState("hero");

  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 20);
      const ids = ["historie", "carnaval", "lustrum", "over", "contact"];
      let cur = "hero";
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top < 120) cur = id;
      }
      setActive(cur);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const goTo = (id) => (e) => {
    e.preventDefault();
    setOpen(false);
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="nav-inner">
        <a href="#hero" onClick={goTo("hero")} className="brand">
          <span className="brand-mark"><img src="assets/OsWapen.webp" alt="Wapen De Goeie Orde" /></span>
          <span className="brand-text">
            <span className="small">Anno MMXXII</span>
            <span className="big">De Goeie Orde</span>
          </span>
        </a>

        <button className={`menu-toggle ${open ? "open" : ""}`} onClick={() => setOpen((o) => !o)} aria-label="Menu">
          <span></span><span></span><span></span>
        </button>

        <ul className={`nav-links ${open ? "open" : ""}`}>
          <li><button className={`nav-link ${active === "historie" ? "active" : ""}`} onClick={goTo("historie")}>{t.nav.historie}</button></li>
          <li><button className={`nav-link ${active === "carnaval" ? "active" : ""}`} onClick={goTo("carnaval")}>{t.nav.carnaval}</button></li>
          <li><button className={`nav-link ${active === "lustrum" ? "active" : ""}`} onClick={goTo("lustrum")}>{t.nav.lustrum}</button></li>
          <li><button className={`nav-link ${active === "over" ? "active" : ""}`} onClick={goTo("over")}>{t.nav.over}</button></li>
          <li><button className={`nav-link ${active === "contact" ? "active" : ""}`} onClick={goTo("contact")}>{t.nav.contact}</button></li>
          <li>
            <div className="lang-switch" role="group" aria-label="Taal">
              <button className={lang === "nl" ? "active" : ""} onClick={() => setLang("nl")}>NL</button>
              <button className={lang === "st" ? "active" : ""} onClick={() => setLang("st")}>STEINS</button>
            </div>
          </li>
          <li><button className="nav-cta" onClick={onCta}>{t.nav.cta}</button></li>
        </ul>
      </div>
    </nav>
  );
}

// ---- Hero ----
function Hero({ t, onPrimary, onSecondary }) {
  return (
    <section className="hero" id="hero">
      <div className="hero-bg-ornament" aria-hidden="true"></div>
      <div className="hero-inner">
        <div className="hero-text">
          <div className="hero-eyebrow reveal">{t.hero.eyebrow}</div>
          <h1 className="reveal delay-1">
            <span className="gothic" dangerouslySetInnerHTML={{__html: t.hero.gothic}} />
            {t.hero.title1} <em>{t.hero.title2}</em>
          </h1>
          <p className="hero-lead reveal delay-2">{t.hero.lead}</p>
          <div className="hero-cta-row reveal delay-3">
            <button className="btn btn-primary" onClick={onPrimary}>
              {t.hero.ctaPrimary}<span className="btn-arrow">→</span>
            </button>
            <button className="btn btn-ghost" onClick={onSecondary}>
              {t.hero.ctaSecondary}
            </button>
          </div>
          <div className="hero-meta reveal delay-4">
            {t.hero.stats.map((s, i) => (
              <div className="hero-meta-item" key={i}>
                <span className="hero-meta-num">{s.num}</span>
                <span className="hero-meta-label">{s.label}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="hero-crest-wrap reveal delay-2">
          <div className="hero-crest">
            <img src="assets/OsWapen.webp" alt="Wapenschild De Goeie Orde" />
          </div>
        </div>
      </div>
    </section>
  );
}

// ---- Divider ----
function Divider() {
  return (
    <div className="divider-ornament" aria-hidden="true">
      <span className="glyph">✦</span>
    </div>
  );
}

// ---- Historie / Timeline ----
function HistorieSection({ t }) {
  return (
    <section className="section section-historie" id="historie">
      <div className="section-inner">
        <div className="section-eyebrow reveal">{t.historie.eyebrow}</div>
        <h2 className="reveal delay-1" dangerouslySetInnerHTML={{__html: t.historie.title}} />
        <p className="section-lead reveal delay-2">{t.historie.lead}</p>

        <Divider />

        <div className="timeline">
          {t.historie.timeline.map((it, i) => (
            <div className="tl-item reveal" key={i}>
              <div className="tl-dot" aria-hidden="true"></div>
              <div className="tl-content">
                <span className="tl-date">{it.date}</span>
                <h3>{it.title}</h3>
                <p>{it.body}</p>
              </div>
              <div className="tl-side" aria-hidden="true">{it.glyph}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---- Story (about origin) ----
function StorySection({ t }) {
  return (
    <section className="section">
      <div className="section-inner">
        <div className="section-eyebrow reveal">{t.story.eyebrow}</div>
        <h2 className="reveal delay-1">{t.story.title}</h2>
        <div className="story-grid">
          <div className="story-prose reveal delay-2">
            <p className="dropcap">{t.story.paras[0]}</p>
            <p>{t.story.paras[1]}</p>
            <blockquote>{t.story.quote}</blockquote>
            <p>{t.story.paras[2]}</p>
          </div>
          <div className="story-image-stack reveal delay-3">
            <div className="photo photo-1"></div>
            <div className="photo photo-2"></div>
            <div className="photo photo-3"></div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---- Carnaval ----
function CarnavalSection({ t }) {
  return (
    <section className="section section-carnaval" id="carnaval">
      <div className="section-inner">
        <div className="section-eyebrow reveal">{t.carnaval.eyebrow}</div>
        <h2 className="reveal delay-1" dangerouslySetInnerHTML={{__html: t.carnaval.title}} />
        <p className="section-lead reveal delay-2">{t.carnaval.lead}</p>

        <div className="carnaval-grid">
          <div className="reveal delay-2">
            <ul className="carnaval-list">
              {t.carnaval.bullets.map((b, i) => (
                <li key={i}>
                  <span className="glyph">{b.glyph}</span>
                  <span>{b.text}</span>
                </li>
              ))}
            </ul>
          </div>
          <div className="confetti-card reveal delay-3">
            <ConfettiBg />
            <h3 style={{fontSize: 28, marginBottom: 14, position: "relative"}}>{t.carnaval.cardTitle}</h3>
            <p style={{position: "relative", fontSize: 18, color: "var(--c-ink-soft)", margin: 0}}>{t.carnaval.cardLead}</p>
          </div>
        </div>

        <FormSection t={t} />
      </div>
    </section>
  );
}

function ConfettiBg() {
  const colors = ["#8b1f1f", "#c89530", "#1e4a8c", "#6b1414", "#d9b04a"];
  const pieces = Array.from({length: 18}, (_, i) => ({
    left: (i * 5.5 + (i % 3) * 4) % 100,
    delay: (i * 0.35) % 6,
    color: colors[i % colors.length],
    rot: (i * 23) % 360,
  }));
  return (
    <div aria-hidden="true" style={{position: "absolute", inset: 0, pointerEvents: "none"}}>
      {pieces.map((p, i) => (
        <span key={i} className="confetti" style={{
          left: `${p.left}%`,
          top: -20,
          background: p.color,
          animationDelay: `-${p.delay}s`,
          transform: `rotate(${p.rot}deg)`,
        }} />
      ))}
    </div>
  );
}

// ---- Over Ons ----
function OverSection({ t }) {
  return (
    <section className="section" id="over">
      <div className="section-inner">
        <div className="section-eyebrow reveal">{t.over.eyebrow}</div>
        <h2 className="reveal delay-1" dangerouslySetInnerHTML={{__html: t.over.title}} />
        <p className="section-lead reveal delay-2">{t.over.lead}</p>

        <div className="over-grid">
          {t.over.cards.map((c, i) => (
            <div className="stat-card reveal" key={i} style={{transitionDelay: `${100 + i*120}ms`}}>
              <div className="label">{c.label}</div>
              <div className="name">{c.name}</div>
              <div className="num">{c.num}<em>{c.numSuffix}</em></div>
              <p className="desc">{c.desc}</p>
            </div>
          ))}
        </div>

        <RoundTable t={t} />
        <StichtingWrap t={t} />
        <BestuurSection t={t} />
      </div>
    </section>
  );
}

function StichtingWrap({ t }) {
  return (
    <div className="stichting-wrap reveal delay-2">
      <Divider />
      <div className="section-eyebrow">{t.over.stichting.eyebrow}</div>
      <div className="stichting-card">
        <h3>{t.over.stichting.title}</h3>
        <dl className="stichting-dl">
          {t.over.stichting.items.map((item, i) => (
            <React.Fragment key={i}>
              <dt>{item.label}</dt>
              <dd>{item.value}</dd>
            </React.Fragment>
          ))}
        </dl>
      </div>
    </div>
  );
}

function BestuurSection({ t }) {
  return (
    <div className="bestuur-section">
      <Divider />
      <div className="section-eyebrow reveal">{t.over.bestuur.eyebrow}</div>
      <h3 className="bestuur-title reveal delay-1">{t.over.bestuur.title}</h3>
      <div className="bestuur-grid">
        {t.over.bestuur.members.map((m, i) => (
          <div className="bestuur-card reveal" key={i} style={{transitionDelay: `${80 + i * 80}ms`}}>
            <div className="bestuur-photo">
              <div className="bestuur-photo-placeholder">{m.initials}</div>
            </div>
            <div className="bestuur-name">{m.name}</div>
            <div className="bestuur-role">{m.role}</div>
            <div className="bestuur-email">
              {m.emailUser}
              <span className="bestuur-at" aria-label={t.over.bestuur.bij}>[{t.over.bestuur.bij}]</span>
              {m.emailDomain}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function RoundTable({ t }) {
  const [seats, setSeats] = React.useState(56);

  // shoulder width per seat for round-table circumference calc
  const SHOULDER_CM = 70;
  const radiusCm = (seats * SHOULDER_CM) / (2 * Math.PI);
  const radiusM = (radiusCm / 100).toFixed(2);
  const diameterM = ((radiusCm * 2) / 100).toFixed(2);

  // dimensions of the SVG viewBox
  const VB = 600;
  const cx = VB / 2;
  const cy = VB / 2;
  // outer ring radius (visual)
  const ringR = 260;
  const innerR = ringR - 38;

  return (
    <div className="round-table-wrap reveal delay-2">
      <div className="round-table-controls">
        <div className="rt-control-group">
          <label>{t.over.tableSeatsLabel}</label>
          <input
            type="range"
            min="6"
            max="120"
            value={seats}
            onChange={(e) => setSeats(parseInt(e.target.value, 10))}
            className="rt-slider"
            aria-label={t.over.tableSeatsLabel}
          />
          <div className="rt-readout">
            <div><span className="rt-num">{seats}</span><span className="rt-unit">{t.over.seats}</span></div>
            <div className="rt-divider" />
            <div><span className="rt-num">⌀ {diameterM}</span><span className="rt-unit">{t.over.diameter}</span></div>
            <div className="rt-divider" />
            <div><span className="rt-num">↔ {radiusM}</span><span className="rt-unit">{t.over.radius}</span></div>
          </div>
          <p className="rt-formula">{t.over.formula}</p>
        </div>

        <div className="round-table-vis">
          <svg viewBox={`0 0 ${VB} ${VB}`} width="100%" height="100%" aria-hidden="true">
            <defs>
              <radialGradient id="tableGrad" cx="38%" cy="35%" r="70%">
                <stop offset="0%" stopColor="#ead8b1" />
                <stop offset="60%" stopColor="#d8c293" />
                <stop offset="100%" stopColor="#a87a3e" />
              </radialGradient>
              <pattern id="woodGrain" x="0" y="0" width="600" height="600" patternUnits="userSpaceOnUse">
                <rect width="600" height="600" fill="url(#tableGrad)" />
                {Array.from({length: 7}, (_, i) => (
                  <ellipse key={i} cx={cx} cy={cy} rx={innerR - i * 18} ry={innerR - i * 18} fill="none" stroke="rgba(120, 80, 40, 0.08)" strokeWidth="1" />
                ))}
              </pattern>
            </defs>

            {/* outer ring (decorative) */}
            <circle cx={cx} cy={cy} r={ringR + 18} fill="none" stroke="rgba(139, 31, 31, 0.18)" strokeWidth="1" strokeDasharray="2 6" />

            {/* table top */}
            <circle cx={cx} cy={cy} r={ringR} fill="url(#woodGrain)" stroke="#5a3a1a" strokeWidth="2" />
            <circle cx={cx} cy={cy} r={ringR - 8} fill="none" stroke="rgba(90, 58, 26, 0.4)" strokeWidth="0.6" />

            {/* center medallion */}
            <circle cx={cx} cy={cy} r={70} fill="rgba(139, 31, 31, 0.12)" stroke="#8b1f1f" strokeWidth="1.2" />
            <text x={cx} y={cy - 4} textAnchor="middle" fill="#8b1f1f" fontFamily="Cinzel, serif" fontWeight="700" fontSize="16" letterSpacing="2">DGO</text>
            <text x={cx} y={cy + 14} textAnchor="middle" fill="#4a2f1f" fontFamily="IM Fell English, serif" fontStyle="italic" fontSize="11" letterSpacing="1.5">MMXXII</text>

            {/* seats */}
            {Array.from({length: seats}, (_, i) => {
              const angle = (i / seats) * Math.PI * 2 - Math.PI / 2;
              const sr = ringR + 22;
              const x = cx + Math.cos(angle) * sr;
              const y = cy + Math.sin(angle) * sr;
              // chair size scales down inversely with count, clamped
              const size = Math.max(4, Math.min(11, 28 - seats * 0.18));
              return (
                <g key={i}>
                  <circle cx={x} cy={y} r={size} fill="#8b1f1f" stroke="#f3e8ce" strokeWidth="1.5" />
                </g>
              );
            })}
          </svg>
        </div>
      </div>

      <div className="round-table-caption">{t.over.tableCenter}</div>
    </div>
  );
}

// ---- Contact ----
function ContactSection({ t }) {
  return (
    <section className="section section-contact" id="contact">
      <div className="section-inner">
        <div className="section-eyebrow reveal">{t.contact.eyebrow}</div>
        <h2 className="reveal delay-1">{t.contact.title}</h2>
        <p className="section-lead reveal delay-2">{t.contact.lead}</p>

        <div className="contact-grid">
          <div className="contact-card reveal delay-2">
            <h3>{t.contact.cardTitle}</h3>
            <div className="sub">{t.contact.cardSub}</div>
            <dl>
              <dt>{t.contact.labels.staminee}</dt>
              <dd>Café 't Veurletste</dd>
              <dt>{t.contact.labels.plaats}</dt>
              <dd>{t.contact.address}</dd>
              <dt>{t.contact.labels.email}</dt>
              <dd><a href="mailto:tafelheer@degoeieorde.nl">tafelheer@degoeieorde.nl</a></dd>
              <dt>{t.contact.labels.sociaal}</dt>
              <dd>
                <a href="https://www.facebook.com/profile.php?id=61587423475336" target="_blank" rel="noopener">Facebook</a>{" · "}
                <a href="https://instagram.com/cvdegoeieorde" target="_blank" rel="noopener">Instagram</a>
              </dd>
            </dl>
          </div>
          <div className="staminee-art reveal delay-3">
            <div className="bg-stripes"></div>
            <div className="staminee-content">
              <div className="pre">{t.contact.stamineePre}</div>
              <div className="name">'t Veurletste</div>
              <div className="where">{t.contact.stamineeWhere}</div>
              <p style={{maxWidth: 320, margin: "0 auto 18px", color: "var(--c-cream)", fontSize: 17}}>{t.contact.stamineeNote}</p>
              <div className="placeholder-note"></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---- Footer ----
function Footer({ t, onNav }) {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-top">
          <div>
            <div className="footer-brand-mark"><img src="assets/OsWapen.webp" alt="" /></div>
            <h4 style={{color: "var(--c-cream)", fontSize: 18, letterSpacing: "0.08em", marginBottom: 8}}>De Goeie Orde</h4>
            <p className="footer-motto">{t.footer.motto}</p>
            <p style={{marginTop: 14}}>{t.footer.tagline}</p>
          </div>
          <div>
            <h4>{t.footer.navTitle}</h4>
            <ul>
              <li><a href="#historie" onClick={onNav("historie")}>{t.nav.historie}</a></li>
              <li><a href="#carnaval" onClick={onNav("carnaval")}>{t.nav.carnaval}</a></li>
              <li><a href="#lustrum" onClick={onNav("lustrum")}>{t.nav.lustrum}</a></li>
              <li><a href="#over" onClick={onNav("over")}>{t.nav.over}</a></li>
              <li><a href="#contact" onClick={onNav("contact")}>{t.nav.contact}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.footer.contactTitle}</h4>
            <ul>
              <li>Café 't Veurletste</li>
              <li>Stein, Limburg</li>
              <li><a href="mailto:tafelheer@degoeieorde.nl">tafelheer@degoeieorde.nl</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.footer.followTitle}</h4>
            <div className="social-row">
              <a className="social-btn" href="https://www.facebook.com/profile.php?id=61587423475336" target="_blank" rel="noopener" aria-label="Facebook">
                <svg viewBox="0 0 24 24" fill="currentColor"><path d="M13 22v-9h3l1-4h-4V6.5c0-1.1.4-1.8 2-1.8h2V1.1C16.5 1 15.4.9 14.2.9c-2.6 0-4.2 1.6-4.2 4.4V9H7v4h3v9h3z"/></svg>
              </a>
              <a className="social-btn" href="https://instagram.com/cvdegoeieorde" target="_blank" rel="noopener" aria-label="Instagram">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                  <rect x="3" y="3" width="18" height="18" rx="4"/>
                  <circle cx="12" cy="12" r="4"/>
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor"/>
                </svg>
              </a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.footer.copyright}</span>
          <div className="legal">
            <a href="#privacy">{t.footer.privacy}</a>
            <a href="#cookies">{t.footer.cookies}</a>
            <a href="uploads/HUISHOUDELIJK%20REGELEMENT%202027.pdf" target="_blank" rel="noopener">{t.footer.reglement}</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ---- Lustrum 2027 ----
function LustrumSection({ t }) {
  const [now, setNow] = React.useState(() => Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const target = new Date("2027-05-02T20:00:00").getTime();
  const diff = Math.max(0, target - now);
  const d = Math.floor(diff / (1000 * 60 * 60 * 24));
  const h = Math.floor((diff / (1000 * 60 * 60)) % 24);
  const m = Math.floor((diff / (1000 * 60)) % 60);
  const s = Math.floor((diff / 1000) % 60);
  const pad = (n) => String(n).padStart(2, "0");

  return (
    <section className="section section-lustrum" id="lustrum">
      <div className="lustrum-bg-ornament" aria-hidden="true">
        <span className="orb orb-1"></span>
        <span className="orb orb-2"></span>
      </div>
      <div className="section-inner lustrum-inner">
        <div className="lustrum-text">
          <div className="section-eyebrow reveal" style={{color: "var(--c-gold-light)"}}>{t.lustrum.eyebrow}</div>
          <h2 className="reveal delay-1" dangerouslySetInnerHTML={{__html: t.lustrum.title}} style={{color: "var(--c-cream)"}} />
          <p className="section-lead reveal delay-2" style={{color: "rgba(248, 239, 217, 0.85)"}}>{t.lustrum.lead}</p>

          <div className="lustrum-bullets reveal delay-3">
            {t.lustrum.bullets.map((b, i) => (
              <div className="lb-item" key={i}>
                <div className="lb-num">{b.num}</div>
                <div>
                  <div className="lb-title">{b.title}</div>
                  <p className="lb-body">{b.body}</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="lustrum-countdown reveal delay-2">
          <div className="lc-year">MMXXVII</div>
          <div className="lc-label">{t.lustrum.countdownLabel}</div>
          <div className="lc-grid">
            <div className="lc-cell"><div className="lc-num">{pad(d)}</div><div className="lc-unit">{t.lustrum.labels.days}</div></div>
            <div className="lc-cell"><div className="lc-num">{pad(h)}</div><div className="lc-unit">{t.lustrum.labels.hours}</div></div>
            <div className="lc-cell"><div className="lc-num">{pad(m)}</div><div className="lc-unit">{t.lustrum.labels.minutes}</div></div>
            <div className="lc-cell"><div className="lc-num">{pad(s)}</div><div className="lc-unit">{t.lustrum.labels.seconds}</div></div>
          </div>
          <div className="lc-date">II · V · MMXXVII</div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { useReveal, Navbar, Hero, HistorieSection, StorySection, CarnavalSection, OverSection, StichtingWrap, BestuurSection, ContactSection, Footer, Divider, LustrumSection });
