/* ============================================================
   Dispatcher's Work — daily task checklist (auto-saved)
   ============================================================ */

// Task legs: pickups/deliveries the dispatcher must track each day.
// kind 'out' = NC→NJ outbound side, 'back' = NJ→NC return side.
const DISPATCH_WEEK = [
  { day: 'Monday', tasks: [
    { driver: 1, action: 'Pickup from NC', loc: 'NC origin', kind: 'out' },
    { driver: 1, action: 'Deliver in NJ',  loc: 'NJ delivery', kind: 'out' },
    { driver: 5, action: 'Deliver in NC',  loc: 'NC return', kind: 'back' },
    { driver: 6, action: 'Pickup from NJ', loc: 'NJ return load', kind: 'back' },
  ]},
  { day: 'Tuesday', tasks: [
    { driver: 2, action: 'Pickup from NC', loc: 'NC origin', kind: 'out' },
    { driver: 2, action: 'Deliver in NJ',  loc: 'NJ delivery', kind: 'out' },
    { driver: 6, action: 'Deliver in NC',  loc: 'NC return', kind: 'back' },
    { driver: 1, action: 'Pickup from NJ', loc: 'NJ return load', kind: 'back' },
  ]},
  { day: 'Wednesday', tasks: [
    { driver: 3, action: 'Pickup from NC', loc: 'NC origin', kind: 'out' },
    { driver: 3, action: 'Deliver in NJ',  loc: 'NJ delivery', kind: 'out' },
    { driver: 1, action: 'Deliver in NC',  loc: 'NC return', kind: 'back' },
    { driver: 2, action: 'Pickup from NJ', loc: 'NJ return load', kind: 'back' },
  ]},
  { day: 'Thursday', tasks: [
    { driver: 4, action: 'Pickup from NC', loc: 'NC origin', kind: 'out' },
    { driver: 4, action: 'Deliver in NJ',  loc: 'NJ delivery', kind: 'out' },
    { driver: 2, action: 'Deliver in NC',  loc: 'NC return', kind: 'back' },
    { driver: 3, action: 'Pickup from NJ', loc: 'NJ return load', kind: 'back' },
  ]},
  { day: 'Friday', tasks: [
    { driver: 5, action: 'Pickup from NC', loc: 'NC origin', kind: 'out' },
    { driver: 5, action: 'Deliver in NJ',  loc: 'NJ delivery', kind: 'out' },
    { driver: 3, action: 'Deliver in NC',  loc: 'NC return', kind: 'back' },
    { driver: 4, action: 'Pickup from NJ', loc: 'NJ return load', kind: 'back' },
  ]},
  { day: 'Saturday', tasks: [
    { driver: 6, action: 'Pickup from NC', loc: 'NC origin', kind: 'out' },
    { driver: 6, action: 'Deliver in NJ',  loc: 'NJ delivery', kind: 'out' },
    { driver: 4, action: 'Deliver in NC',  loc: 'NC return', kind: 'back' },
    { driver: 5, action: 'Pickup from NJ', loc: 'NJ return load', kind: 'back' },
  ]},
];

const DW_STORE = 'ejay_dispatcher_v1';

function DispatcherView({ ctx }) {
  const done = ctx.dispatcherDone;
  const setDone = ctx.setDispatcherDone;

  const toggle = (key) => setDone(d => {
    const n = { ...d };
    if (n[key]) delete n[key]; else n[key] = true;
    return n;
  });

  const resetAll = () => setDone({});

  const driverName = (id) => {
    const d = ctx.drivers.find(x => x.id === id);
    return d ? d.name : ('Driver ' + id);
  };

  const monday = Engine.snapToMonday(ctx.weekStart);
  // "today" follows the live-sim clock while running, else NC (US Eastern) date
  const todayStr = ctx.simulating ? ctx.simDate : Engine.todayET();

  const total = DISPATCH_WEEK.reduce((s, d) => s + d.tasks.length, 0);
  let completed = 0;
  DISPATCH_WEEK.forEach((d, di) => d.tasks.forEach((t, ti) => { if (done[di + '-' + ti]) completed++; }));
  const allDone = completed === total;
  const pct = Math.round((completed / total) * 100);

  // missed = tasks on a day that is already over (date < today) and still unchecked
  const missedDays = [];
  let missedTotal = 0;
  DISPATCH_WEEK.forEach((d, di) => {
    const dayDate = Engine.addDays(monday, di);
    if (dayDate < todayStr) {
      const miss = d.tasks.filter((t, ti) => !done[di + '-' + ti]).length;
      if (miss > 0) { missedDays.push({ day: d.day, count: miss }); missedTotal += miss; }
    }
  });

  return (
    <div className="view">
      {missedTotal > 0 && (
        <div className="missed-banner">
          <div className="mb-ic"><Icon name="flag" /></div>
          <div style={{ flex: 1 }}>
            <div className="mb-title">{missedTotal} task{missedTotal > 1 ? 's' : ''} missed</div>
            <div className="mb-sub">
              Incomplete on {missedDays.map(m => m.day + ' (' + m.count + ')').join(', ')}. These days are over — follow up with the drivers.
            </div>
          </div>
        </div>
      )}

      {allDone && (
        <div className="all-done-banner">
          <div className="adb-ic"><Icon name="check" /></div>
          <div>
            <div className="adb-title">All Tasks Completed</div>
            <div className="adb-sub">Every pickup and delivery for the week is checked off and saved.</div>
          </div>
        </div>
      )}

      <div className="toolbar">
        <div>
          <div style={{ fontWeight: 700, fontSize: 15 }}>Weekly Task Checklist</div>
          <div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>
            What each driver must do, day by day — tick as you go.
          </div>
        </div>
        <div className="grow"></div>
        <span className="save-note"><Icon name="check" /> Progress auto-saved</span>
        <button className="btn" onClick={resetAll}><Icon name="refresh" /> Reset Checklist</button>
      </div>

      {/* overall progress */}
      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-body" style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap' }}>Week Progress</div>
          <div className="util-bar-track" style={{ flex: 1 }}>
            <div className="util-bar-fill" style={{
              width: Math.max(pct, 6) + '%',
              background: allDone ? 'linear-gradient(90deg, var(--green), var(--green))' : undefined
            }}>{pct}%</div>
          </div>
          <div className="mono" style={{ fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap' }}>{completed} / {total}</div>
        </div>
      </div>

      <div className="dispatch-grid">
        {DISPATCH_WEEK.map((d, di) => {
          const dayDoneCount = d.tasks.filter((t, ti) => done[di + '-' + ti]).length;
          const dayAllDone = dayDoneCount === d.tasks.length;
          const dayDateStr = Engine.addDays(monday, di);
          const dayDate = Engine.fmtShort(dayDateStr);
          const isOver = dayDateStr < todayStr;
          const isToday = dayDateStr === todayStr;
          const dayMissed = isOver && !dayAllDone ? (d.tasks.length - dayDoneCount) : 0;
          let cardCls = 'card day-card';
          if (dayMissed > 0) cardCls += ' missed';
          else if (dayAllDone) cardCls += ' done';
          return (
            <div className={cardCls} key={d.day}>
              <div className="day-head">
                <div>
                  <div className="dh-day">{d.day}{isToday && <span className="dh-today">Today</span>}</div>
                  <div className="dh-date">{dayDate} 2026</div>
                </div>
                {dayMissed > 0
                  ? <span className="day-missed-badge"><Icon name="flag" /> {dayMissed} Missed</span>
                  : dayAllDone
                    ? <span className="day-done-badge"><Icon name="check" /> All Tasks Completed</span>
                    : <span className="dh-prog">{dayDoneCount} / {d.tasks.length}</span>}
              </div>
              <div className="day-tasks">
                {d.tasks.map((t, ti) => {
                  const key = di + '-' + ti;
                  const isDone = !!done[key];
                  const rowMissed = isOver && !isDone;
                  return (
                    <div className={'task-row' + (isDone ? ' done' : '') + (rowMissed ? ' missed' : '')} key={key} onClick={() => toggle(key)}>
                      <div className="task-check"><Icon name={rowMissed ? 'flag' : 'check'} /></div>
                      <div className="task-body">
                        <div className={'task-id ' + (t.kind === 'out' ? 't-out' : 't-back')}>{t.driver}</div>
                        <div className="task-text">
                          <div className="tt-main">{t.action}</div>
                          <div className="tt-sub">{driverName(t.driver)} · {t.kind === 'out' ? 'NC → NJ' : 'NJ → NC'}</div>
                        </div>
                      </div>
                      <span className={'task-leg-dot ' + (t.kind === 'out' ? 't-out' : 't-back')}></span>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { DispatcherView, DISPATCH_WEEK });
