// ============================================================
// Components — sidebar identity + sections
// ============================================================

const { useState, useEffect, useRef, useCallback } = React;

// ---------- Avatar carousel ----------

function AvatarCarousel({ images }) {
  const [idx, setIdx] = useState(0);
  const [lightbox, setLightbox] = useState(false);
  const trackRef = useRef(null);

  const go = useCallback((d) => {
    setIdx((i) => (i + d + images.length) % images.length);
  }, [images.length]);

  useEffect(() => {
    if (!lightbox) return;
    const onKey = (e) => {
      if (e.key === "Escape") setLightbox(false);
      if (e.key === "ArrowLeft") go(-1);
      if (e.key === "ArrowRight") go(1);
    };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [lightbox, go]);

  const lightboxModal = (
    <div className={"lightbox" + (lightbox ? " open" : "")} onClick={() => setLightbox(false)}>
      {lightbox && (
        <>
          <figure className="lightbox-figure" onClick={(e) => e.stopPropagation()}>
            <img className="lightbox-img" src={images[idx]} alt="" />
            <figcaption className="lightbox-caption">Real Life Visual Performance May Vary</figcaption>
          </figure>
          <button className="lightbox-close" aria-label="Close" onClick={() => setLightbox(false)}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
          <button className="lightbox-arrow left" aria-label="Previous" onClick={(e) => { e.stopPropagation(); go(-1); }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
          </button>
          <button className="lightbox-arrow right" aria-label="Next" onClick={(e) => { e.stopPropagation(); go(1); }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 6 15 12 9 18"/></svg>
          </button>
        </>
      )}
    </div>
  );

  return (
    <>
      <div className="avatar-wrap" role="region" aria-label="Profile photos">
        <div
          className="avatar-track"
          ref={trackRef}
          style={{ transform: `translateX(-${idx * 100}%)` }}
        >
          {images.map((src, i) => (
            <img
              key={src}
              src={src}
              alt={`Tony Danjun Wang, photo ${i + 1}`}
              loading={i === 0 ? "eager" : "lazy"}
              onClick={() => setLightbox(true)}
              draggable={false}
            />
          ))}
        </div>
        {images.length > 1 && (
          <>
            <button className="avatar-arrow left" aria-label="Previous" onClick={() => go(-1)}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
            </button>
            <button className="avatar-arrow right" aria-label="Next" onClick={() => go(1)}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 6 15 12 9 18"/></svg>
            </button>
            <div className="avatar-dots">
              {images.map((_, i) => (
                <button
                  key={i}
                  className={i === idx ? "active" : ""}
                  aria-label={`Go to photo ${i + 1}`}
                  onClick={() => setIdx(i)}
                />
              ))}
            </div>
          </>
        )}
      </div>
      {ReactDOM.createPortal(lightboxModal, document.body)}
    </>
  );
}

// ---------- Identity sidebar ----------

function Identity() {
  const s = window.SITE;
  const [copied, setCopied] = useState(false);

  const copyEmail = async () => {
    try {
      await navigator.clipboard.writeText(s.email);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {}
  };

  return (
    <aside className="identity">
      <AvatarCarousel images={s.avatars} />

      <h1>
        {s.name}
        <span className="name-zh">{s.nameZh}</span>
      </h1>
      <p className="position">{s.position}</p>
      <span className="affiliation">
        <a href={s.affiliationLink} target="_blank" rel="noopener">{s.affiliation}</a>
      </span>

      <button className={"email-pill" + (copied ? " copied" : "")} onClick={copyEmail} aria-label="Copy email">
        <span>{copied ? "Copied" : s.email}</span>
        <span className="copy-icon">{copied ? "✓" : "⎘"}</span>
      </button>

      <div className="link-row">
        {s.links.cv && (
          <a href={s.links.cv} target="_blank" rel="noopener" aria-label="CV" title="CV">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="15" y2="17"/></svg>
          </a>
        )}
        <a href={s.links.github} target="_blank" rel="noopener" aria-label="GitHub" title="GitHub">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2.2c-3.3.7-4-1.4-4-1.4-.6-1.4-1.4-1.8-1.4-1.8-1.1-.7.1-.7.1-.7 1.2.1 1.9 1.3 1.9 1.3 1.1 1.9 2.9 1.3 3.6 1 .1-.8.4-1.3.8-1.6-2.7-.3-5.5-1.3-5.5-5.9 0-1.3.5-2.4 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2a11.5 11.5 0 0 1 6 0c2.3-1.5 3.3-1.2 3.3-1.2.7 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.6-2.8 5.6-5.5 5.9.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A12 12 0 0 0 12 .3"/></svg>
        </a>
        <a href={s.links.linkedin} target="_blank" rel="noopener" aria-label="LinkedIn" title="LinkedIn">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M19 0h-14c-2.8 0-5 2.2-5 5v14c0 2.8 2.2 5 5 5h14c2.8 0 5-2.2 5-5v-14c0-2.8-2.2-5-5-5zm-11 19h-3v-11h3v11zm-1.5-12.3c-1 0-1.7-.8-1.7-1.7s.7-1.7 1.7-1.7 1.7.8 1.7 1.7-.7 1.7-1.7 1.7zm13.5 12.3h-3v-5.6c0-1.4-.5-2.4-1.8-2.4-1 0-1.6.7-1.8 1.3-.1.2-.1.5-.1.8v5.9h-3s.04-9.6 0-11h3v1.6c.4-.6 1.1-1.4 2.7-1.4 2 0 3.5 1.3 3.5 4.1v6.7z"/></svg>
        </a>
        <a href={s.links.scholar} target="_blank" rel="noopener" aria-label="Google Scholar" title="Google Scholar">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M5.242 13.769L0 9.5 12 0l12 9.5-5.242 4.269C17.548 11.249 14.978 9.5 12 9.5c-2.977 0-5.548 1.748-6.758 4.269zM12 10a7 7 0 1 0 0 14 7 7 0 0 0 0-14z"/></svg>
        </a>
      </div>
    </aside>
  );
}

// ---------- Section ----------

function Section({ num, title, id, children }) {
  return (
    <section className="block" id={id}>
      <div className="section-head">
        <span className="section-num">{num}</span>
        <h2>{title}</h2>
      </div>
      {children}
    </section>
  );
}

// ---------- About ----------

function About() {
  const s = window.SITE;
  return (
    <Section num="01" title="About" id="about">
      <div className="about">
        <p>
          I'm <strong>{s.name}</strong> ({s.nameZh}), a {s.position} at the{" "}
          <a href={s.groupLink} target="_blank" rel="noopener">{s.group}</a> at the{" "}
          <a href={s.affiliationLink} target="_blank" rel="noopener">Technical University of Munich</a>,
          supervised by <a href={s.advisorLink} target="_blank" rel="noopener">{s.advisor}</a>.
          I work on <strong>3D computer vision</strong> for <strong>surgical data science</strong> —
          mostly geometric scene understanding in the operating room.
        </p>
        <p>
          Outside of academics I am passionate about music 🎹 and have played the piano actively for over 14 years, winning several competitions. Sports are also a big part of my life; I worked as a swim coach and continue to swim actively 🏊. Additionally, my commitment to helping others extends beyond the pool as I am also a trained paramedic 🚑! •ᴗ•
        </p>
      </div>
    </Section>
  );
}

// ---------- Education ----------

function Education() {
  return (
    <Section num="02" title="Education" id="education">
      <div className="edu-timeline">
        {window.EDUCATION.map((e, i) => (
          <div key={i} className={"edu-entry" + (i === 0 ? " current" : "")}>
            <div className="edu-degree">{e.degree}</div>
            <div className="edu-school">
              <a href={e.schoolLink} target="_blank" rel="noopener">{e.school}</a>
            </div>
            <div className="edu-meta">
              <span className="duration">{e.duration}</span>
              {e.note && <span className="note">{e.note}</span>}
            </div>
          </div>
        ))}
      </div>
    </Section>
  );
}

// ---------- News ----------

function News() {
  const [expanded, setExpanded] = useState(false);
  const initial = 5;
  const items = window.NEWS;
  const hasMore = items.length > initial;

  return (
    <Section num="03" title="News" id="news">
      <ul className="news-list">
        {items.map((n, i) => (
          <li key={i} className={!expanded && i >= initial ? "collapsed" : ""}>
            <span className="news-date">{n.date}</span>
            <span dangerouslySetInnerHTML={{ __html: n.html }} />
          </li>
        ))}
      </ul>
      {hasMore && (
        <button className="news-toggle" onClick={() => setExpanded(!expanded)}>
          {expanded ? "Show less" : `Show ${items.length - initial} more`}
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ transform: expanded ? "rotate(180deg)" : "none", transition: "transform .2s" }}>
            <polyline points="6 9 12 15 18 9"/>
          </svg>
        </button>
      )}
    </Section>
  );
}

// Expose
Object.assign(window, { AvatarCarousel, Identity, Section, About, Education, News });
