/* global window, React */
// ============================================================
// Trip list — left column
// ============================================================

const { useState } = React;

function TripCard({ trip, selected, checked, onClick, onCheck, onEdit }) {
  const urgClass = `urg-${trip.urgency}`;
  const fleetPillKind = {
    private: 'green',
    dedicated: 'amber',
    market: 'blue',
    spot: 'red',
  }[trip.fleet];
  const utilFillClass = trip.utilState === 'low' ? 'low'
    : trip.utilState === 'red' ? 'over'
    : trip.utilState === 'amber' ? 'warn' : '';

  const minsAgoLabel = (m) => m < 60 ? `${m}m ago` : `${Math.round(m/60*10)/10}h ago`;

  return (
    <div
      className={`trip-card ${selected ? 'trip-card--selected' : ''}`}
      onClick={onClick}
      data-screen-label={`Trip ${trip.id}`}
    >
      <span className={`trip-card__urgency ${urgClass}`}></span>

      <div
        className={`trip-card__check ${checked ? 'on' : ''}`}
        onClick={(e) => { e.stopPropagation(); onCheck(); }}
        title="Select for bulk action"
      ></div>

      {trip.changedInLastRun && (
        <span className="trip-card__changed-pill changed-pill">
          <span className="dot"></span>
          UPD · {minsAgoLabel(trip.updatedMinsAgo)}
        </span>
      )}

      <div className="trip-card__row1">
        <span className="trip-id">{trip.id}</span>
        <span className={`pill pill--${fleetPillKind}`}>{trip.fleetLabel}</span>
      </div>

      <div className="trip-card__row2">
        {trip.route.from}
        <span className="arrow">→</span>
        {trip.route.to}
      </div>

      <div className="trip-card__customer">{trip.customer}</div>

      <div className="trip-card__chips">
        {trip.chips.map((c, i) => (
          <span key={i} className={`chip chip--${c.kind}`}>{c.label}</span>
        ))}
      </div>

      <div className="trip-card__row4">
        <div className="util-mini">
          <div
            className={`util-mini__fill ${utilFillClass}`}
            style={{ width: `${Math.min(trip.util, 100)}%` }}
          ></div>
        </div>
        <span className="util-pct">{trip.util}%</span>
        <span className={`window-pill ${trip.window.state}`}>
          <span className="ic">{trip.window.icon}</span>
          {trip.window.value}
        </span>
      </div>

      <button
        className="trip-card__edit"
        onClick={(e) => { e.stopPropagation(); onEdit(); }}
        title="Edit trip"
      >✎</button>
    </div>
  );
}

function TripList({ trips, selectedId, onSelect, onBatchApprove, checked, onCheck, onClearChecks, onEdit, onBulkEdit }) {
  const [filter, setFilter] = useState('action');

  const filters = [
    { id: 'action',  label: 'Needs action',         n: trips.length },
    { id: 'changed', label: 'Changed',              n: trips.filter(t => t.changedInLastRun).length },
    { id: 'recent',  label: '< 2h',                 n: trips.filter(t => t.updatedMinsAgo < 120).length },
    { id: 'held',    label: 'HELD',                 n: trips.filter(t => /HELD/i.test(t.chips.map(c=>c.label).join(' '))).length },
  ];

  const filtered = trips.filter(t => {
    if (filter === 'changed') return t.changedInLastRun;
    if (filter === 'recent')  return t.updatedMinsAgo < 120;
    if (filter === 'held')    return /HELD/i.test(t.chips.map(c=>c.label).join(' '));
    return true; // 'action' shows all needing review
  });

  const numChecked = checked.size;

  return (
    <aside className="triplist" data-screen-label="Trip list">
      {numChecked > 0 && (
        <div className="triplist__bulk">
          <span className="triplist__bulk-count">{numChecked}</span>
          <span>trip{numChecked === 1 ? '' : 's'} selected</span>
          <div className="triplist__bulk-actions">
            <button className="triplist__bulk-btn" onClick={onClearChecks}>Clear</button>
            <button className="triplist__bulk-btn" onClick={onBulkEdit}>✎ Edit</button>
            <button className="triplist__bulk-btn triplist__bulk-btn--primary" onClick={onBatchApprove}>✓ Confirm all</button>
          </div>
        </div>
      )}

      <div className="triplist__header">
        <div className="triplist__eyebrow">
          <span className="triplist__eyebrow-dot"></span>
          LAST WAVE · WAVE 7 · 23M AGO
        </div>
        <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap:8 }}>
          <div className="triplist__title">Updated this run</div>
          {selectedId && (
            <button
              style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-3)', letterSpacing: '0.04em' }}
              onClick={() => onSelect(null)}
              title="Show all trips"
            >← ALL TRIPS</button>
          )}
        </div>
        <div className="triplist__sub">{trips.length} trips changed by agent · need TP review</div>
        <div className="triplist__filters">
          {filters.map(f => (
            <button
              key={f.id}
              className={`filter-chip ${filter === f.id ? 'filter-chip--active' : ''}`}
              onClick={() => setFilter(f.id)}
            >
              {f.label} <span className="n">{f.n}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="triplist__scroll">
        <div className="triplist__section-label">
          <span>Needs review · {filtered.length}</span>
        </div>
        {filtered.map(t => (
          <TripCard
            key={t.id}
            trip={t}
            selected={t.id === selectedId}
            checked={checked.has(t.id)}
            onClick={() => onSelect(t.id)}
            onCheck={() => onCheck(t.id)}
            onEdit={() => onEdit(t.id)}
          />
        ))}

        <div className="triplist__section-label">
          <span>Agent pre-cleared · 12 · this wave</span>
          <button className="batch-btn" onClick={onBatchApprove}>Batch approve →</button>
        </div>
        {window.PREAPPROVED.map(p => (
          <div key={p.id} className="trip-card" style={{ opacity: 0.78 }}>
            <span className="trip-card__urgency urg-none"></span>
            <span className="trip-card__check" style={{ visibility:'hidden' }}></span>
            <div className="trip-card__row1">
              <span className="trip-id">{p.id}</span>
              <span className="pill pill--green">Pre-cleared</span>
            </div>
            <div className="trip-card__row2" style={{ fontSize: '13.5px' }}>{p.route}</div>
            <div className="trip-card__row4" style={{ marginTop: 4 }}>
              <div className="util-mini">
                <div className="util-mini__fill" style={{ width: `${p.util}%` }}></div>
              </div>
              <span className="util-pct">{p.util}%</span>
              <span className="window-pill green"><span className="ic">✓</span>{p.window}</span>
            </div>
          </div>
        ))}
      </div>
    </aside>
  );
}

Object.assign(window, { TripList });
