/* global window, React */
// ============================================================
// Trip detail — Tab 1: Load composition
// ============================================================

function StatBox({ label, value, unit, sub, kind }) {
  return (
    <div className={`card stat stat--${kind || ''}`}>
      <div className="stat__label">{label}</div>
      <div className="stat__value">{value}{unit && <span className="unit">{unit}</span>}</div>
      {sub && <div className="stat__sub">{sub}</div>}
    </div>
  );
}

function UtilBar({ pct }) {
  const state = pct > 97 ? 'red' : pct >= 80 ? 'green' : 'amber';
  const capped = Math.min(pct, 110);
  return (
    <div className="card util-bar-wrap">
      <div className="util-bar">
        <div
          className={`util-bar__fill ${state}`}
          style={{ width: `${capped}%` }}
        >
          {pct}%
        </div>
        <div className="util-bar__threshold" style={{ left: '80%' }}>
          <span className="util-bar__threshold-label">80%</span>
        </div>
        <div className="util-bar__threshold" style={{ left: '97%' }}>
          <span className="util-bar__threshold-label">97%</span>
        </div>
      </div>
      <div className="util-bar__axis">
        <span>0%</span><span>25%</span><span>50%</span><span>75%</span><span>100%</span>
      </div>
    </div>
  );
}

function OrdersTable({ orders }) {
  return (
    <div className="card orders">
      <div className="orders__head">
        <span></span>
        <span>Order ID</span>
        <span>Customer / SKU</span>
        <span style={{ textAlign: 'right' }}>Pallets</span>
        <span style={{ textAlign: 'right' }}>Weight</span>
        <span style={{ textAlign: 'right' }}>Cube</span>
        <span style={{ textAlign: 'right' }}>Invoice $</span>
        <span style={{ textAlign: 'right' }}>Ship by</span>
        <span></span>
      </div>
      {orders.map(o => (
        <div key={o.id} className="order-row">
          <span className="drag">⋮⋮</span>
          <span className="oid">
            {o.id}
            {o.held && <span className="pill pill--red" style={{ marginLeft: 6, fontSize: 9, padding: '1px 5px' }}>HELD</span>}
          </span>
          <span>
            <div className="cust">{o.customer}</div>
            <div className="cust-sub">{o.sku}</div>
          </span>
          <span className="num">{o.pallets}</span>
          <span className="num">{o.lbs.toLocaleString()}</span>
          <span className="num">{o.cuft.toLocaleString()} ft³</span>
          <span className="num">
            ${o.invoiceValue ? o.invoiceValue.toLocaleString() : '—'}
            {o.invoiceRate && (
              <span className="cust-sub" style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 9.5 }}>
                ${o.invoiceRate.toFixed(2)}/lb
              </span>
            )}
          </span>
          <span className="num">{o.ship}</span>
          <button className="x-btn" title="Remove from trip">×</button>
        </div>
      ))}
      <div className="add-order-row">
        <span>＋</span>
        <span>Add order from pool</span>
      </div>
    </div>
  );
}

function OptCards({ items }) {
  return (
    <div className="opt-grid">
      {items.map((o, i) => (
        <div key={i} className={`opt-card opt-card--${o.kind}`}>
          <div className="opt-card__label">{o.label}</div>
          <div className="opt-card__title">{o.title}</div>
          <div className="opt-card__body" dangerouslySetInnerHTML={{ __html: o.body }}></div>
          <button className="opt-card__action">{o.cta}</button>
        </div>
      ))}
    </div>
  );
}

function LoadCompositionTab({ trip }) {
  const totalPallets = trip.orders.reduce((a, o) => a + o.pallets, 0);
  const totalLbs = trip.orders.reduce((a, o) => a + o.lbs, 0);
  const totalCuft = trip.orders.reduce((a, o) => a + o.cuft, 0);
  const cubePct = Math.round((totalCuft / 3500) * 100);

  const invoice = trip.loadInvoice || trip.orders.reduce((a, o) => a + (o.invoiceValue || 0), 0);
  const recOption = trip.fleetOptions.find(o => o.recommended) || trip.fleetOptions[0];
  const recCost = recOption && recOption.costToServeDollar ? recOption.costToServeDollar : null;
  const c2s = trip.costToServePct;
  // benchmark — lane-typical c2s in this fixture
  const c2sBench = 7.5;
  const c2sKind = !c2s ? '' : c2s > c2sBench * 1.2 ? 'red' : c2s < c2sBench * 0.8 ? 'green' : 'amber';

  return (
    <div>
      <div className="section">
        <div className="section__head">
          <div className="section__title">Utilisation &amp; load economics</div>
          <div className="section__sub">53 ft trailer · max 45,000 lbs · 32 pallet positions · lane benchmark cost-to-serve <span style={{ fontFamily: 'var(--font-mono)' }}>{c2sBench}%</span></div>
        </div>
        <div className="stats-row">
          <StatBox label="Weight" value={trip.util} unit="%" sub={`${totalLbs.toLocaleString()} / 45,000 lbs`}
            kind={trip.util > 97 ? 'red' : trip.util < 80 ? 'amber' : 'green'} />
          <StatBox label="Cube"   value={cubePct} unit="%" sub={`${totalCuft.toLocaleString()} / 3,500 ft³`} kind="green" />
          <StatBox label="Pallets" value={totalPallets} sub={`of 32 positions · ${32 - totalPallets} spare`} kind={totalPallets < 26 ? 'amber' : 'green'} />
          <StatBox label="Invoice value" value={`$${invoice.toLocaleString()}`}
            sub={`${trip.orders.length} order${trip.orders.length === 1 ? '' : 's'} · $${Math.round(invoice/totalLbs * 100) / 100}/lb avg`} />
          <StatBox label="Cost to serve" value={c2s ? `${c2s}%` : '—'}
            sub={recCost ? `$${recCost.toLocaleString()} / $${invoice.toLocaleString()} · ${recOption ? recOption.name.split(' ·')[0] : 'recommended'}` : 'no eligible carrier'}
            kind={c2sKind} />
        </div>
        <UtilBar pct={trip.util} />
      </div>

      <div className="section">
        <div className="section__head">
          <div className="section__title">Orders on this load · {trip.orders.length}</div>
          <div className="section__sub">
            Drag to reorder · × removes back to pool ·
            <span style={{ marginLeft: 8, fontFamily: 'var(--font-mono)', color: 'var(--ink)' }}>
              Σ invoice ${invoice.toLocaleString()}
            </span>
          </div>
        </div>
        <OrdersTable orders={trip.orders} />
      </div>

      <div className="section">
        <div className="section__head">
          <div className="section__title">Optimisation options · agent</div>
          <div className="section__sub">{trip.opt.length} suggestion{trip.opt.length === 1 ? '' : 's'}</div>
        </div>
        <OptCards items={trip.opt} />
      </div>
    </div>
  );
}

Object.assign(window, { LoadCompositionTab });
