function fmt(seconds) {
  if (seconds == null) return null
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  if (h > 0) return `${h}h ${m}m`
  return `${m}m`
}

function fmtDays(seconds) {
  if (seconds == null) return null
  const days = seconds / 57600 // 16 hours per day
  return days < 1 ? `${(days * 24).toFixed(1)}h` : `${days.toFixed(1)}d (16h/day)`
}

function fmtCompletionDate(seconds) {
  if (seconds == null) return null
  const days = seconds / 57600  // 16 hours per day
  const date = new Date(Date.now() + days * 24 * 3600 * 1000)
  return date.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' })
}

export default function TimeDisplay({ elapsedSeconds, estimatedRemainingSeconds, byType }) {
  const missingTypes = byType
    ? Object.entries(byType)
        .filter(([, v]) => v.remaining > 0 && v.avgSeconds === null)
        .map(([t]) => t)
    : []

  const days = fmtDays(estimatedRemainingSeconds)
  const completionDate = fmtCompletionDate(estimatedRemainingSeconds)

  return (
    <div className="bg-slate-900 border border-slate-800 rounded-xl p-4 flex flex-col gap-3">
      <div className="flex flex-wrap gap-6">
        <div>
          <p className="text-slate-400 text-xs uppercase tracking-widest">Time Elapsed</p>
          <p className="text-2xl font-bold text-slate-100 mt-0.5">
            {fmt(elapsedSeconds) ?? '—'}
          </p>
        </div>
        <div>
          <p className="text-slate-400 text-xs uppercase tracking-widest">Est. Time Remaining</p>
          <p className={`text-2xl font-bold mt-0.5 ${estimatedRemainingSeconds != null ? 'text-slate-100' : 'text-amber-400'}`}>
            {estimatedRemainingSeconds != null ? fmt(estimatedRemainingSeconds) : '—'}
          </p>
          {days && (
            <p className="text-slate-400 text-xs mt-0.5">{days}</p>
          )}
        </div>
        {completionDate && (
          <div>
            <p className="text-slate-400 text-xs uppercase tracking-widest">Est. Completion</p>
            <p className="text-lg font-semibold text-slate-100 mt-0.5">{completionDate}</p>
          </div>
        )}
      </div>

      {missingTypes.length > 0 && (
        <p className="text-amber-400 text-xs">
          ⚠ No completed {missingTypes.join('/')} tests yet — enter avg time in Settings to estimate.
        </p>
      )}
    </div>
  )
}
