/* eslint-disable no-undef */
const { useState, useEffect, useRef } = React;

function cls(...xs) { return xs.filter(Boolean).join(" "); }

/* ---- Reveal hook ---- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("is-in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.15, rootMargin: "0px 0px -10% 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ---- Scroll detection ---- */
function useScrolled(threshold = 30) {
  const [s, setS] = useState(false);
  useEffect(() => {
    const onScroll = () => setS(window.scrollY > threshold);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [threshold]);
  return s;
}

/* ---- NAV ---- */
function Nav({ page = "home", minimal = false }) {
  const scrolled = useScrolled();
  const isAbout = page === "about";
  const link = (id) => isAbout ? `index.html#${id}` : `#${id}`;
  return (
    <header className={cls("nav", scrolled && "is-scrolled", minimal && "is-minimal")}>
      <div className="container">
        <div className="nav-inner">
          <a href="index.html" className="nav-brand">Resonet</a>
          {!minimal && (
            <nav className="nav-links">
              <a className={cls("nav-link", isAbout && "is-active")}
                 href={isAbout ? "#top" : "#about"}>About</a>
              <a className="nav-link" href={link("consulting")}>Consulting</a>
              <a className="nav-link" href={link("haus")}>Haus</a>
              <a className="nav-link" href={link("team")}>Team</a>
              <a className="nav-link" href={link("contact")}>Contact</a>
            </nav>
          )}
          {!minimal && (
            <a className="nav-cta" href={isAbout ? "index.html#contact" : "#contact"}>Begin a Conversation</a>
          )}
        </div>
      </div>
    </header>
  );
}

/* ---- HERO ---- */
function Hero() {
  // Headline split into two lines for the wordUp animation
  const lines = [
    [
      { t: "Discover", em: false },
      { t: "Your", em: false },
      { t: "Own", em: false },
      { t: "Resonance.", em: true },
    ],
  ];
  let counter = 0;

  return (
    <section className="hero" id="top">
      <div className="container">
        <div className="hero-grid">
          <div className="hero-eyebrow">
            <span className="line" />
            <span className="eyebrow">Bespoke Admissions Consulting · Since 2011</span>
          </div>

          <h1 className="serif hero-headline">
            {lines.map((line, li) => (
              <span className="word-line" key={li}>
                {line.map((w, wi) => {
                  const d = (counter++) * 0.14 + 0.3;
                  return (
                    <React.Fragment key={wi}>
                      <span className="hl-word" style={{ "--d": `${d}s` }}>
                        {w.em ? <em>{w.t}</em> : w.t}
                      </span>
                      {wi < line.length - 1 ? <span className="hl-gap">{"\u00A0"}</span> : null}
                    </React.Fragment>
                  );
                })}
              </span>
            ))}
          </h1>

          <p className="hero-sub serif">You, before the application.</p>

          <div className="hero-bottom">
            <p className="hero-lede han">
              <strong>Resonet</strong>이 새로운 모습으로 시작합니다.<br/>
              학생의 정체성에서 시작하는 입시 컨설팅,<br/>
              15년의 경험을 한 자리에 다시 담아.
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- D-day Counter (standalone section) ---- */
function DDaySection() {
  return (
    <section className="dday-section">
      <div className="container">
        <DDayCounter target="2026-06-15T00:00:00+09:00" />
      </div>
    </section>
  );
}

/* ---- D-day Counter ---- */
function DDayCounter({ target }) {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const now = new Date();
  const end = new Date(target);
  const ms = end - now;
  const past = ms < 0;
  const total = Math.abs(ms);
  const days = Math.floor(total / 86400000);
  const hrs = Math.floor((total % 86400000) / 3600000);
  const mins = Math.floor((total % 3600000) / 60000);
  const secs = Math.floor((total % 60000) / 1000);
  const fmt = (n, w = 2) => String(n).padStart(w, "0");
  return (
    <div className="dday">
      <div className="dday-eyebrow-row">
        <span className="dday-line" />
        <span className="dday-eyebrow">{past ? "Since Launch" : "Opening"} · 2026 . 06 . 15</span>
        <span className="dday-line" />
      </div>

      <div className="dday-days">
        <span className="dday-days-prefix">{past ? "+" : "D−"}</span>
        <span className="dday-days-num">{fmt(days, 3)}</span>
      </div>

      <div className="dday-hms">
        <span className="dday-hms-cell">
          <span className="dday-hms-num">{fmt(hrs)}</span>
          <span className="dday-hms-cap">Hrs</span>
        </span>
        <span className="dday-hms-sep">:</span>
        <span className="dday-hms-cell">
          <span className="dday-hms-num">{fmt(mins)}</span>
          <span className="dday-hms-cap">Min</span>
        </span>
        <span className="dday-hms-sep">:</span>
        <span className="dday-hms-cell">
          <span className="dday-hms-num">{fmt(secs)}</span>
          <span className="dday-hms-cap">Sec</span>
        </span>
      </div>

      <p className="dday-foot han"></p>
    </div>
  );
}

/* ---- Marquee ---- */
function Marquee() {
  const phrases = [
    "Most consultants build applications. We build students.",
    "15 years.",
    "Every student, one at a time.",
    "Good college. Better person.",
    "정체성을 먼저 세우고, 그 위에 전략을 쌓는다.",
  ];
  const items = [...phrases, ...phrases];
  return (
    <div className="quiet-marquee">
      <div className="qm-track">
        {items.map((p, i) => (
          <span className="qm-item" key={i}>
            <span>{p}</span>
            <span className="sep" />
          </span>
        ))}
      </div>
    </div>
  );
}

window.cls = cls;
window.useReveal = useReveal;
window.useScrolled = useScrolled;
window.Nav = Nav;
window.Hero = Hero;
window.DDaySection = DDaySection;
window.Marquee = Marquee;

/* ---- SectionIndicator: fixed vertical rail showing active section ---- */
function SectionIndicator() {
  const sections = [
    { id: "top",        index: "00", title: "Resonance" },
    { id: "about",      index: "01", title: "About" },
    { id: "consulting", index: "02", title: "Consulting" },
    { id: "haus",       index: "03", title: "Haus" },
    { id: "team",       index: "04", title: "Team" },
    { id: "contact",    index: "05", title: "Contact" },
  ];
  const [activeId, setActiveId] = React.useState("top");

  React.useEffect(() => {
    const els = sections
      .map(s => ({ ...s, el: document.getElementById(s.id) }))
      .filter(s => s.el);

    const pickActive = () => {
      // Pick the section whose top is closest to (and at/above) ~38% of viewport
      const probe = window.innerHeight * 0.38;
      let current = els[0];
      for (const s of els) {
        const rect = s.el.getBoundingClientRect();
        if (rect.top <= probe) current = s;
      }
      setActiveId(current.id);
    };

    pickActive();
    window.addEventListener("scroll", pickActive, { passive: true });
    window.addEventListener("resize", pickActive);
    return () => {
      window.removeEventListener("scroll", pickActive);
      window.removeEventListener("resize", pickActive);
    };
  }, []);

  const active = sections.find(s => s.id === activeId) || sections[0];
  const total = String(sections.length - 1).padStart(2, "0");

  return (
    <div className={cls("section-indicator", activeId === "contact" && "is-dark")} aria-hidden="true">
      <span className="si-index">{active.index} / {total}</span>
      <span className="si-line" />
      <span className="si-title" key={active.id}>{active.title}</span>
    </div>
  );
}

window.SectionIndicator = SectionIndicator;
