async function initWorkout() {
  const lastWorkout = await API.getLastWorkout();
  if ( lastWorkout ) {
    document.querySelector( "a[href='/exercise?']" ).setAttribute( "href", `/exercise?id=${ lastWorkout._id }` );

    let totalDuration = 0;
    for ( let item of lastWorkout.exercises ) {
      totalDuration += item.duration;
    }

    const workoutSummary = {
      date: formatDate( lastWorkout.day ),
      // totalDuration: lastWorkout.totalDuration,
      totalDuration: totalDuration,
      numExercises: lastWorkout.exercises.length,
      ...tallyExercises( lastWorkout.exercises ),
    };
    renderWorkoutSummary( workoutSummary );
  } else {
    renderNoWorkoutText();
  }
}

function tallyExercises( exercises ) {
  const tallied = exercises.reduce( ( acc, curr ) => {
    if ( curr.type === "resistance" ) {
      acc.totalWeight = ( acc.totalWeight || 0 ) + ( curr.weight || 0 );
      acc.totalSets = ( acc.totalSets || 0 ) + ( curr.sets || 0 );
      acc.totalReps = ( acc.totalReps || 0 ) + ( curr.reps || 0 );
    } else if ( curr.type === "cardio" ) {
      acc.totalDistance = ( acc.totalDistance || 0 ) + ( curr.distance || 0 );
    }
    return acc;
  }, {} );
  return tallied;
}

function formatDate( date ) {
  const options = {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  };

  return new Date( date ).toLocaleDateString( options );
}

function renderWorkoutSummary( summary ) {
  const container = document.querySelector( ".workout-stats" );

  const workoutKeyMap = {
    date: "Date",
    totalDuration: "Total Workout Duration",
    numExercises: "Exercises Performed",
    totalWeight: "Total Weight Lifted",
    totalSets: "Total Sets Performed",
    totalReps: "Total Reps Performed",
    totalDistance: "Total Distance Covered",
  };

  Object.keys( summary ).forEach( ( key ) => {
    const p = document.createElement( "p" );
    const strong = document.createElement( "strong" );

    strong.textContent = workoutKeyMap[ key ];
    const textNode = document.createTextNode( `: ${ summary[ key ] }` );

    p.appendChild( strong );
    p.appendChild( textNode );

    container.appendChild( p );
  } );
}

function renderNoWorkoutText() {
  const container = document.querySelector( ".workout-stats" );
  const p = document.createElement( "p" );
  const strong = document.createElement( "strong" );
  strong.textContent = "You have not created a workout yet!";

  p.appendChild( strong );
  container.appendChild( p );
}

initWorkout();
