// Wrap-up ritual — fires when a burst finishes or a task is marked done.
// Forces the user to organize "open loops" (random ideas, follow-ups,
// new thoughts) into their proper homes BEFORE moving on.
//
// Routes per loop:
//   • Zip  → Brain zips (kind=dump)
//   • Idea → Brain zips (kind=idea)
//   • →P   → sub-task on a chosen priority
//   • Discard
//
// Plus a win to log + checkbox to mark the source task as done.

function Wrap() {
  const { state, addLoop, routeLoop, setWrapWin, completeWrap, dismissWrap } = useStore();
  const w = state.wrap;
  if (!w.active) return null;

  const [draft, setDraft] = React.useState('');
  const [markDone, setMarkDone] = React.useState(true);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    // focus the loop input on open
    setTimeout(() => inputRef.current?.focus(), 250);
  }, []);

  const submitLoop = (e) => {
    e?.preventDefault();
    if (!draft.trim()) return;
    addLoop(draft.trim());
    setDraft('');
    inputRef.current?.focus();
  };

  const stats = {
    total:    w.loops.length,
    routed:   w.loops.filter((l) => l.routed).length,
    pending:  w.loops.filter((l) => !l.routed).length,
  };

  const close = () => {
    completeWrap({ markTaskDone: markDone });
  };

  return (
    <div className="mc-wrap" onClick={(e) => { if (e.target === e.currentTarget) dismissWrap(); }}>
      <div className="mc-wrap-card">
        <div className="mc-wrap-hd">
          <div className="eyebrow"><span className="dot"/> Burst complete · close the loops</div>
          <h2>Nice. You worked on "{w.taskLabel}".</h2>
          <div className="src">60 seconds to sort what came up, before you walk off.</div>
          <button className="x" onClick={dismissWrap} title="Skip wrap-up">
            <Icons.X size={14}/>
          </button>
        </div>

        <div className="mc-wrap-body">
          {/* Task-done toggle, only if there's a task */}
          {w.taskId && (
            <label style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '10px 12px', borderRadius: 'var(--radius-md)',
              background: markDone ? 'var(--success-bg)' : 'var(--bg)',
              border: '1px solid ' + (markDone ? 'color-mix(in oklch, var(--success) 30%, var(--border))' : 'var(--border)'),
              cursor: 'pointer',
              transition: 'all var(--dur-1) var(--ease-standard)',
            }}>
              <input type="checkbox" checked={markDone} onChange={(e) => setMarkDone(e.target.checked)}
                     style={{ accentColor: 'var(--success)', width: 16, height: 16 }}/>
              <span style={{ fontSize: 13, color: 'var(--fg)', fontWeight: 500 }}>
                Mark task done: <b>{w.taskLabel}</b>
              </span>
            </label>
          )}

          {/* Loops capture */}
          <div className="mc-wrap-sect">
            <div className="hd">
              <span>Open loops</span>
              <span className="hint">
                Random stuff that came up. Type, ↵, then route each one.
              </span>
            </div>
            <form onSubmit={submitLoop}>
              <input
                ref={inputRef}
                className="mc-wrap-input"
                value={draft}
                onChange={(e) => setDraft(e.target.value)}
                placeholder='e.g. "follow up with Anna about pricing", "read that Sequoia memo", "Tella has 4K export now?"'
              />
            </form>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {w.loops.map((l) => (
                <LoopRow key={l.id} loop={l}
                         priorities={state.priorities.filter((p) => !p.done)}
                         onRoute={(dest) => routeLoop(l.id, dest)}/>
              ))}
              {w.loops.length === 0 && (
                <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '4px 4px', textAlign: 'center' }}>
                  Nothing came up? Skip ahead.
                </div>
              )}
            </div>
          </div>

          {/* Win to log */}
          <div className="mc-wrap-sect">
            <div className="hd">
              <span>Win to log <span style={{ color: 'var(--fg-3)' }}>· optional</span></span>
              <span className="hint">Something to remember went well</span>
            </div>
            <input
              className="mc-wrap-input"
              value={w.win}
              onChange={(e) => setWrapWin(e.target.value)}
              placeholder='e.g. "traction slide finally clicks", "closed Liesel reference check"'
            />
          </div>
        </div>

        <div className="mc-wrap-foot">
          <div className="stats">
            <span><b>{stats.routed}</b>/{stats.total} loops sorted</span>
            {stats.pending > 0 && (
              <span style={{ color: 'var(--warning)' }}>
                · {stats.pending} still pending
              </span>
            )}
            <span style={{ marginLeft: 4 }}>
              wrap streak <b>{state.wrapStreak || 0}</b>
            </span>
          </div>
          <div className="actions">
            <button className="skip" onClick={dismissWrap}>
              Skip
            </button>
            <button className="done" onClick={close}>
              <Icons.Check size={13}/> Sort & close
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function LoopRow({ loop, priorities, onRoute }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const btnRef = React.useRef(null);

  if (loop.routed) {
    const lbl = loop.routed === 'zip' ? 'in zips'
              : loop.routed === 'idea' ? 'in ideas'
              : loop.routed === 'discard' ? 'discarded'
              : loop.routed.startsWith('priority:')
                ? `→ ${priorities.find((p) => p.id === loop.routed.slice(9))?.title?.slice(0, 28) || 'priority'}…`
                : loop.routed;
    return (
      <div className="mc-loop routed">
        <Icons.Check size={13} style={{ color: 'var(--success)', flexShrink: 0 }}/>
        <span className="text">{loop.text}</span>
        <span className="routed-to">{lbl}</span>
      </div>
    );
  }

  return (
    <div className="mc-loop" style={{ position: 'relative' }}>
      <span className="text">{loop.text}</span>
      <div className="mc-loop-actions">
        <button className="mc-loop-btn" onClick={() => onRoute('zip')} title="Save to Brain zips">
          <Icons.Brain size={11}/> zip
        </button>
        <button className="mc-loop-btn idea" onClick={() => onRoute('idea')} title="Save as an idea">
          <Icons.Lightbulb size={11}/> idea
        </button>
        <button ref={btnRef} className="mc-loop-btn priority" onClick={() => setMenuOpen((o) => !o)} title="Add as sub-task to a priority">
          <Icons.Target size={11}/> →P
        </button>
        <button className="mc-loop-btn discard" onClick={() => onRoute('discard')} title="Let it go">
          <Icons.X size={11}/>
        </button>
      </div>
      {menuOpen && (
        <div className="mc-priority-menu" style={{ top: '100%', right: 0, marginTop: 4 }}
             onMouseLeave={() => setMenuOpen(false)}>
          <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase',
            letterSpacing: '0.08em', color: 'var(--fg-3)', padding: '6px 10px 4px' }}>
            Add as sub-task to…
          </div>
          {priorities.map((p, i) => (
            <button key={p.id} onClick={() => { onRoute(`priority:${p.id}`); setMenuOpen(false); }}>
              <span style={{
                width: 18, height: 18, borderRadius: 4, background: 'var(--grad-brand)',
                color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 10, fontWeight: 800, flexShrink: 0,
              }}>{i + 1}</span>
              <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {p.title}
              </span>
            </button>
          ))}
          {priorities.length === 0 && (
            <div style={{ fontSize: 11, color: 'var(--fg-3)', padding: '8px 10px' }}>No active priorities</div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Wrap });
