// Header / topbar for the command center.

function HeaderBar() {
  const { state, syncState, setEnergy } = useStore();
  const today = new Date();
  const dateLabel = today.toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric' });

  const energies = [
    { id: 'spent',  label: 'Spent'  },
    { id: 'steady', label: 'Steady' },
    { id: 'strong', label: 'Strong' },
    { id: 'wired',  label: 'Wired'  },
  ];
  const cur = energies.find((e) => e.id === state.energy) || energies[2];

  // small dropdown for energy
  const [open, setOpen] = React.useState(false);

  return (
    <header className="mc-hdr">
      <div className="mc-hdr-brand">
        <img src="assets/logo-wordmark.svg" alt="optimer"/>
        <span className="pipe">/</span>
        <span className="title">command center</span>
      </div>

      <div className="mc-hdr-week">
        <b>Week {state.week}</b> · {dateLabel}
      </div>

      <div className="mc-hdr-spacer"/>

      <div style={{ position: 'relative' }}>
        <button className={`mc-energy ${cur.id}`} onClick={() => setOpen((o) => !o)}>
          <span className="dot"/>
          <span>Energy: <b style={{ color: 'var(--fg)' }}>{cur.label}</b></span>
        </button>
        {open && (
          <div style={{
            position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 5,
            background: 'var(--bg-elev)', border: '1px solid var(--border)',
            borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-lg)',
            padding: 6, display: 'flex', flexDirection: 'column', gap: 2, minWidth: 160,
          }}>
            <div style={{ fontSize: 10, color: 'var(--fg-3)', padding: '6px 8px 4px',
              textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>
              How are you, really?
            </div>
            {energies.map((e) => (
              <button key={e.id}
                onClick={() => { setEnergy(e.id); setOpen(false); }}
                style={{
                  appearance: 'none', border: 0, background: state.energy === e.id ? 'var(--ink-100)' : 'transparent',
                  textAlign: 'left', padding: '8px 10px', borderRadius: 6, cursor: 'pointer',
                  fontSize: 13, color: 'var(--fg-1)', display: 'flex', alignItems: 'center', gap: 8,
                  fontFamily: 'inherit', fontWeight: 500,
                }}>
                <span className={`mc-energy ${e.id}`} style={{ pointerEvents: 'none', padding: 0, border: 0, background: 'none' }}>
                  <span className="dot"/>
                </span>
                {e.label}
              </button>
            ))}
          </div>
        )}
      </div>

      <div className={`mc-sync ${syncState}`}>
        <span className="pulse"/>
        {syncState === 'saving' ? 'saving…' : 'synced'}
      </div>

      <BurstLauncher />

      <a className="mc-rituals" href="rituals.html" title="Rituals · morning + nightly">
        <span className="flame"/>
        <span className="lbl">rituals</span>
      </a>

      <div className="mc-avatar">{state.user.initials}</div>
    </header>
  );
}

function BurstLauncher() {
  const { state, startBurst, pauseBurst, tickBurst, closeBurst, toggleTask, setBurstLength } = useStore();
  const b = state.burst;

  // tick the timer when running (header is always mounted, so this is the
  // single source of truth for the timer regardless of which view you're in)
  React.useEffect(() => {
    if (!b.running) return;
    const id = setInterval(tickBurst, 1000);
    return () => clearInterval(id);
  }, [b.running, tickBurst]);

  // find the active task, or the next suggested one if idle
  let priority = state.priorities.find((p) => p.id === b.priorityId);
  let task = priority?.tasks.find((t) => t.id === b.taskId);
  if (!b.active || !task) {
    for (const p of state.priorities) {
      for (const t of p.tasks) { if (!t.done) { priority = p; task = t; break; } }
      if (task) break;
    }
  }

  const startNext = () => {
    if (priority && task) startBurst(priority.id, task.id, b.length);
  };

  const mins = Math.floor(b.remaining / 60);
  const secs = b.remaining % 60;
  const showSecs = b.active && b.running;
  const time = b.active
    ? `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
    : `${b.length / 60}:00`;

  const pct = b.length > 0 && b.active ? 1 - b.remaining / b.length : 0;
  const r = 11;
  const C = 2 * Math.PI * r;

  const finished = b.active && b.remaining === 0;

  const openFullscreen = () => {
    // surface the fullscreen takeover by activating it (if not already)
    if (b.active) return; // already active — overlay's already there in Desktop
    startNext();
  };

  return (
    <div className={`mc-bw ${b.running ? 'running' : ''} ${finished ? 'finished' : ''}`}>
      <div className="mc-bw-ring">
        <svg viewBox="0 0 30 30">
          <defs>
            <linearGradient id="mc-bw-grad" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#5d6dee"/>
              <stop offset="100%" stopColor="#ec33fa"/>
            </linearGradient>
          </defs>
          <circle className="track" cx="15" cy="15" r={r}/>
          <circle className="fill"  cx="15" cy="15" r={r}
                  strokeDasharray={C} strokeDashoffset={C * (1 - pct)}/>
        </svg>
      </div>

      <span className="mc-bw-time">{time}</span>

      <div className="mc-bw-task">
        <span className="lbl">{b.active ? (finished ? 'finished' : (b.running ? 'in flow' : 'paused')) : 'next burst'}</span>
        <span className="txt">{task ? task.label : 'No open tasks — add one'}</span>
      </div>

      <div className="mc-bw-actions">
        {finished ? (
          <button className="mc-bw-btn primary" title="Mark done"
                  onClick={() => { if (task) toggleTask(priority.id, task.id); closeBurst(); }}>
            <Icons.Check size={14} sw={2.5}/>
          </button>
        ) : b.active ? (
          <>
            <button className="mc-bw-btn pause" title={b.running ? 'Pause' : 'Resume'} onClick={pauseBurst}>
              {b.running ? <Icons.Pause size={14}/> : <Icons.Play size={14}/>}
            </button>
            <button className="mc-bw-btn" title="Stop & close" onClick={closeBurst}>
              <Icons.X size={14}/>
            </button>
          </>
        ) : (
          <button className="mc-bw-btn primary" title="Start burst" onClick={startNext} disabled={!task}>
            <Icons.Play size={13}/>
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { HeaderBar });
