/* portfolio-pages.jsx — Home, Work, Experience, Interests */
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

/* shared base style so empty image-slots read on the dark theme
   (inline style beats the component's shadow :host defaults) */
const SLOT = { background: "#15171a", color: "rgba(255,255,255,0.40)" };

/* =========================================================
   HOME
   ========================================================= */
function HeroPhoto({ shape = "rounded", size = 360, src }) {
  return (
    <div className="hero-photo-wrap" style={{ width: size }}>
      <image-slot
        id="profile-photo"
        shape={shape}
        radius="6"
        placeholder="Drop your portrait"
        src={src}
        style={{ ...SLOT, width: "100%", height: "auto", aspectRatio: "4 / 5", display: "block" }}
      ></image-slot>
    </div>
  );
}

/* editorial "now" meta — replaces the boxed status panel */
function NowMeta({ p }) {
  return (
    <dl className="now-meta">
      <div className="now-row">
        <dt className="now-label"><span className="now-dot" />Now</dt>
        <dd className="now-val serif">{p.currently}</dd>
      </div>
      <div className="now-row">
        <dt className="now-label">Role</dt>
        <dd className="now-val">{p.position}</dd>
      </div>
    </dl>
  );
}

function Home({ data, layout, animate, onRoute }) {
  const p = data.person;
  const featured = data.projects.slice(0, 3);

  const NameBlock = (
    <h1 className="hero-name">
      <span className="hn-line">{p.name.split(" ")[0]}</span>
      <span className="hn-line italic">{p.name.split(" ").slice(1).join(" ")}</span>
    </h1>
  );

  let hero;
  if (layout === "stacked") {
    hero = (
      <div className="hero stacked">
        <Reveal className="hero-stack-inner">
          <div className="hero-photo-center">
            <image-slot id="profile-photo" shape="circle" placeholder="Portrait" src={p.photo}
              style={{ ...SLOT, width: 150, height: 150, display: "block" }}></image-slot>
          </div>
          {NameBlock}
          <p className="hero-blurb center">{p.blurb}</p>
          <div className="hero-charge-center"><ChargeColumn segments={10} filled={7} vertical={false} animate={animate} /></div>
        </Reveal>
        <Reveal delay={120}><NowMeta p={p} /></Reveal>
      </div>
    );
  } else if (layout === "editorial") {
    hero = (
      <div className="hero editorial">
        <div className="hero-ed-top">
          <Reveal className="hero-ed-name">
            <Kicker>{p.location}</Kicker>
            {NameBlock}
          </Reveal>
          <Reveal delay={120} className="hero-ed-photo">
            <HeroPhoto shape="rounded" size={300} src={p.photo} />
            <ChargeColumn segments={8} filled={6} animate={animate} />
          </Reveal>
        </div>
        <div className="hero-ed-bottom">
          <Reveal delay={80}><p className="hero-blurb">{p.blurb}</p></Reveal>
          <Reveal delay={160}><NowMeta p={p} /></Reveal>
        </div>
      </div>
    );
  } else {
    /* portrait (default) */
    hero = (
      <div className="hero portrait">
        <div className="hero-head">
          <Reveal className="hero-photo-col">
            <HeroPhoto shape="rounded" size={200} src={p.photo} />
            <div className="photo-caption">
              <span className="mono dim">{p.location}</span>
              <span className="photo-charge"><ChargeColumn segments={8} filled={6} vertical={false} animate={animate} /></span>
            </div>
          </Reveal>
          <div className="hero-headtext">
            <Reveal>{NameBlock}</Reveal>
            <Reveal delay={90}><p className="hero-tagline">{p.tagline}</p></Reveal>
          </div>
        </div>
        <div className="hero-body">
          <Reveal delay={140}><p className="hero-blurb">{p.blurb}</p></Reveal>
          <Reveal delay={200}><NowMeta p={p} /></Reveal>
        </div>
      </div>
    );
  }

  return (
    <div className="view view-home">
      {hero}

      {/* selected work teaser */}
      <section className="home-featured">
        <Reveal className="section-head">
          <Kicker>Selected work</Kicker>
          <button className="text-link" onClick={() => onRoute("work")}>
            <span>All projects</span> <IconArrow size={16} />
          </button>
        </Reveal>
        <div className="featured-grid">
          {featured.map((proj, i) => (
            <Reveal key={proj.id} delay={i * 90} className="featured-card"
              onClick={() => onRoute("work")}>
              <div className="fc-thumb">
                <image-slot id={"thumb-" + proj.id} shape="rect" placeholder={proj.title} src={proj.image}
                  style={{ ...SLOT, width: "100%", height: "auto", aspectRatio: "16 / 11", display: "block" }}></image-slot>
              </div>
              <div className="fc-meta">
                <span className="mono dim">{proj.year}</span>
                <h3 className="fc-title">{proj.title}</h3>
                <p className="fc-one">{proj.one}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </section>
    </div>
  );
}

/* =========================================================
   WORK
   ========================================================= */
function ProjectDetail({ proj, onClose }) {
  const [imgIdx, setImgIdx] = useStateP(0);

  useEffectP(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (proj && proj.images && proj.images.length > 1) {
        if (e.key === "ArrowRight") setImgIdx(i => (i + 1) % proj.images.length);
        if (e.key === "ArrowLeft") setImgIdx(i => (i - 1 + proj.images.length) % proj.images.length);
      }
    };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [proj]);

  if (!proj) return null;

  const images = proj.images || [proj.image];

  return (
    <div className="detail-scrim" onClick={onClose}>
      <div className="detail-panel" onClick={(e) => e.stopPropagation()}>
        <button className="detail-close" onClick={onClose} aria-label="Close"><IconClose /></button>
        <div className="detail-media relative" style={{ position: "relative" }}>
          {images.map((imgUrl, i) => (
            <div key={i} style={{
              position: "absolute", inset: 0,
              opacity: i === imgIdx ? 1 : 0,
              visibility: i === imgIdx ? "visible" : "hidden",
              transition: "opacity 0.25s ease",
              zIndex: i === imgIdx ? 1 : 0
            }}>
              <image-slot id={"detail-" + proj.id + "-" + i} shape="rect" placeholder={proj.title} src={imgUrl} fit="contain"
                style={{ ...SLOT, width: "100%", height: "100%", display: "block" }}></image-slot>
            </div>
          ))}

          {images.length > 1 && (
            <div className="carousel-controls" style={{ position: "absolute", bottom: "16px", left: "0", right: "0", display: "flex", justifyContent: "center", gap: "8px", zIndex: 2 }}>
              {images.map((_, i) => (
                <button key={i} onClick={(e) => { e.stopPropagation(); setImgIdx(i); }}
                  style={{ width: "8px", height: "8px", borderRadius: "50%", background: i === imgIdx ? "white" : "rgba(255,255,255,0.5)", border: "none", cursor: "pointer", padding: 0 }}
                  aria-label={`Go to slide ${i + 1}`}
                />
              ))}
            </div>
          )}
          {images.length > 1 && (
            <>
              <button onClick={(e) => { e.stopPropagation(); setImgIdx(i => (i - 1 + images.length) % images.length); }} style={{ position: "absolute", left: "16px", top: "50%", transform: "translateY(-50%)", background: "rgba(0,0,0,0.5)", color: "white", border: "none", borderRadius: "50%", width: "32px", height: "32px", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", paddingBottom: "3px", zIndex: 2 }} aria-label="Previous image">‹</button>
              <button onClick={(e) => { e.stopPropagation(); setImgIdx(i => (i + 1) % images.length); }} style={{ position: "absolute", right: "16px", top: "50%", transform: "translateY(-50%)", background: "rgba(0,0,0,0.5)", color: "white", border: "none", borderRadius: "50%", width: "32px", height: "32px", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", paddingBottom: "3px", zIndex: 2 }} aria-label="Next image">›</button>
            </>
          )}
        </div>
        <div className="detail-body">
          <span className="mono dim">{proj.year}</span>
          <h2 className="detail-title">{proj.title}</h2>
          <div className="tag-row">{proj.tags.map((t) => <Tag key={t}>{t}</Tag>)}</div>
          <p className="detail-text">{proj.body}</p>

          {(proj.github || proj.pdf || proj.demo) && (
            <div className="detail-links" style={{ display: "flex", flexWrap: "wrap", gap: "12px", marginTop: "24px" }}>
              {proj.github && (
                <a href={proj.github} target="_blank" rel="noopener noreferrer" className="btn small" style={{ display: "inline-flex", alignItems: "center", gap: "6px" }}>
                  <IconGitHub size={16} /> GitHub
                </a>
              )}
              {proj.pdf && (
                <a href={proj.pdf} target="_blank" rel="noopener noreferrer" className="btn small" style={{ display: "inline-flex", alignItems: "center", gap: "6px" }}>
                  <IconDownload size={16} /> Poster
                </a>
              )}
              {proj.demo && (
                <a href={proj.demo} target="_blank" rel="noopener noreferrer" className="btn small" style={{ display: "inline-flex", alignItems: "center", gap: "6px" }}>
                  <IconArrow size={16} /> Live Demo
                </a>
              )}
            </div>
          )}

          {proj.stat && (
            <div className="detail-stat">
              <span className="ds-value">{proj.stat.value}</span>
              <span className="ds-unit mono">{proj.stat.unit}</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Work({ data, animate }) {
  const [filter, setFilter] = useStateP("All");
  const [open, setOpen] = useStateP(null);
  const keywords = ["All", ...data.keywords];
  const shown = data.projects.filter((p) => filter === "All" || p.tags.includes(filter));

  return (
    <div className="view view-work">
      <Reveal className="view-head">
        <Kicker>Work</Kicker>
        <h1 className="view-title">Projects &amp; <span className="italic">build logs</span></h1>
        <p className="view-sub">Things I’ve designed, broken, characterized, and occasionally shipped.
          Filter by keyword.</p>
      </Reveal>

      <Reveal className="filter-bar">
        {keywords.map((k) => (
          <Tag key={k} as="button" active={filter === k} onClick={() => setFilter(k)}>{k}</Tag>
        ))}
        <span className="filter-count mono">{shown.length} / {data.projects.length}</span>
      </Reveal>

      <div className="work-grid">
        {shown.map((proj, i) => (
          <Reveal key={proj.id} delay={(i % 3) * 80} className="work-card"
            onClick={() => setOpen(proj)}>
            <div className="wc-thumb">
              <image-slot id={"work-" + proj.id} shape="rect" placeholder={proj.title} src={proj.image}
                style={{ ...SLOT, width: "100%", height: "auto", aspectRatio: "16 / 10", display: "block" }}></image-slot>
              <span className="wc-open"><IconArrow size={16} /></span>
            </div>
            <div className="wc-body">
              <div className="wc-top">
                <h3 className="wc-title">{proj.title}</h3>
                <span className="mono dim">{proj.year}</span>
              </div>
              <p className="wc-one">{proj.one}</p>
              <div className="tag-row">{proj.tags.map((t) => <Tag key={t}>{t}</Tag>)}</div>
            </div>
          </Reveal>
        ))}
      </div>

      {open && <ProjectDetail proj={open} onClose={() => setOpen(null)} />}
    </div>
  );
}

/* =========================================================
   EXPERIENCE
   ========================================================= */
function Experience({ data, animate }) {
  return (
    <div className="view view-exp">
      <Reveal className="view-head">
        <Kicker>Experience</Kicker>
        <h1 className="view-title">Internships &amp; <span className="italic">research</span></h1>
        <p className="view-sub">In labs, test benches, and on the line.</p>
      </Reveal>

      <div className="timeline">
        <div className="timeline-spine"><ChargeColumn segments={data.experience.length * 3}
          filled={data.experience.length * 3} animate={animate} /></div>
        {data.experience.map((x, i) => (
          <Reveal key={i} delay={i * 70} className="exp-item">
            <div className="exp-node" />
            <div className="exp-head">
              <span className="exp-kind mono">{x.kind}</span>
              <span className="exp-period mono dim">{x.period}</span>
            </div>
            <h3 className="exp-role">{x.role}</h3>
            <div className="exp-org">{x.org} <span className="dotsep" /> <span className="dim">{x.where}</span></div>
            <ul className="exp-points">
              {x.points.map((pt, j) => <li key={j}>{pt}</li>)}
            </ul>
            <div className="tag-row">{x.tags.map((t) => <Tag key={t}>{t}</Tag>)}</div>
          </Reveal>
        ))}
      </div>
    </div>
  );
}

/* =========================================================
   INTERESTS
   ========================================================= */
function Interests({ data }) {
  return (
    <div className="view view-interests">
      <Reveal className="view-head">
        <Kicker>Interests</Kicker>
        <h1 className="view-title">Outside the <span className="italic">lab</span></h1>
        <p className="view-sub">A few things that keep me curious.</p>
      </Reveal>

      <div className="interest-grid">
        {data.interests.map((it, i) => (
          <Reveal key={i} delay={i * 80} className="interest-card">
            <span className="interest-num mono">{String(i + 1).padStart(2, "0")}</span>
            <h3 className="interest-title">{it.title}</h3>
            <p className="interest-body">
              {it.body}
              {it.link && (
                <span style={{ display: "block", marginTop: "12px" }}>
                  <a href={it.link} target="_blank" rel="noopener noreferrer" className="text-link" style={{ fontSize: "14px" }}>
                    {it.linkLabel || "Learn more"} <IconArrow size={14} />
                  </a>
                </span>
              )}
            </p>
          </Reveal>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Home, Work, Experience, Interests });
