// OrderPanel.jsx — sticky right-side cart/order summary

function OrderPanel({ orderItems, collection, info, onOpenSku, onSubmit, onOpenDrafts, onClear, setOrderQty, collapsed, setCollapsed }) {
  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;
    return acc;
  }, { units: 0, value: 0 });
  // DTC sessions have no separate MSRP (their price IS the RRP) — hide the row
  // and never say "wholesale". Session flag first so the EMPTY panel is right too.
  const dtc = !!(info && info.dtc) || itemsArr.some((x) => x.product.priceMode === "dtc");
  const msrpTotal = dtc ? 0 : itemsArr.reduce((s, x) => s + x.units * (x.product.msrp || 0), 0);
  // automatic discount: original (pre-discount) subtotal + the amount saved
  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);

  if (collapsed) {
    return (
      <aside className="panel-rail" onClick={() => setCollapsed(false)}>
        <span className="mono dim" style={{fontSize: 18}}>⟶</span>
        <span className="rail-vert">{itemsArr.length ? "ORDER · " + totals.units + " UNITS" : "ORDER · EMPTY"}</span>
        <span className="rail-num">{itemsArr.length}</span>
      </aside>
    );
  }

  return (
    <aside className="panel">
      <header className="panel-head">
        <div>
          <div className="h">[ order draft ]</div>
          <div className="sub">{info.retailer}  ·  {info.season}</div>
        </div>
        <button className="panel-collapse" onClick={() => setCollapsed(true)} title="collapse">⟶</button>
      </header>

      <div className="panel-body">
        {itemsArr.length === 0 ? (
          <div className="panel-empty">
            <img className="glyph" src="assets/icons/pouch.png" alt="" />
            <div className="lede">nothing here yet.</div>
            <div className="meta">add skus from the grid or line sheet.</div>
            <button className="btn btn-ghost" style={{marginTop: 24}} onClick={onOpenDrafts}>
              [ open saved drafts ]
            </button>
          </div>
        ) : (
          itemsArr.map(({ product, qtys, units, line }) => (
            <div key={product.id} className="order-item">
              <div className="order-item-thumb" style={{background: product.bg, cursor: "pointer"}}
                onClick={() => onOpenSku(product)} />
              <div>
                <div className="order-item-name">{product.name.toLowerCase()}</div>
                <div className="order-item-idx">FW·26 / {product.idx}  ·  {product.colorway.name}</div>
                <div className="order-item-sizes">
                  {Object.entries(qtys).filter(([, q]) => q > 0).map(([sz, q]) => (
                    <span key={sz} className="order-item-size">
                      <button className="oi-step" onClick={() => setOrderQty(product, sz, q - 1)}>−</button>
                      {sz}·{q}
                      <button className="oi-step" onClick={() => setOrderQty(product, sz, q + 1)}>+</button>
                    </span>
                  ))}
                </div>
                <div className="order-item-price mono">{product.currency}{line.toLocaleString()}  <span className="dim">· {units} units</span></div>
              </div>
              <button className="order-item-remove" onClick={() => onClear(product.id)}>×</button>
            </div>
          ))
        )}
      </div>

      <footer className="panel-foot">
        {!dtc && (
          <div className="totals-row">
            <span className="lbl">SKUs</span>
            <span className="val">{itemsArr.length}</span>
          </div>
        )}
        {!dtc && (
          <div className="totals-row">
            <span className="lbl">Units</span>
            <span className="val">{totals.units}</span>
          </div>
        )}
        {saved > 0 && (
          <div className="totals-row">
            <span className="lbl">Subtotal</span>
            <span className="val dim"><s>{info.currency}{subtotal.toLocaleString()}</s></span>
          </div>
        )}
        {saved > 0 && (
          <div className="totals-row">
            <span className="lbl">{(info.discountName || "discount").toLowerCase()}{discPct > 0 ? ` · ${discPct}%` : ""}</span>
            <span className="val">−{info.currency}{saved.toLocaleString()}</span>
          </div>
        )}
        {!dtc && (
          <div className="totals-row">
            <span className="lbl">MSRP value</span>
            <span className="val dim">{info.currency}{msrpTotal.toLocaleString()}</span>
          </div>
        )}
        <div className="totals-row is-grand">
          <span className="lbl">{dtc ? "[ total ]" : "[ wholesale ]"}</span>
          <span className="val">{info.currency}{totals.value.toLocaleString()}</span>
        </div>
        {saved > 0 && (
          <div className="mono dim" style={{fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", textAlign: "right"}}>
            you saved {info.currency}{saved.toLocaleString()}
          </div>
        )}
        <div style={{display: "flex", gap: 8, marginTop: 8}}>
          <button className="btn btn-primary" style={{flex: 1, justifyContent: "center"}}
            disabled={!itemsArr.length} onClick={onSubmit}>
            review & submit ⟶
          </button>
          <button className="btn btn-outline" onClick={onOpenDrafts} title="saved drafts">
            [ DRAFTS ]
          </button>
        </div>
        {!dtc && info.advancePercent && (
          <div className="mono dim" style={{fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", textAlign: "center"}}>
            terms · {info.advancePercent}% advance
          </div>
        )}
      </footer>
    </aside>
  );
}

window.OrderPanel = OrderPanel;
