export type Activity='DRIVING'|'WORK'|'AVAILABILITY'|'REST';
export type Event={id:string;start:number;end:number;activity:Activity;speed:number};
export type State={time:number;speed:number;distance:number;cardInserted:boolean;activity:Activity;events:Event[]};
export function initialState():State{return {time:Date.now(),speed:0,distance:0,cardInserted:false,activity:'REST',events:[]}}
export function tick(state:State,seconds:number):State{const elapsed=Math.max(0,Math.min(seconds,3600));const activity:Activity=state.speed>0?'DRIVING':state.activity==='DRIVING'?'WORK':state.activity;const start=state.time,end=start+elapsed*1000;const events=[...state.events];if(state.cardInserted&&elapsed){const last=events[events.length-1];if(last&&last.activity===activity&&last.end===start){events[events.length-1]={...last,end,speed:state.speed}}else{events.push({id:`${start}-${events.length}`,start,end,activity,speed:state.speed})}}return {...state,time:end,distance:state.distance+state.speed*elapsed/3600,activity,events}}
export function drivingSinceBreak(events:Event[]):number{let seconds=0;for(let i=events.length-1;i>=0;i--){const e=events[i];const duration=(e.end-e.start)/1000;if(e.activity==='REST'&&duration>=45*60)break;if(e.activity==='DRIVING')seconds+=duration}return seconds}
export function dailyDriving(events:Event[],now:number):number{const day=new Date(now);day.setHours(0,0,0,0);const from=day.getTime();return events.filter(e=>e.activity==='DRIVING').reduce((n,e)=>n+Math.max(0,Math.min(now,e.end)-Math.max(from,e.start))/1000,0)}
export function fmtDuration(seconds:number){const mins=Math.floor(seconds/60);return `${Math.floor(mins/60)}h ${String(mins%60).padStart(2,'0')}`}
