// Toolbar — top strip with date nav, search, score filter, label filter,
// and the activity sparkline.

const { useState, useEffect, useRef, useMemo } = React;

function Toolbar(props) {
  const {
    endDate, onShiftDays, onJumpToDate,
    scoreThreshold, onScoreThreshold,
    enabledLabels, onToggleLabel,
    rows, totalMeows, visibleMeows,
    zoom, onResetZoom,
    player, onClosePlayer,
  } = props;

  const startDate = new Date(endDate);
  startDate.setDate(startDate.getDate() - 59);

  const [dateInput, setDateInput] = useState(MeowUtil.fmtDateInput(endDate));
  useEffect(() => {
    setDateInput(MeowUtil.fmtDateInput(endDate));
  }, [endDate]);

  function handleJump(e) {
    e.preventDefault();
    const d = MeowUtil.parseDateInput(dateInput);
    if (d) onJumpToDate(d);
  }

  return (
    <div className="toolbar">
      <div className="toolbar-row toolbar-row-top">
        <div className="brand">
          <div className="brand-mark" aria-hidden="true">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
              <path d="M4 11 L4 5 L8 8 M20 11 L20 5 L16 8" />
              <path d="M4 11 C4 16, 8 20, 12 20 C16 20, 20 16, 20 11" />
              <circle cx="9.5" cy="12" r="0.6" fill="currentColor" />
              <circle cx="14.5" cy="12" r="0.6" fill="currentColor" />
              <path d="M11 15 Q12 16 13 15" />
            </svg>
          </div>
          <div className="brand-text">
            <div className="brand-title">Meow Detector</div>
            <div className="brand-sub">60-day audio timeline</div>
          </div>
        </div>

        <div className="date-nav">
          <button className="btn btn-ghost" onClick={() => onShiftDays(-14)} title="Older — 14 days back">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="11 17 6 12 11 7" />
              <polyline points="18 17 13 12 18 7" />
            </svg>
            <span>−14d</span>
          </button>
          <div className="date-range">
            <span className="date-range-label">{MeowUtil.fmtDayLabel(startDate)}</span>
            <span className="date-range-sep">→</span>
            <span className="date-range-label">{MeowUtil.fmtDayLabel(endDate)}</span>
          </div>
          <button className="btn btn-ghost" onClick={() => onShiftDays(14)} title="Newer — 14 days forward">
            <span>+14d</span>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="13 7 18 12 13 17" />
              <polyline points="6 7 11 12 6 17" />
            </svg>
          </button>
          <form className="date-jump" onSubmit={handleJump}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <rect x="3" y="4" width="18" height="18" rx="2" />
              <line x1="16" y1="2" x2="16" y2="6" />
              <line x1="8" y1="2" x2="8" y2="6" />
              <line x1="3" y1="10" x2="21" y2="10" />
            </svg>
            <input
              type="date"
              value={dateInput}
              onChange={(e) => setDateInput(e.target.value)}
              onBlur={handleJump}
              aria-label="Jump to date"
            />
          </form>
          <button className="btn btn-ghost" onClick={() => onJumpToDate(new Date())} title="Jump to today">
            Today
          </button>
        </div>

        <div className="filter-group" title="Hide meows below this confidence score">
          <span className="filter-label">min score</span>
          <input
            type="range"
            className="score-slider"
            min="0" max="1" step="0.01"
            value={scoreThreshold}
            onChange={(e) => onScoreThreshold(parseFloat(e.target.value))}
            aria-label="Minimum score"
          />
          <span className="filter-val">{scoreThreshold.toFixed(2)}</span>
        </div>

        <div className="zoom-status">
          <span className="zoom-label">zoom</span>
          <span className="zoom-val">{zoom.toFixed(1)}×</span>
          {zoom > 1.01 ? (
            <button className="btn btn-ghost btn-tight" onClick={onResetZoom} title="Reset zoom (1×)">reset</button>
          ) : null}
        </div>
      </div>

      <div className="toolbar-row toolbar-row-bottom">
        <Sparkline rows={rows} />
        <ToolbarPlayer player={player} onClose={onClosePlayer} />
        <div className="counts">
          <span className="count-num">{visibleMeows.toLocaleString()}</span>
          <span className="count-label">meows · 60 days</span>
        </div>
      </div>
    </div>
  );
}

function Sparkline({ rows }) {
  // rows are most-recent-first; reverse for left-to-right oldest-to-newest
  const ordered = useMemo(() => rows.slice().reverse(), [rows]);
  const data = useMemo(() => ordered.map((r) => r.meows.length), [ordered]);

  const W = 320, H = 36;
  const max = Math.max(1, ...data);
  const bw = W / data.length;

  const [hover, setHover] = useState(null); // { i, x, y }

  return (
    <div className="sparkline">
      <span className="sparkline-label">activity</span>
      <svg
        width={W} height={H} viewBox={`0 0 ${W} ${H}`}
        className="sparkline-svg"
        onMouseLeave={() => setHover(null)}
      >
        {data.map((v, i) => {
          const h = (v / max) * (H - 4);
          const isHover = hover && hover.i === i;
          return (
            <rect
              key={i}
              x={i * bw + 0.5}
              y={H - h}
              width={Math.max(1, bw - 1)}
              height={h}
              rx={1}
              className={'sparkline-bar' + (isHover ? ' sparkline-bar-hover' : '')}
              style={{ opacity: isHover ? 1 : 0.35 + 0.65 * (v / max) }}
              onMouseEnter={(e) => setHover({ i, x: e.clientX, y: e.clientY })}
              onMouseMove={(e) => setHover({ i, x: e.clientX, y: e.clientY })}
            />
          );
        })}
      </svg>
      <span className="sparkline-extents">
        <span>{rows.length ? MeowUtil.fmtDayLabel(rows[rows.length - 1].startDate) : ''}</span>
        <span>·</span>
        <span>{rows.length ? MeowUtil.fmtDayLabel(rows[0].startDate) : ''}</span>
      </span>
      {hover && ordered[hover.i] ? (
        <SparklineTooltip
          date={ordered[hover.i].startDate}
          count={data[hover.i]}
          x={hover.x}
          y={hover.y}
        />
      ) : null}
    </div>
  );
}

function SparklineTooltip({ date, count, x, y }) {
  const W = 180;
  const z = parseFloat(getComputedStyle(document.documentElement).zoom) || 1;
  const cx = x / z;
  const cy = y / z;
  const vw = window.innerWidth / z;
  const ref = useRef(null);
  const [h, setH] = useState(0);
  useEffect(() => {
    if (ref.current) setH(ref.current.offsetHeight);
  }, [date, count]);
  let left = cx - W / 2;
  if (left < 8) left = 8;
  if (left + W > vw - 8) left = vw - 8 - W;
  const top = cy - h - 12;
  return (
    <div ref={ref} className="tooltip sparkline-tooltip" style={{ left, top, width: W }}>
      <div className="tt-row">
        <span className="tt-k">date</span>
        <span className="tt-v">{MeowUtil.fmtDayLabel(date)}</span>
      </div>
      <div className="tt-row">
        <span className="tt-k">meows</span>
        <span className="tt-v tt-mono">{count.toLocaleString()}</span>
      </div>
    </div>
  );
}

window.Toolbar = Toolbar;

// Permanent mini-player rendered in the toolbar.
function ToolbarPlayer({ player, onClose }) {
  const [progress, setProgress] = useState(0);
  const rafRef = useRef(0);

  useEffect(() => {
    if (!player) { setProgress(0); return; }
    function tick() {
      const elapsed = (performance.now() - player.startedAt) / 1000;
      const p = Math.min(1, elapsed / player.dur);
      setProgress(p);
      if (p < 1) rafRef.current = requestAnimationFrame(tick);
    }
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [player]);

  if (!player) {
    return (
      <div className="tb-player tb-player-empty">
        <div className="tb-play-icon-empty" aria-hidden="true">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><polygon points="6 4 20 12 6 20" /></svg>
        </div>
        <div className="tb-empty-text">click any meow to play</div>
        <div className="tb-bar"><div className="tb-bar-fill" style={{ width: '0%' }} /></div>
      </div>
    );
  }

  const meow = player.meow;
  const startDate = MeowUtil.fracToDate(meow.start, player.row.startDate);
  const color = MeowUtil.scoreColor(meow.score);

  return (
    <div className="tb-player tb-player-active" style={{ '--score-color': color }}>
      <div className="tb-play-icon" aria-label="Playing">
        <span className="tb-play-pulse" />
        <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><polygon points="6 4 20 12 6 20" /></svg>
      </div>
      <div className="tb-meta">
        <div className="tb-meta-top">
          <span className={'tt-dot tt-dot-' + meow.label.toLowerCase()} />
          <span className="tb-label">{meow.label}</span>
          <span className="tb-time tt-mono">{MeowUtil.fmtDayLabel(startDate)} · {MeowUtil.fmtClock(startDate)}</span>
          <span className="tb-dur tt-mono">{meow.durSec.toFixed(1)}s</span>
          <span className="tb-score" style={{ color }}>{meow.score.toFixed(2)}</span>
        </div>
        <div className="tb-bar">
          <div className="tb-bar-fill" style={{ width: (progress * 100) + '%', background: color }} />
        </div>
      </div>
      <button className="tb-close" onClick={onClose} aria-label="Stop">
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></svg>
      </button>
    </div>
  );
}