/* global window, React, LoadCompositionTab, RoutingTab, FleetTab, LoadViewTab */
// ============================================================
// Trip detail panel — header + tab nav + content
// ============================================================

const { useState: useDetailState } = React;

function DetailHeader({ trip, focus, onToggleFocus, onConfirm, onClose, onHold, onSplit, onCancel, onEdit, lpStatus }) {
  // Status pill — lpStatus overrides
  let statusLabel = trip.status;
  let statusKind = 'pill--grey';
  if (lpStatus && lpStatus.status === 'PENDING') {
    statusLabel = 'WAITING · LOAD PLANNER';
    statusKind = 'pill--amber';
  } else if (lpStatus && lpStatus.status === 'CONFIRMED') {
    statusLabel = 'LP-CONFIRMED · ' + trip.status;
    statusKind = 'pill--green';
  }
  return (
    <div className="detail__header">
      <div className="detail__head-row1">
        {onClose && (
          <button
            className="detail__back"
            onClick={onClose}
            title="Close trip · back to all trips"
          >
            <span style={{ fontSize: 14, marginRight: 4 }}>←</span> All trips
          </button>
        )}
        <span className="id">{trip.id}</span>
        <span className="sep">·</span>
        <span className={`pill ${statusKind}`} style={{ fontSize: 9.5, padding: '1px 6px' }}>{statusLabel}</span>
        <span className="sep">·</span>
        <span>{trip.wave}</span>
        <span style={{ marginLeft: 'auto' }}>
          <button className="btn btn--ghost btn--icon" onClick={onToggleFocus} title={focus ? 'Restore columns' : 'Maximise detail'}>
            {focus ? '⤡' : '⤢'}
          </button>
        </span>
      </div>

      <div className="detail__head-row2">
        <div className="detail__title">
          {trip.route.from}
          <span className="arrow">→</span>
          {trip.route.to}
        </div>
        <div className="detail__actions">
          <button className="btn btn--ghost" onClick={onEdit} title="Edit trip">✎ Edit</button>
          <button className="btn btn--ghost" onClick={onHold}>Hold</button>
          <button className="btn" onClick={onSplit}>Split load</button>
          <button className="btn btn--danger" onClick={onCancel}>Cancel</button>
          <button className="btn btn--primary" onClick={onConfirm}>
            ✓ Confirm trip
          </button>
        </div>
      </div>

      <div className="detail__meta">
        <span className="meta-item">
          <span className={`pill pill--${ { private:'green', dedicated:'amber', market:'blue', spot:'red' }[trip.fleet] }`}>{trip.fleetLabel}</span>
        </span>
        <span className="sep"></span>
        <span className="meta-item">Window<span className={`v ${trip.window.state === 'red' ? '' : ''}`} style={{
          color: trip.window.state === 'red' ? 'var(--red)' :
                 trip.window.state === 'amber' ? 'var(--amber)' :
                 'var(--green)'
        }}>{trip.window.icon} {trip.window.value}</span></span>
        <span className="sep"></span>
        <span className="meta-item">Mode<span className="v">{trip.mode}</span></span>
        <span className="sep"></span>
        <span className="meta-item">Weight<span className="v">{trip.weight}</span></span>
        <span className="sep"></span>
        <span className="meta-item">Est. cost<span className="v">{trip.cost}</span></span>
        {trip.chips.some(c => /OTIF/i.test(c.label)) && (
          <>
            <span className="sep"></span>
            <span className="chip chip--red">OTIF risk</span>
          </>
        )}
      </div>
    </div>
  );
}

function DetailPanel({ trip, focus, onToggleFocus, onConfirm, onClose, onHold, onSplit, onCancel, onEdit, lpStatus, onSendToLoadPlanner }) {
  const [tab, setTab] = useDetailState('load');

  // Reset to load tab when trip changes
  React.useEffect(() => { setTab('load'); }, [trip.id]);

  const tabs = [
    { id: 'load',    num: '1', label: 'Load composition' },
    { id: 'routing', num: '2', label: 'Routing feasibility' },
    { id: 'fleet',   num: '3', label: 'Fleet & carrier' },
    { id: 'view',    num: '4', label: '3D load view' },
  ];

  return (
    <section className="detail" data-screen-label={`Detail · ${trip.id}`}>
      <DetailHeader
        trip={trip}
        focus={focus}
        onToggleFocus={onToggleFocus}
        onConfirm={onConfirm}
        onClose={onClose}
        onHold={onHold}
        onSplit={onSplit}
        onCancel={onCancel}
        onEdit={onEdit}
        lpStatus={lpStatus}
      />
      <div className="detail__tabs" style={{ paddingLeft: 22, paddingRight: 22 }}>
        {tabs.map(t => (
          <button
            key={t.id}
            className={`detail__tab ${tab === t.id ? 'detail__tab--active' : ''}`}
            onClick={() => setTab(t.id)}
          >
            <span className="num">{t.num}</span>
            {t.label}
            {t.id === 'view' && lpStatus && lpStatus.status === 'PENDING' && (
              <span className="detail__tab-badge detail__tab-badge--amber">●</span>
            )}
          </button>
        ))}
      </div>
      <div className="detail__scroll">
        {tab === 'load'    && <LoadCompositionTab trip={trip} />}
        {tab === 'routing' && <RoutingTab          trip={trip} />}
        {tab === 'fleet'   && <FleetTab            trip={trip} onConfirm={onConfirm} />}
        {tab === 'view'    && <LoadViewTab         trip={trip} lpStatus={lpStatus} onSendToLoadPlanner={onSendToLoadPlanner} />}
      </div>
    </section>
  );
}

Object.assign(window, { DetailPanel });
