/* Shared components. Depends on window.Ic. Exports to window. */
const { useState, useEffect, useRef } = React;

function fmtDate(iso) {
  const d = new Date(iso + "T00:00:00");
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

/* ---------- nav ---------- */
function Nav({ route, go, theme, toggleTheme }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [
    { id: "home", label: "Home" },
    { id: "blog", label: "Writing" },
    { id: "pubs", label: "Publications" },
  ];
  const here = route.name === "post" ? "blog" : route.name;
  return (
    <header className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="wrap nav__inner">
        <div className="brand" onClick={() => go({ name: "home" })} title="Home">
          <span className="brand__mark">XW</span>
          <span className="brand__name">Peppaking8's Website</span>
        </div>
        <nav className="nav__links">
          {links.map((l) => (
            <span key={l.id} className={"nav__link" + (here === l.id ? " active" : "")} onClick={() => go({ name: l.id })}>{l.label}</span>
          ))}
        </nav>
        <button className="icon-btn" onClick={toggleTheme} title={theme === "dark" ? "Switch to light" : "Switch to dark"} aria-label="Toggle theme">
          {theme === "dark" ? <Ic.sun/> : <Ic.moon/>}
        </button>
      </div>
    </header>
  );
}

/* ---------- quick links ---------- */
function QuickLinks({ links }) {
  return (
    <div className="hero__links">
      {links.map((l) => (
        <a key={l.label} className={"btn" + (l.accent ? " btn--accent" : "")} href={l.href}
           target={l.href.startsWith("http") ? "_blank" : undefined} rel="noopener"
           onClick={(e) => { if (l.href === "#") e.preventDefault(); }}>
          {Ic[l.icon] && Ic[l.icon]()}
          {l.label}
        </a>
      ))}
    </div>
  );
}

/* ---------- hero ---------- */
function Hero({ profile, links }) {
  return (
    <section className="hero">
      <div className="wrap hero__grid">
        <div>
          <h1 className="hero__name">
            <span className="grad">{profile.name}</span>
          </h1>
          <p className="hero__role">{profile.role[0]}<b>{profile.role[1]}</b>{profile.role[2]}.</p>
          <p className="hero__bio" dangerouslySetInnerHTML={{ __html: profile.bioHtml }} />
          <QuickLinks links={links} />
        </div>
        <div className="hero__photo">
          <img src="assets/images/photo.jpeg" alt="Xianbang Wang" />
        </div>
      </div>
    </section>
  );
}

/* ---------- publication row ---------- */
function PubCard({ pub, go }) {
  const open = () => pub.post && go({ name: "post", id: pub.post });
  return (
    <article className="pub">
      <div className="pub__media" onClick={open} style={{ cursor: pub.post ? "pointer" : "default" }}>
        {pub.img ? <img src={pub.img} alt="" /> : <div className="ph">figure</div>}
      </div>
      <div>
        <div className="pub__venue"><span className="venue">{pub.venue}{pub.status ? " · " + pub.status : ""}</span></div>
        <h3 className="pub__title"><a onClick={open} style={{ cursor: pub.post ? "pointer" : "default" }}>{pub.title}</a></h3>
        <p className="pub__authors" dangerouslySetInnerHTML={{ __html: pub.authors }} />
        <div className="pub__links">
          {pub.post && <a className="linklet" onClick={open}><Ic.doc/>Details</a>}
          {pub.arxiv && <a className="linklet" href={pub.arxiv} target="_blank" rel="noopener"><Ic.ext/>arXiv</a>}
        </div>
      </div>
    </article>
  );
}

/* ---------- post row (home recent list) ---------- */
function PostRow({ post, go }) {
  return (
    <div className="post-row" onClick={() => go({ name: "post", id: post.id })}>
      <div className="post-row__date">{fmtDate(post.date)}</div>
      <div className="post-row__main">
        <span className={"post-row__type" + (post.type === "Publication" ? " pub-type" : "")}>{post.type}</span>
        <h3 className="post-row__title">{post.title}</h3>
        <div className="post-row__tags">
          {post.tags.slice(0, 3).map((t) => <span key={t} className="chip">#{t}</span>)}
        </div>
      </div>
      <div className="post-row__arrow"><Ic.arrow/></div>
    </div>
  );
}

/* ---------- blog index card ---------- */
function PCard({ post, go }) {
  return (
    <article className="pcard" onClick={() => go({ name: "post", id: post.id })}>
      <div className="pcard__media">
        {post.img ? <img src={post.img} alt="" /> : <div className="ph">{post.type === "Blog" ? "blog illustration" : "figure"}</div>}
      </div>
      <div className="pcard__body">
        <div className="pcard__top">
          <span className="t" style={post.type === "Publication" ? { color: "var(--accent)" } : null}>{post.type}</span>
          <span className="d">{fmtDate(post.date)} · {post.readMin} min</span>
        </div>
        <h3 className="pcard__title">{post.title}</h3>
        <p className="pcard__blurb">{post.blurb}</p>
        <div className="pcard__tags">{post.tags.map((t) => <span key={t} className="chip">#{t}</span>)}</div>
      </div>
    </article>
  );
}

/* ---------- footer ---------- */
function Footer({ profile }) {
  return (
    <footer className="foot">
      <div className="wrap foot__inner">
        <div className="foot__meta">© {new Date().getFullYear()} {profile.name} · built to keep the beginner's mind</div>
        <div className="foot__links">
          <a className="icon-btn" href="https://github.com/PeppaKing8" target="_blank" rel="noopener" aria-label="GitHub"><Ic.github/></a>
          <a className="icon-btn" href="https://scholar.google.com/citations?user=OkWb28sAAAAJ&hl=en" target="_blank" rel="noopener" aria-label="Google Scholar"><Ic.scholar/></a>
          <a className="icon-btn" href="https://www.linkedin.com/in/xianbang-wang-752081382/" target="_blank" rel="noopener" aria-label="LinkedIn"><Ic.linkedin/></a>
          <a className="icon-btn" href={"mailto:" + profile.email} aria-label="Email"><Ic.mail/></a>
        </div>
      </div>
    </footer>
  );
}

/* ---------- easter egg ---------- */
function EasterEgg({ onClose }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div className="egg" onClick={onClose}>
      <div className="egg__card" onClick={(e) => e.stopPropagation()}>
        <div className="zen">🌱</div>
        <h3>Keep the beginner's mind.</h3>
        <p>In the beginner's mind there are many possibilities, but in the expert's there are few. You found the secret — now go build something.</p>
        <div className="egg__hint">press <kbd>Esc</kbd> to close</div>
      </div>
    </div>
  );
}

Object.assign(window, { Nav, QuickLinks, Hero, PubCard, PostRow, PCard, Footer, EasterEgg, fmtDate });
