// Summary.jsx — review & submit screen

function Summary({ orderItems, collection, info, onSubmit, onBack, submitting }) {
  const itemsArr = Object.entries(orderItems).map(([id, item]) => {
    const product = collection.find(p => p.id === id);
    if (!product) return null;
    const units = Object.values(item.qtys).reduce((a, b) => a + (b || 0), 0);
    return { product, qtys: item.qtys, units, line: units * product.ws };
  }).filter(Boolean).filter(x => x.units > 0);

  const totals = itemsArr.reduce((acc, x) => {
    acc.units += x.units; acc.value += x.line; acc.msrp += x.units * (x.product.msrp || 0);
    return acc;
  }, { units: 0, value: 0, msrp: 0 });
  // DTC sessions: their price IS the RRP — no separate MSRP column
  const dtc = !!(info && info.dtc) || itemsArr.some((x) => x.product.priceMode === "dtc");
  const subtotal = itemsArr.reduce((s, x) => s + x.units * Number(x.product.wsOriginal != null ? x.product.wsOriginal : x.product.ws), 0);
  const saved = Math.round((subtotal - totals.value) * 100) / 100;
  const discPct = (info && info.discountPercent) || (subtotal > 0 ? Math.round((saved / subtotal) * 100) : 0);

  return (
    <section className="summary" data-screen-label="06 Summary">
      <button className="btn btn-ghost" onClick={onBack}>← back to collection</button>
      <h1>review the order.</h1>
      <div className="sub">{info.retailer}  ·  {info.season}  ·  {new Date().toLocaleDateString("en-GB", {day:"2-digit", month:"short", year:"numeric"}).toUpperCase()}</div>

      {/* delivery lives below the total now; for DTC nothing is left up here */}
      {!dtc && (
        <div className="summary-meta-grid">
          <div className="stat">
            <span className="lbl">[ skus ]</span>
            <span className="val">{itemsArr.length}</span>
          </div>
          <div className="stat">
            <span className="lbl">[ units ]</span>
            <span className="val">{totals.units}</span>
          </div>
          <div className="stat">
            <span className="lbl">[ terms ]</span>
            <span className="val" style={{fontSize: 24}}>{info.advancePercent ? info.advancePercent + "% advance" : "—"}<em>{info.incoterm}  ·  {info.currency}</em></span>
          </div>
        </div>
      )}

      <div className="summary-rows">
        {itemsArr.length === 0 && (
          <div className="drafts-empty" style={{padding: "96px 16px"}}>
            <img className="glyph" src="assets/icons/orbit.png" alt="" />
            <div className="lede">no items in the order.</div>
            <div className="meta">add skus from the grid or line sheet.</div>
          </div>
        )}
        {itemsArr.map(({ product, qtys, units, line }) => (
          <div key={product.id} className="summary-row">
            <div className="photo" style={{background: product.bg}} />
            <div className="idx">FW·26<br/>{product.idx}</div>
            <div>
              <div className="nm">{product.name.toLowerCase()}</div>
              <div className="mono dim" style={{fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", marginTop: 4}}>
                {product.fabric}  ·  {product.colorway.name}
              </div>
            </div>
            <div className="sizes">
              {Object.entries(qtys).filter(([, q]) => q > 0).map(([sz, q]) => (
                <span key={sz}>{sz}·{q}</span>
              ))}
            </div>
            <div className="qty">{units}  ×  {product.currency}{product.ws}</div>
            <div className="ttl">{product.currency}{line.toLocaleString()}</div>
          </div>
        ))}
      </div>

      {itemsArr.length > 0 && (
        <div className="submit-bar">
          <div className="submit-grand">
            {saved > 0 && (
              <div>
                <div className="mono dim" style={{fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase"}}>[ {(info.discountName || "discount").toLowerCase()}{discPct > 0 ? ` · ${discPct}%` : ""} ]</div>
                <div className="mono" style={{fontSize: 18, marginTop: 4}}><s style={{color: "var(--fg-3)", marginRight: 8}}>{info.currency}{subtotal.toLocaleString()}</s>−{info.currency}{saved.toLocaleString()}</div>
              </div>
            )}
            {!dtc && (
              <div>
                <div className="mono dim" style={{fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase"}}>[ MSRP value ]</div>
                <div className="mono" style={{fontSize: 18, marginTop: 4}}>{info.currency}{totals.msrp.toLocaleString()}</div>
              </div>
            )}
            <div>
              <div className="mono dim" style={{fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase"}}>{dtc ? "[ total ]" : "[ wholesale total ]"}</div>
              <div className="mono" style={{fontSize: 18, marginTop: 4}}>{info.currency}{totals.value.toLocaleString()}</div>
              <div className="below">delivery · {info.deliveryWindow}</div>
            </div>
          </div>
          <button className="btn btn-primary" onClick={onSubmit} disabled={submitting}>
            {submitting ? "submitting…" : "submit order ⟶"}
          </button>
        </div>
      )}
    </section>
  );
}

window.Summary = Summary;
