/* ============================================================
   Views: Schedule Viewer, Dispatch Board, Settings
   ============================================================ */

/* =================== SCHEDULE VIEWER =================== */
function ScheduleView({ ctx }) {
  const activeDrivers = ctx.drivers.filter(d => d.status === 'Active');
  const [sel, setSel] = useState(activeDrivers[0] ? activeDrivers[0].id : (ctx.drivers[0] && ctx.drivers[0].id));

  const driver = ctx.drivers.find(d => d.id === sel);
  const legs = ctx.schedule.filter(l => l.driverId === sel).sort((a, b) => a.date < b.date ? -1 : 1);
  const trk = legs[0] ? ctx.trucks.find(t => t.id === legs[0].truckId) : null;

  // build display rows incl. night rest
  const rows = [];
  legs.forEach((l, i) => {
    rows.push({ kind: 'leg', leg: l });
    if (l.leg === 'outbound') {
      rows.push({ kind: 'rest', date: l.date });
    }
  });

  return (
    <div className="view">
      <div className="toolbar">
        <div className="field" style={{ minWidth: 240 }}>
          <label>Select Driver</label>
          <select className="select" value={sel || ''} onChange={e => setSel(e.target.value)}>
            {ctx.drivers.map(d => <option key={d.id} value={d.id}>Driver {d.id} — {d.name}{d.status !== 'Active' ? ' (Off)' : ''}</option>)}
          </select>
        </div>
        <div className="grow"></div>
        <button className="btn" onClick={ctx.exportExcel}><Icon name="download" /> Excel</button>
        <button className="btn" onClick={ctx.exportPdf}><Icon name="download" /> PDF</button>
      </div>

      {driver && (
        <div className="card" style={{ marginBottom: 18 }}>
          <div className="card-body" style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
            <div className="idchip" style={{ width: 48, height: 48, fontSize: 20, borderRadius: 12 }}>{driver.id}</div>
            <div style={{ flex: 1, minWidth: 160 }}>
              <div style={{ fontSize: 18, fontWeight: 700 }}>{driver.name}</div>
              <div style={{ color: 'var(--text-faint)', fontSize: 13 }}>{driver.phone || 'No phone'} · {driver.license || 'CDL-A'}</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700 }}>Truck</div>
              <div style={{ fontWeight: 700, marginTop: 3 }}>{trk ? trk.name : 'Unassigned'}</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 700 }}>Status</div>
              <div style={{ marginTop: 5 }}>
                <span className={'badge ' + (driver.status === 'Active' ? 'b-green' : 'b-gray')}><span className="dot"></span>{driver.status}</span>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="card">
        <div className="card-head">
          <Icon name="schedule" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
          <h3>Weekly Cycle</h3>
          <span className="sub">{legs.length ? 'NC ⇄ NJ round trip' : 'Not scheduled this week'}</span>
        </div>
        {legs.length === 0 ? (
          <div className="empty-state"><Icon name="calendar" />
            <div>This driver has no loads this week.</div>
            <div style={{ fontSize: 12, marginTop: 4 }}>Generate the schedule or set the driver to Active.</div>
          </div>
        ) : (
          <table className="tbl">
            <thead>
              <tr><th>Date</th><th>Activity</th><th>Route</th><th>Status</th></tr>
            </thead>
            <tbody>
              {rows.map((r, i) => {
                if (r.kind === 'rest') {
                  return (
                    <tr key={'rest' + i} style={{ background: 'var(--surface-2)' }}>
                      <td className="num" style={{ color: 'var(--text-faint)' }}>{Engine.fmtLong(r.date)} · PM</td>
                      <td style={{ color: 'var(--text-dim)' }}>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
                          <Icon name="moon" style={{ width: 15, height: 15, color: 'var(--text-faint)' }} />
                          Mandatory 10-hour DOT rest — NJ
                        </span>
                      </td>
                      <td style={{ color: 'var(--text-faint)' }}>NJ overnight</td>
                      <td><span className="badge b-gray"><span className="dot"></span>Rest</span></td>
                    </tr>
                  );
                }
                const l = r.leg;
                return (
                  <tr key={l.id}>
                    <td className="num" style={{ whiteSpace: 'nowrap' }}>{Engine.fmtLong(l.date)}</td>
                    <td>
                      <span className={'badge ' + (l.leg === 'outbound' ? 'b-green' : 'b-blue')} style={{ marginRight: 8 }}>
                        <span className="dot"></span>{l.leg === 'outbound' ? 'Outbound — Pickup NC' : 'Backhaul — Return NC'}
                      </span>
                      {l.delayed && <span className="badge b-amber"><Icon name="flag" style={{ width: 11, height: 11 }} />Weekend delay</span>}
                    </td>
                    <td><Route from={l.from} to={l.to} /></td>
                    <td><StatusBadge status={l.delayed && l.status !== 'completed' ? 'delayed' : l.status} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

/* =================== DISPATCH BOARD =================== */
function BoardView({ ctx }) {
  const [pop, setPop] = useState(null); // {leg, x, y}
  const dates = Engine.scheduleDates(ctx.schedule);
  const trucks = ctx.trucks;

  // index legs by truck+date
  const cellMap = {};
  ctx.schedule.forEach(l => {
    const key = l.truckId + '|' + l.date;
    (cellMap[key] = cellMap[key] || []).push(l);
  });

  const gridCols = '150px repeat(' + Math.max(dates.length, 1) + ', minmax(108px, 1fr))';

  const openPop = (e, leg) => {
    e.stopPropagation();
    const r = e.currentTarget.getBoundingClientRect();
    let x = r.left, y = r.bottom + 6;
    if (x + 230 > window.innerWidth) x = window.innerWidth - 240;
    if (y + 230 > window.innerHeight) y = r.top - 236;
    setPop({ leg, x, y });
  };

  return (
    <div className="view" onClick={() => setPop(null)}>
      <div className="toolbar">
        <div className="legend">
          <div className="li"><span className="sw" style={{ background: 'var(--green)' }}></span>Outbound (NC→NJ)</div>
          <div className="li"><span className="sw" style={{ background: 'var(--blue)' }}></span>Backhaul (NJ→NC)</div>
          <div className="li"><span className="sw" style={{ background: 'var(--amber)' }}></span>Delayed return</div>
          <div className="li"><span className="sw" style={{ background: 'var(--gray)' }}></span>Off duty</div>
        </div>
        <div className="grow"></div>
        <span style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>Click a load to override status</span>
      </div>

      <div className="card" style={{ padding: 16 }}>
        <div className="board-wrap">
          <div className="board" style={{ gridTemplateColumns: gridCols }}>
            {/* header row */}
            <div className="board-corner"></div>
            {dates.map(dt => {
              const wd = Engine.dow(dt);
              const weekend = wd === 0 || wd === 6;
              return (
                <div className={'board-day' + (weekend ? ' weekend' : '')} key={dt}>
                  <div className="wd">{Engine.weekdayName(dt)}</div>
                  <div className="dt">{Engine.fmtShort(dt)}</div>
                </div>
              );
            })}

            {/* truck rows */}
            {trucks.map(t => (
              <React.Fragment key={t.id}>
                <div className="board-truck">
                  <div className="t-ic"><Icon name="truck" /></div>
                  <div>
                    <div className="t-nm">{t.code}</div>
                    <div className="t-pl">{t.plate}</div>
                  </div>
                </div>
                {dates.map(dt => {
                  const legs = cellMap[t.id + '|' + dt] || [];
                  if (legs.length === 0) return <div className="board-cell empty" key={dt}></div>;
                  return (
                    <div className="board-cell" key={dt}>
                      {legs.map(l => {
                        const drv = ctx.drivers.find(d => d.id === l.driverId);
                        const cls = l.delayed ? 'l-delayed' : (l.leg === 'outbound' ? 'l-out' : 'l-back');
                        return (
                          <div className={'load-chip ' + cls} key={l.id} onClick={e => openPop(e, l)}>
                            <div className="lc-top">
                              <span className="lc-drv">{drv ? drv.name.split(' ')[0] : 'Driver'}</span>
                              <span className="lc-route">{l.from}→{l.to}</span>
                            </div>
                            <div className="lc-st" style={{ color: STATUS_COLOR(l) }}>
                              {l.delayed && l.status !== 'completed' ? 'DELAYED · ' : ''}{(STATUS_META[l.status] || {}).label}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>

      {pop && <CellPopover pop={pop} ctx={ctx} close={() => setPop(null)} />}
    </div>
  );
}

function STATUS_COLOR(l) {
  if (l.delayed && l.status !== 'completed') return 'var(--amber)';
  if (l.status === 'completed') return 'var(--green)';
  if (l.status === 'in_transit') return 'var(--accent-2)';
  return 'var(--text-faint)';
}

function CellPopover({ pop, ctx, close }) {
  const drv = ctx.drivers.find(d => d.id === pop.leg.driverId);
  const opts = [
    { v: 'scheduled', label: 'Scheduled', color: 'var(--gray)' },
    { v: 'in_transit', label: 'In Transit', color: 'var(--accent)' },
    { v: 'completed', label: 'Completed', color: 'var(--green)' },
    { v: 'delayed', label: 'Delayed Return', color: 'var(--amber)' },
  ];
  const choose = (v) => {
    if (v === 'delayed') ctx.overrideLeg(pop.leg.id, { delayed: true });
    else ctx.overrideLeg(pop.leg.id, { status: v, delayed: v === 'completed' ? pop.leg.delayed : false });
    close();
  };
  return (
    <div className="popover" style={{ left: pop.x, top: pop.y }} onClick={e => e.stopPropagation()}>
      <div className="pop-title">{drv ? drv.name : 'Load'} · {pop.leg.from}→{pop.leg.to}</div>
      {opts.map(o => {
        const sel = (o.v === 'delayed') ? (pop.leg.delayed && pop.leg.status !== 'completed') : (pop.leg.status === o.v && !(pop.leg.delayed && pop.leg.status !== 'completed'));
        return (
          <div className={'pop-opt' + (sel ? ' sel' : '')} key={o.v} onClick={() => choose(o.v)}>
            <span className="dot" style={{ background: o.color }}></span>{o.label}
            {sel && <Icon name="check" style={{ width: 15, height: 15, marginLeft: 'auto' }} />}
          </div>
        );
      })}
    </div>
  );
}

/* =================== SETTINGS =================== */
function SettingsView({ ctx }) {
  const [localDate, setLocalDate] = useState(ctx.weekStart);
  const [showPw, setShowPw] = useState(false);
  const snappedNote = Engine.dow(localDate) !== 1;

  return (
    <div className="view" style={{ maxWidth: 760 }}>
      <div className="stack">
        <div className="card">
          <div className="card-head">
            <Icon name="calendar" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
            <h3>Week Start Date</h3>
            <span className="sub">Editable every Monday</span>
          </div>
          <div className="card-body">
            <div className="field-row" style={{ alignItems: 'flex-end' }}>
              <div className="field">
                <label>Operating Week Begins</label>
                <input className="input" type="date" value={localDate} onChange={e => setLocalDate(e.target.value)} />
              </div>
              <button className="btn btn-primary" style={{ height: 41 }}
                      onClick={() => { ctx.setWeekStart(localDate); }}>
                <Icon name="check" /> Apply Date
              </button>
            </div>
            {snappedNote && (
              <div style={{ marginTop: 12, fontSize: 12.5, color: 'var(--amber)', display: 'flex', alignItems: 'center', gap: 7 }}>
                <Icon name="flag" style={{ width: 14, height: 14 }} />
                Not a Monday — the scheduler will snap to the Monday of that week ({Engine.fmtFull(Engine.snapToMonday(localDate))}).
              </div>
            )}
            <div className="divider" style={{ margin: '16px 0' }}></div>
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <button className="btn btn-primary" onClick={ctx.generate}><Icon name="bolt" /> Generate Schedule</button>
              <button className="btn" onClick={ctx.reset}><Icon name="refresh" /> Reset to Default Demo</button>
              <button className="btn" onClick={ctx.exportExcel}><Icon name="download" /> Export Excel</button>
              <button className="btn" onClick={ctx.exportPdf}><Icon name="download" /> Export PDF</button>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <Icon name="settings" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
            <h3>Scheduler Rules</h3>
          </div>
          <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <RuleRow icon="bolt" title="Sequential assignment" desc="Driver N departs on weekStart + N days, one full NC⇄NJ cycle each." />
            <RuleRow icon="moon" title="Mandatory DOT rest" desc="10-hour overnight rest in NJ between outbound and backhaul." />
            <RuleRow icon="flag" title="Weekend backhaul rule" desc="Friday outbound → backhaul returns next Monday; Saturday outbound → backhaul next Tuesday. Both flagged Delayed." />
            <RuleRow icon="truck" title="Truck balancing" desc="Active drivers are assigned to trucks round-robin so no truck is double-booked." />
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <Icon name="sun" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
            <h3>Appearance</h3>
          </div>
          <div className="card-body">
            <div className="seg">
              <button className={ctx.theme === 'light' ? 'on' : ''} onClick={() => ctx.setTheme('light')}>Light</button>
              <button className={ctx.theme === 'dark' ? 'on' : ''} onClick={() => ctx.setTheme('dark')}>Dark</button>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <Icon name="drivers" style={{ width: 17, height: 17, color: 'var(--accent-2)' }} />
            <h3>Quick Admin</h3>
          </div>
          <div className="card-body" style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <button className="btn" onClick={() => ctx.setView('drivers')}><Icon name="drivers" /> Manage Drivers</button>
            <button className="btn" onClick={() => ctx.setView('trucks')}><Icon name="truck" /> Manage Trucks</button>
            <button className="btn" onClick={() => ctx.setView('board')}><Icon name="board" /> Open Dispatch Board</button>
            <button className="btn" onClick={() => setShowPw(true)}><Icon name="settings" /> Reset Password</button>
            <button className="btn btn-danger" onClick={ctx.lockDashboard}><Icon name="x" /> Lock Dashboard</button>
          </div>
        </div>
      </div>
      {showPw && <ChangePasswordModal ctx={ctx} close={() => setShowPw(false)} />}
    </div>
  );
}

function ChangePasswordModal({ ctx, close }) {
  const [cur, setCur] = useState('');
  const [next, setNext] = useState('');
  const [conf, setConf] = useState('');
  const [err, setErr] = useState('');

  const save = () => {
    if (next !== conf) { setErr('New passwords do not match.'); return; }
    const res = ctx.changePassword(cur, next);
    if (res === 'wrong-current') { setErr('Current password is incorrect.'); return; }
    if (res === 'too-short') { setErr('New password must be at least 4 characters.'); return; }
    close();
  };

  return (
    <Modal title="Reset Password" onClose={close}
      footer={<>
        <button className="btn btn-ghost" onClick={() => { ctx.resetPasswordDefault(); close(); }}>Reset to Default</button>
        <div style={{ flex: 1 }}></div>
        <button className="btn btn-ghost" onClick={close}>Cancel</button>
        <button className="btn btn-primary" onClick={save}><Icon name="check" /> Update Password</button>
      </>}>
      <div className="field">
        <label>Current Password</label>
        <input className="input" type="password" value={cur} autoFocus
               onChange={e => { setCur(e.target.value); setErr(''); }} placeholder="Enter current password" />
      </div>
      <div className="field">
        <label>New Password</label>
        <input className="input" type="password" value={next}
               onChange={e => { setNext(e.target.value); setErr(''); }} placeholder="At least 4 characters" />
      </div>
      <div className="field">
        <label>Confirm New Password</label>
        <input className="input" type="password" value={conf}
               onChange={e => { setConf(e.target.value); setErr(''); }} placeholder="Re-enter new password" />
      </div>
      {err && <div className="gate-err"><Icon name="x" style={{ width: 14, height: 14 }} />{err}</div>}
      <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>
        The new password is saved on this device and required next time the dashboard is locked or reopened.
      </div>
    </Modal>
  );
}

function RuleRow({ icon, title, desc }) {
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <div className="activity-dot" style={{ background: 'var(--accent-soft)', color: 'var(--accent-2)', flex: 'none' }}><Icon name={icon} /></div>
      <div>
        <div style={{ fontWeight: 600 }}>{title}</div>
        <div style={{ fontSize: 12.5, color: 'var(--text-dim)' }}>{desc}</div>
      </div>
    </div>
  );
}

Object.assign(window, { ScheduleView, BoardView, SettingsView });
