// FocusMode.jsx — Fase 2.5
// Lever på App-nivå. Triggers fra Tasks/Dashboard via window.dispatchEvent('el-focus-open', { detail: { item } }).
// Item-shape: { id, text, type: 'todo'|'routine'|'deadline'|'bigwin', raw }
const {
  useState: useFState,
  useEffect: useFEffect,
  useRef: useFRef,
  useCallback: useFCallback,
} = React;

// ── Type-farge map ───────────────────────────────────────────────
const FOCUS_TYPE = {
  todo:     { label: 'OPPGAVE',  color: '#38bdf8' },
  routine:  { label: 'RUTINE',   color: '#22c55e' },
  deadline: { label: 'DEADLINE', color: '#ff6b82' },
  bigwin:   { label: 'SEIER',    color: '#fbbf24' },
};

const FOCUS_BG = [
  { bg: 'rgba(10,4,20,0.95)',  extra: 'rgba(80,30,160,0.14)', blur: false, name: 'Cosmic' },
  { bg: 'rgba(2,4,8,0.98)',    extra: null,                   blur: false, name: 'Mørk' },
  { bg: 'rgba(3,5,12,0.88)',   extra: null,                   blur: true,  name: 'Blur' },
  { bg: 'rgba(2,12,20,0.93)',  extra: 'rgba(0,160,130,0.12)', blur: false, name: 'Aurora' },
  { bg: 'rgba(2,10,4,0.95)',   extra: 'rgba(10,100,40,0.11)', blur: false, name: 'Skog' },
];

// ── Context menu (right-click on task/routine) ───────────────────
function FocusContextMenu({ x, y, item, onFocus, onEdit, onClose }) {
  const ref = useFRef(null);

  useFEffect(() => {
    function down(e) { if (ref.current && !ref.current.contains(e.target)) onClose(); }
    function key(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('mousedown', down);
    document.addEventListener('keydown', key);
    return () => {
      document.removeEventListener('mousedown', down);
      document.removeEventListener('keydown', key);
    };
  }, []);

  const W = 210;
  const left = Math.min(x + 4, window.innerWidth - W - 16);
  const top = Math.min(y + 4, window.innerHeight - 120);
  const typeLabels = FOCUS_TYPE[item?.type]?.label || 'ELEMENT';

  const menu = (
    <div
      ref={ref}
      style={{
        position: 'fixed', left, top, zIndex: 99999,
        background: 'var(--bg-card)',
        border: '1px solid var(--bdr)',
        borderRadius: 13, padding: 5, minWidth: W,
        boxShadow: '0 20px 60px rgba(0,0,0,0.5), 0 0 0 1px var(--accent-d)',
        backdropFilter: 'blur(24px)',
        animation: 'focusMenuIn 0.14s cubic-bezier(0.25,1,0.5,1)',
      }}
    >
      <div style={{ padding: '8px 12px 7px', pointerEvents: 'none' }}>
        <div style={{ fontSize: 9, fontWeight: 700, color: 'var(--accent)', letterSpacing: '1.8px', marginBottom: 3 }}>
          {typeLabels}
        </div>
        <div style={{
          fontSize: 12, color: 'var(--sec)', fontWeight: 500, lineHeight: 1.35,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 176,
        }}>
          {item?.text}
        </div>
      </div>
      <div style={{ height: 1, background: 'var(--bdr)', margin: '3px 0' }} />
      <button
        onClick={() => { onFocus(item); onClose(); }}
        style={{
          width: '100%', padding: '10px 12px',
          display: 'flex', alignItems: 'center', gap: 9,
          borderRadius: 8, border: 'none',
          background: 'var(--accent-d)',
          color: 'var(--accent)', cursor: 'pointer',
          fontFamily: 'inherit',
          fontSize: 13, fontWeight: 600, transition: 'background 0.12s',
        }}
      >
        <svg width="15" height="15" viewBox="0 0 16 16" fill="none">
          <circle cx="8" cy="8" r="5.5" stroke="currentColor" strokeWidth="1.5"/>
          <circle cx="8" cy="8" r="2" fill="currentColor"/>
          <line x1="8" y1="1" x2="8" y2="3.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
          <line x1="8" y1="12.5" x2="8" y2="15" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
          <line x1="1" y1="8" x2="3.5" y2="8" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
          <line x1="12.5" y1="8" x2="15" y2="8" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
        </svg>
        Fokuser på dette
      </button>
      {onEdit && (
        <button
          onClick={() => { onEdit(item); onClose(); }}
          style={{
            width: '100%', padding: '9px 12px', marginTop: 3,
            display: 'flex', alignItems: 'center', gap: 9,
            borderRadius: 8, border: 'none',
            background: 'transparent',
            color: 'var(--sec)', cursor: 'pointer',
            fontFamily: 'inherit',
            fontSize: 13, fontWeight: 500, transition: 'background 0.12s',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.05)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
        >
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <path d="M11.5 2.5a2.121 2.121 0 0 1 3 3L5 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          Rediger
        </button>
      )}
    </div>
  );

  return ReactDOM.createPortal(menu, document.body);
}

// ── Focus Overlay (fullscreen) ───────────────────────────────────
function FocusOverlay({
  item, onClose, onMinimize,
  running, secs, duration,
  onToggleRun, onReset, onChangeDuration,
}) {
  const [taskDone, setTaskDone] = useFState(false);
  const [showSettings, setShowSettings] = useFState(false);
  const [bgIndex, setBgIndex] = useFState(2);
  const [customMin, setCustomMin] = useFState(30);

  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  const pct = duration > 0 ? (duration * 60 - secs) / (duration * 60) : 0;
  const R = 76;
  const circ = 2 * Math.PI * R;
  const { label: typeLabel, color: tColor } = FOCUS_TYPE[item?.type] || { label: 'FOKUS', color: '#00d4aa' };
  const fbg = FOCUS_BG[bgIndex];

  function applyDuration(min) {
    onChangeDuration && onChangeDuration(min);
    setShowSettings(false);
  }

  return (
    <div
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: fbg.bg,
        ...(fbg.blur ? { backdropFilter: 'blur(28px) saturate(0.3)' } : {}),
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        animation: 'focusOverlayIn 0.28s ease',
      }}
    >
      <style>{`
        @keyframes focusOverlayIn { from{opacity:0} to{opacity:1} }
        @keyframes focusCardIn { from{opacity:0;transform:translateY(22px) scale(0.97)} to{opacity:1;transform:none} }
        @keyframes focusMenuIn { from{opacity:0;transform:translateY(-6px) scale(0.97)} to{opacity:1;transform:none} }
        @keyframes focusSettingsIn { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }
        @keyframes miniTimerIn{from{opacity:0;transform:translateY(16px) scale(0.95)}to{opacity:1;transform:none}}
      `}</style>

      {fbg.extra && (
        <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(ellipse at 40% 30%, ${fbg.extra} 0%, transparent 60%)`, pointerEvents: 'none' }} />
      )}

      <div style={{
        position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)',
        width: 600, height: 600, borderRadius: '50%', pointerEvents: 'none',
        background: `radial-gradient(circle, ${tColor}18 0%, transparent 62%)`,
      }} />

      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20,
        padding: '56px 48px 24px',
        background: 'rgba(7,11,22,0.88)',
        border: '1px solid rgba(255,255,255,0.09)',
        borderRadius: 28,
        boxShadow: `0 40px 100px rgba(0,0,0,0.65), 0 0 0 1px ${tColor}1a`,
        backdropFilter: 'blur(8px)',
        minWidth: 420, maxWidth: 460,
        animation: 'focusCardIn 0.4s cubic-bezier(0.25,1,0.5,1)',
        position: 'relative',
      }}>
        {/* Minimize */}
        <button onClick={onMinimize} title="Minimer" style={{
          position: 'absolute', top: 12, left: 12,
          width: 36, height: 36, borderRadius: 10,
          border: 'none', background: 'transparent',
          color: 'rgba(255,255,255,0.28)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'all 0.15s',
        }}>
          <svg width="15" height="15" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="9,5 13,1"/><polyline points="13,1 9,1"/><polyline points="13,1 13,5"/>
            <polyline points="5,9 1,13"/><polyline points="1,13 5,13"/><polyline points="1,13 1,9"/>
          </svg>
        </button>

        {/* Close */}
        <button onClick={onClose} style={{
          position: 'absolute', top: 12, right: 12,
          width: 36, height: 36, borderRadius: 10,
          border: 'none', background: 'transparent',
          color: 'rgba(255,255,255,0.28)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'all 0.15s',
        }}>
          <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round">
            <line x1="1" y1="1" x2="12" y2="12"/><line x1="12" y1="1" x2="1" y2="12"/>
          </svg>
        </button>

        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px', color: tColor, background: `${tColor}1a`, padding: '4px 14px', borderRadius: 20 }}>{typeLabel}</span>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', maxWidth: 320, justifyContent: 'center' }}>
          <button onClick={() => setTaskDone(v => !v)} style={{
            width: 26, height: 26, borderRadius: 7, flexShrink: 0, padding: 0,
            border: `1.5px solid ${taskDone ? tColor : 'rgba(255,255,255,0.22)'}`,
            background: taskDone ? `${tColor}22` : 'transparent',
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'all 0.22s',
          }}>
            {taskDone && (
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M2.5 7l3 3L11.5 4" stroke={tColor} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )}
          </button>
          <h2 style={{
            fontSize: item?.text?.length > 34 ? 15 : 20, fontWeight: 700,
            color: taskDone ? '#6a7394' : '#e4e8f1',
            letterSpacing: '-0.3px', lineHeight: 1.35,
            textAlign: 'center', margin: 0,
            textDecoration: taskDone ? 'line-through' : 'none',
            transition: 'color 0.3s',
          }}>{item?.text}</h2>
        </div>

        {showSettings ? (
          <div style={{ width: '100%', animation: 'focusSettingsIn 0.22s ease' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#6a7394', textTransform: 'uppercase', letterSpacing: '1.5px', textAlign: 'center', marginBottom: 16 }}>Velg varighet</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginBottom: 10 }}>
              {[25, 45, 60].map(min => (
                <button key={min} onClick={() => applyDuration(min)} style={{
                  padding: '14px 8px', borderRadius: 12,
                  border: `2px solid ${duration === min ? tColor : 'transparent'}`,
                  background: duration === min ? `${tColor}15` : 'rgba(255,255,255,0.05)',
                  color: duration === min ? tColor : '#e4e8f1',
                  fontFamily: 'inherit',
                  fontSize: 16, fontWeight: 700, cursor: 'pointer', transition: 'all 0.18s',
                }}>
                  {min}<span style={{ fontSize: 10, fontWeight: 500, opacity: 0.7 }}> min</span>
                </button>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
              <input
                type="number" value={customMin} min={1} max={120}
                onChange={(e) => setCustomMin(Math.max(1, Math.min(120, parseInt(e.target.value) || 1)))}
                style={{
                  flex: 1, padding: '10px 12px', borderRadius: 10,
                  border: '1px solid rgba(255,255,255,0.15)',
                  background: 'rgba(255,255,255,0.06)', color: '#e4e8f1',
                  fontFamily: 'inherit', fontSize: 14, fontWeight: 700, outline: 'none', textAlign: 'center',
                }}
              />
              <button onClick={() => applyDuration(customMin)} style={{
                padding: '10px 16px', borderRadius: 10, border: 'none',
                background: 'rgba(255,255,255,0.09)', color: '#e4e8f1',
                fontFamily: 'inherit', fontSize: 12, fontWeight: 700, cursor: 'pointer',
                whiteSpace: 'nowrap',
              }}>Egendefinert</button>
            </div>
            <button onClick={() => setShowSettings(false)} style={{
              width: '100%', padding: 9, borderRadius: 10, border: 'none',
              background: 'transparent', color: '#3a4260',
              fontFamily: 'inherit', fontSize: 12, cursor: 'pointer',
            }}>← Tilbake</button>
          </div>
        ) : (
          <>
            <div style={{ position: 'relative', width: 168, height: 168 }}>
              <svg width="168" height="168" style={{
                transform: 'rotate(-90deg)',
                filter: running ? `drop-shadow(0 0 22px ${tColor}55)` : 'none',
                transition: 'filter 0.5s',
              }}>
                <circle cx="84" cy="84" r={R} fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="6"/>
                <circle cx="84" cy="84" r={R} fill="none"
                  stroke={running ? tColor : `${tColor}55`}
                  strokeWidth="6" strokeLinecap="round"
                  strokeDasharray={circ} strokeDashoffset={circ * (1 - pct)}
                  style={{ transition: 'stroke-dashoffset 1s linear, stroke 0.4s' }}
                />
              </svg>
              <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                <span style={{ fontSize: 40, fontWeight: 200, color: '#e4e8f1', letterSpacing: '-0.05em', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{mm}:{ss}</span>
                <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '2px', color: running ? tColor : '#3a4260', transition: 'color 0.35s' }}>
                  {running ? 'FOKUSERER' : 'KLAR'}
                </span>
              </div>
            </div>

            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
              <button onClick={onToggleRun} style={{
                width: '100%', padding: 13, borderRadius: 13, border: 'none',
                background: running ? 'rgba(255,255,255,0.07)' : tColor,
                color: running ? '#e4e8f1' : '#000',
                fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
                cursor: 'pointer', transition: 'all 0.22s',
                boxShadow: running ? 'none' : `0 6px 24px ${tColor}50`,
              }}>{running ? '⏸  Pause' : '▶  Start fokus'}</button>

              <div style={{ display: 'flex', gap: 8, width: '100%', justifyContent: 'center' }}>
                {(running || secs < duration * 60) && (
                  <button onClick={onReset} style={{
                    flex: 1, padding: 8, borderRadius: 10,
                    border: '1px solid rgba(255,255,255,0.08)',
                    background: 'transparent', color: '#3a4260',
                    cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 500,
                  }}>Reset</button>
                )}
                <button onClick={() => setShowSettings(true)} style={{
                  flex: 1, padding: '8px 12px', borderRadius: 10,
                  border: '1px solid rgba(255,255,255,0.08)',
                  background: 'rgba(255,255,255,0.04)', color: '#6a7394',
                  cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 600,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                }}>
                  ⚙ {duration} min
                </button>
              </div>
            </div>
          </>
        )}

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, paddingTop: 4 }}>
          {FOCUS_BG.map((b, i) => {
            const isCenter = i === 2;
            const isActive = i === bgIndex;
            return (
              <button
                key={i}
                onClick={() => setBgIndex(i)}
                title={b.name}
                style={{
                  width: isActive ? 12 : isCenter ? 10 : 7,
                  height: isActive ? 12 : isCenter ? 10 : 7,
                  borderRadius: '50%', border: 'none', cursor: 'pointer', padding: 0,
                  background: isActive ? tColor : isCenter ? 'rgba(255,255,255,0.45)' : 'rgba(255,255,255,0.18)',
                  boxShadow: isActive ? `0 0 8px ${tColor}` : 'none',
                  transition: 'all 0.22s',
                }}
              />
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Mini timer bubble (minimized state) ──────────────────────────
function FocusMiniBubble({ item, running, secs, duration, onMaximize, onClose }) {
  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  const pct = duration > 0 ? (duration * 60 - secs) / (duration * 60) : 0;
  const r = 18;
  const circ = 2 * Math.PI * r;
  const tColor = FOCUS_TYPE[item?.type]?.color || '#00d4aa';

  return ReactDOM.createPortal(
    <div style={{
      position: 'fixed', bottom: 28, right: 28, zIndex: 1500,
      background: 'rgba(7,11,22,0.96)',
      border: '1px solid rgba(255,255,255,0.12)',
      borderRadius: 18,
      backdropFilter: 'blur(20px)',
      boxShadow: `0 12px 40px rgba(0,0,0,0.6), 0 0 0 1px ${tColor}22`,
      padding: '14px 16px 14px 14px',
      display: 'flex', alignItems: 'center', gap: 14,
      animation: 'miniTimerIn 0.3s cubic-bezier(0.25,1,0.5,1)',
      minWidth: 230,
    }}>
      <div style={{ position: 'relative', width: 44, height: 44, flexShrink: 0 }}>
        <svg width="44" height="44" style={{ transform: 'rotate(-90deg)' }}>
          <circle cx="22" cy="22" r={r} fill="none" stroke="rgba(255,255,255,0.07)" strokeWidth="3"/>
          <circle cx="22" cy="22" r={r} fill="none"
            stroke={running ? tColor : `${tColor}55`} strokeWidth="3" strokeLinecap="round"
            strokeDasharray={circ} strokeDashoffset={circ * (1 - pct)}
            style={{ transition: 'stroke-dashoffset 1s linear, stroke 0.4s' }}
          />
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ width: 6, height: 6, borderRadius: '50%', background: running ? tColor : 'rgba(255,255,255,0.2)', boxShadow: running ? `0 0 6px ${tColor}` : '' }} />
        </div>
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11, color: '#6a7394', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: 2 }}>
          {item?.text}
        </div>
        <div style={{ fontSize: 20, fontWeight: 700, color: running ? tColor : '#e4e8f1', letterSpacing: '-0.04em', lineHeight: 1.1, fontVariantNumeric: 'tabular-nums' }}>
          {mm}:{ss}
        </div>
      </div>

      <button onClick={onMaximize} title="Åpne fullskjerm" style={{
        width: 28, height: 28, borderRadius: 8, flexShrink: 0,
        border: '1px solid rgba(255,255,255,0.12)',
        background: 'rgba(255,255,255,0.04)', color: '#6a7394',
        cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="7,1 11,1 11,5"/><polyline points="5,11 1,11 1,7"/>
          <line x1="11" y1="1" x2="7" y2="5"/><line x1="1" y1="11" x2="5" y2="7"/>
        </svg>
      </button>

      <button onClick={onClose} style={{
        width: 20, height: 20, borderRadius: 5, flexShrink: 0,
        border: 'none', background: 'transparent', color: '#3a4260',
        cursor: 'pointer', fontSize: 16, lineHeight: 1,
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
      }}>×</button>
    </div>,
    document.body
  );
}

// ══════════════════════════════════════════════════════════════════
// FocusModeRoot — orchestrates context menu, overlay, mini bubble.
// Lives at App-root level. Listens for `el-focus-open` and `el-focus-menu` events.
// ══════════════════════════════════════════════════════════════════
function FocusModeRoot() {
  const [item, setItem] = useFState(null);
  const [minimized, setMinimized] = useFState(false);
  const [duration, setDuration] = useFState(25);
  const [secs, setSecs] = useFState(25 * 60);
  const [running, setRunning] = useFState(false);
  const [contextMenu, setContextMenu] = useFState(null); // { x, y, item }

  // Tick
  useFEffect(() => {
    if (!running) return;
    const id = setInterval(() => {
      setSecs(s => {
        if (s <= 0) {
          setRunning(false);
          return duration * 60;
        }
        return s - 1;
      });
    }, 1000);
    return () => clearInterval(id);
  }, [running, duration]);

  // Reset secs when duration changes
  useFEffect(() => {
    if (!running) setSecs(duration * 60);
  }, [duration]);

  // Listen for events from anywhere in app
  useFEffect(() => {
    function onOpen(e) {
      const it = e.detail?.item;
      if (!it) return;
      setItem(it);
      setMinimized(false);
      setSecs(duration * 60);
      setRunning(false);
      setContextMenu(null);
    }
    function onMenu(e) {
      const { x, y, item: it } = e.detail || {};
      if (!it) return;
      setContextMenu({ x, y, item: it });
    }
    window.addEventListener('el-focus-open', onOpen);
    window.addEventListener('el-focus-menu', onMenu);
    return () => {
      window.removeEventListener('el-focus-open', onOpen);
      window.removeEventListener('el-focus-menu', onMenu);
    };
  }, [duration]);

  function handleClose() {
    setItem(null);
    setRunning(false);
    setMinimized(false);
    setSecs(duration * 60);
  }

  return (
    <>
      {contextMenu && (
        <FocusContextMenu
          x={contextMenu.x}
          y={contextMenu.y}
          item={contextMenu.item}
          onClose={() => setContextMenu(null)}
          onFocus={(it) => {
            setItem(it);
            setMinimized(false);
            setSecs(duration * 60);
            setRunning(false);
          }}
          onEdit={(it) => {
            window.dispatchEvent(new CustomEvent('el-edit-item', { detail: { item: it } }));
          }}
        />
      )}

      {item && !minimized && (
        <FocusOverlay
          item={item}
          onClose={handleClose}
          onMinimize={() => setMinimized(true)}
          running={running}
          secs={secs}
          duration={duration}
          onToggleRun={() => setRunning(r => !r)}
          onReset={() => setSecs(duration * 60)}
          onChangeDuration={(d) => { setDuration(d); setSecs(d * 60); }}
        />
      )}

      {item && minimized && (
        <FocusMiniBubble
          item={item}
          running={running}
          secs={secs}
          duration={duration}
          onMaximize={() => setMinimized(false)}
          onClose={handleClose}
        />
      )}
    </>
  );
}

// ── Helper for trigger from anywhere ─────────────────────────────
// Usage: window.openFocusMenu(event, { id, text, type })
window.openFocusMenu = function (e, item) {
  e.preventDefault();
  window.dispatchEvent(new CustomEvent('el-focus-menu', {
    detail: { x: e.clientX, y: e.clientY, item },
  }));
};
window.openFocus = function (item) {
  window.dispatchEvent(new CustomEvent('el-focus-open', { detail: { item } }));
};
