/* global window, React, ReactDOM, TRIPS, TripList, DetailPanel, DemandSidebar, AgentStrip, OverviewBoard, ConfirmModal, EditDrawer, StrategicHorizon, HoldModal, CancelModal, SplitModal, AgentPolicy, TodayTab */
// ============================================================
// Top-level app — view tabs, layout, state
// Multi-DC aware: dcScope filters everything ('all' or a DC id).
// ============================================================

const { useState: useAppState, useRef: useAppRef, useEffect: useAppEffect } = React;

// ---------- DC scope selector (lives in the topbar) ----------
function DcScopeSelector({ scope, onChange, dcs }) {
  const [open, setOpen] = useAppState(false);
  const ref = useAppRef(null);

  useAppEffect(() => {
    const close = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

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

  const primary = dcs.find((d) => d.primary);

  return (
    <div className="dc-scope" ref={ref}>
      <button className={`dc-scope__btn ${open ? 'open' : ''}`} onClick={() => setOpen((v) => !v)} style={{ margin: "5px 0px 0px 8px" }}>
        <span className="dc-scope__icon">⌂</span>
        <span className="dc-scope__main">
          <span className="dc-scope__eyebrow">SCOPE</span>
          <span className="dc-scope__label">{currentLabel}</span>
        </span>
        <span className="dc-scope__chev">▾</span>
      </button>
      {open &&
      <div className="dc-scope__menu">
          <div className="dc-scope__menu-section">
            <div className="dc-scope__menu-eyebrow">AGGREGATE</div>
            <button
            className={`dc-scope__opt ${scope === 'all' ? 'on' : ''}`}
            onClick={() => {onChange('all');setOpen(false);}}>
              <span className="dc-scope__opt-name">All my DCs</span>
              <span className="dc-scope__opt-meta">
                {dcs.reduce((a, d) => a + d.trips, 0)} trips · {dcs.reduce((a, d) => a + d.otif, 0)} OTIF risk
              </span>
            </button>
          </div>
          <div className="dc-scope__menu-section">
            <div className="dc-scope__menu-eyebrow">SINGLE DC</div>
            {dcs.map((d) =>
          <button
            key={d.id}
            className={`dc-scope__opt ${scope === d.id ? 'on' : ''}`}
            onClick={() => {onChange(d.id);setOpen(false);}}>
                <span className="dc-scope__opt-name">
                  {d.name} DC
                  {d.primary && <span className="dc-scope__opt-primary">PRIMARY</span>}
                </span>
                <span className="dc-scope__opt-meta">{d.region} · {d.trips} trips · {d.lanes} lanes</span>
              </button>
          )}
          </div>
        </div>
      }
    </div>);

}

function TopBar({ view, onView, scope, onScope, dcs }) {
  const views = [
  { id: 'today', label: 'Today' },
  { id: 'tactical', label: 'Tactical', count: '7' },
  { id: 'strategic', label: 'Strategic horizon' },
  { id: 'policy', label: 'Agent policy' }];

  return (
    <div className="topbar">
      <div className="topbar__brand">
        <div className="topbar__brand-mark"></div>
        <div className="topbar__brand-text">
          Mojro
          <span className="slash">/</span>
          <span className="sub">Transportation Planner</span>
        </div>
      </div>
      <DcScopeSelector scope={scope} onChange={onScope} dcs={dcs} />
      <div className="topbar__tabs">
        {views.map((v) =>
        <button
          key={v.id}
          className={`topbar__tab ${view === v.id ? 'topbar__tab--active' : ''}`}
          onClick={() => onView(v.id)}>
          
            {v.label}
            {v.count && <span className="count">{v.count}</span>}
          </button>
        )}
      </div>
      <div className="topbar__right">
        <div className="wave-indicator">
          <span className="wave-dot"></span>
          <span className="wave-label">Wave 7 running</span>
          <span className="wave-meta">· next in 23m</span>
        </div>
        <div className="topbar__user">
          <span className="avatar">JM</span>
          <span style={{ color: 'var(--ink-2)' }}>J. Morales · TP</span>
        </div>
      </div>
    </div>);

}

function Placeholder({ title, body }) {
  return (
    <div className="placeholder" data-screen-label={title}>
      <div className="placeholder__title">{title}</div>
      <div className="placeholder__body">{body}</div>
    </div>);

}

function App() {
  const [view, setView] = useAppState('today');
  const [dcScope, setDcScope] = useAppState('all'); // 'all' | dc.id
  // selectedId === null → overview mode
  const [selectedId, setSelectedId] = useAppState(null);
  const [focus, setFocus] = useAppState(false);
  const [agentOpen, setAgentOpen] = useAppState(true);
  const [toast, setToast] = useAppState(null);
  const [checked, setChecked] = useAppState(new Set());
  const [confirmOpen, setConfirmOpen] = useAppState(false);
  const [editingTripId, setEditingTripId] = useAppState(null); // single trip id
  const [bulkEditing, setBulkEditing] = useAppState(false);

  // Trip-action modals (Hold / Cancel / Split)
  const [holdOpen, setHoldOpen] = useAppState(false);
  const [cancelOpen, setCancelOpen] = useAppState(false);
  const [splitOpen, setSplitOpen] = useAppState(false);

  // Load-planner statuses keyed by trip id. Status: 'PENDING' | 'CONFIRMED'.
  const [lpStatuses, setLpStatuses] = useAppState({});

  // Filter trips by scope. DC mapping: each trip has a `dc` field.
  // The detailed 7 trips are all Chicago (chi).
  const tripsInScope = dcScope === 'all' ?
  TRIPS :
  TRIPS.filter((t) => t.dc === dcScope);

  const trip = selectedId ? TRIPS.find((t) => t.id === selectedId) || TRIPS[0] : null;
  const editingTrip = editingTripId ? TRIPS.find((t) => t.id === editingTripId) : null;
  const editingMulti = bulkEditing ? TRIPS.filter((t) => checked.has(t.id)) : null;

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

  const onConfirm = () => {setConfirmOpen(true);};

  const onConfirmPicked = (opt) => {
    if (opt && opt.unavailable) return;
    const label = opt && opt.name ? opt.name : 'recommended carrier';
    showToast(`✓ ${trip.id} CONFIRMED → ${label}. Load instructions sent to WMS. ${opt && opt.kind === 'private' ? 'DAE triggered.' : 'Tender fired.'}`);
    setConfirmOpen(false);
  };

  const onBatch = () => {
    showToast('✓ 12 pre-cleared trips auto-confirmed by agent. Tenders + DAE dispatched.');
  };

  const toggleCheck = (id) => {
    setChecked((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);else
      next.add(id);
      return next;
    });
  };
  const clearChecks = () => setChecked(new Set());

  const onEditSave = (vals) => {
    const targetLabel = bulkEditing ?
    `${editingMulti.length} trips` :
    editingTrip.id;
    showToast(`✓ ${targetLabel} updated · feasibility re-run · audit logged.`);
    setEditingTripId(null);
    setBulkEditing(false);
    if (bulkEditing) clearChecks();
  };

  const overviewMode = view === 'tactical' && !selectedId;

  // Trip action handlers
  const onHoldConfirm = (data) => {
    showToast(`✓ ${trip.id} placed on HOLD · reason: ${data.reason} · revisit ${data.until}.`);
    setHoldOpen(false);
  };
  const onCancelConfirm = (data) => {
    showToast(`✕ ${trip.id} CANCELLED · ${data.returnOrders ? trip.orders.length + ' orders returned to pool' : 'orders dropped'}${data.notifyCustomer ? ' · customer notified' : ''}.`);
    setCancelOpen(false);
    setSelectedId(null);
  };
  const onSplitConfirm = (data) => {
    showToast(`✓ ${trip.id} split → ${data.newTripId} created with ${data.move.length} order${data.move.length === 1 ? '' : 's'} · feasibility re-run on both.`);
    setSplitOpen(false);
  };

  const onSendToLoadPlanner = (data) => {
    if (data.kind === 'cancel') {
      setLpStatuses((prev) => {const next = { ...prev };delete next[trip.id];return next;});
      showToast(`Load planner request for ${trip.id} cancelled.`);
      return;
    }
    setLpStatuses((prev) => ({
      ...prev,
      [trip.id]: { status: 'PENDING', planner: data.planner, note: data.note, at: data.at }
    }));
    showToast(`⇨ ${trip.id} sent to ${data.planner.name} for load-plan confirmation · trip now WAITING-LP.`);
    const tripId = trip.id;
    setTimeout(() => {
      setLpStatuses((prev) => prev[tripId] && prev[tripId].status === 'PENDING' ?
      { ...prev, [tripId]: { ...prev[tripId], status: 'CONFIRMED' } } :
      prev);
    }, 6000);
  };

  const currentLpStatus = trip ? lpStatuses[trip.id] : null;

  // From Today tab: jump into Tactical, optionally focused on a DC or a trip
  const switchToTactical = ({ dc, tripId }) => {
    if (dc) setDcScope(dc);
    if (tripId) setSelectedId(tripId);
    setView('tactical');
  };

  return (
    <div className="app">
      <TopBar view={view} onView={setView} scope={dcScope} onScope={setDcScope} dcs={window.DCS || []} />

      {view === 'today' &&
      <TodayTab dcScope={dcScope} onSwitchToTactical={switchToTactical} />
      }

      {view === 'tactical' &&
      <div className={`main ${focus ? 'focus' : ''} ${overviewMode ? 'overview' : ''}`}>
          {/* Trip list always present in tactical, except when focus is on */}
          {!focus &&
        <TripList
          trips={tripsInScope}
          selectedId={selectedId}
          onSelect={setSelectedId}
          onBatchApprove={onBatch}
          checked={checked}
          onCheck={toggleCheck}
          onClearChecks={clearChecks}
          onEdit={(id) => setEditingTripId(id)}
          onBulkEdit={() => setBulkEditing(true)} />

        }

          {overviewMode ?
        <OverviewBoard
          trips={tripsInScope}
          checked={checked}
          onCheck={toggleCheck}
          onClearChecks={clearChecks}
          onOpen={setSelectedId}
          onEdit={(id) => setEditingTripId(id)}
          onToast={showToast}
          onBulkEdit={() => setBulkEditing(true)}
          onBatch={onBatch}
          dcScope={dcScope}
          dcs={window.DCS || []} /> :


        <DetailPanel
          trip={trip}
          focus={focus}
          onToggleFocus={() => setFocus((f) => !f)}
          onConfirm={onConfirm}
          onClose={() => {setSelectedId(null);setFocus(false);}}
          onHold={() => setHoldOpen(true)}
          onSplit={() => setSplitOpen(true)}
          onCancel={() => setCancelOpen(true)}
          onEdit={() => setEditingTripId(trip.id)}
          lpStatus={currentLpStatus}
          onSendToLoadPlanner={onSendToLoadPlanner} />

        }

          {!overviewMode && !focus && <DemandSidebar trip={trip} />}

          <AgentStrip
          trip={trip}
          overview={overviewMode}
          expanded={agentOpen}
          onToggle={() => setAgentOpen((o) => !o)} />
        
        </div>
      }

      {view === 'strategic' &&
      <StrategicHorizon />
      }

      {view === 'policy' &&
      <AgentPolicy />
      }

      {/* Modals & drawers */}
      {confirmOpen && trip &&
      <ConfirmModal
        trip={trip}
        onCancel={() => setConfirmOpen(false)}
        onConfirm={onConfirmPicked} />

      }

      {holdOpen && trip &&
      <HoldModal
        trip={trip}
        onCancel={() => setHoldOpen(false)}
        onConfirm={onHoldConfirm} />

      }

      {cancelOpen && trip &&
      <CancelModal
        trip={trip}
        onCancel={() => setCancelOpen(false)}
        onConfirm={onCancelConfirm} />

      }

      {splitOpen && trip &&
      <SplitModal
        trip={trip}
        onCancel={() => setSplitOpen(false)}
        onConfirm={onSplitConfirm} />

      }

      {editingTrip &&
      <EditDrawer
        trip={editingTrip}
        onClose={() => setEditingTripId(null)}
        onSave={onEditSave} />

      }

      {bulkEditing && editingMulti && editingMulti.length > 0 &&
      <EditDrawer
        trip={null}
        trips={editingMulti}
        onClose={() => setBulkEditing(false)}
        onSave={onEditSave} />

      }

      {toast &&
      <div style={{
        position: 'fixed', bottom: agentOpen ? overviewMode ? 380 : 260 : 56, left: '50%', transform: 'translateX(-50%)',
        background: 'var(--ink)', color: 'white', padding: '10px 18px', borderRadius: 6,
        fontSize: 12.5, fontWeight: 500, zIndex: 100,
        boxShadow: '0 4px 20px rgba(0,0,0,0.18)',
        maxWidth: 600, textAlign: 'center'
      }}>{toast}</div>
      }
    </div>);

}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);