// Cover.jsx — collection cover/intro

function Cover({ collection, info, onEnter, coverBg }) {
  const ec = React.useContext(window.EditCtx);
  const hasImage = coverBg && coverBg.type === "image";
  const stageStyle = { position: "relative" };
  if (hasImage) {
    stageStyle.backgroundImage = `url("${coverBg.value}")`;
    stageStyle.backgroundSize = "cover";
    stageStyle.backgroundPosition = "center";
  } else if (coverBg && coverBg.type === "color") {
    stageStyle.background = coverBg.value;
  }
  const isDarkBg = coverBg && coverBg.type === "color" && ["#2A2722", "#16140F", "#6B655B", "#6B3A24", "#3F4A2E"].includes(coverBg.value);

  // Auto-contrast the title against an image background: sample the image
  // pixels behind the title and flip it (and its em + the season line) so it
  // stays readable on light or dark photos. A soft halo backs that up.
  React.useEffect(() => {
    const title = document.querySelector(".cover-title");
    const mark = document.querySelector(".cover-mark-area");
    if (!title || !mark) return;
    const reset = () => {
      ["--title-fg", "--title-em", "--title-shadow"].forEach((p) => title.style.removeProperty(p));
      mark.classList.remove("cover-on-dark", "cover-on-light");
    };
    if (!hasImage) { reset(); return; }
    const stage = document.querySelector(".cover-stage");
    const lum = (r, g, b) => 0.299 * r + 0.587 * g + 0.114 * b;
    const img = new Image();
    const apply = () => {
      if (!img.naturalWidth || !stage) return;
      const SW = stage.clientWidth, SH = stage.clientHeight;
      const IW = img.naturalWidth, IH = img.naturalHeight;
      const scale = Math.max(SW / IW, SH / IH);       // background-size: cover
      const offX = (SW - IW * scale) / 2;             // background-position: center
      const offY = (SH - IH * scale) / 2;
      const canvas = document.createElement("canvas");
      canvas.width = IW; canvas.height = IH;
      const ctx = canvas.getContext("2d");
      try { ctx.drawImage(img, 0, 0); } catch (e) { return; }
      const tr = title.getBoundingClientRect();
      const sr = stage.getBoundingClientRect();
      let total = 0, n = 0;
      for (let i = 0; i <= 4; i++) for (let j = 0; j <= 4; j++) {
        const sx = (tr.left - sr.left) + (tr.width * i) / 4;
        const sy = (tr.top - sr.top) + (tr.height * j) / 4;
        const ix = Math.round((sx - offX) / scale);
        const iy = Math.round((sy - offY) / scale);
        if (ix < 0 || iy < 0 || ix >= IW || iy >= IH) continue;
        try { const d = ctx.getImageData(ix, iy, 1, 1).data; total += lum(d[0], d[1], d[2]); n++; } catch (e) {}
      }
      if (!n) return;
      const light = total / n > 140;                  // light backdrop → dark text
      title.style.setProperty("--title-fg", light ? "#16140f" : "#ffffff");
      title.style.setProperty("--title-em", light ? "#5a554b" : "#d2ccbf");
      title.style.setProperty("--title-shadow", light
        ? "0 1px 32px rgba(255,255,255,0.5)"
        : "0 1px 32px rgba(16,20,15,0.45)");
      mark.classList.toggle("cover-on-dark", !light);
      mark.classList.toggle("cover-on-light", light);
    };
    img.onload = apply;
    img.src = coverBg.value;
    if (img.complete) apply();
    window.addEventListener("resize", apply);
    return () => window.removeEventListener("resize", apply);
  }, [coverBg]);

  const booking = (info.bookingWindow || "").replace(/^booking\s*·\s*/i, "");
  const bookingMonth = (booking.split(/[-–]/)[0] || booking).trim();
  return (
    <section className="cover" data-screen-label="01 Cover">
      <div className="cover-stage" style={stageStyle}
        {...window.dropProps(ec, (path) => ec.saveSetting({ coverBg: { type: "image", value: path } }))}>
        <window.EditableImage title="⤓ replace cover background"
          onPick={(path) => ec.saveSetting({ coverBg: { type: "image", value: path } })} />
        <div className="cover-mark-area" style={isDarkBg ? { color: "var(--sb-bone)" } : null}>
          <div className="cover-season">
            <window.EditableText value={info.season} onSave={(v) => ec.saveSetting({ season: v })} />  ·  WHOLESALE
          </div>
          <h1 className="cover-title">
            {ec.edit ? (
              <window.EditableText value={info.title} onSave={(v) => ec.saveSetting({ title: v })} />
            ) : (
              info.title.split(" ").map((w, i, arr) =>
                <span key={i}>
                  {i === arr.length - 1 ? <em>{w}</em> : w}
                  {i < arr.length - 1 ? " " : ""}
                </span>
              )
            )}
          </h1>
          <div style={{ display: "flex", gap: 24, alignItems: "center", marginTop: 8, flexWrap: "wrap" }}>
            <button className="btn btn-primary" onClick={() => onEnter("lookbook")}>view the lookbook ⟶</button>
            <button className="btn btn-outline" onClick={() => onEnter("linesheet")}
              style={isDarkBg ? { borderColor: "var(--sb-bone)", color: "var(--sb-bone)" } : null}>open line sheet</button>
          </div>
        </div>
      </div>

      <div className="cover-deetz">
        <div>
          <div className="col-h">[ BOOKING ]</div>
          <div className="col-v">{bookingMonth || "—"}<em>{booking}</em></div>
        </div>
        <div>
          <div className="col-h">[ DELIVERY ]</div>
          <div className="col-v">{info.deliveryWindow.split(" · ")[1] || "AUG"}<em>{info.deliveryWindow.split(" · ")[0]}</em></div>
        </div>
        {!info.dtc && (
          <div>
            <div className="col-h">[ TERMS ]</div>
            <div className="col-v">
              <window.EditableText value={String(info.advancePercent || "")} onSave={(v) => ec.saveSetting({ advancePercent: v })} />% advance
              <em>{info.currency} · <window.EditableText value={info.incoterm} onSave={(v) => ec.saveSetting({ incoterm: v })} /></em>
            </div>
          </div>
        )}
      </div>

      <div className="cover-letter">
        <div className="ltr-h">[ <window.EditableText value={info.letterHeading || "A NOTE FROM THE ATELIER"} onSave={(v) => ec.saveSetting({ letterHeading: v })} /> ]</div>
        <div className="ltr-body">
          {ec.edit ? (
            <window.EditableText tag="p" multiline value={info.letterBody || ""}
              placeholder="write the atelier note · blank line starts a new paragraph"
              onSave={(v) => ec.saveSetting({ letterBody: v })} />
          ) : (
            (info.letterBody || "").split(/\n\s*\n/).filter(Boolean).map((para, i) => (
              <p key={i}>{para}</p>
            ))
          )}
          <div className="ltr-sig"><window.EditableText value={info.letterSignature || "— the studio"} onSave={(v) => ec.saveSetting({ letterSignature: v })} /></div>
        </div>
      </div>
    </section>);

}

window.Cover = Cover;
