/* global window, React */
// ============================================================
// Today — situational snapshot across all DCs the TP covers.
// This is the morning-ritual tab: less interactive than Tactical,
// more readout. Sections:
//   1. Hero header (date / time / one-liner)
//   2. Day KPI strip (6 KPIs)
//   3. Per-DC pulse cards (1 per DC in scope)
//   4. Two-col row: Wave health timeline + Today vs Yesterday variance
//   5. On the clock — trips delivering in the next 8h
//   6. Live agent decision stream
// ============================================================

const { useState: useTodayState, useMemo: useTodayMemo } = React;

function TodayKpi({ label, value, sub, kind }) {
  return (
    <div className={`tdk ${kind ? `tdk--${kind}` : ''}`}>
      <div className="tdk__label">{label}</div>
      <div className="tdk__value">{value}</div>
      {sub && <div className="tdk__sub">{sub}</div>}
    </div>
  );
}

// Tiny sparkline used in DC pulse cards
function Sparkline({ values, width = 100, height = 24, color = 'var(--ink-2)' }) {
  if (!values || values.length === 0) return null;
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const pad = 2;
  const dx = (width - pad * 2) / (values.length - 1);
  const pts = values.map((v, i) => {
    const x = pad + i * dx;
    const y = pad + (1 - (v - min) / range) * (height - pad * 2);
    return [x, y];
  });
  const d = pts.map(([x, y], i) => (i === 0 ? `M ${x} ${y}` : `L ${x} ${y}`)).join(' ');
  const last = pts[pts.length - 1];
  return (
    <svg viewBox={`0 0 ${width} ${height}`} width={width} height={height} className="spark">
      <path d={d} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={last[0]} cy={last[1]} r="2.2" fill={color} />
    </svg>
  );
}

// ---------- Per-DC pulse card ----------
function DcPulseCard({ dc, onOpenDc }) {
  const tierColor = dc.pulseTier === 'green' ? 'var(--green)' : dc.pulseTier === 'amber' ? 'var(--amber)' : 'var(--red)';
  return (
    <div className={`dc-pulse dc-pulse--${dc.pulseTier}`}>
      <div className="dc-pulse__head">
        <div className="dc-pulse__name-row">
          <span className={`dc-pulse__dot dc-pulse__dot--${dc.pulseTier}`}></span>
          <span className="dc-pulse__name">{dc.label}</span>
          {dc.primary && <span className="dc-pulse__primary">PRIMARY</span>}
        </div>
        <div className="dc-pulse__region">{dc.region}</div>
      </div>

      <div className="dc-pulse__hero">
        <div className="dc-pulse__hero-num">{dc.tripsToday}</div>
        <div className="dc-pulse__hero-lbl">trips today</div>
      </div>

      <div className="dc-pulse__breakdown">
        <span className="dc-pulse__b-item"><span className="v">{dc.inflight}</span> in-flight</span>
        <span className="dc-pulse__b-item"><span className="v">{dc.delivered}</span> delivered</span>
        <span className="dc-pulse__b-item"><span className="v">{dc.planned}</span> planned</span>
        {dc.held > 0 && <span className="dc-pulse__b-item dc-pulse__b-item--amber"><span className="v">{dc.held}</span> held</span>}
      </div>

      <div className="dc-pulse__risks">
        <div className={`dc-pulse__risk ${dc.otif > 0 ? 'dc-pulse__risk--red' : ''}`}>
          <span className="dc-pulse__risk-val">{dc.otif}</span>
          <span className="dc-pulse__risk-lbl">OTIF risk</span>
        </div>
        <div className={`dc-pulse__risk ${dc.lowUtil > 0 ? 'dc-pulse__risk--amber' : ''}`}>
          <span className="dc-pulse__risk-val">{dc.lowUtil}</span>
          <span className="dc-pulse__risk-lbl">low util</span>
        </div>
        <div className={`dc-pulse__risk ${dc.overweight > 0 ? 'dc-pulse__risk--red' : ''}`}>
          <span className="dc-pulse__risk-val">{dc.overweight}</span>
          <span className="dc-pulse__risk-lbl">overweight</span>
        </div>
      </div>

      <div className="dc-pulse__foot">
        <div className="dc-pulse__util">
          <span className="dc-pulse__util-lbl">avg util</span>
          <span className="dc-pulse__util-val">{dc.avgUtil}%</span>
          <Sparkline values={dc.sparkUtil} width={70} height={18} color={tierColor} />
        </div>
        <button className="dc-pulse__open" onClick={() => onOpenDc(dc.dc)}>Open in Tactical →</button>
      </div>

      <div className={`dc-pulse__status dc-pulse__status--${dc.pulseTier}`}>
        <span className="dc-pulse__status-lbl">STATUS</span>
        <span>{dc.pulseLabel}</span>
      </div>
    </div>
  );
}

// ---------- Wave health timeline ----------
function WaveHealth({ waves }) {
  return (
    <div className="wave-health">
      <div className="wave-health__head">
        <div className="wave-health__title">Wave-run health · last 6 waves</div>
        <div className="wave-health__sub">One per hour · current wave (W7) is live</div>
      </div>
      <div className="wave-health__strip">
        {waves.map(w => {
          const isLive = w.status === 'live';
          return (
            <div key={w.wave} className={`wh-wave wh-wave--${w.status}`}>
              <div className="wh-wave__bar"></div>
              <div className="wh-wave__label">{w.wave}</div>
              <div className="wh-wave__nums">
                {isLive ? (
                  <span className="wh-wave__live"><span className="wh-wave__live-dot"></span> live</span>
                ) : (
                  <>
                    <span className="wh-wave__num">{w.autoN}<span className="lbl">auto</span></span>
                    <span className={`wh-wave__num ${w.reviewN > 5 ? 'wh-wave__num--amber' : ''}`}>{w.reviewN}<span className="lbl">review</span></span>
                  </>
                )}
              </div>
              {!isLive && <div className="wh-wave__dur">{(w.durationS / 60).toFixed(1)}m</div>}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---------- Today vs Yesterday variance ----------
function VariancePanel({ variance }) {
  return (
    <div className="var-panel">
      <div className="var-panel__head">
        <div className="var-panel__title">Today vs yesterday</div>
        <div className="var-panel__sub">What's different · what to watch</div>
      </div>
      <div className="var-panel__list">
        {variance.map(v => (
          <div key={v.label} className={`var-row var-row--${v.kind}`}>
            <span className={`var-row__arrow var-row__arrow--${v.dir}`}>
              {v.dir === 'up' ? '↑' : v.dir === 'down' ? '↓' : '→'}
            </span>
            <div className="var-row__main">
              <div className="var-row__line1">
                <span className="var-row__label">{v.label}</span>
                <span className="var-row__nums">
                  <span className="var-row__today">{v.today}</span>
                  <span className="var-row__yest">vs {v.yesterday}</span>
                </span>
              </div>
              <div className="var-row__sub">{v.sub}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- On the clock table ----------
function OnTheClock({ items, scope, onOpenTrip }) {
  const filtered = scope === 'all' ? items : items.filter(i => i.dc === scope);
  return (
    <div className="otc">
      <div className="otc__head">
        <div className="otc__title">On the clock · next 8h</div>
        <div className="otc__sub">{filtered.length} delivery windows · sorted by urgency</div>
      </div>
      <div className="otc__table">
        <div className="otc__row otc__row--head">
          <span></span>
          <span>Trip</span>
          <span>DC</span>
          <span>Destination</span>
          <span>Customer</span>
          <span>Deadline</span>
          <span className="num">Hrs out</span>
          <span>Status</span>
          <span>Agent note</span>
          <span></span>
        </div>
        {filtered.map(it => (
          <div key={it.tripId} className={`otc__row otc__row--${it.risk}`} onClick={() => onOpenTrip(it.tripId)}>
            <span className={`otc__risk otc__risk--${it.risk}`}></span>
            <span className="otc__trip">{it.tripId}</span>
            <span className="otc__dc">{it.dc.toUpperCase()}</span>
            <span className="otc__dest">{it.dest}</span>
            <span className="otc__cust">{it.customer}</span>
            <span className="otc__deadline">{it.deadline}</span>
            <span className="num otc__hrs">
              <span className={`otc__hrs-val otc__hrs-val--${it.risk}`}>{it.hrsToDeadline}h</span>
            </span>
            <span><span className={`pill pill--${it.status === 'IN-TRANSIT' ? 'blue' : it.status === 'HELD' ? 'amber' : 'red'}`}>{it.status}</span></span>
            <span className="otc__note">
              <span className="otc__ai">TP</span>
              <span>{it.note}</span>
            </span>
            <button className="otc__open">Open →</button>
          </div>
        ))}
        {filtered.length === 0 && (
          <div className="otc__empty">No deliveries in scope.</div>
        )}
      </div>
    </div>
  );
}

// ---------- Agent decision stream ----------
function AgentStream({ items, scope }) {
  const filtered = scope === 'all' ? items : items.filter(i => i.dc === scope);
  const kindKind = (k) => k.startsWith('auto') ? 'green' :
                          k === 'notified' ? 'blue' :
                          k === 'awaiting TP' ? 'amber' : 'grey';
  return (
    <div className="stream">
      <div className="stream__head">
        <div className="stream__title">Agent stream · last hour</div>
        <div className="stream__sub">
          <span className="stream__live"><span className="stream__live-dot"></span> live</span>
          · {filtered.length} decisions
        </div>
      </div>
      <div className="stream__list">
        {filtered.map((it, i) => (
          <div key={i} className={`stream-row stream-row--${kindKind(it.kind)}`}>
            <span className="stream-row__ts">{it.ts}</span>
            <span className="stream-row__dc">{it.dc.toUpperCase()}</span>
            <span className="stream-row__trip">{it.tripId}</span>
            <span className={`stream-row__kind pill pill--${kindKind(it.kind)}`}>{it.kind}</span>
            <span className="stream-row__text">{it.text}</span>
            {it.dollars && <span className="stream-row__$">+${it.dollars}</span>}
          </div>
        ))}
        {filtered.length === 0 && <div className="otc__empty">No agent activity in this scope.</div>}
      </div>
    </div>
  );
}

// ---------- Main ----------
function TodayTab({ dcScope, onSwitchToTactical }) {
  const T = window.TODAY;
  const dcs = window.DCS;
  const scope = dcScope || 'all';

  // Pulse cards — filter to DCs in scope
  const visiblePulse = scope === 'all'
    ? T.pulse
    : T.pulse.filter(p => p.dc === scope);

  // Aggregate KPIs across visible DCs
  const agg = useTodayMemo(() => {
    const ps = visiblePulse;
    return {
      tripsToday: ps.reduce((a, p) => a + p.tripsToday, 0),
      inflight:   ps.reduce((a, p) => a + p.inflight, 0),
      delivered:  ps.reduce((a, p) => a + p.delivered, 0),
      planned:    ps.reduce((a, p) => a + p.planned, 0),
      otif:       ps.reduce((a, p) => a + p.otif, 0),
      held:       ps.reduce((a, p) => a + p.held, 0),
    };
  }, [visiblePulse]);

  const handleOpenTrip = (tripId) => {
    onSwitchToTactical && onSwitchToTactical({ tripId });
  };
  const handleOpenDc = (dcId) => {
    onSwitchToTactical && onSwitchToTactical({ dc: dcId });
  };

  const scopeLabel = scope === 'all'
    ? `${dcs.length} DCs`
    : dcs.find(d => d.id === scope)?.name + ' DC';

  return (
    <div className="today" data-screen-label="Today">
      {/* Hero header */}
      <div className="td-hero">
        <div className="td-hero__left">
          <div className="td-hero__eyebrow">
            <span className="td-hero__pulse"></span>
            TODAY · {T.timeNow}
          </div>
          <div className="td-hero__date">{T.date}</div>
          <div className="td-hero__one-liner">
            <span className="td-hero__big">{agg.tripsToday}</span> trips delivering today across {scopeLabel}.
            <span className="td-hero__strong"> {agg.otif} at OTIF risk</span> ·
            <span className="td-hero__strong"> {agg.inflight} in-flight</span> ·
            est. day cost <span className="td-hero__strong">${T.dayKpis.estDayCost.toLocaleString()}</span>
            <span className="td-hero__delta">{T.dayKpis.estDayCost > T.dayKpis.lastDayCost ? '+' : '−'}${Math.abs(T.dayKpis.estDayCost - T.dayKpis.lastDayCost).toLocaleString()} vs yesterday</span>
          </div>
        </div>
        <div className="td-hero__right">
          <button className="btn">⤓ Day briefing PDF</button>
          <button className="btn btn--primary" onClick={() => onSwitchToTactical && onSwitchToTactical({})}>Open Tactical →</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="td-kpis">
        <TodayKpi label="OTIF at risk"        value={agg.otif} sub={`$${T.dayKpis.otifPenalty$.toLocaleString()} penalty exposure`} kind="red" />
        <TodayKpi label="Trips planned"       value={agg.planned} sub={`${agg.held} held`} />
        <TodayKpi label="In-flight"           value={agg.inflight} sub="on plan" kind="green" />
        <TodayKpi label="Delivered today"     value={agg.delivered} sub="this morning" />
        <TodayKpi label="Agent decisions"     value={T.dayKpis.agentDecisionsToday} sub={`TP intervened ${T.dayKpis.tpDecisionsToday}×`} />
        <TodayKpi label="On-time YTD"         value={`${T.dayKpis.onTimeYTD}%`} sub="contract target 92%" kind="green" />
      </div>

      {/* Per-DC pulse */}
      <div className="td-section">
        <div className="td-section__head">
          <div>
            <div className="td-section__title">DC pulse {scope !== 'all' && '· (others hidden)'}</div>
            <div className="td-section__sub">Live per-DC snapshot · click any DC to drill into Tactical</div>
          </div>
        </div>
        <div className="td-dc-grid" style={{ gridTemplateColumns: `repeat(${Math.min(visiblePulse.length, 3)}, 1fr)` }}>
          {visiblePulse.map(p => (
            <DcPulseCard key={p.dc} dc={p} onOpenDc={handleOpenDc} />
          ))}
        </div>
      </div>

      {/* Two-col: Wave health + Variance */}
      <div className="td-two-col">
        <WaveHealth waves={T.waveHealth} />
        <VariancePanel variance={T.variance} />
      </div>

      {/* On the clock */}
      <div className="td-section">
        <OnTheClock items={T.onTheClock} scope={scope} onOpenTrip={handleOpenTrip} />
      </div>

      {/* Agent stream */}
      <div className="td-section">
        <AgentStream items={T.agentStream} scope={scope} />
      </div>
    </div>
  );
}

Object.assign(window, { TodayTab });
