// LineSheet.jsx — line-sheet BODY (table + totals) rendered inside the
// Collection page when the Grid/Line toggle is set to "line". The page header,
// category filter and toggle live in GridView; this is just the body.

function LineSheet({ rows, allProducts, orderItems, setOrderQty, info, onOpenSku, editing, dragVisual, startDrag, overDrag, endDrag }) {
  // Totals reflect the whole order (every product), not just the filtered rows.
  const totals = (allProducts || rows).reduce((acc, p) => {
    const qtys = (orderItems[p.id] && orderItems[p.id].qtys) || {};
    const units = Object.values(qtys).reduce((a, b) => a + (b || 0), 0);
    acc.units += units;
    acc.value += units * p.ws;
    if (units > 0) acc.skus += 1;
    return acc;
  }, { units: 0, value: 0, skus: 0 });

  return (
    <React.Fragment>
      <div className="lsheet-scroll">
      <div className="lsheet-table">
        <div className="lsheet-h">
          <div></div>
          <div>STYLE</div>
          <div>FIBRE · COLOUR</div>
          <div className="h-num">XS</div>
          <div className="h-num">S</div>
          <div className="h-num">M</div>
          <div className="h-num">L</div>
          <div className="h-num">XL</div>
          <div className="h-num">UNITS</div>
          <div style={{justifyContent: "flex-end"}}>{(rows[0] && rows[0].priceMode === "dtc") ? "PRICE" : "WS / MSRP"}</div>
          <div style={{justifyContent: "flex-end"}}>LINE</div>
        </div>

        {rows.map(p => {
          const qtys = (orderItems[p.id] && orderItems[p.id].qtys) || {};
          const sizes = p.sizes || ["ONE SIZE"];
          const units = Object.values(qtys).reduce((a, b) => a + (b || 0), 0);
          const line = units * p.ws;
          const allSizes = ["XS", "S", "M", "L", "XL"];
          const noSize = !p.sizes;

          return (
            <div key={p.id}
              className={"lsheet-row" + (units > 0 ? " has-qty" : "") + (editing ? " lsheet-row-edit" : "") + (dragVisual === p.id ? " is-dragging" : "")}
              draggable={editing}
              onDragStart={editing ? startDrag(p.id) : undefined}
              onDragOver={editing ? overDrag(p.id) : undefined}
              onDragEnd={editing ? endDrag : undefined}>
              <div className="c-thumb">
                <div className="photo" style={{background: p.bg, cursor: "pointer"}} onClick={() => onOpenSku(p)} />
              </div>
              <div className="c-name">
                <div className="nm">{p.name.toLowerCase()}</div>
                <div className="idx">{p.idx}</div>
                <div className="ctg">{(p.categories && p.categories.length ? p.categories : [p.category]).join(" · ")}</div>
              </div>
              <div className="c-fabric">
                <span className="top">{p.fabric}</span>
                <span>· {p.colorway.name}</span>
                <span>· {p.weight}</span>
              </div>
              {allSizes.map(s => {
                if (noSize) {
                  if (s === "M") {
                    const v = qtys["ONE SIZE"] || 0;
                    return (
                      <div key={s} className={"c-size" + (v > 0 ? " has-qty" : "")}>
                        <input type="number" min="0" placeholder="—" value={v || ""}
                          onChange={e => setOrderQty(p, "ONE SIZE", parseInt(e.target.value || "0", 10))} />
                      </div>
                    );
                  } else {
                    return <div key={s} className="c-size mono dim" style={{justifyContent: "center", color: "var(--fg-mute)"}}>·</div>;
                  }
                }
                if (!sizes.includes(s)) {
                  return <div key={s} className="c-size mono dim" style={{justifyContent: "center", color: "var(--fg-mute)"}}>·</div>;
                }
                const v = qtys[s] || 0;
                return (
                  <div key={s} className={"c-size" + (v > 0 ? " has-qty" : "")}>
                    <input type="number" min="0" placeholder="0" value={v || ""}
                      onChange={e => setOrderQty(p, s, parseInt(e.target.value || "0", 10))} />
                  </div>
                );
              })}
              <div className="c-total mono">{units || "—"}</div>
              <div className="c-price">
                <span className="ws">
                  {p.wsOriginal != null && <span className="price-strike">{p.currency}{p.wsOriginal}</span>}
                  {p.currency}{p.ws}
                </span>
                {p.msrp != null && <span className="msrp">{p.currency}{p.msrp} MSRP</span>}
              </div>
              <div className="c-line mono">{line ? `${p.currency}${line.toLocaleString()}` : "—"}</div>
            </div>
          );
        })}
      </div>
      </div>

      <div className="lsheet-foot">
        <div className="totals">
          <div className="stat">
            <div className="lbl">[ skus ]</div>
            <div className="val">{totals.skus}</div>
          </div>
          <div className="stat">
            <div className="lbl">[ units ]</div>
            <div className="val">{totals.units}</div>
          </div>
          <div className="stat">
            <div className="lbl">[ wholesale value ]</div>
            <div className="val">{info.currency}{totals.value.toLocaleString()}</div>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

window.LineSheet = LineSheet;
