const { Button, IconButton, Icon, Card, Badge, Tag } = window.SuperiorPrintingHouseDesignSystem_81d178;

const TONES = ["mid", "light", "dark", "mid", "light", "mid"];

/* The card opens here: the photographs at the size they were shot, and the copy
   that was too long for a card, without leaving the grid behind. A page per project
   would need routes, a URL scheme and a way back — this needs a piece of state.

   Esc, the backdrop and the close button all close it, and the page behind is frozen while it
   is open: an overlay you can scroll the page under looks broken the moment the
   wheel moves. */
function Lightbox({ item, t, onClose }) {
  const p = item.p;
  const v = cardView(t, p);
  const imgs = galleryList(p.images, p.src);
  const [at, setAt] = React.useState(0);
  const step = (d) => setAt((n) => (n + d + imgs.length) % imgs.length);

  React.useEffect(() => {
    const key = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowRight") step(1);
      else if (e.key === "ArrowLeft") step(-1);
    };
    document.addEventListener("keydown", key);
    const held = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", key); document.body.style.overflow = held; };
  }, [imgs.length]);

  return (
    <div className="lightbox" onClick={onClose} role="dialog" aria-modal="true" aria-label={v.t}>
      {/* Clicks inside the panel must not reach the backdrop's close handler. */}
      <div className="lightbox-panel" onClick={(e) => e.stopPropagation()}>
        <div className="lightbox-stage">
          {/* Every image is mounted from the start and only its opacity changes. A
              single tag whose src is swapped goes blank for as long as the next file
              takes to decode, which is the flicker the card galleries already had. */}
          {imgs.map((src, i) => (
            <img key={src} src={src} alt={v.t} className={i === at ? "is-on" : ""} />
          ))}
          {!imgs.length && <Ph label={t.work.soon} tone="mid" radius="var(--radius-xl)" labelAlign="center" style={{ aspectRatio: "4 / 3" }} />}
          {imgs.length > 1 && (
            <React.Fragment>
              <div className="lightbox-nav lightbox-nav--prev">
                <IconButton icon="arrow-left" label={t.work.prev} variant="outline" size="lg"
                  onClick={() => step(-1)} style={{ background: "var(--white)", boxShadow: "var(--shadow-md)" }} />
              </div>
              <div className="lightbox-nav lightbox-nav--next">
                <IconButton icon="arrow-right" label={t.work.next} variant="outline" size="lg"
                  onClick={() => step(1)} style={{ background: "var(--white)", boxShadow: "var(--shadow-md)" }} />
              </div>
            </React.Fragment>
          )}
        </div>
        <div className="lightbox-info">
          {v.c && <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--tr-label)", textTransform: "uppercase", color: "var(--text-subtle)" }}>{v.c}</span>}
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 30, lineHeight: 1.3,
            letterSpacing: "-.005em", color: "var(--text-strong)", margin: 0, whiteSpace: "pre-line" }}>{v.t}</h2>
          <p style={{ fontSize: 15, lineHeight: 1.8, color: "var(--text-muted)", margin: 0, whiteSpace: "pre-line" }}>{v.d}</p>
          {imgs.length > 1 && (
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontVariantNumeric: "lining-nums tabular-nums", color: "var(--text-subtle)", marginTop: "auto" }}>
              {(at + 1) + " / " + imgs.length}
            </span>
          )}
        </div>
        <div className="lightbox-close">
          <IconButton icon="x" label={t.work.close} variant="outline" size="md"
            onClick={onClose} style={{ background: "var(--white)" }} />
        </div>
      </div>
    </div>
  );
}

/* The grid is every card the home page rails carry, not a second list that has to
   be kept in step with them — same photographs, same copy, same admin paths. The
   chips are the categories those cards declare, so adding a card in the admin adds
   its category here for free. `focus` is the category the visitor clicked on a home
   card; null means show everything. */
function Work({ go, t, focus }) {
  const revealGrid = useReveal(), revealCta = useReveal();
  /* `focus` says where the visitor came from: { rail } is the copy.js path of the
     rail they were looking at, { cat } a category they clicked on a card. The page
     never mixes rails — arriving from Slogan shows Slogan's work and Slogan's
     categories, not every tag on the site. */
  const rail = (focus && focus.rail) || null;
  const items = allWorkItems(t).filter(it => !rail || it.path.indexOf(rail + ".") === 0);
  /* Chip order follows the master list in copy.js so it does not reshuffle every
     time a card is added, but a category only appears once a card actually carries
     it — and a category typed onto a card without being in the master list still
     gets a chip rather than being unreachable. */
  const used = new Set(items.flatMap(it => workCats(it.p)));
  const master = t.work.categories || [];
  const cats = [...master.filter(c => used.has(c)), ...[...used].filter(c => !master.includes(c))];
  const [filter, setFilter] = React.useState(focus && cats.includes(focus.cat) ? focus.cat : null);
  /* The open card itself, not its index: the filter chips rebuild the list under it. */
  const [open, setOpen] = React.useState(null);
  /* Order is the order in copy.js — the panel's reordering arrows are the only thing
     that decides it, now that the year is gone. */
  const list = filter ? items.filter(it => workCats(it.p).includes(filter)) : items;
  return (
    <div>
      <section className="pad-x premium-reveal" style={{ padding: "24px 56px 0" }}>
        <SectionHead eyebrow={t.work.eyebrowFmt(list.length)} title={railTitle(t, rail)} aside={t.work.aside} style={{ marginBottom: 32 }} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Tag onSelect={() => setFilter(null)} selected={!filter}>{t.work.filterAll}</Tag>
          {cats.map(c => <Tag key={c} onSelect={() => setFilter(c)} selected={filter === c}>{c}</Tag>)}
        </div>
      </section>

      <section ref={revealGrid} className="pad-x grid-3 work-grid reveal" style={{ padding: "36px 56px 88px", display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 24 }}>
        {list.map(({ p, path }, n) => (
          <Card key={path} interactive eyebrow={cardView(t, p).c} title={cardView(t, p).t} text={cardView(t, p).d}
            onClick={() => setOpen({ p, path })} style={{ cursor: "pointer" }}
            media={<div data-copy-image={path} style={{ position: "absolute", inset: 0 }}>
              <Ph label={cardView(t, p).label} images={p.images} focal={p.focal} fit="cover"
                tone={TONES[n % TONES.length]} radius="0" labelAlign="center" style={{ position: "absolute", inset: 0 }} />
            </div>} />
        ))}
      </section>

      {open && <Lightbox item={open} t={t} onClose={() => setOpen(null)} />}

      <section ref={revealCta} className="reveal" style={{ padding: "0 20px 20px" }}>
        <div data-theme="inverse" style={{ background: "var(--ink-900)", borderRadius: "var(--radius-panel)", padding: 56, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 40, flexWrap: "wrap" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, maxWidth: 560 }}>
            <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--tr-label)", textTransform: "uppercase", color: "rgba(255,255,255,.55)" }}>{t.work.cta.eyebrow}</span>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 40, lineHeight: 1.25, letterSpacing: "-.01em", color: "var(--white)", margin: 0 }}>{t.work.cta.title}</h2>
          </div>
          <Button className="line-btn" variant="accent" size="lg" href={lineHref(t)} target="_blank" rel="noopener" iconRight="arrow-up-right">{t.work.cta.button}</Button>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { Work });
