/* global React, COLLECTIONS, useViewport, PageIntro, DOWNLOADS, downloadURL, trackDownload, RequestForm */
const { useState: useStateD } = React;

/* -------------------------------------------------------------------------
   Downloads — specifier resource hub (manifest-driven)

   Reads window.DOWNLOADS (src/data/downloads.jsx). Heavy CAD/3D/BIM files are
   meant to live on external object storage (Cloudflare R2 / CDN) — this page
   is just the catalogue. Each download fires a GTM `file_download` event.
   ------------------------------------------------------------------------- */

const INK = "#1a1917", STONE = "#6c6862", RULE = "rgba(26,25,23,0.18)", MUTE = "#b4b2a9";
const MONO = "ui-monospace, Menlo, Consolas, monospace";

function FormatBadge({ format }) {
  return (
    <span style={{
      fontFamily: MONO, fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase",
      color: STONE, border: "0.5px solid " + RULE, padding: "3px 7px", whiteSpace: "nowrap",
    }}>{format}</span>
  );
}

function DownloadAction({ item, onRequest }) {
  const ctaBase = {
    fontFamily: "inherit", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
    fontWeight: 500, border: "0.5px solid", borderRadius: 0, padding: "8px 14px",
    textDecoration: "none", display: "inline-block", whiteSpace: "nowrap",
  };
  // Gated — released on request via the lead-capture form.
  if (item.gated) {
    return <button onClick={() => onRequest && onRequest(item)}
              style={{ ...ctaBase, color: INK, borderColor: INK, background: "transparent", cursor: "pointer" }}>Request</button>;
  }
  const url = downloadURL(item.file);
  if (item.status === "soon" || !url) {
    return <span style={{ ...ctaBase, color: MUTE, borderColor: "rgba(26,25,23,0.18)", cursor: "default" }}>Coming soon</span>;
  }
  const external = /^https?:/i.test(url);
  return (
    <a href={url} target="_blank" rel="noopener" download={!external ? "" : undefined}
       onClick={() => trackDownload(item)}
       style={{ ...ctaBase, color: INK, borderColor: INK }}>
      {item.format === "Link" ? "Open" : "Download"}
    </a>
  );
}

function FileRow({ item, last, isMobile, onRequest }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: isMobile ? "1fr auto" : "minmax(0,1fr) auto 64px auto",
      gap: isMobile ? 12 : 24, alignItems: "center",
      padding: "16px 0", borderBottom: last ? "none" : "0.5px solid " + RULE,
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 15, color: INK }}>{item.name}</div>
        {item.note && <div style={{ fontSize: 12, color: STONE, marginTop: 3, lineHeight: 1.4 }}>{item.note}</div>}
        {isMobile && <div style={{ marginTop: 7, display: "flex", gap: 12, alignItems: "center" }}>
          <FormatBadge format={item.format} />
          <span style={{ fontSize: 11, color: STONE, fontFamily: MONO }}>{item.size || "—"}</span>
        </div>}
      </div>
      {!isMobile && <FormatBadge format={item.format} />}
      {!isMobile && <div style={{ fontSize: 11, color: STONE, fontFamily: MONO, textAlign: "right" }}>{item.size || "—"}</div>}
      <DownloadAction item={item} onRequest={onRequest} />
    </div>
  );
}

function Section({ label, children }) {
  return (
    <div style={{ marginBottom: 8 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: STONE, fontWeight: 500, marginBottom: 16 }}>{label}</div>
      {children}
    </div>
  );
}

/* -------------------------------------------------------------------------
   TEMPORARY — "Coming soon" curtain. The Downloads catalogue below is not
   ready for the public yet, so we render a full-screen white overlay that
   hides the page and blocks interaction. Delete this block (and the early
   return inside Downloads) to bring the page back online.
   ------------------------------------------------------------------------- */
function DownloadsComingSoon() {
  // z-index 40 sits below the fixed header (50) and its mobile menu (49) so the
  // nav stays visible and clickable — visitors can leave the page — while the
  // white curtain covers everything below it.
  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 40, background: "#ffffff",
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      textAlign: "center", padding: "24px",
    }}>
      <div style={{
        fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
        color: STONE, fontWeight: 500, marginBottom: 18,
      }}>
        Downloads
      </div>
      <h1 style={{
        fontWeight: 400, fontSize: "clamp(20px, 2.4vw, 26px)", lineHeight: 1.2,
        letterSpacing: "0.01em", color: INK, margin: 0,
      }}>
        Coming soon
      </h1>
    </div>
  );
}

function Downloads() {
  // TEMPORARY — page is gated behind a "Coming soon" curtain (see above).
  return <DownloadsComingSoon />;

  /* eslint-disable no-unreachable */
  const [slug, setSlug]   = useStateD("");
  const [open, setOpen]   = useStateD(false);
  const [req, setReq]     = useStateD(null);
  const vw = useViewport();
  const isMobile = vw < 760;
  const openRequest = (item) => setReq({
    kind: "file",
    label: item.name + (item.format && item.format !== "Link" ? " (" + item.format + ")" : ""),
    scope: item.scope, format: item.format,
  });

  const ALL  = window.DOWNLOADS || [];
  const COLS = window.COLLECTIONS || [];
  const range = ALL.filter(d => d.scope === "range");

  const selected = COLS.find(c => c.slug === slug);
  const collFiles = ALL.filter(d => d.scope === slug);
  // group the selected collection's files by their `group` bucket, preserving order
  const groups = [];
  collFiles.forEach(f => {
    let g = groups.find(x => x.name === f.group);
    if (!g) { g = { name: f.group, items: [] }; groups.push(g); }
    g.items.push(f);
  });
  const hasFiles = new Set(ALL.map(d => d.scope));

  return (
    <div>
      <PageIntro
        eyebrow="Downloads"
        title="Every file you need to specify Derlot."
        body="Finish and material libraries, spec sheets, 2D drawings, and 3D / BIM files — organised by collection. Large CAD and BIM files are served from our asset library; tap Request for files released on enquiry."
      />

      {/* ===== Whole-range libraries ===== */}
      <section style={{ padding: "0 max(24px, 3vw) 64px", maxWidth: 1440, margin: "0 auto" }}>
        <div style={{ paddingTop: 48, borderTop: "0.5px solid #d3d1c7" }} />
        <Section label="Libraries · whole range">
          <div>
            {range.map((item, i, arr) => (
              <FileRow key={item.name} item={item} last={i === arr.length - 1} isMobile={isMobile} onRequest={openRequest} />
            ))}
          </div>
        </Section>
      </section>

      {/* ===== By collection ===== */}
      <section style={{ padding: "0 max(24px, 3vw) 160px", maxWidth: 1440, margin: "0 auto" }}>
        <div style={{ paddingTop: 48, borderTop: "0.5px solid #d3d1c7" }} />
        <Section label="By collection">
          {/* Dropdown selector */}
          <div style={{ position: "relative", maxWidth: 560, marginBottom: 48 }}>
            <button
              onClick={() => setOpen(!open)}
              style={{
                width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "18px 20px", background: "#ffffff", border: "0.5px solid #1a1917", borderRadius: 0,
                fontFamily: "inherit", fontSize: 17, color: selected ? INK : STONE, fontWeight: selected ? 500 : 400,
                cursor: "pointer", textAlign: "left",
              }}
            >
              <span>{selected ? selected.name + " — " + selected.year : "Select a collection"}</span>
              <span style={{ fontSize: 14, transform: open ? "rotate(180deg)" : "none", transition: "transform 180ms ease" }}>▾</span>
            </button>
            {open && (
              <div style={{ position: "absolute", top: "calc(100% - 0.5px)", left: 0, right: 0, background: "#fff", border: "0.5px solid #1a1917", maxHeight: 360, overflowY: "auto", zIndex: 10 }}>
                {COLS.filter(c => !c.discontinued).map(c => (
                  <button
                    key={c.slug}
                    onClick={() => { setSlug(c.slug); setOpen(false); }}
                    style={{
                      display: "flex", justifyContent: "space-between", alignItems: "baseline", width: "100%",
                      padding: "12px 20px", background: "transparent", border: "none", borderRadius: 0,
                      borderBottom: "0.5px solid rgba(26,25,23,0.10)", fontFamily: "inherit", fontSize: 15,
                      color: INK, cursor: "pointer", textAlign: "left",
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = "#f5f3ef"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <span style={{ fontWeight: 500, display: "flex", alignItems: "center", gap: 8 }}>
                      {c.name}
                      {!hasFiles.has(c.slug) && <span style={{ fontSize: 9, letterSpacing: "0.1em", textTransform: "uppercase", color: MUTE }}>· on request</span>}
                    </span>
                    <span style={{ fontSize: 11, color: STONE, letterSpacing: "0.08em", textTransform: "uppercase" }}>{c.year}</span>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Selected collection's files, grouped by type */}
          {selected ? (
            groups.length ? (
              groups.map(g => (
                <div key={g.name} style={{ marginBottom: 36 }}>
                  <div style={{ fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 500, color: INK, paddingBottom: 12, borderBottom: "0.5px solid #d3d1c7", marginBottom: 4 }}>{g.name}</div>
                  {g.items.map((item, i, arr) => (
                    <FileRow key={item.name + item.format} item={item} last={i === arr.length - 1} isMobile={isMobile} onRequest={openRequest} />
                  ))}
                </div>
              ))
            ) : (
              <div style={{ padding: "60px 0", borderTop: "0.5px solid rgba(26,25,23,0.18)", textAlign: "center", color: STONE, fontSize: 14 }}>
                Files for {selected.name} are available on request — <button onClick={() => setReq({ kind: "file", label: selected.name + " — specifier files", scope: selected.slug })} style={{ fontFamily: "inherit", fontSize: 14, color: INK, background: "transparent", border: "none", borderBottom: "0.5px solid " + INK, padding: "0 0 2px", cursor: "pointer" }}>request them</button>.
              </div>
            )
          ) : (
            <div style={{ padding: "60px 0", borderTop: "0.5px solid rgba(26,25,23,0.18)", textAlign: "center", color: STONE, fontSize: 14 }}>
              Select a collection above to see its spec sheets, drawings and 3D / BIM files.
            </div>
          )}
        </Section>
      </section>

      {req && <RequestForm context={req} onClose={() => setReq(null)} />}
    </div>
  );
}

window.Downloads = Downloads;
