/* global window, React */
// ============================================================
// All-trips overview — shown when no trip is selected.
// Displays trips ACROSS WAVES (the system runs a wave every hour
// and trips accumulate). Filters by utilization / route / fleet / order id.
// Clicking a "review needed" trip drills into detail; thin trips
// (already dispatched / pre-cleared / completed) are read-only.
// ============================================================

const { useState: useOvState, useMemo: useOvMemo } = React;

function Kpi({ label, value, sub, kind }) {
  return (
    <div className={`kpi ${kind ? `kpi--${kind}` : ''}`}>
      <div className="kpi__label">{label}</div>
      <div className="kpi__value">{value}</div>
      {sub && <div className="kpi__sub">{sub}</div>}
    </div>);

}

// Status pill — colour-coded
function StatusPill({ status }) {
  const map = {
    'PLANNED': { cls: 'pill--red', label: 'Needs review' },
    'HELD': { cls: 'pill--amber', label: 'HELD' },
    'PRE-CLEARED': { cls: 'pill--green', label: 'Pre-cleared' },
    'IN-TRANSIT': { cls: 'pill--blue', label: 'In-transit' },
    'DELIVERED': { cls: 'pill--grey', label: 'Delivered' }
  };
  const m = map[status] || { cls: 'pill--grey', label: status };
  return <span className={`pill ${m.cls}`}>{m.label}</span>;
}

function WaveBadge({ wave }) {
  // wave string like "Wave 7" — extract number
  const n = (wave || '').replace('Wave ', 'W');
  return <span className="wave-badge">{n}</span>;
}

// Compact filter dropdown
function FilterSelect({ label, value, options, onChange }) {
  return (
    <label className="ov-filter">
      <span className="ov-filter__label">{label}</span>
      <select className="ov-filter__select" value={value} onChange={(e) => onChange(e.target.value)}>
        {options.map((o) =>
        <option key={o.value} value={o.value}>{o.label}</option>
        )}
      </select>
    </label>);

}

function OverviewBoard({ trips: detailedTrips, checked, onCheck, onClearChecks, onOpen, onEdit, onBulkEdit, onBatch, onToast, dcScope = 'all', dcs = [] }) {
  const baseTrips = window.ALL_TRIPS || detailedTrips;
  const allTrips = dcScope === 'all' ? baseTrips : baseTrips.filter((t) => (t.dc || 'chi') === dcScope);
  const showDcCol = dcScope === 'all';
  const numChecked = checked.size;

  // ---------- filter state ----------
  const [fUtil, setFUtil] = useOvState('all'); // all | low | balanced | tight | over
  const [fRoute, setFRoute] = useOvState('all');
  const [fFleet, setFFleet] = useOvState('all');
  const [fOrder, setFOrder] = useOvState(''); // text search

  // build route options (unique destinations)
  const routeOptions = useOvMemo(() => {
    const dests = Array.from(new Set(allTrips.map((t) => t.route.to.split(' ')[0])));
    dests.sort();
    return [{ value: 'all', label: 'All routes' }, ...dests.map((d) => ({ value: d, label: 'Chi → ' + d }))];
  }, [allTrips]);

  const fleetOptions = [
  { value: 'all', label: 'All fleets' },
  { value: 'private', label: 'Private' },
  { value: 'dedicated', label: 'Dedicated' },
  { value: 'market', label: 'Market' },
  { value: 'spot', label: 'Spot' }];


  const utilOptions = [
  { value: 'all', label: 'All util' },
  { value: 'low', label: '< 80% low' },
  { value: 'balanced', label: '80–95%' },
  { value: 'tight', label: '95–100%' },
  { value: 'over', label: '> 100% over' }];


  // ---------- filter logic ----------
  const filtered = useOvMemo(() => {
    return allTrips.filter((t) => {
      if (fFleet !== 'all' && t.fleet !== fFleet) return false;
      if (fRoute !== 'all' && !t.route.to.startsWith(fRoute)) return false;
      if (fUtil !== 'all') {
        const u = t.util;
        if (fUtil === 'low' && !(u < 80)) return false;
        if (fUtil === 'balanced' && !(u >= 80 && u < 95)) return false;
        if (fUtil === 'tight' && !(u >= 95 && u <= 100)) return false;
        if (fUtil === 'over' && !(u > 100)) return false;
      }
      if (fOrder.trim()) {
        const q = fOrder.trim().toLowerCase();
        const inOrders = (t.orders || []).some((o) => (o.id || '').toLowerCase().includes(q));
        const inTrip = (t.id || '').toLowerCase().includes(q);
        if (!inOrders && !inTrip) return false;
      }
      return true;
    });
  }, [allTrips, fFleet, fRoute, fUtil, fOrder]);

  const hasFilter = fUtil !== 'all' || fRoute !== 'all' || fFleet !== 'all' || fOrder.trim();

  // KPIs reflect filtered view (or overall when no filter)
  const summary = useOvMemo(() => {
    const review = filtered.filter((t) => t.status === 'PLANNED').length;
    const held = filtered.filter((t) => t.status === 'HELD').length;
    const preC = filtered.filter((t) => t.status === 'PRE-CLEARED').length;
    const flight = filtered.filter((t) => t.status === 'IN-TRANSIT').length;
    const done = filtered.filter((t) => t.status === 'DELIVERED').length;
    const otif = filtered.filter((t) => t.chips && t.chips.some((c) => /OTIF/i.test(c.label))).length;
    const over = filtered.filter((t) => t.util > 100).length;
    const lowU = filtered.filter((t) => t.util < 80).length;
    return { review, held, preC, flight, done, otif, over, lowU };
  }, [filtered]);

  const fleetPillKind = { private: 'green', dedicated: 'amber', market: 'blue', spot: 'red' };

  const clickRow = (trip) => {
    if (trip.isThin) {
      onToast && onToast(`${trip.id} · ${trip.status.toLowerCase()} — read-only (${trip.wave}). No actions available.`);
      return;
    }
    onOpen(trip.id);
  };

  return (
    <div className="overview" data-screen-label="All trips overview">
      <div className="overview__head">
        <div>
          <div className="overview__title">All active trips{dcScope !== 'all' && ` · ${(dcs.find((d) => d.id === dcScope)?.name || dcScope).toUpperCase()}`}</div>
          <div className="overview__sub">
            Live across waves · system runs every hour ·
            <span className="overview__sub-em"> {summary.review + summary.held} need TP review</span> ·
            {summary.preC} pre-cleared · {summary.flight} in-flight · {summary.done} delivered (wave 5)
            {dcScope !== 'all' && <span style={{ marginLeft: 8, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)' }}>scoped to {dcScope.toUpperCase()}</span>}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn" onClick={onBulkEdit} disabled={numChecked === 0} style={{ opacity: numChecked === 0 ? 0.5 : 1 }}>
            ✎ Edit selected ({numChecked})
          </button>
          <button className="btn btn--primary" onClick={onBatch}>✓ Batch approve {summary.preC} pre-cleared</button>
        </div>
      </div>

      <div className="overview__kpis">
        <Kpi label="Total trips · visible" value={filtered.length} sub={`of ${allTrips.length} across W5–W7`} />
        <Kpi label="Needs review" value={summary.review} sub="this wave · planned" kind="red" />
        <Kpi label="HELD" value={summary.held} sub="inventory pending" kind="amber" />
        <Kpi label="OTIF-sensitive" value={summary.otif} sub="Walmart, Costco" kind="amber" />
        <Kpi label="Low utilisation" value={summary.lowU} sub="<80% threshold" kind="amber" />
        <Kpi label="Overweight" value={summary.over} sub="must split" kind="red" />
      </div>

      {/* Filter bar */}
      <div className="ov-filters">
        <div className="ov-filters__left">
          <FilterSelect label="Utilization" value={fUtil} options={utilOptions} onChange={setFUtil} />
          <FilterSelect label="Route" value={fRoute} options={routeOptions} onChange={setFRoute} />
          <FilterSelect label="Fleet" value={fFleet} options={fleetOptions} onChange={setFFleet} />
          <label className="ov-filter">
            <span className="ov-filter__label">Order ID</span>
            <input
              className="ov-filter__input"
              type="text"
              placeholder="ORD-… or TR-…"
              value={fOrder}
              onChange={(e) => setFOrder(e.target.value)} />
            
          </label>
          {hasFilter &&
          <button className="ov-filters__clear" onClick={() => {setFUtil('all');setFRoute('all');setFFleet('all');setFOrder('');}}>
              Clear filters ×
            </button>
          }
        </div>
        <div className="ov-filters__right">
          <span className="ov-filters__count">{filtered.length} of {allTrips.length} trips</span>
        </div>
      </div>

      <div className="overview__section-title">
        <span>Trip detail · {filtered.length} match{filtered.length === 1 ? '' : 'es'}</span>
        <span style={{ fontFamily: 'var(--font-sans)', textTransform: 'none', letterSpacing: 0, fontSize: 11 }}>
          Click any row to open · ✎ to edit · ☐ to multi-select · pre-cleared / in-flight are read-only
        </span>
      </div>

      <div className={`trips-table trips-table--cross ${showDcCol ? 'trips-table--withdc' : ''}`}>
        <div className="trips-table__head">
          <span></span>
          <span></span>
          <span>Trip ID</span>
          {showDcCol && <span>DC</span>}
          <span>Wave</span>
          <span style={{ width: "101px" }}>Status</span>
          <span>Route / Customer</span>
          <span>Fleet</span>
          <span className="num">Util</span>
          <span className="num">Weight</span>
          <span className="num">Orders</span>
          <span>Window</span>
          <span>Agent suggestion</span>
          <span></span>
        </div>

        {filtered.map((t) => {
          const totalLbs = t.orders.reduce((a, o) => a + (o.lbs || 0), 0) || parseInt(t.weight.replace(/[^\d]/g, ''), 10) || 0;
          const isReadOnly = t.isThin;
          return (
            <div
              key={t.id}
              className={`trips-row ${isReadOnly ? 'trips-row--readonly' : ''}`}
              onClick={() => clickRow(t)}>
              
              <span className={`trips-row__urgency urg-${t.urgency}`}></span>

              {!isReadOnly ?
              <div
                className={`trips-row__check ${checked.has(t.id) ? 'on' : ''}`}
                onClick={(e) => {e.stopPropagation();onCheck(t.id);}}>
              </div> :

              <span></span>
              }

              <div className="trips-row__id" style={{ width: "28px" }}>
                {t.id}
                {t.changedInLastRun && <span className="sub" style={{ color: 'var(--purple-2)', fontWeight: 600 }}>
                  upd {t.updatedMinsAgo < 60 ? `${t.updatedMinsAgo}m` : `${(t.updatedMinsAgo / 60).toFixed(1)}h`} ago
                </span>}
              </div>

              {showDcCol &&
              <div>
                  <span className={`dc-chip dc-chip--${t.dc || 'chi'}`}>{(t.dc || 'chi').toUpperCase()}</span>
                </div>
              }

              <div>
                <WaveBadge wave={t.wave} />
              </div>

              <div>
                <StatusPill status={t.status} />
              </div>

              <div className="trips-row__route">
                {t.route.from}<span className="arrow">→</span>{t.route.to}
                <span className="cust">{t.customer}</span>
              </div>

              <div>
                <span className={`pill pill--${fleetPillKind[t.fleet]}`}>{t.fleetLabel}</span>
              </div>

              <div className="trips-row__num">
                <span style={{
                  color: t.util > 100 ? 'var(--red-2)' : t.util < 80 ? 'var(--amber-2)' : 'var(--ink)',
                  fontWeight: 600
                }}>{t.util}%</span>
              </div>

              <div className="trips-row__num">
                {totalLbs.toLocaleString()}
                <span className="sub">lbs</span>
              </div>

              <div className="trips-row__num">
                {t.orders.length}
              </div>

              <div className="trips-row__num" style={{ textAlign: 'left' }}>
                <span style={{
                  color: t.window.state === 'red' ? 'var(--red)' : t.window.state === 'amber' ? 'var(--amber)' : 'var(--green-2)',
                  fontFamily: 'var(--font-mono)', fontSize: 11.5
                }}>
                  {t.window.icon} {t.window.value}
                </span>
              </div>

              <div className="trips-row__suggestion">
                <span className="ai">TP</span>
                <span className="text" style={{ color: isReadOnly ? 'var(--ink-3)' : 'var(--ink-2)' }}>{t.shortSuggestion}</span>
              </div>

              <div style={{ display: 'flex', gap: 4, alignItems: 'center', justifyContent: 'flex-end' }}>
                {!isReadOnly ?
                <>
                    <button
                    className="btn btn--ghost btn--icon"
                    style={{ padding: '5px 7px', fontSize: 13 }}
                    onClick={(e) => {e.stopPropagation();onEdit(t.id);}}
                    title="Edit trip">
                    ✎</button>
                    <button
                    className="trips-row__action"
                    onClick={(e) => {e.stopPropagation();onOpen(t.id);}}>
                    Open →</button>
                  </> :

                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.04em' }}>
                    READ-ONLY
                  </span>
                }
              </div>
            </div>);

        })}

        {filtered.length === 0 &&
        <div style={{ padding: '32px 14px', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>
            No trips match the current filters.
          </div>
        }
      </div>
    </div>);

}

Object.assign(window, { OverviewBoard });