/* global React */
/*
 * SpecificationSection — shared specifier-facing block used by every collection PDP.
 * Renders: eyebrow + headline, meta grid (4 cols), Materials row, grouped SKU tables
 *          with mm/in unit toggle, and a Finishes → PDF link row.
 *
 * Props:
 *   headline        — string, big display headline (e.g. "Three modules. Infinite runs.")
 *   meta            — array of [label, value] pairs for the 4-col grid (e.g. [["Design", "Alexander Lotersztain, 2026"], ...])
 *   materials       — string, specifier paragraph
 *   groups          — array of { label, note, items: [{ sku, name, dims }] }  (dims in mm, "W × D × H" string)
 *   finishHeadline  — string, large editorial line in the Finishes row
 */

function SpecGroup({ group: g, isLast, isMobile, formatDim, unitLabel, unit, setUnit, defaultOpen, skuImageBase }) {
  const [open, setOpen] = React.useState(!!defaultOpen);
  const PREVIEW = 4;
  const total = g.items.length;
  const needsCollapse = total > PREVIEW; // any group over the preview collapses
  const visible = open || !needsCollapse ? g.items : g.items.slice(0, PREVIEW);
  // Isometric SKU drawings: when a collection supplies a base path, each row
  // leads with its <sku>.png. Missing drawings hide gracefully (onError).
  const thumbs = !isMobile && !!skuImageBase;
  const rowCols = thumbs ? "84px 100px minmax(0, 1fr) 210px" : "100px minmax(0, 1fr) 210px";
  const hiddenCount = total - visible.length;

  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: isMobile ? "1fr" : "minmax(0, 2fr) minmax(0, 5fr)",
      gap: isMobile ? 12 : 48,
      paddingBottom: isMobile ? 24 : 28,
      borderBottom: isLast ? "none" : "0.5px solid rgba(26,25,23,0.12)",
    }}>
      <div>
        <div style={{ fontSize: 15, fontWeight: 500, color: "#1a1917", marginBottom: 6 }}>{g.label}</div>
        <div style={{ fontSize: 12, color: "#6c6862", lineHeight: 1.5, maxWidth: "34ch" }}>{g.note}</div>
        <div style={{ fontSize: 11, color: "#a9a49c", marginTop: 10, letterSpacing: "0.06em" }}>{total} SKU{total === 1 ? "" : "s"}</div>
      </div>
      <div style={{ alignSelf: "start" }}>
        {!isMobile && (
          <div style={{
            display: "grid",
            gridTemplateColumns: rowCols,
            gap: "0 18px",
            padding: "0 0 8px 0",
            borderBottom: "0.5px solid rgba(26,25,23,0.25)",
            fontSize: 10,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            color: "#6c6862",
            fontWeight: 500,
            alignItems: "baseline",
          }}>
            {thumbs && <div></div>}
            <div>SKU</div>
            <div>Module</div>
            <div style={{ textAlign: "right", display: "inline-flex", gap: 6, justifyContent: "flex-end" }}>
              <span>W × D × H</span>
              <button
                type="button"
                onClick={() => setUnit(unit === "mm" ? "in" : "mm")}
                style={{
                  appearance: "none", background: "transparent", border: "none", padding: 0,
                  fontFamily: "inherit",
                  fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
                  color: "#1a1917", cursor: "pointer",
                  borderBottom: "0.5px solid #1a1917", lineHeight: 1,
                  fontWeight: 500,
                }}
                aria-label="Toggle units"
              >{unitLabel}</button>
            </div>
          </div>
        )}
        {visible.map((it, si) => (
          <div key={si} style={{
            display: "grid",
            gridTemplateColumns: isMobile ? "90px 1fr" : rowCols,
            gap: "0 18px",
            padding: "10px 0",
            borderBottom: "0.5px dashed rgba(26,25,23,0.12)",
            alignItems: thumbs ? "center" : "baseline",
          }}>
            {thumbs && (
              <div style={{ height: 56, display: "flex", alignItems: "center" }}>
                <img
                  src={`${skuImageBase}/${it.sku}.png`}
                  alt={`${it.sku} isometric drawing`}
                  loading="lazy"
                  onError={(e) => { e.target.style.visibility = "hidden"; }}
                  style={{ maxWidth: 78, maxHeight: 56, objectFit: "contain", display: "block" }}
                />
              </div>
            )}
            <div style={{
              fontFamily: "var(--font-mono, ui-monospace, SFMono-Regular, monospace)",
              fontSize: 12, letterSpacing: "0.04em", color: "#1a1917",
            }}>{it.sku}</div>
            <div style={{ fontSize: 13, color: "#1a1917", lineHeight: 1.4 }}>{it.name}</div>
            {!isMobile && (
              <div style={{
                fontFamily: "var(--font-mono, ui-monospace, SFMono-Regular, monospace)",
                fontSize: 11, color: "#6c6862", letterSpacing: "0.04em",
                textAlign: "right", whiteSpace: "nowrap",
              }}>{formatDim(it.dims)} {unitLabel}</div>
            )}
            {isMobile && (
              <div style={{ gridColumn: "1 / -1", fontFamily: "var(--font-mono, ui-monospace, SFMono-Regular, monospace)", fontSize: 11, color: "#6c6862", letterSpacing: "0.04em", marginTop: 4, paddingLeft: 90 }}>
                {formatDim(it.dims)} {unitLabel}
                {" · "}
                <button
                  type="button"
                  onClick={() => setUnit(unit === "mm" ? "in" : "mm")}
                  style={{
                    appearance: "none", background: "transparent", border: "none", padding: 0,
                    fontFamily: "inherit", fontSize: 11, color: "#1a1917", cursor: "pointer",
                    borderBottom: "0.5px solid #1a1917", lineHeight: 1,
                  }}
                >switch</button>
              </div>
            )}
          </div>
        ))}

        {needsCollapse && (
          <button
            type="button"
            onClick={() => setOpen(!open)}
            style={{
              appearance: "none",
              background: "transparent",
              border: "none",
              padding: "14px 0 0",
              width: "100%",
              textAlign: "left",
              cursor: "pointer",
              color: "#1a1917",
              fontFamily: "inherit",
              fontSize: 11,
              letterSpacing: "0.14em",
              textTransform: "uppercase",
              fontWeight: 500,
              display: "flex",
              alignItems: "center",
              gap: 12,
            }}
            aria-expanded={open}
          >
            <span>{open ? "Hide" : `Show all · ${total} SKUs`}</span>
            <span style={{ flex: 1, height: "0.5px", background: "rgba(26,25,23,0.25)" }} />
            <span style={{
              fontSize: 14,
              lineHeight: 1,
              transition: "transform 220ms cubic-bezier(0.2,0.6,0.2,1)",
              transform: open ? "rotate(180deg)" : "rotate(0deg)",
              display: "inline-block",
            }}>↓</span>
          </button>
        )}
      </div>
    </div>
  );
}

function SpecificationSection({ headline, meta, materials, groups, extras, finishHeadline, skuImageBase, finishHref = "assets/downloads/derlot-finishes-and-materials.pdf" }) {
  const vw = (typeof useViewport === "function") ? useViewport() : (typeof window !== "undefined" ? window.innerWidth : 1200);
  const isMobile = vw < 720;
  const [unit, setUnit] = React.useState("mm");
  const [skusOpen, setSkusOpen] = React.useState(false);

  const skuCount = (groups || []).reduce((n, g) => n + (g.items ? g.items.length : 0), 0);

  const mmToIn = (dimStr) => dimStr.split("×").map(s => {
    const trimmed = s.trim();
    // Strip thousands separators ("1,200" → "1200") and capture an optional
    // "Ø" prefix so circular dims round-trip cleanly to inches.
    const prefix = trimmed.startsWith("Ø") ? "Ø" : "";
    const numeric = trimmed.replace(/^Ø/, "").replace(/,/g, "");
    const n = parseFloat(numeric);
    if (isNaN(n)) return trimmed;
    const inches = n / 25.4;
    return prefix + (Math.round(inches * 20) / 20).toFixed(2).replace(/\.?0+$/, "");
  }).join(" × ");
  const formatDim = (d) => unit === "mm" ? d : mmToIn(d);
  const unitLabel = unit === "mm" ? "mm" : "in";

  return (
    <>
      <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 ? 28 : 40 }}>
          <div style={{ fontSize: 13, letterSpacing: "0.18em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 18 }}>Specification</div>
          <h2 style={{
            fontFamily: "var(--font-display, Poppins, sans-serif)",
            fontWeight: 500,
            fontSize: isMobile ? "clamp(28px, 7vw, 36px)" : "clamp(34px, 3.4vw, 48px)",
            lineHeight: 1.1, letterSpacing: "-0.015em",
            color: "#1a1917", margin: 0, maxWidth: "24ch",
            textWrap: "balance",
          }}>{headline}</h2>
        </div>

        {/* Meta grid */}
        {meta && meta.length > 0 && (
          <div style={{
            display: "grid",
            gridTemplateColumns: isMobile ? "1fr 1fr" : "repeat(4, 1fr)",
            gap: isMobile ? "20px 24px" : 40,
            paddingTop: isMobile ? 0 : 8,
            paddingBottom: isMobile ? 32 : 40,
            borderBottom: "0.5px solid rgba(26,25,23,0.18)",
            marginBottom: isMobile ? 32 : 48,
            fontSize: 13,
          }}>
            {meta.map(([k, v]) => (
              <div key={k}>
                <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 6 }}>{k}</div>
                <div style={{ color: "#1a1917" }}>{v}</div>
              </div>
            ))}
          </div>
        )}

        {/* Materials paragraph */}
        {materials && (
          <div style={{
            display: "grid",
            gridTemplateColumns: isMobile ? "1fr" : "minmax(0, 2fr) minmax(0, 5fr)",
            gap: isMobile ? 14 : 48,
            paddingBottom: isMobile ? 32 : 40,
            borderBottom: "0.5px solid rgba(26,25,23,0.12)",
            marginBottom: isMobile ? 32 : 40,
          }}>
            <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500 }}>Materials</div>
            <p style={{ margin: 0, fontSize: isMobile ? 13 : 14, lineHeight: 1.6, color: "#1a1917", maxWidth: "62ch" }}>
              {materials}
            </p>
          </div>
        )}

        {/* SKU groups — collapsed by default behind a single toggle */}
        {((groups && groups.length > 0) || (extras && extras.length > 0)) && (
          <div style={{ borderBottom: skusOpen ? "none" : "0.5px solid rgba(26,25,23,0.18)", marginBottom: skusOpen ? 0 : 0 }}>
            <button
              type="button"
              onClick={() => setSkusOpen(!skusOpen)}
              aria-expanded={skusOpen}
              style={{
                appearance: "none",
                background: "transparent",
                border: "none",
                padding: isMobile ? "4px 0 28px" : "8px 0 36px",
                width: "100%",
                textAlign: "left",
                cursor: "pointer",
                color: "#1a1917",
                fontFamily: "inherit",
                display: "grid",
                gridTemplateColumns: isMobile ? "1fr" : "minmax(0, 2fr) minmax(0, 5fr)",
                gap: isMobile ? 12 : 48,
                alignItems: "baseline",
              }}
            >
              <div>
                <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 6 }}>SKUs &amp; dimensions</div>
                <div style={{ fontSize: 15, fontWeight: 500, color: "#1a1917" }}>
                  {skusOpen ? "Hide specifications" : "Explore all specifications"}
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500 }}>
                <span style={{ flex: 1, height: "0.5px", background: "rgba(26,25,23,0.25)" }} />
                <span style={{ whiteSpace: "nowrap" }}>{skuCount} SKU{skuCount === 1 ? "" : "s"} · {(groups || []).length} group{(groups || []).length === 1 ? "" : "s"}</span>
                <span style={{
                  fontSize: 14,
                  lineHeight: 1,
                  transition: "transform 220ms cubic-bezier(0.2,0.6,0.2,1)",
                  transform: skusOpen ? "rotate(180deg)" : "rotate(0deg)",
                  display: "inline-block",
                  color: "#1a1917",
                }}>↓</span>
              </div>
            </button>
          </div>
        )}

        {skusOpen && (
        <div style={{ display: "grid", gap: isMobile ? 28 : 36, paddingTop: isMobile ? 12 : 16 }}>
          {(groups || []).map((g, gi, arr) => (
            <SpecGroup
              key={gi}
              group={g}
              isLast={gi === arr.length - 1 && (!extras || extras.length === 0)}
              isMobile={isMobile}
              formatDim={formatDim}
              unitLabel={unitLabel}
              unit={unit}
              setUnit={setUnit}
              defaultOpen={(groups.length === 1) || ((g.items || []).length <= 6)}
              skuImageBase={skuImageBase}
            />
          ))}

          {/* Extras — freeform rows (e.g. Fixings & power) */}
          {(extras || []).map((ex, ei, exArr) => (
            <div key={`ex-${ei}`} style={{
              display: "grid",
              gridTemplateColumns: isMobile ? "1fr" : "minmax(0, 2fr) minmax(0, 5fr)",
              gap: isMobile ? 12 : 48,
              paddingTop: isMobile ? 8 : 12,
              paddingBottom: isMobile ? 24 : 28,
              borderTop: "0.5px solid rgba(26,25,23,0.12)",
              borderBottom: ei === exArr.length - 1 ? "none" : "0.5px solid rgba(26,25,23,0.12)",
            }}>
              <div>
                <div style={{ fontSize: 15, fontWeight: 500, color: "#1a1917", marginBottom: 6 }}>{ex.label}</div>
                {ex.note && <div style={{ fontSize: 12, color: "#6c6862", lineHeight: 1.5, maxWidth: "34ch" }}>{ex.note}</div>}
              </div>
              <div style={{ display: "grid", gap: 10, alignSelf: "start", fontSize: 13, color: "#1a1917", lineHeight: 1.5 }}>
                {(ex.rows || []).map((r, ri) => (
                  <div key={ri} style={r.muted ? { fontSize: 12, color: "#6c6862" } : null}>{r.text || r}</div>
                ))}
              </div>
            </div>
          ))}
        </div>
        )}
      </section>

      {/* Finishes — single-line row linking to full library PDF */}
      {finishHeadline && (
        <section style={{ padding: isMobile ? "0 20px" : "0 max(24px, 3vw)", maxWidth: 1440, margin: "0 auto" }}>
          <a
            href={finishHref}
            target="_blank"
            rel="noopener"
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              gap: 24,
              padding: isMobile ? "28px 0" : "36px 0",
              borderTop: "0.5px solid rgba(26,25,23,0.18)",
              borderBottom: "0.5px solid rgba(26,25,23,0.18)",
              color: "#1a1917",
              textDecoration: "none",
              cursor: "pointer",
            }}
          >
            <div>
              <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 8 }}>Finishes</div>
              <div style={{
                fontFamily: "var(--font-display, Poppins, sans-serif)",
                fontWeight: 500,
                fontSize: isMobile ? "clamp(20px, 5vw, 24px)" : "clamp(22px, 1.8vw, 28px)",
                lineHeight: 1.2, letterSpacing: "-0.01em", maxWidth: "32ch",
              }}>{finishHeadline}</div>
            </div>
            <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 500, whiteSpace: "nowrap", display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
              {!isMobile && <span>Open finish library</span>}
              <span style={{ fontSize: 16, lineHeight: 1 }}>↓</span>
            </div>
          </a>
        </section>
      )}
    </>
  );
}

window.SpecificationSection = SpecificationSection;
