/* App shell + router (Bastion-styled) */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

const ROUTES = [
  { id: "home",     label: "首頁",   en: "INDEX"     },
  { id: "courses",  label: "課程",   en: "PROGRAMS"  },
  { id: "schedule", label: "課表",   en: "SCHEDULE"  },
  { id: "pricing",  label: "費用",   en: "MEMBERSHIP"},
  { id: "about",    label: "關於",   en: "MANIFESTO" },
  { id: "contact",  label: "聯絡",   en: "CONTACT"   },
];

function useHashRoute() {
  const [route, setRoute] = useState(() => (window.location.hash.slice(1) || "home"));
  useEffect(() => {
    const onHash = () => {
      setRoute(window.location.hash.slice(1) || "home");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const navigate = useCallback((id) => { window.location.hash = id; }, []);
  return [route, navigate];
}

// ============ SHIELD MONOGRAM ============
function Shield({ size = 40 }) {
  // Hand-drawn shield monogram for "AF" — Attack First
  return (
    <svg width={size} height={size * 1.16} viewBox="0 0 100 116" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <path d="M2 4 H98 V62 C98 86 80 104 50 114 C20 104 2 86 2 62 Z"
            stroke="currentColor" strokeWidth="2" fill="none" />
      <path d="M14 16 H86 V60 C86 78 72 92 50 100 C28 92 14 78 14 60 Z"
            stroke="currentColor" strokeWidth="0.6" fill="none" opacity="0.5" />
      <text x="50" y="62" textAnchor="middle" fontFamily="Vanguard, Bebas Neue, Oswald, sans-serif" fontWeight="400" fontSize="38" fill="currentColor" letterSpacing="-1">AF</text>
      <line x1="20" y1="76" x2="80" y2="76" stroke="currentColor" strokeWidth="0.5" opacity="0.5" />
      <text x="50" y="88" textAnchor="middle" fontFamily="Suisse Intl, Inter, sans-serif" fontWeight="500" fontSize="6.5" fill="currentColor" letterSpacing="1.5">EST · 2026</text>
    </svg>
  );
}

// ============ TWEAKS ============
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "gold": "#a8804f",
  "displayFont": "vanguard"
}/*EDITMODE-END*/;

function applyTweaks(t) {
  const root = document.documentElement;
  root.style.setProperty("--gold", t.gold);
  // soft variants derived from primary
  const hex = t.gold.replace("#", "");
  const r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16);
  root.style.setProperty("--gold-soft",  `rgba(${r},${g},${b},0.5)`);
  root.style.setProperty("--gold-mute",  `rgba(${r},${g},${b},0.3)`);
  root.style.setProperty("--gold-faint", `rgba(${r},${g},${b},0.12)`);
  root.style.setProperty("--hairline", t.gold);
  root.style.setProperty("--hairline-soft", `rgba(${r},${g},${b},0.25)`);

  if (t.displayFont === "vanguard") {
    root.style.setProperty("--display", '"Vanguard", "Bebas Neue", "Oswald", "Archivo Narrow", "Noto Sans TC", sans-serif');
  } else if (t.displayFont === "bebas") {
    root.style.setProperty("--display", '"Bebas Neue", "Noto Sans TC", sans-serif');
  } else if (t.displayFont === "oswald") {
    root.style.setProperty("--display", '"Oswald", "Noto Sans TC", sans-serif');
  } else if (t.displayFont === "anton") {
    root.style.setProperty("--display", '"Anton", "Noto Sans TC", sans-serif');
  }
}

function TweaksApp() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffect(() => { applyTweaks(tweaks); }, [tweaks]);
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="品牌金 BRAND TONE">
        <TweakColor
          label="Gold"
          value={tweaks.gold}
          onChange={(v) => setTweak("gold", v)}
          options={["#a8804f", "#c89860", "#8a6b3f", "#b89968", "#9a7a5a"]}
        />
      </TweakSection>
      <TweakSection title="展示字體 DISPLAY">
        <TweakSelect
          label="Display Face"
          value={tweaks.displayFont}
          onChange={(v) => setTweak("displayFont", v)}
          options={[
            { value: "vanguard", label: "Vanguard / Narrow (default)" },
            { value: "bebas",    label: "Bebas Neue" },
            { value: "oswald",   label: "Oswald" },
            { value: "anton",    label: "Anton" },
          ]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ============ NAV ============
function Nav({ route, navigate, menuOpen, setMenuOpen }) {
  return (
    <nav className="nav">
      <div className="nav-logo" onClick={() => { navigate("home"); setMenuOpen(false); }}>
        <span className="shield-mark"><Shield size={28} /></span>
        <div className="nav-club">ATTACK FIRST<br/>CYCLING · 國王俱樂部</div>
      </div>
      <button className={"nav-trigger" + (menuOpen ? " open" : "")} onClick={() => setMenuOpen(o => !o)}>
        <span className="lines"><span></span><span></span></span>
        {menuOpen ? "CLOSE" : "MENU"}
      </button>
    </nav>
  );
}

function MenuOverlay({ open, route, navigate, close }) {
  return (
    <div className={"overlay" + (open ? " open" : "")}>
      <div></div>
      <div className="overlay-list">
        {ROUTES.map((r, i) => (
          <a key={r.id}
             className="overlay-link"
             onClick={(e) => { e.preventDefault(); navigate(r.id); close(); }}>
            <span>
              <span className="idx" style={{ display: "inline-block", marginRight: 24, opacity: 0.5 }}>0{i + 1} /</span>
              {r.en}
            </span>
            <span className="idx" style={{ opacity: 0.5 }}>{r.label}</span>
          </a>
        ))}
      </div>
      <div className="overlay-foot">
        <span className="caption">ATTACK FIRST CYCLING · 國王單車俱樂部 · EST 2026</span>
        <span className="caption">台中 · 北屯 · 旱溪東路三段 20 號</span>
      </div>
    </div>
  );
}

// ============ FOOTER ============
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-mega">A&nbsp;BOLD&nbsp;NEW&nbsp;ERA</div>

        <div className="footer-grid">
          <div className="footer-brand">
            <span className="shield-mark"><Shield size={32} /></span>
            <p>ATTACK FIRST CYCLING — 國王單車俱樂部。一座為熱愛速度的單車人打造的室內訓練基地。Powered by Magene · CORE · TrainingPeaks.</p>
          </div>
          <div>
            <h4>Index</h4>
            <ul>
              {ROUTES.map(r => (
                <li key={r.id}><a href={"#" + r.id} onClick={(e) => { e.preventDefault(); navigate(r.id); }}>{r.en}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h4>Studio</h4>
            <ul>
              <li>台中市北屯區</li>
              <li>旱溪東路三段 20 號</li>
              <li>週一 ~ 週四 07:00–22:00</li>
              <li>週五 17:00–22:00</li>
            </ul>
          </div>
          <div>
            <h4>Channels</h4>
            <ul>
              <li><a href="#">Facebook</a></li>
              <li><a href="#">Instagram</a></li>
              <li><a href="#contact" onClick={(e) => { e.preventDefault(); navigate("contact"); }}>私訊報名</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-bottom">
          <span>© 2026 ATTACK FIRST CYCLING · 國王單車俱樂部 ALL RIGHTS RESERVED</span>
          <span>POWERED BY MAGENE × CORE × TRAININGPEAKS</span>
          <a href="#home" onClick={(e) => { e.preventDefault(); navigate("home"); window.scrollTo({ top: 0, behavior: "smooth" }); }}>BACK TO TOP ↑</a>
        </div>
      </div>
    </footer>
  );
}

// ============ MAIN APP ============
function App() {
  const [route, navigate] = useHashRoute();
  const [signupOpen, setSignupOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  // Close overlay on route change
  useEffect(() => { setMenuOpen(false); }, [route]);

  const Page = useMemo(() => {
    switch (route) {
      case "courses":  return <CoursesPage navigate={navigate} openSignup={() => setSignupOpen(true)} />;
      case "schedule": return <SchedulePage navigate={navigate} openSignup={() => setSignupOpen(true)} />;
      case "pricing":  return <PricingPage navigate={navigate} openSignup={() => setSignupOpen(true)} />;
      case "about":    return <AboutPage navigate={navigate} />;
      case "contact":  return <ContactPage navigate={navigate} openSignup={() => setSignupOpen(true)} />;
      default:         return <HomePage navigate={navigate} openSignup={() => setSignupOpen(true)} />;
    }
  }, [route, navigate]);

  return (
    <>
      <Nav route={route} navigate={navigate} menuOpen={menuOpen} setMenuOpen={setMenuOpen} />
      <MenuOverlay open={menuOpen} route={route} navigate={navigate} close={() => setMenuOpen(false)} />
      <main key={route} data-screen-label={route} style={{ opacity: menuOpen ? 0 : 1, transition: "opacity 0.3s ease" }}>
        {Page}
      </main>
      <Footer navigate={navigate} />
      {signupOpen && <SignupModal onClose={() => setSignupOpen(false)} />}
      <TweaksApp />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);

window.Shield = Shield;
