// Shared components used across all pages of Fitbull Training Lab
const { useState, useEffect, useRef } = React;

// ───────────────────────────── Star (brutalist asterisk)
function BigStar({ className = "", style = {} }) {
  return (
    <svg viewBox="0 0 100 100" className={`bigstar ${className}`} style={style} aria-hidden>
      <g fill="currentColor">
        {Array.from({ length: 12 }).map((_, i) => (
          <rect key={i} x="48" y="4" width="4" height="92" transform={`rotate(${i * 15} 50 50)`} />
        ))}
        <circle cx="50" cy="50" r="6" />
      </g>
    </svg>
  );
}

// ───────────────────────────── Reveal-on-scroll wrapper
function Reveal({ children, delay = 0, as: Tag = "div", style = {}, className = "" }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { setSeen(true); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <Tag ref={ref} className={`reveal ${seen ? "in" : ""} ${className}`}
      style={{ ...style, transitionDelay: `${delay}ms` }}>
      {children}
    </Tag>
  );
}

// ───────────────────────────── Logo mark (with image)
function LogoMark({ size = 36, dark = false }) {
  return (
    <img src="assets/fitbull-logo.png" alt="Fitbull Gym"
      style={{ width: size, height: size, objectFit: "contain", filter: dark ? "invert(1)" : "none" }} />
  );
}

// ───────────────────────────── NAV
const NAV_LINKS = [
  { href: "index.html", label: "Home", num: "01" },
  { href: "programs.html", label: "Programs", num: "02" },
  { href: "trainers.html", label: "Trainers", num: "03" },
  { href: "pricing.html", label: "Pricing", num: "04" },
  { href: "gallery.html", label: "Gallery", num: "05" },
  { href: "reviews.html", label: "Reviews", num: "06" },
  { href: "blog.html", label: "Journal", num: "07" },
  { href: "contact.html", label: "Contact", num: "08" },
];

function Nav({ active = "index.html", dark = false }) {
  const [open, setOpen] = useState(false);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  return (
    <>
      <nav className={`nav ${dark ? "dark-nav" : ""}`}>
        <div className="nav-inner">
          <a href="index.html" className="nav-logo">
            <LogoMark size={36} dark={dark} />
            <span>FITBULL<span style={{ color: "var(--accent)" }}>·</span>TRAINING LAB</span>
          </a>
          <div className="nav-links">
            {NAV_LINKS.slice(0, 7).map(l => (
              <a key={l.href} href={l.href} className={active === l.href ? "active" : ""}>{l.label}</a>
            ))}
          </div>
          <div className="nav-cta-wrap">
            <a href="contact.html" className="nav-cta">무료체험 예약 →</a>
          </div>
          <button className="nav-burger" onClick={() => setOpen(true)} aria-label="Open menu">
            <span></span>
          </button>
        </div>
      </nav>

      <div className={`mobile-menu ${open ? "open" : ""}`}>
        <div className="mm-top">
          <a href="index.html" className="nav-logo" style={{ color: "var(--bone)" }}>
            <LogoMark size={36} dark={true} />
            <span>FITBULL · T.LAB</span>
          </a>
          <button className="mm-close" onClick={() => setOpen(false)} aria-label="Close" />
        </div>
        <div className="mm-list">
          {NAV_LINKS.map(l => (
            <a key={l.href} href={l.href}>
              {l.label}
              <span>{l.num}</span>
            </a>
          ))}
        </div>
        <div className="mm-foot">
          <span>PANGYO · KR</span>
          <span>평일 07:00 — 23:00</span>
        </div>
      </div>
    </>
  );
}

// ───────────────────────────── Marquee
function Marquee({ items = ["TRAINING IS A SKILL", "PAIN-FREE PERFORMANCE", "TRAIN OLDER, TRAIN HARDER", "FITBULL · T.LAB", "EST. 2016"], dark = false }) {
  // Duplicate for seamless loop
  const all = [...items, ...items];
  return (
    <div className={`marquee ${dark ? "ink-bg" : ""}`}>
      <div className="marquee-track">
        {all.map((it, i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 60 }}>
            {it}<span className="star">✦</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ───────────────────────────── Footer
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div>
            <div className="footer-mark">FITBULL<br/>TRAINING<br/>LAB.<span style={{ color: "var(--accent)" }}>*</span></div>
            <p className="lead" style={{ marginTop: 24 }}>
              30~40대 이상을 위한 통증 케어 &amp; 퍼포먼스 PT 스튜디오. 분당 동판교에서 평일 07:00부터 운영합니다.
            </p>
          </div>
          <div>
            <h5>SITEMAP</h5>
            <ul>
              {NAV_LINKS.map(l => <li key={l.href}><a href={l.href}>{l.label}</a></li>)}
            </ul>
          </div>
          <div>
            <h5>CONTACT</h5>
            <ul>
              <li>0507-1430-9683</li>
              <li>fitbullgym@naver.com</li>
              <li>@fitbull.t.lab</li>
              <li>YouTube 핏불짐 판교</li>
            </ul>
          </div>
          <div>
            <h5>LOCATION</h5>
            <ul>
              <li>경기 성남시 분당구</li>
              <li>동판교로 61, 자유퍼스트프라자2 3F</li>
              <li>평일 · 07:00–23:00</li>
              <li>토 · 10:00–14:00 / 일 휴무</li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>© 2016—2026 FITBULL TRAINING LAB</span>
          <span>BUILT TO MOVE WELL. LIFT HEAVY. AGE WELL.</span>
          <span>v.04.26</span>
        </div>
      </div>
    </footer>
  );
}

// ───────────────────────────── Tweaks (accent color toggle)
const ACCENT_PRESETS = [
  { id: "blood", label: "BLOOD RED",   color: "#E63946", ink: "#0A0A0A" },
  { id: "volt",  label: "VOLT YELLOW", color: "#F1FF00", ink: "#0A0A0A" },
  { id: "neon",  label: "NEON LIME",   color: "#B8FF3C", ink: "#0A0A0A" },
  { id: "safe",  label: "SAFETY ORG.", color: "#FF5A1F", ink: "#0A0A0A" },
  { id: "ice",   label: "ICE BLUE",    color: "#7CC4FF", ink: "#0A0A0A" },
  { id: "bone",  label: "OFF-WHITE",   color: "#F5F1EA", ink: "#0A0A0A" },
];

function applyAccent(id) {
  const p = ACCENT_PRESETS.find(x => x.id === id) || ACCENT_PRESETS[0];
  document.documentElement.style.setProperty("--accent", p.color);
  document.documentElement.style.setProperty("--accent-ink", p.ink);
}

function FitbullTweaks() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS || { accent: "blood" });

  useEffect(() => { applyAccent(t.accent); }, [t.accent]);

  return (
    <TweaksPanel title="TWEAKS">
      <TweakSection label="Accent color" />
      <TweakRadio
        label="Preset"
        value={t.accent}
        options={ACCENT_PRESETS.map(p => ({ value: p.id, label: p.label.split(" ")[0] }))}
        onChange={(v) => setTweak("accent", v)}
      />
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 4, marginTop: 4
      }}>
        {ACCENT_PRESETS.map(p => (
          <button key={p.id} onClick={() => setTweak("accent", p.id)}
            title={p.label}
            style={{
              height: 28, border: t.accent === p.id ? "2px solid #0A0A0A" : "1px solid rgba(0,0,0,.15)",
              background: p.color, cursor: "pointer", padding: 0
            }} />
        ))}
      </div>
    </TweaksPanel>
  );
}

// Boot the tweaks panel into a fixed mount once per page
function bootTweaks() {
  const mount = document.getElementById("tweaks-mount") || (() => {
    const d = document.createElement("div"); d.id = "tweaks-mount"; document.body.appendChild(d); return d;
  })();
  ReactDOM.createRoot(mount).render(<FitbullTweaks />);
  // Apply default accent on load
  applyAccent((window.TWEAK_DEFAULTS && window.TWEAK_DEFAULTS.accent) || "blood");
}

// Expose globally so per-page scripts can use them
Object.assign(window, {
  Nav, Footer, Marquee, BigStar, Reveal, LogoMark,
  bootTweaks, applyAccent, ACCENT_PRESETS, NAV_LINKS,
});
