/* Time-travel scrubber overlay */
const { useState: useStateTT, useMemo: useMemoTT, useRef: useRefTT } = React;

function Scrubber() {
  const { viewDate, setViewDate, scrubOpen, setScrubOpen } = window.useApp();
  if (!scrubOpen) return null;

  // axis spans HORIZON_PAST..HORIZON_FUTURE
  const start = window.HORIZON_PAST;
  const end = window.HORIZON_FUTURE;
  const total = end - start;

  const pct = (date) => (date - start) / total * 100;

  // monthly ticks (every quarter labelled)
  const ticks = useMemoTT(() => {
    const out = [];
    let cur = new Date(start);
    cur.setDate(1);
    while (cur <= end) {
      const isMajor = cur.getMonth() % 3 === 0;
      out.push({ date: new Date(cur), major: isMajor });
      cur = window.addMonths(cur, 1);
    }
    return out;
  }, []);

  const sliderMax = 1000;
  const sliderVal = Math.round((viewDate - start) / total * sliderMax);
  const onChange = (e) => {
    const v = +e.target.value;
    const ms = start.getTime() + v / sliderMax * total;
    setViewDate(new Date(ms));
  };

  const upcoming = window.eventsBetween(window.TODAY, end).slice(0, 4);

  return (
    <div className="scrub-veil" onClick={(e) => {if (e.target.classList.contains("scrub-veil")) setScrubOpen(false);}}>
      <div className="scrub-panel" onClick={(e) => e.stopPropagation()}>
        <div className="scrub-head">
          <Icon name="settings-sliders" style={{ color: "var(--mf-watermelon-700)" }} />
          <div>
            <div className="scrub-title">Time machine</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", marginTop: 2 }}>
              Rebuild the organisation at any past or future date.
            </div>
          </div>
          <div className="scrub-date">{window.dstr(viewDate)}</div>
        </div>

        <div className="scrub-track-wrap">
          <div className="scrub-axis">
            {ticks.map((t, i) =>
            <div key={i} className={`scrub-tick ${t.major ? "major" : ""}`} style={{ left: `${pct(t.date)}%` }}>
                {t.major && <label>{t.date.toLocaleDateString("en-GB", { month: "short", year: "2-digit" })}</label>}
              </div>
            )}
            {window.EVENTS.map((e) =>
            <div key={e.id}
            className={`scrub-event ${e.type === "hire" ? "hire" : e.type === "move" ? "move" : e.type === "role" ? "role" : e.payload && e.payload.planned ? "planned" : "end"}`}
            style={{ left: `${pct(e.date)}%` }}
            title={`${e.type} · ${window.pById[e.personId]?.name} · ${window.dstrShort(e.date)}`} />

            )}
            <div className="scrub-today" style={{ left: `${pct(window.TODAY)}%` }} />
            <div className="scrub-cursor" style={{ left: `${pct(viewDate)}%` }} />
            <input className="scrub-input" type="range" min={0} max={sliderMax} value={sliderVal} onChange={onChange} />
          </div>
        </div>

        <div className="scrub-foot">
          <div className="legend"><span className="ldot" style={{ background: "#6AC58C" }} />Hire</div>
          <div className="legend"><span className="ldot" style={{ background: "var(--mf-watermelon-700)" }} />Move</div>
          <div className="legend"><span className="ldot" style={{ background: "#BB8FE3" }} />Role change</div>
          <div className="legend"><span className="ldot" style={{ background: "#B9B0B6" }} />End</div>
          <div className="legend"><span className="ldot" style={{ background: "#E9B254" }} />Planned</div>
          <div className="scrub-actions">
            <button className="btn btn-dark" onClick={() => setViewDate(window.HORIZON_PAST)}>← Jan 2024</button>
            <button className="btn btn-dark" onClick={() => setViewDate(window.addMonths(window.TODAY, -6))}>−6 mo</button>
            <button className="btn btn-dark" onClick={() => setViewDate(window.TODAY)}>Today</button>
            <button className="btn btn-dark" onClick={() => setViewDate(window.addMonths(window.TODAY, 6))}>+6 mo</button>
            <button className="btn btn-dark" onClick={() => setViewDate(window.HORIZON_FUTURE)}>Dec 2026 →</button>
          </div>
        </div>

        {upcoming.length > 0 &&
        <div style={{ marginTop: 16, borderTop: "1px solid rgba(255,255,255,0.08)", paddingTop: 14 }}>
            <div style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "rgba(255,255,255,0.45)", marginBottom: 8 }}>
              Upcoming events · jump to
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {upcoming.map((ev) =>
            <button key={ev.id} className="btn btn-dark" onClick={() => setViewDate(new Date(ev.date.getTime() - 1000 * 60 * 60 * 24))}
            style={{ fontSize: 11 }}>
                  <span style={{ color: "var(--mf-watermelon-700)" }}>{window.dstrShort(ev.date)}</span>
                  <span style={{ marginLeft: 6 }}>{ev.type} · {window.pById[ev.personId]?.name?.split(" ")[0]}</span>
                </button>
            )}
            </div>
          </div>
        }
      </div>
    </div>);

}
window.Scrubber = Scrubber;

/* ===== Command palette ===== */
function CommandPalette() {
  const { paletteOpen, setPaletteOpen, paletteCtx, go, setDrawer } = window.useApp();
  const [q, setQ] = useStateTT("");
  const [active, setActive] = useStateTT(0);
  const inputRef = useRefTT(null);

  React.useEffect(() => {
    if (paletteOpen) {
      setQ("");
      setActive(0);
      setTimeout(() => inputRef.current?.focus(), 30);
    }
  }, [paletteOpen]);

  if (!paletteOpen) return null;

  const ql = q.toLowerCase().trim();

  const ACTIONS = [
  { id: "act-hire", label: "Onboard new person…", icon: "user", kind: "action", drawer: { kind: "hire" } },
  { id: "act-alloc", label: "Adjust allocations…", icon: "settings-sliders", kind: "action", drawer: { kind: "allocate" } },
  { id: "act-mgr", label: "Change manager…", icon: "arrow-turn", kind: "action", drawer: { kind: "manager" } },
  { id: "act-role", label: "Change role…", icon: "user-advisor", kind: "action", drawer: { kind: "role" } },
  { id: "act-ext", label: "Extend contractor…", icon: "arrow-right", kind: "action", drawer: { kind: "extend" } },
  { id: "act-end", label: "End contract / employment…", icon: "cancel-circle", kind: "action", drawer: { kind: "end" } }];

  const NAV = [
  { id: "nav-ov", label: "Organisation overview", icon: "dashboard", kind: "nav", route: "overview" },
  { id: "nav-exp", label: "Dimension explorer", icon: "settings-sliders", kind: "nav", route: "explorer" },
  { id: "nav-tms", label: "Work groups", icon: "user-multiple", kind: "nav", route: "teams" },
  { id: "nav-fns", label: "Functions", icon: "target", kind: "nav", route: "functions" },
  { id: "nav-rep", label: "Line reporting", icon: "arrow-turn", kind: "nav", route: "reporting" },
  { id: "nav-ppl", label: "People", icon: "user", kind: "nav", route: "people" },
  { id: "nav-time", label: "Time machine", icon: "arrow-left", kind: "nav", route: "timeline" },
  { id: "nav-evt", label: "Event log", icon: "invoice", kind: "nav", route: "events" }];


  let groups;
  if (ql.length === 0) {
    if (paletteCtx?.kind === "new-event") {
      groups = [{ title: "New event", items: ACTIONS }];
    } else {
      groups = [
      { title: "Quick actions", items: ACTIONS.slice(0, 4) },
      { title: "Jump to", items: NAV.slice(0, 5) }];

    }
  } else {
    const people = window.PEOPLE.filter((p) => p.name.toLowerCase().includes(ql)).slice(0, 6).map((p) => ({
      id: `p-${p.id}`, label: p.name, icon: "user", kind: "person", meta: window.assignmentAt(p, window.TODAY)?.role || p.kind, route: "person", routeParams: { id: p.id }
    }));
    const teams = window.TEAMS.filter((t) => t.name.toLowerCase().includes(ql)).slice(0, 5).map((t) => ({
      id: `t-${t.id}`, label: t.name, icon: "user-multiple", kind: "team", meta: "Team", route: "team", routeParams: { id: t.id }
    }));
    const actions = ACTIONS.filter((a) => a.label.toLowerCase().includes(ql));
    const nav = NAV.filter((a) => a.label.toLowerCase().includes(ql));
    groups = [];
    if (actions.length) groups.push({ title: "Actions", items: actions });
    if (people.length) groups.push({ title: "People", items: people });
    if (teams.length) groups.push({ title: "Teams", items: teams });
    if (nav.length) groups.push({ title: "Jump to", items: nav });
    if (groups.length === 0) groups.push({ title: "No results", items: [] });
  }

  const flat = groups.flatMap((g) => g.items);
  const safeActive = Math.min(active, Math.max(0, flat.length - 1));

  const runItem = (item) => {
    if (item.drawer) {setPaletteOpen(false);setDrawer(item.drawer);return;}
    if (item.route) {setPaletteOpen(false);go(item.route, item.routeParams || {});return;}
  };

  const onKey = (e) => {
    if (e.key === "ArrowDown") {e.preventDefault();setActive((a) => Math.min(a + 1, flat.length - 1));} else
    if (e.key === "ArrowUp") {e.preventDefault();setActive((a) => Math.max(a - 1, 0));} else
    if (e.key === "Enter") {e.preventDefault();if (flat[safeActive]) runItem(flat[safeActive]);}
  };

  return (
    <div className="palette-veil" onClick={(e) => {if (e.target.classList.contains("palette-veil")) setPaletteOpen(false);}}>
      <div className="palette" onClick={(e) => e.stopPropagation()}>
        <div className="palette-head">
          <Icon name="search" style={{ color: "var(--fg-3)" }} />
          {paletteCtx?.kind === "new-event" &&
          <span className="palette-context"><Icon name="plus" />New event</span>
          }
          <input ref={inputRef} value={q} onChange={(e) => {setQ(e.target.value);setActive(0);}} placeholder={paletteCtx?.kind === "new-event" ? "Choose event type…" : "Search or type a command…"} onKeyDown={onKey} />
          <span className="kbd-mini">esc</span>
        </div>
        <div className="palette-list">
          {groups.map((g, gi) =>
          <div key={gi}>
              <div className="palette-sec">{g.title}</div>
              {g.items.length === 0 && <div style={{ padding: "8px 10px", color: "var(--fg-4)", fontSize: 12 }}>Try a person, team, or command.</div>}
              {g.items.map((it, ii) => {
              const flatIdx = groups.slice(0, gi).reduce((s, gg) => s + gg.items.length, 0) + ii;
              return (
                <div key={it.id} className={`palette-item ${safeActive === flatIdx ? "is-active" : ""}`}
                onMouseEnter={() => setActive(flatIdx)}
                onClick={() => runItem(it)}>
                    <Icon name={it.icon} className="pi-icon" />
                    <span>{it.label}</span>
                    {it.meta && <span className="pi-meta">{it.meta}</span>}
                  </div>);

            })}
            </div>
          )}
        </div>
        <div className="palette-foot">
          <span className="pf-hint"><span className="kbd-mini">↑↓</span> navigate</span>
          <span className="pf-hint"><span className="kbd-mini">↵</span> select</span>
          <span className="pf-hint"><span className="kbd-mini">esc</span> close</span>
          <span style={{ marginLeft: "auto" }}>Tip: press <span className="kbd-mini">T</span> anywhere to jump to today</span>
        </div>
      </div>
    </div>);

}
window.CommandPalette = CommandPalette;

/* ===== Event creation drawer ===== */
function EventDrawer() {
  const { drawer, setDrawer } = window.useApp();
  if (!drawer) return null;
  const kind = drawer.kind;

  const titles = {
    hire: { eb: "Event · onboarding", t: "Onboard a new person" },
    allocate: { eb: "Event · allocation", t: "Adjust capacity allocations" },
    move: { eb: "Event · work group move", t: "Move someone to another work group" },
    manager: { eb: "Event · line change", t: "Change line manager" },
    role: { eb: "Event · role change", t: "Change role or title" },
    extend: { eb: "Event · extension", t: "Extend contractor contract" },
    end: { eb: "Event · end", t: "End contract or employment" }
  };
  const meta = titles[kind] || { eb: "Event", t: "New event" };

  const close = () => setDrawer(null);

  /* tiny form, just for show */
  return (
    <>
      <div className="drawer-veil" onClick={close} />
      <aside className="drawer">
        <div className="drawer-head">
          <Icon name="invoice" style={{ color: "var(--mf-watermelon-900)" }} />
          <div>
            <div className="drawer-eyebrow">{meta.eb}</div>
            <div className="drawer-title">{meta.t}</div>
          </div>
          <button className="btn btn-icon btn-ghost" style={{ marginLeft: "auto" }} onClick={close}><Icon name="cancel" /></button>
        </div>
        <div className="drawer-body" data-comment-anchor="d986cba103-div-263-9">
          <DrawerBody kind={kind} payload={drawer.payload || {}} />
        </div>
        <div className="drawer-foot">
          <span className="muted" style={{ fontSize: 11 }}>This will append a new record. The previous one will be closed automatically.</span>
          <span className="spacer" />
          <button className="btn" onClick={close}>Cancel</button>
          <button className="btn btn-primary" onClick={close}>Commit event</button>
        </div>
      </aside>
    </>);

}
window.EventDrawer = EventDrawer;

function DrawerBody({ kind, payload }) {
  const initialPerson = payload.personId ? window.pById[payload.personId] : window.PEOPLE.find((p) => p.id === "p-ali");
  const [person, setPerson] = useStateTT(initialPerson);
  const [date, setDate] = useStateTT(window.dstr(new Date(window.TODAY.getFullYear(), window.TODAY.getMonth() + 1, 1)));
  const [functionId, setFunctionId] = useStateTT(window.assignmentAt(initialPerson, window.TODAY)?.functionId || "fn-eng");
  const [role, setRole] = useStateTT(kind === "role" ? window.fnById[functionId]?.roles[0] : "");
  const [hireKind, setHireKind] = useStateTT(initialPerson?.kind || "employee");
  const [hireEnd, setHireEnd] = useStateTT(window.dstr(window.addMonths(window.TODAY, 6)));

  const cur = window.assignmentAt(person, window.TODAY);
  const fn = window.fnById[functionId];
  const fnRoles = (fn?.roles) || [];

  // For role drawer — restrict to person's current function
  const personFn = window.fnById[cur?.functionId];
  const personFnRoles = personFn?.roles || [];

  return (
    <>
      {kind !== "create-role" && (
        <div className="field">
          <label>Person</label>
          <div className="ctrl">
            <Avatar person={person} />
            <select value={person.id} onChange={(e) => setPerson(window.pById[e.target.value])}>
              {window.PEOPLE.map((p) => <option key={p.id} value={p.id}>{p.name} — {p.kind}</option>)}
            </select>
          </div>
        </div>
      )}

      {kind === "hire" &&
      <>
          <div className="field-row">
            <div className="field"><label>Type</label><div className="ctrl"><select value={hireKind} onChange={(e) => setHireKind(e.target.value)} data-comment-anchor="f7ad2d9fe1-select-304-77"><option value="employee">Employee</option><option value="contractor">Contractor</option></select></div></div>
            <div className="field"><label>Start date</label><div className="ctrl"><Icon name="calendar" style={{ color: "var(--fg-4)" }} /><input defaultValue={date} /></div></div>
          </div>
          {hireKind === "contractor" && (
            <div className="field-row">
              <div className="field">
                <label>End date <span style={{ color: "var(--mf-watermelon-900)" }}>*</span></label>
                <div className="ctrl"><Icon name="calendar" style={{ color: "var(--fg-4)" }} /><input value={hireEnd} onChange={(e) => setHireEnd(e.target.value)} /></div>
                <span className="hint">Required — contractors always have an end date.</span>
              </div>
              <div className="field"><label>Agency</label><div className="ctrl"><input defaultValue="Reply Tech" /></div></div>
            </div>
          )}
          <div className="field-row">
            <div className="field">
              <label>Function</label>
              <div className="ctrl">
                <select value={functionId} onChange={(e) => { setFunctionId(e.target.value); setRole(window.fnById[e.target.value]?.roles[0] || ""); }}>
                  {window.FUNCTIONS.map((f) => <option key={f.id} value={f.id}>{f.name}</option>)}
                </select>
              </div>
            </div>
            <div className="field">
              <label>Role</label>
              <div className="ctrl">
                <select value={role} onChange={(e) => setRole(e.target.value)}>
                  {fnRoles.map((r) => <option key={r} value={r}>{r}</option>)}
                </select>
              </div>
              <span className="hint">Pick from {fn?.name}'s allowed roles — create new ones in the Function page.</span>
            </div>
          </div>
          <div className="field"><label>Line manager</label><div className="ctrl"><select defaultValue="p-gio">{window.PEOPLE.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></div></div>
          <div className="field">
            <label>Allocations</label>
            <window.AllocateForm person={person} cur={{ allocations: [{ groupId: payload.groupId || "wg-core", pct: 100 }] }} embedded />
          </div>
        </>
      }

      {kind === "allocate" &&
      <window.AllocateForm person={person} cur={cur} />
      }

      {kind === "role" &&
      <>
          <div className="field-row">
            <div className="field"><label>Effective from</label><div className="ctrl"><input value={date} onChange={(e) => setDate(e.target.value)} /></div></div>
            <div className="field">
              <label>New role</label>
              <div className="ctrl">
                <select value={role || cur?.role || ""} onChange={(e) => setRole(e.target.value)}>
                  {personFnRoles.map((r) => <option key={r} value={r}>{r}</option>)}
                </select>
              </div>
              <span className="hint">From {personFn?.name}'s allowed roles.</span>
            </div>
          </div>
        </>
      }

      {kind === "create-role" &&
      <CreateRoleForm initialFunctionId={payload.functionId || functionId} />
      }

      {kind === "manager" &&
      <div className="field-row">
          <div className="field"><label>Effective from</label><div className="ctrl"><input defaultValue={date} /></div></div>
          <div className="field"><label>New manager</label><div className="ctrl"><select>{window.PEOPLE.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></div></div>
        </div>
      }

      {kind === "extend" &&
      <>
          <div className="field-row">
            <div className="field"><label>Current end</label><div className="ctrl">{window.dstr(person.endDate)}</div></div>
            <div className="field"><label>New end date</label><div className="ctrl"><input defaultValue={window.dstr(window.addMonths(person.endDate || window.TODAY, 3))} /></div></div>
          </div>
          <div className="field-row">
            <div className="field"><label>Daily rate (€)</label><div className="ctrl"><input defaultValue={person.dailyRate || 600} /></div></div>
            <div className="field"><label>Days / week</label><div className="ctrl"><input defaultValue={person.daysPerWeek || 5} /></div></div>
          </div>
        </>
      }

      {kind === "end" &&
      <>
          <div className="field-row">
            <div className="field"><label>Last day</label><div className="ctrl"><input defaultValue={date} /></div></div>
            <div className="field"><label>Reason</label><div className="ctrl"><select defaultValue="end"><option>Contract end</option><option>Resigned</option><option>Mutual termination</option><option>Re-org</option></select></div></div>
          </div>
        </>
      }

      {kind !== "allocate" && kind !== "hire" && kind !== "create-role" && (
        <div className="diff-preview">
          <div className="dp-title">Change preview</div>
          {kind === "role" && cur &&
          <>
              <div className="diff-row"><span className="dk">Role</span><span className="dv-from">{cur.role}</span><span className="diff-arrow">→</span><span className="dv-to">{role}</span></div>
              <div className="diff-row"><span className="dk">Effective</span><span className="dv-to">{date}</span></div>
            </>
          }
          {kind === "end" &&
          <div className="diff-row"><span className="dk">Closes</span><span className="dv-to">All active assignments on {date}</span></div>
          }
          {kind === "extend" &&
          <div className="diff-row"><span className="dk">Extends</span><span className="dv-to">{person.name} · adds new assignment record</span></div>
          }
          {kind === "manager" &&
          <div className="diff-row"><span className="dk">Manager</span><span className="dv-from">{window.pById[cur?.managerId]?.name || "—"}</span><span className="diff-arrow">→</span><span className="dv-to">New manager</span></div>
          }
        </div>
      )}
    </>);
}

function CreateRoleForm({ initialFunctionId }) {
  const [fnId, setFnId] = useStateTT(initialFunctionId || "fn-eng");
  const [roleName, setRoleName] = useStateTT("");
  const [note, setNote] = useStateTT("");
  const fn = window.fnById[fnId];
  return (
    <>
      <div className="field">
        <label>Function</label>
        <div className="ctrl">
          <select value={fnId} onChange={(e) => setFnId(e.target.value)}>
            {window.FUNCTIONS.map((f) => <option key={f.id} value={f.id}>{f.name}</option>)}
          </select>
        </div>
      </div>
      <div className="field">
        <label>Role name</label>
        <div className="ctrl"><input value={roleName} onChange={(e) => setRoleName(e.target.value)} placeholder="e.g. Principal Engineer" /></div>
        <span className="hint">Roles are scoped to one function. People are assigned only to existing roles — never free text.</span>
      </div>
      <div className="field">
        <label>Note</label>
        <div className="ctrl"><textarea rows={2} value={note} onChange={(e) => setNote(e.target.value)} placeholder="What this role is for…" style={{ resize: "vertical", height: 50 }} /></div>
      </div>
      <div className="diff-preview">
        <div className="dp-title">Change preview</div>
        <div className="diff-row"><span className="dk">Creates</span><span className="dv-to">{roleName || "(role)"} in <strong>{fn?.name}</strong></span></div>
        <div className="diff-row"><span className="dk">Existing</span><span className="dv-to muted">{(fn?.roles || []).length} role{(fn?.roles || []).length === 1 ? "" : "s"} already defined</span></div>
      </div>
    </>
  );
}
