library(readr)
library(dplyr)
library(tidyr)
library(janitor)
library(plotly)
library(htmlwidgets)

data <- read_csv(
  ('/Users/shanehanrahan/Downloads/Excel&CSVs/EMBER_DUE_DECEMBER.csv'),
  skip = 1,                     
  show_col_types = FALSE
) %>%
  clean_names()

if (!"year" %in% names(data)) {
  
  year_guess <- names(data)[which.max(sapply(data, function(x) {
    sum(grepl("^\\s*\\d{4}\\s*$", as.character(x)))
  }))]
  data <- rename(data, year = all_of(year_guess))
}

data <- data %>%
  mutate(across(everything(), ~ if (is.character(.x)) parse_number(.x) else .x)) %>%
  mutate(year = as.integer(year)) %>%
  filter(!is.na(year))

long_data <- data %>%
  pivot_longer(-year, names_to = "energy_type", values_to = "value") %>%
  mutate(value = as.numeric(value))  

plt <- plot_ly(
  long_data,
  x = ~year, y = ~value,
  color = ~energy_type,
  type = "scatter", mode = "lines+markers",
  text = ~paste0(
    "Year: ", year,
    "<br>Type: ", energy_type,
    "<br>Value: ", round(value, 2), " TWh"
  ),
  hoverinfo = "text"
) %>%
  layout(
    title = "Energy Generation Over Time",
    xaxis = list(title = "Year", rangeslider = list(visible = TRUE)),
    yaxis = list(title = "Energy (TWh)"),
    hovermode = "x unified",
    plot_bgcolor = "#222222",
    paper_bgcolor = "#222222",
    font = list(color = "white")
  )

plt