// Tasks tab — behaviors + reward jars in one place.
// Tasks/jars with the same definition are grouped; one capsule shows all assigned kids.

function taskGroupKey(t) {
  return `${t.kind}|${t.emoji}|${t.label}|${t.points}`;
}

function jarGroupKey(j) {
  return `${j.emoji}|${j.label}|${j.goal}|${j.color}|${j.note || ''}`;
}

function groupTasks(tasks) {
  const map = new Map();
  for (const t of tasks) {
    const key = taskGroupKey(t);
    if (!map.has(key)) map.set(key, []);
    map.get(key).push(t);
  }
  return Array.from(map.entries()).map(([key, items]) => ({ key, items, rep: items[0] }));
}

function groupJars(jars) {
  const map = new Map();
  for (const j of jars) {
    const key = jarGroupKey(j);
    if (!map.has(key)) map.set(key, []);
    map.get(key).push(j);
  }
  return Array.from(map.entries()).map(([key, items]) => ({ key, items, rep: items[0] }));
}

function TaskManager() {
  const s = window.useStore();
  const [openTasks, setOpenTasks] = React.useState(true);
  const [openJars, setOpenJars] = React.useState(true);
  const [filterKid, setFilterKid] = React.useState('all');

  // Tasks
  const [taskFilter, setTaskFilter] = React.useState('all');
  const [editingTaskKey, setEditingTaskKey] = React.useState(null); // null | 'new' | group key
  const [taskDraft, setTaskDraft] = React.useState({ emoji: '⭐', label: '', points: 3, kind: 'good', assignedTo: [] });

  // Jars
  const [editingJarKey, setEditingJarKey] = React.useState(null);
  const [jarDraft, setJarDraft] = React.useState({ emoji: '🏆', label: '', goal: 20, color: 'mango', note: '', assignedTo: [] });

  const tasks = s.tasks;
  const jars = s.jars;

  const allTaskGroups = groupTasks(tasks);
  const allJarGroups = groupJars(jars);

  const visibleTaskGroups = allTaskGroups.filter(g => {
    if (taskFilter !== 'all' && g.rep.kind !== taskFilter) return false;
    if (filterKid !== 'all' && !g.items.some(t => t.kid_id === filterKid)) return false;
    return true;
  });
  const visibleJarGroups = allJarGroups.filter(g =>
    filterKid === 'all' || g.items.some(j => j.kid_id === filterKid)
  );

  const goodCount = allTaskGroups.filter(g => g.rep.kind === 'good').length;
  const badCount  = allTaskGroups.filter(g => g.rep.kind === 'bad').length;

  const kidsForGroup = (items) => items
    .map(item => s.kids.find(k => k.id === item.kid_id))
    .filter(Boolean)
    .sort((a, b) => a.name.localeCompare(b.name));

  // ── Task actions ──
  const openNewTask = () => {
    setTaskDraft({ emoji: '⭐', label: '', points: 3, kind: 'good', assignedTo: s.kids.map(k => k.id) });
    setEditingTaskKey('new');
  };
  const openEditTask = (group) => {
    setTaskDraft({
      ...group.rep,
      assignedTo: group.items.map(t => t.kid_id),
    });
    setEditingTaskKey(group.key);
  };

  const saveTask = async () => {
    const fields = {
      emoji: taskDraft.emoji,
      label: taskDraft.label,
      points: taskDraft.points,
      kind: taskDraft.kind,
    };
    if (editingTaskKey === 'new') {
      await s.addTask({ kidIds: taskDraft.assignedTo, ...fields });
    } else {
      const group = allTaskGroups.find(g => g.key === editingTaskKey);
      if (!group) return;
      const oldKidIds = group.items.map(t => t.kid_id);
      const nextKidIds = taskDraft.assignedTo || [];
      for (const t of group.items) await s.updateTask(t.id, fields);
      for (const kidId of nextKidIds.filter(id => !oldKidIds.includes(id))) {
        await s.addTask({ kidIds: [kidId], ...fields });
      }
      for (const t of group.items.filter(t => !nextKidIds.includes(t.kid_id))) {
        await s.removeTask(t.id);
      }
    }
    setEditingTaskKey(null);
  };

  const bumpPoints = async (group, dir) => {
    const rep = group.rep;
    const newAbs = Math.max(1, Math.min(20, Math.abs(rep.points) + dir));
    const signed = rep.kind === 'good' ? newAbs : -newAbs;
    for (const t of group.items) await s.updateTask(t.id, { points: signed });
  };

  const delTaskGroup = async (group) => {
    const names = kidsForGroup(group.items).map(k => k.name).join(', ');
    const msg = group.items.length > 1
      ? `Remove "${group.rep.label}" for ${names}?`
      : `Remove "${group.rep.label}"?`;
    if (!window.confirm(msg)) return;
    for (const t of group.items) await s.removeTask(t.id);
  };

  const addSuggestion = async (sug) => {
    if (!s.kids.length) return;
    const points = parseInt(sug.p, 10);
    const signed = sug.k === 'good' ? Math.abs(points) : -Math.abs(points);
    const key = `${sug.k}|${sug.e}|${sug.l}|${signed}`;
    const existing = allTaskGroups.find(g => g.key === key);
    const kidIds = existing
      ? s.kids.filter(k => !existing.items.some(t => t.kid_id === k.id)).map(k => k.id)
      : s.kids.map(k => k.id);
    if (!kidIds.length) return;
    await s.addTask({
      kidIds,
      emoji: sug.e, label: sug.l,
      points: signed,
      kind: sug.k,
    });
  };

  // ── Jar actions ──
  const openNewJar = () => {
    setJarDraft({ emoji: '🏆', label: '', goal: 20, color: 'mango', note: '', assignedTo: s.kids.map(k => k.id) });
    setEditingJarKey('new');
  };
  const openEditJar = (group) => {
    setJarDraft({
      ...group.rep,
      assignedTo: group.items.map(j => j.kid_id),
    });
    setEditingJarKey(group.key);
  };

  const saveJar = async () => {
    const fields = {
      emoji: jarDraft.emoji,
      label: jarDraft.label.trim(),
      goal: Math.max(1, Math.round(jarDraft.goal)),
      color: jarDraft.color,
      note: jarDraft.note?.trim() || null,
    };
    if (editingJarKey === 'new') {
      for (const kidId of jarDraft.assignedTo) await s.addJar(kidId, fields);
    } else {
      const group = allJarGroups.find(g => g.key === editingJarKey);
      if (!group) return;
      const oldKidIds = group.items.map(j => j.kid_id);
      const nextKidIds = jarDraft.assignedTo || [];
      for (const j of group.items) await s.updateJar(j.id, fields);
      for (const kidId of nextKidIds.filter(id => !oldKidIds.includes(id))) {
        await s.addJar(kidId, fields);
      }
      for (const j of group.items.filter(j => !nextKidIds.includes(j.kid_id))) {
        await s.removeJar(j.id);
      }
    }
    setEditingJarKey(null);
  };

  const delJarGroup = async (group) => {
    const names = kidsForGroup(group.items).map(k => k.name).join(', ');
    const msg = group.items.length > 1
      ? `Remove "${group.rep.label}" for ${names}? Stars in each jar go back to the pile.`
      : 'Remove this jar? Stars in it go back to the pile.';
    if (!window.confirm(msg)) return;
    for (const j of group.items) await s.removeJar(j.id);
  };

  return (
    <div className="screen">
      <TaskManagerStyles />

      <header style={{ display: 'flex', alignItems: 'center', marginBottom: 28, gap: 20, flexWrap: 'wrap' }}>
        <div className="mascot-bob">
          <window.Suri mood="thinking" size={80} color="#A878E8" />
        </div>
        <div>
          <window.Eyebrow>Settings</window.Eyebrow>
          <h1 className="h-display h2" style={{ marginTop: 6 }}>Tasks & jars</h1>
          <p className="lede" style={{ marginTop: 8, fontSize: 17 }}>
            What earns or loses stars, and what kids save toward. Tap a capsule to edit.
          </p>
        </div>
      </header>

      {/* Shared kid filter */}
      {s.kids.length > 0 && (
        <div style={{ display: 'flex', gap: 8, marginBottom: 20, alignItems: 'center', flexWrap: 'wrap' }}>
          <span className="eyebrow" style={{ marginRight: 4 }}>Show for</span>
          <KidFilterChip active={filterKid === 'all'} onClick={() => setFilterKid('all')}>All kids</KidFilterChip>
          {s.kids.map(k => (
            <KidFilterChip key={k.id} kid={k} active={filterKid === k.id} onClick={() => setFilterKid(k.id)}>
              {k.name}
            </KidFilterChip>
          ))}
        </div>
      )}

      {/* ── Tasks section ── */}
      <CollapsibleSection
        title="Tasks"
        subtitle="What earns or loses stars"
        count={visibleTaskGroups.length}
        open={openTasks}
        onToggle={() => setOpenTasks(o => !o)}
        action={
          <button type="button" className="tm-add-btn" onClick={(e) => { e.stopPropagation(); openNewTask(); }}>
            ＋ Add task
          </button>
        }>
        <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
          {[
            { id: 'all',  label: 'All',          count: allTaskGroups.length, color: 'var(--ink)' },
            { id: 'good', label: 'Earns',        count: goodCount,    color: 'var(--success)' },
            { id: 'bad',  label: 'Loses',        count: badCount,     color: 'var(--alert)' },
          ].map(t => (
            <FilterPill key={t.id} active={taskFilter === t.id} color={t.color} onClick={() => setTaskFilter(t.id)}>
              {t.label} <span className="tm-count">{t.count}</span>
            </FilterPill>
          ))}
        </div>

        {visibleTaskGroups.length === 0 ? (
          <EmptyHint onAdd={openNewTask} label="No tasks yet — add one or pick a suggestion below." />
        ) : (
          <div className="tm-capsule-grid">
            {visibleTaskGroups.map(group => (
              <TaskCapsule key={group.key} group={group} kids={kidsForGroup(group.items)}
                onEdit={() => openEditTask(group)}
                onDel={() => delTaskGroup(group)}
                onBump={(d) => bumpPoints(group, d)} />
            ))}
          </div>
        )}

        <div className="tm-suggestions">
          <span className="eyebrow">Quick-add</span>
          <div className="tm-suggestion-row">
            {[
              { e: '🥗', l: 'Eat veggies', p: '4', k: 'good' },
              { e: '😴', l: 'In bed by 9pm', p: '3', k: 'good' },
              { e: '🎻', l: 'Practice instrument', p: '5', k: 'good' },
              { e: '😡', l: 'Hit a sibling', p: '-6', k: 'bad' },
            ].map((sug, i) => (
              <button key={i} type="button" className="tm-sug-chip" onClick={() => addSuggestion(sug)}>
                {sug.e} {sug.l}
                <span style={{ color: sug.k === 'good' ? 'var(--success)' : 'var(--alert)' }}>
                  {sug.k === 'good' ? `+${sug.p}` : sug.p}
                </span>
              </button>
            ))}
          </div>
        </div>
      </CollapsibleSection>

      {/* ── Jars section ── */}
      <CollapsibleSection
        title="Reward jars"
        subtitle="Goals kids save stars toward"
        count={visibleJarGroups.length}
        open={openJars}
        onToggle={() => setOpenJars(o => !o)}
        action={
          <button type="button" className="tm-add-btn" onClick={(e) => { e.stopPropagation(); openNewJar(); }}>
            ＋ Add jar
          </button>
        }>
        {visibleJarGroups.length === 0 ? (
          <EmptyHint onAdd={openNewJar} label="No jars yet — create a reward goal for a kid." />
        ) : (
          <div className="tm-jar-grid">
            {visibleJarGroups.map(group => (
              <JarCapsule key={group.key} group={group} kids={kidsForGroup(group.items)}
                onEdit={() => openEditJar(group)}
                onDel={() => delJarGroup(group)} />
            ))}
          </div>
        )}
      </CollapsibleSection>

      {editingTaskKey && (
        <TaskEditor
          draft={taskDraft} setDraft={setTaskDraft}
          onSave={saveTask} onClose={() => setEditingTaskKey(null)}
          isNew={editingTaskKey === 'new'}
          kids={s.kids}
        />
      )}

      {editingJarKey && (
        <JarEditorModal
          draft={jarDraft} setDraft={setJarDraft}
          onSave={saveJar} onClose={() => setEditingJarKey(null)}
          isNew={editingJarKey === 'new'}
          kids={s.kids}
        />
      )}
    </div>
  );
}

// ── Collapsible section shell ──

function CollapsibleSection({ title, subtitle, count, open, onToggle, action, children }) {
  return (
    <section className={`tm-section ${open ? 'open' : 'closed'}`}>
      <button type="button" className="tm-section-head" onClick={onToggle} aria-expanded={open}>
        <span className="tm-chevron" aria-hidden="true">{open ? '▾' : '▸'}</span>
        <span className="tm-section-titles">
          <span className="tm-section-title">{title}</span>
          {subtitle && <span className="tm-section-sub">{subtitle}</span>}
        </span>
        <span className="tm-section-count">{count}</span>
        {action && <span className="tm-section-action" onClick={(e) => e.stopPropagation()}>{action}</span>}
      </button>
      {open && <div className="tm-section-body">{children}</div>}
    </section>
  );
}

// ── Compact capsules ──

function TaskCapsule({ group, kids, onEdit, onDel, onBump }) {
  const task = group.rep;
  const isGood = task.kind === 'good';
  const c = isGood ? 'var(--success)' : 'var(--alert)';
  const bg = isGood ? 'var(--mint-soft)' : 'var(--blush-soft)';

  return (
    <div className="tm-capsule" style={{ borderColor: c, background: bg }}>
      <span className="tm-capsule-emoji">{task.emoji}</span>
      <span className="tm-capsule-label" title={task.label}>{task.label}</span>
      <div className="tm-capsule-points">
        <button type="button" className="tm-bump" onClick={() => onBump(-1)} aria-label="Less">−</button>
        <span style={{ color: c, fontWeight: 700 }}>{task.points > 0 ? `+${task.points}` : task.points}</span>
        <button type="button" className="tm-bump" onClick={() => onBump(1)} aria-label="More">＋</button>
      </div>
      <div className="tm-kid-tags">
        {kids.map(kid => {
          const kc = window.KID_COLORS_V3[kid.color] || window.KID_COLORS_V3.mango;
          return (
            <span key={kid.id} className="tm-kid-tag" style={{ background: kc.soft, color: kc.hex, borderColor: kc.hex }}>
              {kid.name}
            </span>
          );
        })}
      </div>
      <div className="tm-capsule-actions">
        <button type="button" className="tm-icon-btn" onClick={onEdit} title="Edit">✎</button>
        <button type="button" className="tm-icon-btn tm-icon-btn--danger" onClick={onDel} title="Remove">×</button>
      </div>
    </div>
  );
}

function JarCapsule({ group, kids, onEdit, onDel }) {
  const jar = group.rep;
  const jc = (window.KID_COLORS_V3 || {})[jar.color] || window.KID_COLORS_V3.mango;
  const avgFill = group.items.reduce((sum, item) => sum + Math.min(1, (item.current || 0) / Math.max(jar.goal, 1)), 0) / group.items.length;

  return (
    <article className="tm-jar-bubble" style={{ '--jar-color': jc.hex, '--jar-soft': jc.soft }}>
      <div className="tm-jar-bubble-illo">
        <window.StarJar id={group.key} color={jc.hex} fillPct={avgFill} size={76} mood="idle" emoji={jar.emoji} />
      </div>
      <div className="tm-jar-bubble-label" title={jar.label}>{jar.label}</div>
      <div className="tm-jar-bubble-goal">{jar.goal} ★ goal</div>
      <div className="tm-kid-tags tm-kid-tags--jar">
        {group.items.map(item => {
          const kid = kids.find(k => k.id === item.kid_id);
          if (!kid) return null;
          const kc = window.KID_COLORS_V3[kid.color] || window.KID_COLORS_V3.mango;
          const full = (item.current || 0) >= jar.goal;
          return (
            <span key={item.id} className="tm-kid-tag tm-kid-tag--jar" style={{ background: kc.soft, color: kc.hex, borderColor: kc.hex }}>
              {kid.name} · {item.current || 0}/{jar.goal}
              {full && <span className="tm-full-dot" title="Full">●</span>}
            </span>
          );
        })}
      </div>
      <div className="tm-jar-bubble-actions">
        <button type="button" className="tm-icon-btn" onClick={onEdit} title="Edit">✎</button>
        <button type="button" className="tm-icon-btn tm-icon-btn--danger" onClick={onDel} title="Remove">×</button>
      </div>
    </article>
  );
}

// ── Small helpers ──

function KidFilterChip({ kid, active, onClick, children }) {
  const kc = kid ? (window.KID_COLORS_V3[kid.color] || window.KID_COLORS_V3.mango) : null;
  return (
    <button type="button" onClick={onClick} className="chip" style={{
      background: active ? (kc ? kc.hex : 'var(--ink)') : 'var(--paper)',
      color: active ? 'white' : 'var(--ink)',
      border: '1.5px solid ' + (active ? (kc ? kc.hex : 'var(--ink)') : 'var(--rule-strong)'),
      cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13,
    }}>{children}</button>
  );
}

function FilterPill({ active, color, onClick, children }) {
  return (
    <button type="button" onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '7px 14px', borderRadius: 999,
      background: active ? color : 'var(--paper)',
      color: active ? 'white' : 'var(--ink)',
      border: active ? `1.5px solid ${color}` : '1.5px solid var(--rule-strong)',
      fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13,
      cursor: 'pointer',
    }}>{children}</button>
  );
}

function EmptyHint({ label, onAdd }) {
  return (
    <div className="tm-empty">
      <span>{label}</span>
      <button type="button" className="tm-add-btn tm-add-btn--inline" onClick={onAdd}>＋ Add</button>
    </div>
  );
}

// ── Modals (unchanged logic, jar editor mirrors task editor) ──

function TaskEditor({ draft, setDraft, onSave, onClose, isNew, kids }) {
  const emojis = ['⭐', '🦷', '📚', '🧺', '🍽️', '🏃', '🤝', '🛏️', '🎨', '🎻', '🥗', '😴', '🚿', '😤', '📵', '🙊', '🤥', '😡'];

  return (
    <ModalShell onClose={onClose} title={isNew ? 'New task' : 'Edit task'}
      mood={draft.kind === 'good' ? 'cheer' : 'thinking'}
      moodColor={draft.kind === 'good' ? '#2EC7A0' : '#F25C7F'}>
      <div className="tm-kind-toggle">
        {['good', 'bad'].map(k => (
          <button key={k} type="button" onClick={() => setDraft({ ...draft, kind: k, points: k === 'good' ? Math.abs(draft.points) : -Math.abs(draft.points) })}
            className={draft.kind === k ? 'on' : ''}
            style={{ color: draft.kind === k ? (k === 'good' ? 'var(--success)' : 'var(--alert)') : 'var(--ink-soft)' }}>
            {k === 'good' ? '＋ Earns' : '− Loses'}
          </button>
        ))}
      </div>

      <EmojiPicker emojis={emojis} value={draft.emoji} onChange={(e) => setDraft({ ...draft, emoji: e })} />

      <div className="field" style={{ marginBottom: 14 }}>
        <label>What is it?</label>
        <input type="text" placeholder="e.g. Brush teeth" value={draft.label}
          onChange={(e) => setDraft({ ...draft, label: e.target.value })} autoFocus />
      </div>

      <PointsPicker kind={draft.kind} value={draft.points}
        onChange={(n) => setDraft({ ...draft, points: n })} />

      {kids?.length > 0 && (
        <KidMultiSelect kids={kids} selected={draft.assignedTo}
          onChange={(ids) => setDraft({ ...draft, assignedTo: ids })}
          hint={isNew ? 'Creates one task per selected kid.' : 'Add or remove kids for this task.'} />
      )}

      <ModalFooter onClose={onClose} onSave={onSave}
        saveLabel={isNew ? 'Add task' : 'Save'}
        disabled={!draft.label || !draft.assignedTo?.length} />
    </ModalShell>
  );
}

function JarEditorModal({ draft, setDraft, onSave, onClose, isNew, kids }) {
  const emojis = ['🏆', '📺', '🍭', '🎮', '✈️', '🐷', '💝', '📚', '🎨', '🎀', '🚲', '🎁'];
  const colors = ['mango', 'mint', 'periwinkle', 'blush', 'butter', 'berry'];

  return (
    <ModalShell onClose={onClose} title={isNew ? 'New jar' : 'Edit jar'} mood="proud" moodColor="#FF6B2C">
      <EmojiPicker emojis={emojis} value={draft.emoji} onChange={(e) => setDraft({ ...draft, emoji: e })} />

      <div className="field" style={{ marginBottom: 14 }}>
        <label>Reward name</label>
        <input type="text" placeholder="e.g. Screen time" value={draft.label}
          onChange={(e) => setDraft({ ...draft, label: e.target.value })} autoFocus />
      </div>

      <div className="field" style={{ marginBottom: 14 }}>
        <label>Goal (stars to fill)</label>
        <input type="number" min="1" value={draft.goal}
          onChange={(e) => setDraft({ ...draft, goal: parseInt(e.target.value || '0', 10) || 0 })} />
      </div>

      <div className="field" style={{ marginBottom: 14 }}>
        <label>Jar color</label>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {colors.map(cn => {
            const hex = window.KID_COLORS_V3[cn].hex;
            const on = draft.color === cn;
            return (
              <button key={cn} type="button" onClick={() => setDraft({ ...draft, color: cn })}
                style={{
                  width: 28, height: 28, borderRadius: '50%', background: hex, padding: 0,
                  border: on ? '2px solid var(--ink)' : '2px solid transparent',
                  boxShadow: on ? `0 0 0 3px ${hex}50` : 'none', cursor: 'pointer',
                }} aria-label={cn} />
            );
          })}
        </div>
      </div>

      <div className="field" style={{ marginBottom: 14 }}>
        <label>Note (optional)</label>
        <input type="text" placeholder="e.g. 30 min of iPad" value={draft.note || ''}
          onChange={(e) => setDraft({ ...draft, note: e.target.value })} />
      </div>

      {kids?.length > 0 && (
        <KidMultiSelect kids={kids} selected={draft.assignedTo}
          onChange={(ids) => setDraft({ ...draft, assignedTo: ids })}
          hint={isNew ? 'Creates one jar per selected kid.' : 'Add or remove kids for this jar.'} />
      )}

      <ModalFooter onClose={onClose} onSave={onSave}
        saveLabel={isNew ? 'Add jar' : 'Save'}
        disabled={!draft.label?.trim() || draft.goal < 1 || !draft.assignedTo?.length} />
    </ModalShell>
  );
}

function ModalShell({ onClose, title, mood, moodColor, children }) {
  return (
    <div className="tm-modal-backdrop" onClick={onClose}>
      <div className="card tm-modal pop-in" onClick={(e) => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <window.Suri mood={mood} size={48} color={moodColor} />
            <h2 className="h-display h3" style={{ margin: 0 }}>{title}</h2>
          </div>
          <button type="button" onClick={onClose} className="tm-icon-btn" style={{ fontSize: 22 }}>×</button>
        </div>
        {children}
      </div>
    </div>
  );
}

function ModalFooter({ onClose, onSave, saveLabel, disabled }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, gap: 12 }}>
      <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
      <button type="button" className="btn btn-primary" onClick={onSave} disabled={disabled}
        style={{ opacity: disabled ? 0.4 : 1 }}>{saveLabel}</button>
    </div>
  );
}

function EmojiPicker({ emojis, value, onChange }) {
  return (
    <div className="field" style={{ marginBottom: 14 }}>
      <label>Icon</label>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {emojis.map(e => (
          <button key={e} type="button" onClick={() => onChange(e)} style={{
            width: 40, height: 40, fontSize: 22, borderRadius: 10,
            background: value === e ? 'var(--mango-soft)' : 'var(--paper)',
            border: '1.5px solid ' + (value === e ? 'var(--mango)' : 'var(--rule)'),
            cursor: 'pointer',
          }}>{e}</button>
        ))}
      </div>
    </div>
  );
}

function PointsPicker({ kind, value, onChange }) {
  return (
    <div className="field" style={{ marginBottom: 14 }}>
      <label>Points</label>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {[1, 2, 3, 4, 5, 6, 8, 10].map(n => {
          const on = Math.abs(value) === n;
          const c = kind === 'good' ? 'var(--success)' : 'var(--alert)';
          return (
            <button key={n} type="button" onClick={() => onChange(kind === 'good' ? n : -n)} style={{
              minWidth: 44, padding: '10px 0', borderRadius: 999,
              background: on ? c : 'var(--paper)', color: on ? 'white' : 'var(--ink)',
              border: on ? `1.5px solid ${c}` : '1.5px solid var(--rule-strong)',
              fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, cursor: 'pointer',
            }}>{n}</button>
          );
        })}
      </div>
    </div>
  );
}

function KidMultiSelect({ kids, selected, onChange, hint }) {
  return (
    <div className="field" style={{ marginBottom: 18 }}>
      <label>Who is this for?</label>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {kids.map(k => {
          const on = selected?.includes(k.id);
          const kc = window.KID_COLORS_V3[k.color] || window.KID_COLORS_V3.mango;
          return (
            <button key={k.id} type="button" onClick={() => onChange(
              on ? selected.filter(x => x !== k.id) : [...(selected || []), k.id]
            )} style={{
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '5px 12px 5px 5px', borderRadius: 999,
              background: on ? kc.soft : 'var(--paper)',
              border: '1.5px solid ' + (on ? kc.hex : 'var(--rule-strong)'),
              cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13,
            }}>
              <window.KidAvatar kid={k} />
              {k.name}
            </button>
          );
        })}
      </div>
      {hint && <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 6 }}>{hint}</div>}
    </div>
  );
}

function TaskManagerStyles() {
  return <style>{`
    .tm-section {
      background: var(--paper-2);
      border-radius: var(--r-lg);
      border: 1px solid var(--rule);
      box-shadow: var(--shadow-1);
      margin-bottom: 16px;
      overflow: hidden;
    }
    .tm-section-head {
      display: flex; align-items: center; gap: 12px;
      width: 100%; padding: 16px 18px;
      background: transparent; border: 0; text-align: left;
      cursor: pointer; font-family: inherit;
      transition: background 160ms ease;
    }
    .tm-section-head:hover { background: rgba(31, 26, 61, 0.03); }
    .tm-chevron {
      font-size: 14px; color: var(--ink-faint); width: 16px; flex: none;
    }
    .tm-section-titles { flex: 1; min-width: 0; }
    .tm-section-title {
      font-family: var(--font-display); font-weight: 700; font-size: 18px;
      letter-spacing: -0.02em; color: var(--ink); display: block;
    }
    .tm-section-sub {
      font-size: 13px; color: var(--ink-soft); margin-top: 2px; display: block;
    }
    .tm-section-count {
      font-family: var(--font-display); font-weight: 600; font-size: 12px;
      background: var(--paper-soft); color: var(--ink-soft);
      padding: 4px 10px; border-radius: 999px; flex: none;
    }
    .tm-section-action { flex: none; margin-left: 8px; }
    .tm-section-body { padding: 0 18px 18px; }

    .tm-add-btn {
      display: inline-flex; align-items: center; gap: 4px;
      padding: 7px 14px; border-radius: 999px;
      background: var(--mango-soft); color: var(--mango-deep);
      border: 1.5px solid var(--mango);
      font-family: var(--font-display); font-weight: 600; font-size: 13px;
      cursor: pointer; white-space: nowrap;
    }
    .tm-add-btn:hover { background: var(--mango); color: white; }
    .tm-add-btn--inline { margin-left: 8px; }

    .tm-capsule-grid {
      display: flex; flex-wrap: wrap; gap: 8px;
    }
    .tm-capsule {
      display: inline-flex; align-items: center; gap: 8px;
      padding: 6px 8px 6px 10px;
      border-radius: 999px;
      border: 1.5px solid var(--rule-strong);
      background: var(--paper);
      max-width: 100%;
      font-size: 13px;
      transition: box-shadow 160ms ease;
    }
    .tm-capsule:hover { box-shadow: var(--shadow-1); }
    .tm-jar-grid {
      display: flex; flex-wrap: wrap; gap: 14px;
    }
    .tm-jar-bubble {
      width: 148px;
      padding: 12px 12px 10px;
      border-radius: 999px 999px 36px 36px;
      background: linear-gradient(180deg, var(--jar-soft) 0%, var(--paper-2) 100%);
      border: 2.5px solid var(--jar-color);
      box-shadow: 0 5px 0 rgba(31, 26, 61, 0.08), var(--shadow-1);
      text-align: center;
      position: relative;
      transition: transform 180ms ease, box-shadow 180ms ease;
    }
    .tm-jar-bubble:hover {
      transform: translateY(-3px) rotate(-1deg);
      box-shadow: 0 7px 0 rgba(31, 26, 61, 0.07), var(--shadow-2);
    }
    .tm-jar-bubble-illo {
      position: relative;
      display: grid;
      place-items: center;
      height: 82px;
      margin-bottom: 2px;
    }
    .tm-jar-bubble-label {
      font-family: var(--font-display);
      font-weight: 700;
      font-size: 14px;
      letter-spacing: -0.02em;
      color: var(--ink);
      line-height: 1.15;
      padding: 0 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .tm-jar-bubble-goal {
      font-family: var(--font-display);
      font-weight: 600;
      font-size: 11px;
      color: var(--ink-soft);
      margin-top: 2px;
      margin-bottom: 8px;
    }
    .tm-kid-tags--jar {
      justify-content: center;
      margin-bottom: 6px;
    }
    .tm-jar-bubble-actions {
      display: flex;
      justify-content: center;
      gap: 4px;
    }
    .tm-capsule-emoji { font-size: 18px; line-height: 1; flex: none; }
    .tm-capsule-label {
      font-family: var(--font-display); font-weight: 600;
      white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
      max-width: 140px; color: var(--ink);
    }
    .tm-capsule-points {
      display: inline-flex; align-items: center; gap: 2px;
      background: rgba(255,255,255,0.6); border-radius: 999px;
      padding: 2px 4px; flex: none;
    }
    .tm-bump {
      width: 22px; height: 22px; border-radius: 50%;
      background: var(--paper-2); border: 1px solid var(--rule);
      font-size: 14px; font-weight: 700; cursor: pointer;
      display: grid; place-items: center; padding: 0; color: inherit;
    }
    .tm-kid-tags {
      display: inline-flex; flex-wrap: wrap; gap: 4px; flex: none;
    }
    .tm-kid-tag {
      font-family: var(--font-display); font-weight: 600; font-size: 11px;
      padding: 3px 8px; border-radius: 999px;
      border: 1px solid; white-space: nowrap; flex: none;
    }
    .tm-kid-tag--jar { display: inline-flex; align-items: center; gap: 3px; font-size: 10px; padding: 2px 7px; }
    .tm-full-dot { color: var(--butter); font-size: 10px; }
    .tm-capsule-actions {
      display: inline-flex; gap: 2px; margin-left: auto; flex: none;
    }
    .tm-icon-btn {
      width: 26px; height: 26px; border-radius: 50%;
      background: transparent; border: 0;
      color: var(--ink-faint); font-size: 14px;
      cursor: pointer; display: grid; place-items: center;
    }
    .tm-icon-btn:hover { background: rgba(31,26,61,0.06); color: var(--ink); }
    .tm-icon-btn--danger:hover { color: var(--alert); }

    .tm-empty {
      padding: 20px 16px; text-align: center;
      color: var(--ink-soft); font-size: 14px;
      background: var(--paper-soft); border-radius: 14px;
      border: 1.5px dashed var(--rule-strong);
    }
    .tm-suggestions {
      margin-top: 16px; padding-top: 14px;
      border-top: 1px solid var(--rule);
    }
    .tm-suggestion-row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
    .tm-sug-chip {
      display: inline-flex; align-items: center; gap: 6px;
      padding: 8px 12px; border-radius: 999px;
      background: var(--paper); border: 1.5px solid var(--rule-strong);
      font-family: var(--font-display); font-weight: 500; font-size: 13px;
      cursor: pointer;
    }
    .tm-sug-chip:hover { border-color: var(--mango); background: var(--mango-soft); }
    .tm-count {
      background: rgba(255,255,255,0.25); padding: 1px 7px; border-radius: 999px; font-size: 11px;
    }
    .tm-kind-toggle {
      display: flex; gap: 4px; padding: 4px;
      background: var(--paper-soft); border-radius: 999px; margin-bottom: 16px;
    }
    .tm-kind-toggle button {
      flex: 1; padding: 10px; border-radius: 999px; border: 0;
      background: transparent; font-family: var(--font-display);
      font-weight: 700; font-size: 14px; cursor: pointer;
    }
    .tm-kind-toggle button.on {
      background: var(--paper-2); box-shadow: var(--shadow-1);
    }
    .tm-modal-backdrop {
      position: fixed; inset: 0; z-index: 100;
      background: rgba(31, 26, 61, 0.4);
      display: grid; place-items: center; padding: 20px;
      backdrop-filter: blur(4px);
    }
    .tm-modal {
      width: 520px; max-width: 100%; max-height: 90vh; overflow-y: auto;
      padding: 24px 26px;
    }
    @media (max-width: 640px) {
      .tm-capsule-label { max-width: 100px; }
      .tm-section-head { flex-wrap: wrap; }
      .tm-section-action { width: 100%; margin-left: 28px; margin-top: 4px; }
    }
  `}</style>;
}

window.TaskManager = TaskManager;
