/* ============================================================
   Views: Dashboard, Drivers, Trucks
   ============================================================ */

function driverById(ctx, id) { return ctx.drivers.find(d => d.id === id); }
function truckById(ctx, id) { return ctx.trucks.find(t => t.id === id); }

/* =================== DASHBOARD =================== */
function DashboardView({ ctx }) {
  const k = Engine.kpis(ctx.schedule);
  const activeDrivers = ctx.drivers.filter(d => d.status === 'Active').length;

  // current-week legs, full week, by date (outbound before backhaul same day)
  const snapshot = [...ctx.schedule]
    .filter(l => !l.carryover)
    .sort((a, b) => {
      if (a.date !== b.date) return a.date < b.date ? -1 : 1;
      return a.leg === 'outbound' ? -1 : 1;
    });
  const util = Engine.utilization(ctx.schedule, ctx.trucks, Engine.scheduleDates(ctx.schedule));

  // activity feed (most recent completed / in transit)
  const feed = [...ctx.schedule]
    .filter(l => l.status !== 'scheduled')
    .sort((a, b) => (a.date < b.date ? 1 : -1))
    .slice(0, 6);

  return (
    <div className="view">
      {/* KPIs */}
      <div className="kpi-grid">
        <Kpi label="Total Drivers" value={ctx.drivers.length} icon="drivers" tone="accent"
             foot={<span><b>{activeDrivers}</b> active this week</span>} />
        <Kpi label="Total Trucks" value={ctx.trucks.length} icon="truck" tone="gray"
             foot={<span>Fleet in rotation</span>} />
        <Kpi label="Active Loads" value={k.active} icon="box" tone="green"
             foot={<span><b>{k.total}</b> legs scheduled</span>} />
        <Kpi label="In Transit" value={k.inTransit} icon="bolt" tone="blue"
             foot={<span>On the road now</span>} />
        <Kpi label="Completed" value={k.completed} icon="check" tone="amber"
             foot={<span><b>{k.delayed}</b> delayed returns</span>} />
      </div>

      {/* Weekly control panel */}
      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-head">
          <Icon name="bolt" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
          <h3>Weekly Control Panel</h3>
          <span className="sub">Generate & manage this week's dispatch cycle</span>
        </div>
        <div className="card-body">
          <div className="toolbar" style={{ marginBottom: 0 }}>
            <div className="field" style={{ minWidth: 200 }}>
              <label>Week Start (Monday)</label>
              <input className="input" type="date" value={ctx.weekStart}
                     onChange={e => ctx.setWeekStart(e.target.value)} />
            </div>
            <div className="grow"></div>
            <button className="btn btn-primary" onClick={ctx.generate}>
              <Icon name="bolt" /> Generate Weekly Schedule
            </button>
            <button className="btn" onClick={ctx.reset}>
              <Icon name="refresh" /> Reset
            </button>
            <button className="btn" onClick={ctx.exportExcel}>
              <Icon name="download" /> Excel
            </button>
            <button className="btn" onClick={ctx.exportPdf}>
              <Icon name="download" /> PDF
            </button>
          </div>
        </div>
      </div>

      <div className="two-col">
        {/* schedule snapshot */}
        <div className="card">
          <div className="card-head">
            <Icon name="schedule" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
            <h3>This Week's Dispatch</h3>
            <span className="sub" style={{ marginLeft: 'auto', cursor: 'pointer', color: 'var(--accent-2)' }}
                  onClick={() => ctx.setView('board')}>Open board →</span>
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table className="tbl">
              <thead>
                <tr><th>Date</th><th>Driver</th><th>Truck</th><th>Route</th><th>Leg</th><th>Status</th></tr>
              </thead>
              <tbody>
                {snapshot.map(l => {
                  const drv = driverById(ctx, l.driverId);
                  const trk = truckById(ctx, l.truckId);
                  return (
                    <tr key={l.id}>
                      <td className="num" style={{ whiteSpace: 'nowrap' }}>{Engine.fmtLong(l.date)}</td>
                      <td><span style={{ fontWeight: 600 }}>{drv ? drv.name : '—'}</span></td>
                      <td className="num">{trk ? trk.code : '—'}</td>
                      <td><Route from={l.from} to={l.to} /></td>
                      <td>
                        <span className={'badge ' + (l.leg === 'outbound' ? 'b-green' : 'b-blue')}>
                          <span className="dot"></span>{l.leg === 'outbound' ? 'Outbound' : 'Backhaul'}
                        </span>
                      </td>
                      <td><StatusBadge status={l.delayed && l.status !== 'completed' ? 'delayed' : l.status} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* right stack */}
        <div className="stack">
          <div className="card">
            <div className="card-head">
              <Icon name="chart" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
              <h3>Truck Utilization</h3>
            </div>
            <div className="card-body">
              {util.map(u => (
                <div className="util-row" key={u.truck.id}>
                  <div className="util-label">
                    <div className="tn">{u.truck.name}</div>
                    <div className="ts">{u.days}/{u.span} days</div>
                  </div>
                  <div className="util-bar-track">
                    <div className="util-bar-fill" style={{ width: Math.max(u.pct, 8) + '%' }}>{u.pct}%</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <Icon name="clock" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
              <h3>Recent Activity</h3>
            </div>
            <div className="card-body" style={{ paddingTop: 4, paddingBottom: 4 }}>
              {feed.length === 0 && <div className="empty-state" style={{ padding: '24px 0' }}>No live activity yet — run the sim.</div>}
              {feed.map(l => {
                const drv = driverById(ctx, l.driverId);
                const isDone = l.status === 'completed';
                return (
                  <div className="activity-item" key={l.id}>
                    <div className="activity-dot" style={{
                      background: isDone ? 'var(--green-soft)' : 'var(--accent-soft)',
                      color: isDone ? 'var(--green)' : 'var(--accent-2)' }}>
                      <Icon name={isDone ? 'check' : 'bolt'} />
                    </div>
                    <div style={{ flex: 1 }}>
                      <div className="ai-main">
                        <b>{drv ? drv.name : 'Driver'}</b> {isDone ? 'completed' : 'started'} {l.leg} {l.from}→{l.to}
                      </div>
                      <div className="ai-time">{Engine.fmtLong(l.date)}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* =================== DRIVERS =================== */
function DriversView({ ctx }) {
  const [editing, setEditing] = useState(null); // driver obj or {new:true}

  return (
    <div className="view">
      <div className="toolbar">
        <div>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{ctx.drivers.length} Drivers</div>
          <div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>
            {ctx.drivers.filter(d => d.status === 'Active').length} active · {ctx.drivers.filter(d => d.status !== 'Active').length} off duty
          </div>
        </div>
        <div className="grow"></div>
        <button className="btn btn-primary" onClick={() => setEditing({ new: true, status: 'Active' })}>
          <Icon name="plus" /> Add Driver
        </button>
      </div>

      <div className="card">
        <table className="tbl">
          <thead>
            <tr><th>ID</th><th>Driver</th><th>Phone</th><th>Assigned Truck</th><th>Status</th><th style={{ textAlign: 'right' }}>Actions</th></tr>
          </thead>
          <tbody>
            {ctx.drivers.map(d => {
              const trk = truckById(ctx, d.assignedTruck);
              return (
                <tr key={d.id}>
                  <td><div className="idchip">{d.id}</div></td>
                  <td>
                    <div className="cell-driver">
                      <div>
                        <div className="nm">{d.name}</div>
                        <div className="ph">{d.license || 'CDL-A'}</div>
                      </div>
                    </div>
                  </td>
                  <td className="num" style={{ color: 'var(--text-dim)' }}>{d.phone || '—'}</td>
                  <td>{trk
                    ? <span className="badge b-accent"><span className="dot"></span>{trk.name}</span>
                    : <span style={{ color: 'var(--text-faint)' }}>Unassigned</span>}</td>
                  <td>
                    <span className={'badge ' + (d.status === 'Active' ? 'b-green' : 'b-gray')}>
                      <span className="dot"></span>{d.status}
                    </span>
                  </td>
                  <td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
                    <button className="btn btn-ghost btn-sm" onClick={() => setEditing({ ...d })}><Icon name="edit" /> Edit</button>
                    <button className="btn btn-danger btn-sm" onClick={() => ctx.deleteDriver(d.id)}><Icon name="trash" /></button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {editing && <DriverModal ctx={ctx} editing={editing} close={() => setEditing(null)} />}
    </div>
  );
}

function DriverModal({ ctx, editing, close }) {
  const [form, setForm] = useState({
    name: editing.name || '', phone: editing.phone || '',
    license: editing.license || 'CDL-A',
    assignedTruck: editing.assignedTruck || (ctx.trucks[0] && ctx.trucks[0].id) || null,
    status: editing.status || 'Active',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const save = () => {
    if (!form.name.trim()) return;
    if (editing.new) ctx.addDriver(form);
    else ctx.updateDriver(editing.id, form);
    close();
  };
  return (
    <Modal title={editing.new ? 'Add Driver' : 'Edit ' + editing.name} onClose={close}
      footer={<>
        <button className="btn btn-ghost" onClick={close}>Cancel</button>
        <button className="btn btn-primary" onClick={save}><Icon name="check" /> Save Driver</button>
      </>}>
      <div className="field">
        <label>Driver Name</label>
        <input className="input" value={form.name} autoFocus
               onChange={e => set('name', e.target.value)} placeholder="e.g. Marcus Bell" />
      </div>
      <div className="field-row">
        <div className="field">
          <label>Phone (optional)</label>
          <input className="input" value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="(704) 555-0142" />
        </div>
        <div className="field">
          <label>License</label>
          <input className="input" value={form.license} onChange={e => set('license', e.target.value)} />
        </div>
      </div>
      <div className="field-row">
        <div className="field">
          <label>Assigned Truck</label>
          <select className="select" value={form.assignedTruck || ''} onChange={e => set('assignedTruck', e.target.value || null)}>
            <option value="">Unassigned</option>
            {ctx.trucks.map(t => <option key={t.id} value={t.id}>{t.name} ({t.code})</option>)}
          </select>
        </div>
        <div className="field">
          <label>Status</label>
          <select className="select" value={form.status} onChange={e => set('status', e.target.value)}>
            <option>Active</option>
            <option>Off Duty</option>
          </select>
        </div>
      </div>
    </Modal>
  );
}

/* =================== TRUCKS =================== */
function TrucksView({ ctx }) {
  const [editing, setEditing] = useState(null);
  const dates = Engine.scheduleDates(ctx.schedule);
  const util = Engine.utilization(ctx.schedule, ctx.trucks, dates);

  return (
    <div className="view">
      <div className="toolbar">
        <div>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{ctx.trucks.length} Trucks</div>
          <div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>Fleet rotation & utilization</div>
        </div>
        <div className="grow"></div>
        <button className="btn" onClick={ctx.autoAssign}><Icon name="refresh" /> Auto-assign Drivers</button>
        <button className="btn btn-primary" onClick={() => setEditing({ new: true })}><Icon name="plus" /> Add Truck</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
        {ctx.trucks.map(t => {
          const drivers = ctx.drivers.filter(d => d.assignedTruck === t.id);
          const u = util.find(x => x.truck.id === t.id) || { pct: 0, days: 0, span: dates.length };
          return (
            <div className="card" key={t.id}>
              <div className="card-head">
                <div className="board-truck" style={{ padding: 0, flex: 1 }}>
                  <div className="t-ic" style={{ background: 'var(--accent-soft)', color: 'var(--accent-2)' }}><Icon name="truck" /></div>
                  <div>
                    <div className="t-nm">{t.name}</div>
                    <div className="t-pl">{t.code} · {t.plate}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 4 }}>
                  <button className="btn btn-ghost btn-sm" onClick={() => setEditing({ ...t })}><Icon name="edit" /></button>
                  <button className="btn btn-danger btn-sm" onClick={() => ctx.deleteTruck(t.id)}><Icon name="trash" /></button>
                </div>
              </div>
              <div className="card-body">
                <div className="util-row" style={{ marginBottom: 16 }}>
                  <div className="util-label" style={{ width: 78 }}>
                    <div className="tn">Utilization</div>
                    <div className="ts">{u.days}/{u.span} days</div>
                  </div>
                  <div className="util-bar-track">
                    <div className="util-bar-fill" style={{ width: Math.max(u.pct, 8) + '%' }}>{u.pct}%</div>
                  </div>
                </div>
                <div style={{ fontSize: 11.5, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700, marginBottom: 8 }}>
                  Assigned Drivers
                </div>
                {drivers.length === 0 && <div style={{ color: 'var(--text-faint)', fontSize: 13 }}>No drivers assigned</div>}
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {drivers.map(d => (
                    <span key={d.id} className="badge b-gray" style={{ padding: '5px 11px' }}>
                      <span className="idchip" style={{ width: 18, height: 18, fontSize: 10, borderRadius: 5 }}>{d.id}</span>
                      {d.name}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {editing && <TruckModal ctx={ctx} editing={editing} close={() => setEditing(null)} />}
    </div>
  );
}

function TruckModal({ ctx, editing, close }) {
  const [form, setForm] = useState({
    name: editing.name || '', code: editing.code || '', plate: editing.plate || '',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const save = () => {
    if (!form.name.trim()) return;
    if (editing.new) ctx.addTruck(form);
    else ctx.updateTruck(editing.id, form);
    close();
  };
  return (
    <Modal title={editing.new ? 'Add Truck' : 'Edit ' + editing.name} onClose={close}
      footer={<>
        <button className="btn btn-ghost" onClick={close}>Cancel</button>
        <button className="btn btn-primary" onClick={save}><Icon name="check" /> Save Truck</button>
      </>}>
      <div className="field">
        <label>Truck Name</label>
        <input className="input" value={form.name} autoFocus onChange={e => set('name', e.target.value)} placeholder="e.g. Truck 4 — Freightliner" />
      </div>
      <div className="field-row">
        <div className="field">
          <label>Code</label>
          <input className="input" value={form.code} onChange={e => set('code', e.target.value)} placeholder="T-04" />
        </div>
        <div className="field">
          <label>Plate</label>
          <input className="input" value={form.plate} onChange={e => set('plate', e.target.value)} placeholder="NC ABC-1234" />
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { DashboardView, DriversView, TrucksView });
