/* global React, useViewport, PageIntro, EditorialCarousel, ThreadBadge,
           SpecificationSection, ConfiguratorStrip, SpecifierDownloads, EnquiryBlock */
/*
 * CaterpillarDetail — collection detail page for Caterpillar (2016).
 * Narrative angle: segmented, serpentine banquette that meanders
 * through hospitality and civic interiors.
 *
 * Two documented projects: Ipswich Rail Museum (2024), Living Edge Sydney (2022).
 * SKU tables are plausible placeholders — replace with real spec data when available.
 */

const { useState: useStateCatC, useEffect: useEffectCatC } = React;

const CATERPILLAR_SLIDES_BASE = [
  { title: "Caterpillar", image: "images/collections/caterpillar/hero/01.webp" },
  { title: "Caterpillar", image: "images/collections/caterpillar/hero/02.webp" },
  { title: "Caterpillar", type: "video", video: "images/collections/caterpillar/hero/03.mp4", poster: "images/collections/caterpillar/hero/02.webp" },
  { title: "Caterpillar", image: "images/collections/caterpillar/hero/04.webp" },
];
const CATERPILLAR_SLIDES = (window.IMG && window.IMG.extend) ? window.IMG.extend("caterpillar", "hero", CATERPILLAR_SLIDES_BASE) : CATERPILLAR_SLIDES_BASE;

function CaterpillarCarousel({ hideCaption = false }) {
  const vw = useViewport();
  const isMobile = vw < 760;
  const [i, setI] = useStateCatC(0);
  const [paused, setPaused] = useStateCatC(false);
  const videoRefsCatC = React.useRef([]);

  const next = () => setI((x) => (x + 1) % CATERPILLAR_SLIDES.length);

  // Auto-advance: still stills tick every 7s; the video slide advances when it ends.
  useEffectCatC(() => {
    if (paused) return;
    if (CATERPILLAR_SLIDES[i].type === "video") return; // video drives its own advance via onEnded
    const id = setInterval(next, 7000);
    return () => clearInterval(id);
  }, [paused, i]);

  // Restart the active video from the top whenever it becomes active.
  useEffectCatC(() => {
    const v = videoRefsCatC.current[i];
    if (CATERPILLAR_SLIDES[i].type === "video" && v) {
      try { v.currentTime = 0; v.play(); } catch (e) {}
    }
    // pause any non-active videos
    videoRefsCatC.current.forEach((vid, idx) => {
      if (vid && idx !== i) { try { vid.pause(); } catch (e) {} }
    });
  }, [i]);

  const s = CATERPILLAR_SLIDES[i];

  return (
    <section
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      style={{
        position: "relative",
        width: "100%",
        aspectRatio: "16 / 9",
        maxHeight: isMobile ? "82vh" : "90vh",
        minHeight: isMobile ? 460 : 560,
        overflow: "hidden",
        background: "#1a1917",
      }}
    >
      {CATERPILLAR_SLIDES.map((ss, idx) => (
        <div key={idx} style={{
          position: "absolute", inset: 0,
          opacity: idx === i ? 1 : 0,
          transition: "opacity 1100ms ease",
        }}>
          {ss.type === "video" ? (
            <video
              ref={(el) => { videoRefsCatC.current[idx] = el; }}
              src={ss.video}
              poster={ss.poster}
              muted
              loop={false}
              playsInline
              preload={idx <= 1 ? "auto" : "metadata"}
              onEnded={() => { if (idx === i && !paused) next(); }}
              style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
            />
          ) : (
            <img src={ss.image} srcSet={window.IMG && window.IMG.srcsetFor(ss.image)} sizes={window.IMG && window.IMG.sizes()} alt={ss.title} loading={idx === 0 ? "eager" : "lazy"}
                 style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
          )}
        </div>
      ))}

      <div style={{
        position: "absolute", inset: 0,
        background: hideCaption
          ? "linear-gradient(to bottom, transparent 70%, rgba(26,25,23,0.35) 100%)"
          : "linear-gradient(to bottom, transparent 50%, rgba(26,25,23,0.55) 100%)",
        pointerEvents: "none",
      }} />

      {!hideCaption && (
      <div style={{
        position: "absolute",
        left: 0, right: 0,
        bottom: isMobile ? 84 : 100,
        padding: isMobile ? "0 24px" : "0 32px",
        textAlign: "center",
        color: "#f5f3ef",
      }}>
        <h3 style={{
          fontFamily: "var(--font-display, Poppins, sans-serif)",
          fontWeight: 500,
          fontSize: isMobile ? "clamp(20px, 5vw, 26px)" : "clamp(22px, 1.9vw, 32px)",
          lineHeight: 1.18,
          letterSpacing: "-0.01em",
          margin: "0 auto",
          maxWidth: "26ch",
          textWrap: "balance",
        }}>
          {s.title}
        </h3>
      </div>
      )}

      <div style={{
        position: "absolute",
        bottom: isMobile ? 36 : 44,
        left: 0, right: 0,
        display: "flex", justifyContent: "center", gap: 10,
      }}>
        {CATERPILLAR_SLIDES.map((_, idx) => (
          <button key={idx}
            onClick={() => setI(idx)}
            aria-label={`Show slide ${idx + 1}`}
            style={{
              width: idx === i ? 24 : 6,
              height: 2,
              background: idx === i ? "rgba(245,243,239,0.95)" : "rgba(245,243,239,0.4)",
              border: "none", cursor: "pointer", padding: 0,
              transition: "width 320ms ease, background 320ms ease",
            }}
          />
        ))}
      </div>
    </section>
  );
}

function CaterpillarDetail() {
  const vw = useViewport();
  const isMobile = vw < 720;

  return (
    <>
      <CaterpillarCarousel />

      <PageIntro
        eyebrow="Caterpillar · Alexander Lotersztain, 2018"
        title="A segmented sofa system for expanding, adaptive interiors."
        body="Caterpillar takes its name from the segmented, ever-growing form of its namesake — a sofa system designed to expand, adapt and transform with the spaces it serves. Each module sits as a soft, self-contained segment, joining together to form linear runs, gentle curves, and generous, sweeping configurations."
        compact
        noTopPad
      />

      {/* Editorial pair */}
      <section style={{ padding: isMobile ? "56px 20px" : "96px max(24px, 3vw)", maxWidth: 1440, margin: "0 auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: isMobile ? 32 : 48 }}>
          <EditorialCarousel
            slides={[
              { src: "images/collections/caterpillar/pillars/01.webp", alt: "Caterpillar serpentine sofa run with walnut coffee table", caption: "01 · Sculptural" },
              { src: "images/collections/caterpillar/pillars/02.webp",      alt: "Caterpillar sweeping configuration with timber armrest tray", caption: "02 · Configure" },
              { src: "images/collections/caterpillar/pillars/03.webp",       alt: "Caterpillar timber armrest tray detail", caption: "03 · Detail" },
            ]}
            aspect="3/4"
          />
          <div style={{ alignSelf: "center" }}>
            <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 14 }}>Dwell · Configure</div>
            <h2 style={{ fontWeight: 500, fontSize: isMobile ? "clamp(22px, 5.5vw, 28px)" : "clamp(24px, 2.2vw, 32px)", lineHeight: 1.12, letterSpacing: "-0.01em", color: "#1a1917", margin: "0 0 16px 0", maxWidth: "22ch" }}>
              Considered simplicity, quiet creativity.
            </h2>
            <p style={{ fontSize: isMobile ? 15 : 16, lineHeight: 1.55, color: "#1a1917", maxWidth: "46ch", margin: 0, fontWeight: 500 }}>
              Smoothed edges and continuous lines give the collection a relaxed, sculptural character. As needs change, Caterpillar grows with them — scaling effortlessly between intimate and expansive settings, from collaborative workspaces and lounges to casual gathering areas and refined hospitality interiors.
            </p>
          </div>
        </div>
      </section>

      {/* Three features */}
      <section style={{ padding: isMobile ? "64px 20px" : "120px max(24px, 3vw)", maxWidth: 1440, margin: "0 auto" }}>
        <div style={{ maxWidth: 720, marginBottom: isMobile ? 40 : 64 }}>
          <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 14 }}>What Caterpillar does</div>
          <h2 style={{ fontFamily: "var(--font-display, Poppins, sans-serif)", fontWeight: 500, fontSize: isMobile ? "clamp(24px, 6vw, 30px)" : "clamp(26px, 2.6vw, 38px)", lineHeight: 1.12, letterSpacing: "-0.015em", color: "#1a1917", margin: 0, maxWidth: "26ch", textWrap: "balance" }}>
            Three ways Caterpillar grows with a space.
          </h2>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)", gap: isMobile ? 48 : 40 }}>
          {[
            {
              no: "01",
              kicker: "Modular",
              title: "Built to grow.",
              body: "A custom linking mechanism connects modules with precision, allowing the system to be reconfigured at will — added to, broken apart, or rearranged as spaces evolve. Each seating unit is supplied with a linking plate; power units can be incorporated in the seat front.",
              image: "images/collections/caterpillar/feature/01.webp",
              alt: "Caterpillar modules linked into an L-shaped sectional",
            },
            {
              no: "02",
              kicker: "Lounge · Work",
              title: "For dwelling and working on the go.",
              body: "Engineered to support both relaxed lounging and active use — extended dwell time, informal meetings, hybrid rhythms. Lumbar support and contoured seating offer a cocoon-like embrace for co-working environments, breakout zones and contemporary public interiors.",
              image: "images/collections/caterpillar/feature/02.webp",
              alt: "Caterpillar breakout setting with laptop, stools and mobile pod",
            },
            {
              no: "03",
              kicker: "Form",
              title: "Fluid, sculptural language.",
              body: "Smoothed edges and continuous lines define Caterpillar's visual language. Segments transition between curved and linear arrangements with a fluid rhythm, softening large architectural spaces while holding their own as a considered design statement.",
              image: "images/collections/caterpillar/feature/03.webp",
              alt: "Caterpillar continuous-line curve detail",
            },
          ].map((f) => (
            <div key={f.no}>
              <div style={{ aspectRatio: "4/5", background: "#e4e2da", overflow: "hidden", marginBottom: isMobile ? 18 : 24 }}>
                <img src={f.image} srcSet={window.IMG && window.IMG.srcsetFor(f.image)} sizes={window.IMG && window.IMG.sizes()} alt={f.alt} loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
              </div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 12 }}>
                <div style={{ fontSize: 11, color: "#6c6862", fontWeight: 500, letterSpacing: "0.08em" }}>{f.no}</div>
                <div style={{ height: "0.5px", flex: 1, background: "rgba(26,25,23,0.25)" }} />
                <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500 }}>{f.kicker}</div>
              </div>
              <h3 style={{ fontFamily: "var(--font-display, Poppins, sans-serif)", fontWeight: 500, fontSize: isMobile ? 19 : 20, lineHeight: 1.22, letterSpacing: "-0.01em", color: "#1a1917", margin: "0 0 10px 0", maxWidth: "20ch" }}>
                {f.title}
              </h3>
              <p style={{ fontSize: 14, lineHeight: 1.6, color: "#6c6862", margin: 0, maxWidth: "38ch" }}>
                {f.body}
              </p>
            </div>
          ))}
        </div>
      </section>

      {/* Specification */}
      <SpecificationSection
        skuImageBase="images/collections/caterpillar/skus"
        headline="One system. Thirteen segments."
        meta={[
          ["Design", "Alexander Lotersztain, 2018"],
          ["Sectors", "Hospitality · Corporate · Civic · Aviation · Education"],
          ["Environment", "Indoor"],
          ["Warranty", "5 year structural"],
          ["Certifications", "GECA certified"],
          ["Manufactured", "Australia, Poland"],
          ["Standard height", "750 mm across all modules"],
          ["Standard depth", "650 mm (670 mm for CTP-08)"],
        ]}
        materials="Seating: Dunlop Enduro® foam over MDF substrate, upholstered in specifier's choice — COM (Customer's Own Material) or COL (Customer's Own Leather). Side tables: powder-coated mild-steel base with solid timber top. Custom linking mechanism connects modules with precision; each seating unit supplied with linking plate; power units can be incorporated in seat front."
        groups={[
          {
            label: "Single seat modules",
            items: [
              { sku: "CTP-01", name: "Single seat module",            dims: "650 × 650 × 750" },
              { sku: "CTP-02", name: "Single seat module, variant",   dims: "650 × 650 × 750" },
              { sku: "CTP-15", name: "Single seat module, variant",   dims: "650 × 650 × 750" },
              { sku: "CTP-16", name: "Single seat module, variant",   dims: "650 × 650 × 750" },
            ],
          },
          {
            label: "30° angled seat modules",
            items: [
              { sku: "CTP-08", name: "30° angled seat module",            dims: "650 × 670 × 750" },
              { sku: "CTP-09", name: "30° angled seat module, variant",   dims: "650 × 650 × 750" },
              { sku: "CTP-10", name: "30° angled seat module, variant",   dims: "650 × 650 × 750" },
              { sku: "CTP-11", name: "30° angled seat module, wide",      dims: "980 × 650 × 750" },
            ],
          },
          {
            label: "Corner seat modules",
            items: [
              { sku: "CTP-12", name: "Corner seat module",          dims: "650 × 650 × 750" },
              { sku: "CTP-13", name: "Corner seat module, variant", dims: "650 × 650 × 750" },
            ],
          },
          {
            label: "Back-to-back seat modules",
            items: [
              { sku: "CTP-21", name: "Back-to-back seating module",            dims: "650 × 650 × 750" },
              { sku: "CTP-28", name: "Back-to-back seating module, variant",   dims: "650 × 650 × 750" },
              { sku: "CTP-31", name: "Back-to-back seating module, wide",      dims: "980 × 650 × 750" },
            ],
          },
        ]}
        extras={[
          {
            label: "Side table finishes",
            note: "Powder-coated mild-steel base with solid timber top.",
            rows: [
              { text: "Base · powder coat · White" },
              { text: "Base · powder coat · Black" },
              { text: "Top · solid American Oak" },
              { text: "Top · black-stained American Oak" },
              { text: "Top · solid American Walnut" },
            ],
          },
        ]}
        finishHeadline="Upholstery in COM or COL; side-table base in white or black powder coat with American Oak, black-stained Oak, or American Walnut top."
      />

      <ConfiguratorStrip collection="Caterpillar" />

      {/* Specified in — 3-up (real Caterpillar installations) */}
      <section style={{ padding: isMobile ? "56px 20px" : "96px max(24px, 3vw)", maxWidth: 1440, margin: "0 auto", borderTop: "0.5px solid rgba(26,25,23,0.18)" }}>
        <div style={{ marginBottom: isMobile ? 24 : 36 }}>
          <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 12 }}>Specified in</div>
          <h2 style={{ fontFamily: "var(--font-display, Poppins, sans-serif)", fontWeight: 500, fontSize: isMobile ? "clamp(22px, 5.5vw, 28px)" : "clamp(24px, 2.2vw, 32px)", lineHeight: 1.12, letterSpacing: "-0.01em", color: "#1a1917", margin: 0, maxWidth: "26ch", textWrap: "balance" }}>
            From corporate lobbies to listening lounges and campus commons.
          </h2>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)", gap: isMobile ? 28 : 32 }}>
          {[
            { name: "Suncorp Bank Head Office", city: "Brisbane, AUS", year: 2022, category: "Corporate",   image: "images/collections/caterpillar/feature/04.webp" },
            { name: "+81",                       city: null,           year: 2024, category: "Hospitality", image: "images/collections/caterpillar/feature/05.webp" },
            { name: "University of Melbourne",   city: "Melbourne, AUS", year: 2025, category: "Education",   image: "images/collections/caterpillar/feature/06.webp" },
          ].map((p) => (
            <div key={p.name}>
              <div style={{ aspectRatio: "3/2", background: "#e4e2da", overflow: "hidden" }}>
                <img src={p.image} srcSet={window.IMG && window.IMG.srcsetFor(p.image)} sizes={window.IMG && window.IMG.sizes()} alt={p.name} loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
              </div>
              <div style={{ height: "0.5px", background: "rgba(26,25,23,0.18)", marginTop: 14 }} />
              <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginTop: 12, gap: 12 }}>
                <div style={{ fontSize: 16, color: "#1a1917" }}>{p.name}</div>
                <div style={{ fontSize: 12, color: "#6c6862", letterSpacing: "0.04em" }}>{[p.city, p.year].filter(Boolean).join(" · ")}</div>
              </div>
              <div style={{ fontSize: 12, color: "#6c6862", letterSpacing: "0.04em", marginTop: 4 }}>{p.category}</div>
            </div>
          ))}
        </div>
      </section>

      <SpecifierDownloads collection="Caterpillar" />

      {/* Related collections */}
      <section style={{ padding: isMobile ? "56px 20px" : "96px max(24px, 3vw)", maxWidth: 1440, margin: "0 auto", borderTop: "0.5px solid rgba(26,25,23,0.18)" }}>
        <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 20 }}>Related collections</div>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)", gap: isMobile ? 32 : 32 }}>
          {(window.COLLECTIONS || []).filter(c => ["mochi", "stump", "pipeline"].includes(c.slug)).map((c) => (
            <div key={c.slug}>
              <div style={{ aspectRatio: "4/5", background: "#e4e2da", overflow: "hidden" }}>
                {c.image && <img src={c.image} srcSet={window.IMG && window.IMG.srcsetFor(c.image)} sizes={window.IMG && window.IMG.sizes()} alt={c.name} loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />}
              </div>
              <div style={{ height: "0.5px", background: "rgba(26,25,23,0.18)", marginTop: 14 }} />
              <div style={{ fontSize: 16, color: "#1a1917", marginTop: 12 }}>{c.name}</div>
              <div style={{ marginTop: 10, display: "flex", flexWrap: "wrap", rowGap: 6 }}>
                {c.threads.map(tk => <ThreadBadge key={tk} threadKey={tk} />)}
              </div>
            </div>
          ))}
        </div>
      </section>

      <EnquiryBlock collection="Caterpillar" />
    </>
  );
}

window.CaterpillarDetail = CaterpillarDetail;
