/* Bulk action bar, confetti, onboarding hint, save-view modal */

function BulkBar({ selectedIds, allTasks, onClear, onStatusAll, onPriorityAll, onArchiveAll, onDeleteAll }) {
  const [statusOpen, setStatusOpen]     = React.useState(false);
  const [priorityOpen, setPriorityOpen] = React.useState(false);
  if (selectedIds.length === 0) return null;

  return (
    <div className="fadein" style={{
      position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
      background: 'rgb(var(--ink))', color: 'white',
      borderRadius: 14, padding: '8px 12px',
      display: 'flex', alignItems: 'center', gap: 8,
      boxShadow: 'var(--sh-pop)', zIndex: 90,
      animation: 'fadein .2s ease-out',
    }}>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '4px 12px',
        background: 'rgb(var(--accent))', color: 'white',
        borderRadius: 999, fontWeight: 700, fontSize: 12.5,
      }}>
        <span className="num">{selectedIds.length}</span> selected
      </span>

      <span style={{ width: 1, height: 18, background: 'rgba(255,255,255,0.16)', marginInline: 4 }} />

      <BulkAction label="Status" open={statusOpen} setOpen={setStatusOpen}>
        {D.statuses.map(st => (
          <BulkMenuItem key={st.id} onClick={() => { onStatusAll(st.id); setStatusOpen(false); }}>
            <span className="pip" style={{ background: st.colour }} /> {st.title}
          </BulkMenuItem>
        ))}
      </BulkAction>

      <BulkAction label="Priority" open={priorityOpen} setOpen={setPriorityOpen}>
        {[['urgent','Urgent'],['high','High'],['medium','Medium'],['low','Low']].map(([k, lbl]) => (
          <BulkMenuItem key={k} onClick={() => { onPriorityAll(k); setPriorityOpen(false); }}>
            <PriorityDot p={k} /> {lbl}
          </BulkMenuItem>
        ))}
      </BulkAction>

      <button onClick={onArchiveAll} style={bulkBtn} onMouseEnter={onBulkHover} onMouseLeave={offBulkHover}>⊠ Archive</button>
      <button onClick={onDeleteAll}  style={{ ...bulkBtn, color: '#FCA5A5' }} onMouseEnter={onBulkHover} onMouseLeave={offBulkHover}>× Delete</button>

      <span style={{ width: 1, height: 18, background: 'rgba(255,255,255,0.16)', marginInline: 4 }} />

      <button onClick={onClear} style={{ ...bulkBtn, color: 'rgba(255,255,255,0.7)' }} onMouseEnter={onBulkHover} onMouseLeave={offBulkHover}>Clear</button>
    </div>
  );
}
const bulkBtn = {
  padding: '5px 12px', fontSize: 12.5, fontWeight: 600,
  color: 'white', borderRadius: 8, background: 'transparent',
  transition: 'background-color .12s',
};
const onBulkHover  = (e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; };
const offBulkHover = (e) => { e.currentTarget.style.background = 'transparent'; };

function BulkAction({ label, open, setOpen, children }) {
  return (
    <span style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={bulkBtn}
        onMouseEnter={onBulkHover} onMouseLeave={offBulkHover}>
        {label} <span style={{ fontSize: 9, opacity: 0.7 }}>▾</span>
      </button>
      {open && (
        <>
          <span onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 60 }} />
          <div className="shadow-pop fadein" style={{
            position: 'absolute', bottom: '100%', left: 0, marginBottom: 6,
            background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
            minWidth: 170, padding: 4, zIndex: 61, borderRadius: 10,
          }}>{children}</div>
        </>
      )}
    </span>
  );
}
function BulkMenuItem({ onClick, children }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 8, width: '100%',
      padding: '6px 10px', fontSize: 12, color: 'rgb(var(--ink))',
      textAlign: 'left', borderRadius: 6, fontWeight: 500,
    }}
      onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--paper-2))'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>{children}</button>
  );
}

/* ─── Confetti — small canvas burst when an urgent task completes ─── */
function ConfettiBurst({ trigger }) {
  const canvasRef = React.useRef(null);
  React.useEffect(() => {
    if (!trigger) return;
    const canvas = canvasRef.current;
    if (!canvas) return;
    canvas.style.display = 'block';
    canvas.width  = window.innerWidth;
    canvas.height = window.innerHeight;
    const ctx = canvas.getContext('2d');
    const palette = ['#6366F1', '#10B981', '#F59E0B', '#EC4899', '#3B82F6', '#F97316'];
    const N = 90;
    const parts = Array.from({ length: N }, () => {
      const angle = (Math.random() * Math.PI) - Math.PI / 2; // up & out
      const speed = 8 + Math.random() * 8;
      return {
        x: window.innerWidth / 2,
        y: window.innerHeight / 2,
        vx: Math.cos(angle) * speed,
        vy: Math.sin(angle) * speed - 4,
        size: 4 + Math.random() * 5,
        rot: Math.random() * Math.PI,
        vr: (Math.random() - 0.5) * 0.4,
        c: palette[Math.floor(Math.random() * palette.length)],
        life: 0,
        max: 60 + Math.random() * 40,
      };
    });
    let raf;
    const step = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      parts.forEach(p => {
        p.life++;
        p.vy += 0.4;
        p.x += p.vx;
        p.y += p.vy;
        p.rot += p.vr;
        ctx.save();
        ctx.translate(p.x, p.y);
        ctx.rotate(p.rot);
        ctx.globalAlpha = Math.max(0, 1 - p.life / p.max);
        ctx.fillStyle = p.c;
        ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size);
        ctx.restore();
      });
      if (parts.some(p => p.life < p.max)) raf = requestAnimationFrame(step);
      else { canvas.style.display = 'none'; }
    };
    raf = requestAnimationFrame(step);
    return () => { cancelAnimationFrame(raf); };
  }, [trigger]);
  return <canvas ref={canvasRef} style={{ position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 999, display: 'none' }} />;
}

/* ─── Onboarding hints (first-run, 3 tooltips) ─── */
function OnboardingHints({ onDismiss }) {
  const steps = [
    {
      title: '✨ Welcome to Taskhub',
      body: 'A few quick things you can do that aren\'t obvious. Hit "Got it" to dismiss each.',
      anchor: 'center', emoji: '👋',
    },
    {
      title: 'Drag-and-drop on the Board',
      body: 'Switch to Board view at the top and drag a card between columns to change its status. Calendar drag-rescheduling also works.',
      anchor: 'top-toolbar', emoji: '🤏',
    },
    {
      title: 'Press ✦ Pulse for AI',
      body: 'Pulse plans your day, balances workload, drafts replies, and flags risk. Try the chips at the top of the panel.',
      anchor: 'pulse', emoji: '🤖',
    },
    {
      title: 'Customise everything',
      body: 'Hit ⌘ K to jump anywhere, , (comma) for tweaks, and ? for the full keyboard cheatsheet.',
      anchor: 'center', emoji: '⌨',
    },
  ];
  const [idx, setIdx] = React.useState(0);
  const step = steps[idx];
  const next = () => idx < steps.length - 1 ? setIdx(idx + 1) : onDismiss();
  return (
    <div onClick={onDismiss} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 260, padding: 32,
    }}>
      <div onClick={e => e.stopPropagation()} className="fadein shadow-pop" style={{
        background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
        borderRadius: 16, padding: 28, width: 460,
      }}>
        <div style={{ fontSize: 32, marginBottom: 8 }}>{step.emoji}</div>
        <h2 style={{ margin: 0, fontSize: 19, fontWeight: 700, letterSpacing: '-0.02em' }}>{step.title}</h2>
        <p style={{ margin: '8px 0 18px', fontSize: 14, color: 'rgb(var(--ink-2))', lineHeight: 1.55 }}>{step.body}</p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ display: 'inline-flex', gap: 4 }}>
            {steps.map((_, i) => <span key={i} style={{
              width: 6, height: 6, borderRadius: '50%',
              background: i === idx ? 'rgb(var(--accent))' : 'rgb(var(--rule-2))',
              transition: 'background .15s',
            }} />)}
          </span>
          <span style={{ flex: 1 }} />
          <button onClick={onDismiss} className="btn-ghost" style={{ fontSize: 12 }}>Skip tour</button>
          <button onClick={next} className="btn btn-accent" style={{ fontSize: 13 }}>{idx === steps.length - 1 ? 'Let\'s go' : 'Got it →'}</button>
        </div>
      </div>
    </div>
  );
}

/* ─── Save-view modal ─── */
function SaveViewModal({ filters, smartFilter, viewMode, groupBy, sort, searchQ, activeView, onSave, onClose }) {
  const [name, setName] = React.useState('');
  const [pinned, setPinned] = React.useState(true);
  const submit = (e) => {
    e?.preventDefault();
    if (!name.trim()) return;
    onSave({
      id: 'sv-' + Math.random().toString(36).slice(2, 8),
      name: name.trim(),
      pinned,
      state: { filters, smartFilter, viewMode, groupBy, sort, searchQ, activeView },
    });
    onClose();
  };
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.4)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200, padding: 32,
    }}>
      <form onClick={e => e.stopPropagation()} onSubmit={submit} className="fadein shadow-pop" style={{
        background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
        borderRadius: 14, padding: 22, width: 420,
      }}>
        <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700 }}>Save view</h3>
        <p style={{ margin: '4px 0 16px', fontSize: 13, color: 'rgb(var(--muted))' }}>Save the current filters, sort, and view-mode as a one-click view in your sidebar.</p>
        <label style={{ display: 'block', marginBottom: 12 }}>
          <span style={{ display: 'block', fontSize: 11.5, fontWeight: 600, color: 'rgb(var(--muted))', marginBottom: 4, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Name</span>
          <input autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Urgent referrals" style={{ width: '100%', fontSize: 13.5, padding: '8px 12px' }} />
        </label>
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'rgb(var(--ink-2))', cursor: 'pointer', marginBottom: 18 }}>
          <input type="checkbox" checked={pinned} onChange={e => setPinned(e.target.checked)} style={{ accentColor: 'rgb(var(--accent))' }} />
          Pin to sidebar
        </label>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button type="button" onClick={onClose} className="btn btn-secondary" style={{ fontSize: 12.5 }}>Cancel</button>
          <button type="submit" className="btn btn-accent" style={{ fontSize: 12.5 }} disabled={!name.trim()}>Save view</button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { BulkBar, ConfettiBurst, OnboardingHints, SaveViewModal });
