// Kayser v2 — Top bar with status + trust progress launcher.
// Plain-English design for non-technical users.

function KxV2TopBar({ watching, handledToday, trustPct, trustLevel, onOpenStatus, onOpenTrust, onOpenSettings, onOpenThreads, __hidden, activity }) {
  if (__hidden) return null;

  const act = activity || kxv2DefaultActivity(watching, handledToday);

  return (
    <div style={{
      ...kx2Glass({
        borderRadius: 0,
        borderTop: 'none', borderLeft: 'none', borderRight: 'none',
      }),
      padding: '10px 14px',
      display: 'flex', flexDirection: 'column', gap: 8,
      flexShrink: 0,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        {/* Conversations launcher */}
        <button onClick={onOpenThreads} aria-label="Conversations" style={{
          width: 32, height: 32, borderRadius: 16, border: 'none',
          background: KX2.chipBg, color: KX2.ink2, cursor: 'pointer', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <line x1="4" y1="6" x2="20" y2="6"/>
            <line x1="4" y1="12" x2="20" y2="12"/>
            <line x1="4" y1="18" x2="14" y2="18"/>
          </svg>
        </button>

        {/* Kayser avatar */}
        <button onClick={onOpenStatus} aria-label="Kayser status" style={{
          width: 34, height: 34, borderRadius: 17, border: 'none', cursor: 'pointer',
          background: `linear-gradient(135deg, ${KX2.brand} 0%, ${KX2.brandDeep} 100%)`,
          position: 'relative', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: KX2.fontBrand, fontWeight: 700, color: '#fff', fontSize: 14,
          boxShadow: '0 0 0 1px rgba(255,255,255,.18) inset, 0 4px 14px rgba(124,58,237,.4)',
        }}>
          K
          <span style={{
            position: 'absolute', right: -1, bottom: -1,
            width: 10, height: 10, borderRadius: 5,
            background: act.color, border: '2px solid #1a0f3d',
          }} />
        </button>

        {/* Activity block (replaces numeric "Watching X · Handled Y") */}
        <button onClick={onOpenStatus} style={{
          flex: 1, textAlign: 'left', background: 'transparent', border: 'none',
          cursor: 'pointer', padding: 0, fontFamily: KX2.fontUI, minWidth: 0,
        }}>
          <div style={{
            fontSize: 14, fontWeight: 600, color: KX2.ink, lineHeight: 1.2,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>Kayser · {act.short}</div>
          <div style={{
            fontSize: 11.5, color: KX2.ink3, lineHeight: 1.3, marginTop: 2,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{act.detail}</div>
        </button>

        {/* Settings ⋯ */}
        <button onClick={onOpenSettings} aria-label="Settings" style={{
          width: 32, height: 32, borderRadius: 16, border: 'none',
          background: 'transparent', color: KX2.ink2, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>
        </button>
      </div>

      {/* Trust progress strip */}
      <KxV2TrustStrip pct={trustPct} onTap={onOpenTrust} />
    </div>
  );
}

// Honest, plain-English status string for what Kayser is doing right now.
// Build the top-line "status" copy. ``handledToday == null`` means the
// task-completion substrate isn't ready yet (trust v1 fix) — we drop
// the "handled X on my own" tail and just talk about what's active.
function kxv2DefaultActivity(watching, handledToday) {
  const handledTail = handledToday == null ? '' : ` · handled ${handledToday} on my own today`;
  // In production this comes from the Hermes loop state. For the demo, derive a friendly snapshot.
  if (watching > 8) return { short: 'Watching', color: KX2.warn,
    detail: `${watching} things on my radar${handledTail}` };
  if (watching > 0) return { short: 'Watching', color: KX2.edit,
    detail: `${watching} active conversation${watching === 1 ? '' : 's'}${handledTail}` };
  return { short: 'Quiet', color: KX2.approve,
    detail: `Nothing needs you right now${handledTail}` };
}

// Plain-English trust progress strip.
// "I handle X of every 10 things on my own. Approve more and I'll handle more."
function KxV2TrustStrip({ pct, onTap, compact }) {
  // Null / "not yet ready" state — the task-completion substrate
  // hasn't shipped yet, so showing a percentage would be a lie.
  // Render a calm placeholder instead. See docs/trust-v2-plan.md.
  const notReady = pct == null;
  const outOfTen = Math.round((pct || 0) / 10);
  const label = notReady
    ? "Setting up. I'll show your autonomy level here once I've handled work for you."
  : pct < 25  ? "I ask before everything. Approve me a few times and I'll start handling routine things."
  : pct < 50  ? `I handle ${outOfTen} of every 10 routine things on my own.`
  : pct < 75  ? `I handle ${outOfTen} of every 10 things on my own — more if you keep approving.`
  :            "I handle most things on my own. You review the day, not every action.";
  return (
    <button onClick={onTap} style={{
      background: 'transparent', border: 'none', cursor: 'pointer',
      padding: 0, textAlign: 'left', fontFamily: KX2.fontUI,
      width: '100%',
    }}>
      <div style={{
        height: 4, background: 'rgba(255,255,255,.08)', borderRadius: 2,
        overflow: 'hidden', marginBottom: compact ? 4 : 6,
      }}>
        <div style={{
          width: notReady ? '0%' : `${pct}%`, height: '100%',
          background: notReady
            ? 'repeating-linear-gradient(90deg, rgba(255,255,255,.15) 0 6px, transparent 6px 12px)'
            : KX2.brand,
          transition: 'width 250ms ease',
        }} />
      </div>
      {!compact && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{
            fontSize: 11, color: KX2.ink3, fontFamily: KX2.fontUI, lineHeight: 1.4,
            flex: 1, minWidth: 0,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{label}</div>
          {!notReady && (
            <span style={{
              fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3, flexShrink: 0,
            }}>more →</span>
          )}
        </div>
      )}
    </button>
  );
}

// Reusable trust ring SVG — kept for the trust sheet's hero gauge
function TrustRing({ pct, size = 36, stroke = 3, color = KX2.brand, track = 'rgba(255,255,255,.10)' }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const dash = (Math.max(0, Math.min(100, pct)) / 100) * c;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block' }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={track} strokeWidth={stroke} />
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
        strokeLinecap="round"
        strokeDasharray={`${dash} ${c - dash}`}
        transform={`rotate(-90 ${size/2} ${size/2})`}
      />
    </svg>
  );
}

Object.assign(window, { KxV2TopBar, TrustRing, KxV2TrustStrip, kxv2DefaultActivity });
