/* Drawers: backlog (right side), sprint switcher (header dropdown),
   edit sprint panel, toast/undo. */

const { useState: useStateD, useMemo: useMemoD } = React;

/* ============ BACKLOG DRAWER ============ */

function BacklogDrawer({ open, onClose, backlog, sprintTickets, onAdd, dragTicket, setDragTicket, multiSelect, setMultiSelect, onBulkAdd }) {
  const [q, setQ] = useStateD('');
  const [filterType, setFilterType] = useStateD('all');
  const [filterPriority, setFilterPriority] = useStateD('all');

  const filtered = useMemoD(() => {
    return backlog.filter(t => {
      if (q && !(`${t.id} ${t.title}`.toLowerCase().includes(q.toLowerCase()))) return false;
      if (filterType !== 'all' && t.type !== filterType) return false;
      if (filterPriority !== 'all' && t.priority !== filterPriority) return false;
      return true;
    });
  }, [backlog, q, filterType, filterPriority]);

  const totalH = filtered.reduce((s, t) => s + t.hours, 0);

  // Sync to URL — filter state survives refresh
  React.useEffect(() => {
    if (!open) return;
    const usp = new URLSearchParams(window.location.search);
    q ? usp.set('q', q) : usp.delete('q');
    filterType !== 'all' ? usp.set('type', filterType) : usp.delete('type');
    filterPriority !== 'all' ? usp.set('pri', filterPriority) : usp.delete('pri');
    const url = usp.toString() ? '?' + usp.toString() : window.location.pathname;
    window.history.replaceState(null, '', url);
  }, [q, filterType, filterPriority, open]);

  React.useEffect(() => {
    const usp = new URLSearchParams(window.location.search);
    if (usp.get('q')) setQ(usp.get('q'));
    if (usp.get('type')) setFilterType(usp.get('type'));
    if (usp.get('pri')) setFilterPriority(usp.get('pri'));
  }, []);

  return (
    <>
      {open && <div className="drawer-scrim" onClick={onClose} />}
      <aside className={"backlog-drawer" + (open ? " is-open" : "")} aria-hidden={!open}>
        <header className="backlog-drawer__head">
          <div>
            <div className="backlog-drawer__title">Backlog</div>
            <div className="backlog-drawer__sub">
              {filtered.length} tickets · {totalH}h · drag onto any lane, or tap +
            </div>
          </div>
          <button className="icon-btn" onClick={onClose} aria-label="Close backlog">
            <Icon d={ICONS.x} size={16} />
          </button>
        </header>

        {/* Filters — consolidated to ONE surface */}
        <div className="backlog-filters">
          <div className="search">
            <Icon d={ICONS.search} size={14} />
            <input placeholder="Search backlog" value={q} onChange={e => setQ(e.target.value)} />
          </div>
          <div className="filter-row">
            <select className="select select--sm" value={filterType} onChange={e => setFilterType(e.target.value)}>
              <option value="all">All types</option>
              <option value="bug">Bugs</option>
              <option value="story">Stories</option>
              <option value="task">Tasks</option>
              <option value="epic">Epics</option>
            </select>
            <select className="select select--sm" value={filterPriority} onChange={e => setFilterPriority(e.target.value)}>
              <option value="all">All priorities</option>
              <option value="P0">P0 only</option>
              <option value="P1">P0+P1</option>
              <option value="P2">P2</option>
              <option value="P3">P3</option>
            </select>
            <button
              className={"btn btn--ghost btn--sm" + (multiSelect.length ? " is-active" : "")}
              onClick={() => setMultiSelect([])}
            >
              {multiSelect.length ? `${multiSelect.length} selected · clear` : 'Multi-select'}
            </button>
          </div>
        </div>

        {multiSelect.length > 0 && (
          <div className="backlog-bulk">
            <span className="backlog-bulk__lbl">
              {multiSelect.length} selected · {multiSelect.reduce((s, id) => s + (backlog.find(t => t.id === id)?.hours || 0), 0)}h
            </span>
            <button className="btn btn--primary btn--sm" onClick={() => onBulkAdd(multiSelect)}>
              <Icon d={ICONS.plus} size={12} />Add to sprint
            </button>
          </div>
        )}

        <div className="backlog-drawer__list">
          {filtered.map(t => {
            const selected = multiSelect.includes(t.id);
            const assigned = PEOPLE.find(p => p.id === t.assignee);
            const targetBucket = personBucket(assigned, sprintTickets);
            const wouldOver = targetBucket.usedH + t.hours > targetBucket.availH;
            return (
              <div
                key={t.id}
                className={"backlog-row" + (selected ? " is-selected" : "")}
                draggable
                onDragStart={e => { setDragTicket(t); e.dataTransfer.effectAllowed = 'move'; }}
                onDragEnd={() => setDragTicket(null)}
              >
                <label className="backlog-row__check" onClick={e => e.stopPropagation()}>
                  <input
                    type="checkbox"
                    checked={selected}
                    onChange={e => {
                      if (e.target.checked) setMultiSelect([...multiSelect, t.id]);
                      else setMultiSelect(multiSelect.filter(x => x !== t.id));
                    }}
                  />
                </label>
                <span className="backlog-row__type" data-type={t.type}>{TYPE_LABEL[t.type]}</span>
                <div className="backlog-row__body">
                  <div className="backlog-row__title">{t.title}</div>
                  <div className="backlog-row__meta">
                    <code>{t.id}</code>
                    <span className={"prio prio--" + t.priority.toLowerCase()}>{t.priority}</span>
                    <span className="backlog-row__assign">
                      <span className="avatar avatar--sm" data-tone={assigned.tone}>{assigned.name.charAt(0)}</span>
                      {assigned.name.split(' ')[0]}
                      {wouldOver && <span className="warn-dot" title="Would push assignee over capacity">!</span>}
                    </span>
                    {t.meta && <span className="backlog-row__meta__note">· {t.meta}</span>}
                  </div>
                </div>
                <div className="backlog-row__h">{t.hours}h</div>
                <button className="backlog-row__add" onClick={() => onAdd(t)} aria-label={`Add ${t.id} to sprint`}>
                  <Icon d={ICONS.plus} size={13} />
                </button>
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div className="empty">
              <div className="empty__title">No matching tickets</div>
              <div>Adjust the search or filters above.</div>
            </div>
          )}
        </div>
      </aside>
    </>
  );
}

/* ============ SPRINT SWITCHER ============ */

function Switcher({ open, onClose, sprint, project, onPickSprint, onPickProject, onNew }) {
  if (!open) return null;
  return (
    <>
      <div className="drawer-scrim drawer-scrim--light" onClick={onClose} />
      <div className="switcher-pop" role="dialog">
        <div className="switcher-pop__head">
          <div className="eyebrow">PROJECT</div>
          {PROJECTS.map(p => (
            <button
              key={p.id}
              className={"switcher-pop__proj" + (p.id === project.id ? " is-active" : "")}
              onClick={() => onPickProject(p.id)}
            >
              <span className="switcher-pop__proj__dot" data-tone={p.id === 'sym' ? 1 : p.id === 'api' ? 2 : 5} />
              {p.label}
              {p.id === project.id && <Icon d={ICONS.check} size={12} />}
            </button>
          ))}
        </div>
        <div className="switcher-pop__sprints">
          <div className="eyebrow" style={{ padding: '4px 12px' }}>SPRINTS · {project.label}</div>
          {SPRINTS.map(s => (
            <button
              key={s.id}
              className={"switcher-pop__sprint" + (s.id === sprint.id ? " is-active" : "")}
              onClick={() => onPickSprint(s.id)}
            >
              <div className="switcher-pop__sprint__top">
                <span className="switcher-pop__sprint__name">{s.label}</span>
                <span className={"switcher-pop__sprint__state state-" + s.state}>{s.state}</span>
              </div>
              <div className="switcher-pop__sprint__sub">
                <span>{s.range}</span>
                {s.velocityActual && <span className="mono">· shipped {s.velocityActual}h</span>}
              </div>
              <div className="switcher-pop__sprint__goal">{s.goal}</div>
            </button>
          ))}
          <button className="switcher-pop__new" onClick={onNew}>
            <Icon d={ICONS.plus} size={13} />New sprint
          </button>
        </div>
      </div>
    </>
  );
}

/* ============ EDIT SPRINT PANEL ============ */

function EditPanel({ open, onClose, sprint, onSave }) {
  const [name, setName] = useStateD(sprint.label);
  const [goal, setGoal] = useStateD(sprint.goal);
  const [start, setStart] = useStateD('2026-05-20');
  const [end, setEnd] = useStateD('2026-06-02');

  React.useEffect(() => { setName(sprint.label); setGoal(sprint.goal); }, [sprint]);

  if (!open) return null;
  return (
    <>
      <div className="drawer-scrim" onClick={onClose} />
      <aside className="edit-panel">
        <header className="edit-panel__head">
          <div>
            <div className="eyebrow">EDIT</div>
            <div className="edit-panel__title">Sprint settings</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon d={ICONS.x} size={16} /></button>
        </header>
        <div className="edit-panel__body">
          <div className="field">
            <label className="field__label">Name</label>
            <input className="input" value={name} onChange={e => setName(e.target.value)} />
          </div>
          <div className="field">
            <label className="field__label">Goal</label>
            <textarea className="textarea" value={goal} onChange={e => setGoal(e.target.value)} rows={2} />
            <div className="field__hint">Shown to the team and surfaced on the sprint review.</div>
          </div>
          <div className="grid grid--2">
            <div className="field">
              <label className="field__label">Start</label>
              <input className="input" type="date" value={start} onChange={e => setStart(e.target.value)} />
            </div>
            <div className="field">
              <label className="field__label">End</label>
              <input className="input" type="date" value={end} onChange={e => setEnd(e.target.value)} />
            </div>
          </div>
          <div className="edit-panel__warn">
            <Icon d={ICONS.info} size={13} />
            <div>
              Capacity will recompute from the new date range. PTO falling outside the range is auto-removed.
            </div>
          </div>
        </div>
        <footer className="edit-panel__foot">
          <button className="btn btn--ghost" onClick={onClose}>Cancel</button>
          <button className="btn btn--primary" onClick={() => { onSave({ label: name, goal }); onClose(); }}>
            Save changes
          </button>
        </footer>
      </aside>
    </>
  );
}

/* ============ TOAST ============ */

function Toast({ toast, onUndo, onDismiss }) {
  React.useEffect(() => {
    if (!toast) return;
    const id = setTimeout(onDismiss, 6000);
    return () => clearTimeout(id);
  }, [toast]);

  if (!toast) return null;
  return (
    <div className="sp-toast">
      <Icon d={ICONS.check} size={14} />
      <span className="sp-toast__msg">{toast.msg}</span>
      {toast.canUndo && (
        <button className="sp-toast__undo" onClick={onUndo}>
          <Icon d={ICONS.undo} size={12} />Undo
        </button>
      )}
      <button className="sp-toast__x" onClick={onDismiss} aria-label="Dismiss">
        <Icon d={ICONS.x} size={11} />
      </button>
    </div>
  );
}

Object.assign(window, { BacklogDrawer, Switcher, EditPanel, Toast });
