import React from 'react'
import { Tag, Spark } from '../../primitives'
import type { Project } from '../../api/adapters'

// Format TOK: 12400 → "12.4k"; small numbers unchanged
function formatTok(n: number): string {
  if (n >= 1000) {
    return (n / 1000).toFixed(1) + 'k'
  }
  return String(n)
}

interface ProjectHeaderProps {
  cwd: string
  project: Project | undefined
  sessionCount: number
  hosts: string[]
}

export function ProjectHeader({ cwd, project, sessionCount, hosts }: ProjectHeaderProps): React.JSX.Element {
  // Split cwd at the last '/' to get parent path and last segment
  const lastSlash = cwd.lastIndexOf('/')
  const parent = lastSlash >= 0 ? cwd.slice(0, lastSlash + 1) : ''
  const lastSeg = lastSlash >= 0 ? cwd.slice(lastSlash + 1) : cwd

  const tokTotal = project != null ? project.tokensIn + project.tokensOut : 0

  // Build a minimal sparkline: normalise sessions relative to max sessions
  const sparkPoints = project != null ? [0, Math.min(project.sessions, 12)] : [0, 0]

  return (
    <div className="project-header">
      {parent !== '' && (
        <div className="mono muted" style={{ fontSize: 11 }}>{parent}</div>
      )}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
        <span className="mono" style={{ fontSize: 18, fontWeight: 600 }}>{lastSeg || cwd}</span>
        <Tag kind="accent">{sessionCount} sessions</Tag>
        {project != null && (
          <Tag kind="neutral">{formatTok(tokTotal)} tok</Tag>
        )}
        {hosts.map(h => (
          <Tag key={h} kind="host">{h}</Tag>
        ))}
        <span style={{ flex: 1 }} />
        <Spark points={sparkPoints} w={120} h={18} accent />
      </div>
    </div>
  )
}
