/* global window, React */
// ============================================================
// Strategic Horizon — 5-day forward view
// Sections:
//   1. Header + KPI strip
//   2. Lane × Day capacity grid (the centerpiece)
//   3. Pre-tender opportunities  +  Cost variance attribution
//   4. Stale orders panel
// ============================================================

const { useState: useStratState } = React;

// ---------- helpers ----------
function cellState(cell) {
  const gap = cell.loads - cell.cap;
  if (cell.loads === 0) return 'empty';
  if (gap > 0) return 'red';
  if (gap === 0) return 'amber';
  if (cell.cap - cell.loads === 1) return 'tight';
  return 'ok';
}

function fmt$(n) {
  const abs = Math.abs(n);
  if (abs >= 1000) return (n < 0 ? '−$' : '$') + (abs / 1000).toFixed(abs >= 10000 ? 0 : 1) + 'K';
  return (n < 0 ? '−$' : '$') + abs.toLocaleString();
}

// ---------- KPI cards (strategic-tinted, slightly different from overview) ----------
function StratKpi({ label, value, sub, kind, trend }) {
  return (
    <div className={`s-kpi ${kind ? `s-kpi--${kind}` : ''}`}>
      <div className="s-kpi__label">{label}</div>
      <div className="s-kpi__value">
        {value}
        {trend && <span className={`s-kpi__trend s-kpi__trend--${trend.dir}`}>{trend.label}</span>}
      </div>
      {sub && <div className="s-kpi__sub">{sub}</div>}
    </div>
  );
}

// ---------- Capacity grid cell ----------
function CapacityCell({ cell, onClick, isSelected }) {
  const st = cellState(cell);
  const gap = cell.loads - cell.cap;
  const covered = cell.priv + cell.ded + cell.mkt;
  const total = Math.max(cell.loads, cell.cap, 1);
  const pPriv = (cell.priv / total) * 100;
  const pDed  = (cell.ded  / total) * 100;
  const pMkt  = (cell.mkt  / total) * 100;
  const pUnc  = (cell.uncovered / total) * 100;
  const pCapHeadroom = (Math.max(0, cell.cap - covered) / total) * 100;

  return (
    <button
      className={`s-cell s-cell--${st} ${isSelected ? 's-cell--selected' : ''}`}
      onClick={onClick}
    >
      <div className="s-cell__head">
        <span className="s-cell__loads">{cell.loads}</span>
        <span className="s-cell__sep">/</span>
        <span className="s-cell__cap">{cell.cap}</span>
        {gap > 0 && <span className="s-cell__gap">−{gap}</span>}
      </div>
      <div className="s-cell__bar">
        {cell.priv > 0 && <span className="s-cell__seg s-cell__seg--priv" style={{ width: `${pPriv}%` }} />}
        {cell.ded  > 0 && <span className="s-cell__seg s-cell__seg--ded"  style={{ width: `${pDed}%` }} />}
        {cell.mkt  > 0 && <span className="s-cell__seg s-cell__seg--mkt"  style={{ width: `${pMkt}%` }} />}
        {cell.uncovered > 0 && <span className="s-cell__seg s-cell__seg--unc" style={{ width: `${pUnc}%` }} />}
        {pCapHeadroom > 0 && <span className="s-cell__seg s-cell__seg--head" style={{ width: `${pCapHeadroom}%` }} />}
      </div>
    </button>
  );
}

// ---------- Detail panel that appears when a cell is selected ----------
function CellDetail({ lane, dayIdx, days, cell, onClose, onJumpPreTender }) {
  const day = days[dayIdx];
  const gap = cell.loads - cell.cap;
  return (
    <div className="s-cell-detail">
      <div className="s-cell-detail__head">
        <div>
          <div className="s-cell-detail__eyebrow">{day.dow} {day.date} · {lane.from} → {lane.to}</div>
          <div className="s-cell-detail__title">
            {cell.loads} loads · {cell.cap} capacity
            {gap > 0 && <span className="s-cell-detail__gap">  −{gap} uncovered</span>}
          </div>
        </div>
        <button className="s-cell-detail__close" onClick={onClose} title="Close">×</button>
      </div>

      <div className="s-cell-detail__grid">
        <div className="s-cell-detail__stat">
          <span className="s-cell-detail__stat-label">Private</span>
          <span className="s-cell-detail__stat-val" style={{ color: 'var(--green-2)' }}>{cell.priv}</span>
        </div>
        <div className="s-cell-detail__stat">
          <span className="s-cell-detail__stat-label">Dedicated</span>
          <span className="s-cell-detail__stat-val" style={{ color: 'var(--amber-2)' }}>{cell.ded}</span>
        </div>
        <div className="s-cell-detail__stat">
          <span className="s-cell-detail__stat-label">Market tendered</span>
          <span className="s-cell-detail__stat-val" style={{ color: 'var(--blue-2)' }}>{cell.mkt}</span>
        </div>
        <div className="s-cell-detail__stat">
          <span className="s-cell-detail__stat-label">Uncovered</span>
          <span className="s-cell-detail__stat-val" style={{ color: cell.uncovered > 0 ? 'var(--red-2)' : 'var(--ink-3)' }}>{cell.uncovered}</span>
        </div>
      </div>

      {gap > 0 ? (
        <div className="s-cell-detail__rec">
          <span className="s-cell-detail__rec-label">AGENT</span>
          <span>Pre-tender recommended. Spot premium trending up — locking now saves vs forecast.</span>
          <button className="s-cell-detail__rec-btn" onClick={onJumpPreTender}>See pre-tender →</button>
        </div>
      ) : (
        <div className="s-cell-detail__rec s-cell-detail__rec--ok">
          <span className="s-cell-detail__rec-label">STATUS</span>
          <span>Capacity is in balance. {cell.cap - cell.loads} unit{cell.cap - cell.loads === 1 ? '' : 's'} of slack.</span>
        </div>
      )}
    </div>
  );
}

// ---------- Pre-tender card ----------
function PreTenderCard({ rec, onAction }) {
  return (
    <div className={`s-pt s-pt--${rec.kind}`} id={`pt-${rec.id}`}>
      <div className="s-pt__head">
        <span className={`pill pill--${rec.kind === 'red' ? 'red' : 'amber'}`}>{rec.uncovered} uncovered</span>
        <span className="s-pt__lane">{rec.lane}</span>
        <span className="s-pt__day">{rec.day}</span>
        <span className="s-pt__surfaced">flagged {rec.surfaced}</span>
      </div>

      <div className="s-pt__title">{rec.title}</div>

      <div className="s-pt__body" dangerouslySetInnerHTML={{ __html: rec.body }} />

      <div className="s-pt__math">
        <div className="s-pt__math-cell">
          <span className="s-pt__math-label">Lane plan</span>
          <span className="s-pt__math-val">${rec.math.plan.toLocaleString()}</span>
        </div>
        <span className="s-pt__math-arr">→</span>
        <div className="s-pt__math-cell s-pt__math-cell--now">
          <span className="s-pt__math-label">Lock today</span>
          <span className="s-pt__math-val">${rec.math.lockNow.toLocaleString()}</span>
        </div>
        <span className="s-pt__math-arr">vs</span>
        <div className="s-pt__math-cell s-pt__math-cell--risk">
          <span className="s-pt__math-label">Wait → spot</span>
          <span className="s-pt__math-val">${rec.math.waitSpot.toLocaleString()}</span>
        </div>
        <div className="s-pt__math-cell s-pt__math-cell--save">
          <span className="s-pt__math-label">Net savings</span>
          <span className="s-pt__math-val">${rec.math.savings.toLocaleString()}</span>
        </div>
      </div>

      <div className="s-pt__actions">
        <button className="btn btn--primary" onClick={() => onAction(rec, 'primary')}>{rec.action}</button>
        <button className="btn" onClick={() => onAction(rec, 'alt')}>{rec.altAction}</button>
      </div>
    </div>
  );
}

// ---------- Cost variance attribution ----------
function CostVariance({ data }) {
  const max = Math.max(...data.drivers.map(d => Math.abs(d.amount)));
  return (
    <div className="s-var">
      <div className="s-var__top">
        <div className="s-var__top-cell">
          <span className="s-var__top-label">Plan</span>
          <span className="s-var__top-val">${(data.plan / 1000).toFixed(0)}K</span>
        </div>
        <span className="s-var__top-sep">+</span>
        <div className="s-var__top-cell s-var__top-cell--var">
          <span className="s-var__top-label">Variance</span>
          <span className="s-var__top-val s-var__top-val--red">+${(data.variance / 1000).toFixed(1)}K</span>
          <span className="s-var__top-sub">+{data.pct.toFixed(1)}%</span>
        </div>
        <span className="s-var__top-sep">=</span>
        <div className="s-var__top-cell">
          <span className="s-var__top-label">Actual</span>
          <span className="s-var__top-val">${(data.actual / 1000).toFixed(0)}K</span>
        </div>
      </div>

      <div className="s-var__bars">
        {data.drivers.map(d => {
          const pct = (Math.abs(d.amount) / max) * 100;
          const isSave = d.amount < 0;
          return (
            <div key={d.id} className={`s-var__row s-var__row--${d.kind}`}>
              <div className="s-var__row-head">
                <span className="s-var__row-label">{d.label}</span>
                <span className={`s-var__row-amt ${isSave ? 's-var__row-amt--save' : ''}`}>
                  {isSave ? '−' : '+'}${(Math.abs(d.amount) / 1000).toFixed(d.amount < 1500 && d.amount > -1500 ? 1 : 1)}K
                </span>
              </div>
              <div className="s-var__row-bar">
                <span
                  className={`s-var__row-fill ${isSave ? 's-var__row-fill--save' : ''} s-var__row-fill--${d.kind}`}
                  style={{ width: `${pct}%`, [isSave ? 'right' : 'left']: '50%' }}
                />
                <span className="s-var__row-axis" />
              </div>
              <div className="s-var__row-detail">{d.detail}</div>
            </div>
          );
        })}
      </div>

      <div className="s-var__foot">
        <div className="s-var__foot-cell">
          <span className="s-var__foot-label">Next 5d forecast</span>
          <span className="s-var__foot-val">${(data.forecast.fiveDay / 1000).toFixed(0)}K</span>
          <span className="s-var__foot-sub">plan ${(data.forecast.fiveDayPlan / 1000).toFixed(0)}K · +{(((data.forecast.fiveDay - data.forecast.fiveDayPlan) / data.forecast.fiveDayPlan) * 100).toFixed(1)}%</span>
        </div>
        <div className="s-var__foot-cell">
          <span className="s-var__foot-label">YTD vs plan</span>
          <span className="s-var__foot-val">${(data.forecast.ytd / 1000000).toFixed(2)}M</span>
          <span className="s-var__foot-sub">+{(((data.forecast.ytd - data.forecast.ytdPlan) / data.forecast.ytdPlan) * 100).toFixed(1)}% over plan</span>
        </div>
      </div>
    </div>
  );
}

// ---------- Stale orders panel ----------
function StaleOrders({ orders, onAction }) {
  return (
    <div className="s-stale">
      <div className="s-stale__head">
        <span></span>
        <span>Order</span>
        <span>Customer</span>
        <span>Destination</span>
        <span>Ship</span>
        <span className="num">Days out</span>
        <span className="num">Pallets</span>
        <span>In pool</span>
        <span>Reason</span>
        <span>Agent suggestion</span>
        <span></span>
      </div>
      {orders.map(o => (
        <div key={o.id} className={`s-stale__row s-stale__row--${o.risk}`}>
          <span className={`s-stale__risk s-stale__risk--${o.risk}`} title={`${o.risk} risk`}></span>
          <span className="s-stale__id">{o.id}</span>
          <span className="s-stale__cust">{o.customer}</span>
          <span className="s-stale__dest">{o.dest}</span>
          <span className="s-stale__ship">{o.ship}</span>
          <span className="num s-stale__days">
            <span className={`s-stale__days-val s-stale__days-val--${o.risk}`}>{o.daysOut.toFixed(1)}d</span>
          </span>
          <span className="num">{o.pal}<span className="s-stale__sub">{o.lbs.toLocaleString()} lb</span></span>
          <span className="s-stale__inpool">{o.inPool}</span>
          <span className="s-stale__reason">{o.reason}</span>
          <span className="s-stale__suggest">
            <span className="s-stale__ai">TP</span>
            <span>{o.suggest}</span>
          </span>
          <button className="s-stale__act" onClick={() => onAction(o)}>Action →</button>
        </div>
      ))}
    </div>
  );
}

// ---------- Main view ----------
function StrategicHorizon() {
  const S = window.STRATEGIC;
  const [selectedCell, setSelectedCell] = useStratState(null); // { laneId, dayIdx }
  const [range, setRange] = useStratState('5d');
  const [toast, setToast] = useStratState(null);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 3200);
  };

  const totals = S.days.map((_, di) =>
    S.lanes.reduce((acc, lane) => {
      const c = lane.cells[di];
      acc.loads += c.loads;
      acc.cap   += c.cap;
      acc.unc   += c.uncovered;
      return acc;
    }, { loads: 0, cap: 0, unc: 0 })
  );

  const totalUncovered = totals.reduce((a, t) => a + t.unc, 0);
  const totalLoads     = totals.reduce((a, t) => a + t.loads, 0);
  const totalCap       = totals.reduce((a, t) => a + t.cap, 0);
  const totalGapLanes  = S.lanes.filter(l => l.cells.some(c => c.loads > c.cap)).length;

  const selectedLane = selectedCell ? S.lanes.find(l => l.id === selectedCell.laneId) : null;
  const selectedCellData = selectedLane ? selectedLane.cells[selectedCell.dayIdx] : null;

  const onCellClick = (laneId, dayIdx) => {
    if (selectedCell && selectedCell.laneId === laneId && selectedCell.dayIdx === dayIdx) {
      setSelectedCell(null);
    } else {
      setSelectedCell({ laneId, dayIdx });
    }
  };

  const onPreTenderAction = (rec, kind) => {
    if (kind === 'primary') {
      showToast(`✓ Pre-tender executed · ${rec.uncovered} loads locked on ${rec.lane} (${rec.day}) · est. savings $${rec.math.savings.toLocaleString()}`);
    } else {
      showToast(`Alternatives opened for ${rec.lane} · ${rec.day}.`);
    }
  };

  const onStaleAction = (o) => {
    showToast(`Routing ${o.id} → ${o.suggest}`);
  };

  return (
    <div className="strategic" data-screen-label="Strategic horizon">
      {/* Top bar */}
      <div className="s-head">
        <div className="s-head__left">
          <div className="s-head__eyebrow">STRATEGIC HORIZON · 5-DAY</div>
          <div className="s-head__title">Forward plan · <span className="dim">{S.rangeLabel}</span></div>
          <div className="s-head__sub">
            <span className="s-head__sub-strong">8 uncovered loads</span> across 2 lanes in the next 5 days ·
            3 pre-tender moves identified · est. lock-now savings <span className="s-head__sub-strong">$3,135</span>
          </div>
        </div>
        <div className="s-head__right">
          <div className="seg" style={{ marginRight: 8 }}>
            {S.rangeOptions.map(r => (
              <button key={r} className={`seg__btn ${range === r ? 'on' : ''}`} onClick={() => setRange(r)}>{r}</button>
            ))}
          </div>
          <button className="btn">⤓ Export plan</button>
          <button className="btn btn--primary" onClick={() => showToast('✓ 3 pre-tender carriers locked · 8 loads secured · est. $3,135 saved')}>
            Lock 3 pre-tender moves →
          </button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="s-kpis">
        <StratKpi label="Loads (5d)"          value={totalLoads}     sub={`${totalCap} capacity · ${Math.round(totalLoads / totalCap * 100)}% util`} />
        <StratKpi label="Uncovered"           value={totalUncovered} sub={`${totalGapLanes} lanes with gap`} kind="red" />
        <StratKpi label="Pre-tender opps"     value="3"              sub="est. $3,135 savings"        kind="amber" />
        <StratKpi label="Stale orders"        value="6"              sub="2 OTIF-sensitive · 1 HELD"  kind="amber" />
        <StratKpi label="WtD variance"        value="+$25.3K"        sub="+5.2% over plan"            kind="red" />
        <StratKpi label="Forecast vs plan"    value="+$22K"          sub="next 5d · +3.7%"            kind="amber" />
      </div>

      {/* Capacity grid */}
      <div className="s-section">
        <div className="s-section__head">
          <div>
            <div className="s-section__title">Lane × day capacity grid</div>
            <div className="s-section__sub">
              <span className="s-legend-item"><span className="s-legend-sw s-legend-sw--priv" /> Private</span>
              <span className="s-legend-item"><span className="s-legend-sw s-legend-sw--ded" /> Dedicated</span>
              <span className="s-legend-item"><span className="s-legend-sw s-legend-sw--mkt" /> Market</span>
              <span className="s-legend-item"><span className="s-legend-sw s-legend-sw--unc" /> Uncovered</span>
              <span className="s-legend-item"><span className="s-legend-sw s-legend-sw--head" /> Headroom</span>
            </div>
          </div>
          <div className="s-section__sub-r">
            Cells show <span className="s-section__sub-mono">loads / capacity</span>. Red = gap. Click a cell to drill in.
          </div>
        </div>

        <div className="s-grid-wrap">
          <div className="s-grid">
            <div className="s-grid__corner">
              <div className="s-grid__corner-title">Lane</div>
              <div className="s-grid__corner-sub">{S.lanes.length} lanes · Chicago hub</div>
            </div>
            {S.days.map((d, i) => (
              <div key={d.iso} className="s-grid__col-head">
                <div className="s-grid__dow">{d.dow}</div>
                <div className="s-grid__date">{d.date}</div>
                <div className={`s-grid__col-totals ${totals[i].unc > 0 ? 's-grid__col-totals--bad' : ''}`}>
                  {totals[i].loads}/{totals[i].cap}
                  {totals[i].unc > 0 && <span className="s-grid__col-gap">−{totals[i].unc}</span>}
                </div>
              </div>
            ))}
            <div className="s-grid__col-head s-grid__col-head--total">
              <div className="s-grid__dow">TOTAL</div>
              <div className="s-grid__date">5-day</div>
              <div className="s-grid__col-totals">{totalLoads}/{totalCap}</div>
            </div>

            {S.lanes.map(lane => {
              const laneLoads = lane.cells.reduce((a, c) => a + c.loads, 0);
              const laneCap   = lane.cells.reduce((a, c) => a + c.cap, 0);
              const laneUnc   = lane.cells.reduce((a, c) => a + c.uncovered, 0);
              return (
                <React.Fragment key={lane.id}>
                  <div className="s-grid__row-head">
                    <div className="s-grid__lane">
                      {lane.from}<span className="arr">→</span>{lane.to}
                    </div>
                    <div className="s-grid__lane-sub">{lane.miles.toLocaleString()} mi · {lane.mode}</div>
                  </div>
                  {lane.cells.map((cell, di) => (
                    <CapacityCell
                      key={di}
                      cell={cell}
                      isSelected={selectedCell && selectedCell.laneId === lane.id && selectedCell.dayIdx === di}
                      onClick={() => onCellClick(lane.id, di)}
                    />
                  ))}
                  <div className={`s-grid__row-total ${laneUnc > 0 ? 's-grid__row-total--bad' : ''}`}>
                    <span className="s-grid__row-total-main">{laneLoads}/{laneCap}</span>
                    {laneUnc > 0 && <span className="s-grid__row-total-gap">−{laneUnc} unc</span>}
                  </div>
                </React.Fragment>
              );
            })}
          </div>

          {selectedLane && selectedCellData && (
            <CellDetail
              lane={selectedLane}
              dayIdx={selectedCell.dayIdx}
              days={S.days}
              cell={selectedCellData}
              onClose={() => setSelectedCell(null)}
              onJumpPreTender={() => {
                setSelectedCell(null);
                const target = document.getElementById('s-pretender');
                if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
              }}
            />
          )}
        </div>
      </div>

      {/* Two-column: pre-tender + cost variance */}
      <div className="s-two-col">
        <div className="s-section" id="s-pretender">
          <div className="s-section__head">
            <div>
              <div className="s-section__title">Pre-tender opportunities</div>
              <div className="s-section__sub">Lock capacity now while contracted carriers have HOS — vs. waiting for spot to move.</div>
            </div>
            <span className="pill pill--purple">3 agent-flagged</span>
          </div>
          <div className="s-pt-list">
            {S.preTender.map(rec => (
              <PreTenderCard key={rec.id} rec={rec} onAction={onPreTenderAction} />
            ))}
          </div>
        </div>

        <div className="s-section">
          <div className="s-section__head">
            <div>
              <div className="s-section__title">Cost variance attribution</div>
              <div className="s-section__sub">{S.costVariance.period}</div>
            </div>
            <span className="pill pill--red">+5.2%</span>
          </div>
          <CostVariance data={S.costVariance} />
        </div>
      </div>

      {/* Stale orders */}
      <div className="s-section">
        <div className="s-section__head">
          <div>
            <div className="s-section__title">Stale orders · pool aging toward ship date</div>
            <div className="s-section__sub">Orders without a trip assignment, ordered by days-to-ship.</div>
          </div>
          <span className="pill pill--amber">{S.staleOrders.length} pending</span>
        </div>
        <StaleOrders orders={S.staleOrders} onAction={onStaleAction} />
      </div>

      {toast && (
        <div className="s-toast">{toast}</div>
      )}
    </div>
  );
}

Object.assign(window, { StrategicHorizon });
