#' Display BLS Dataset Overview
#'
#' Fetches and displays the overview text file for a BLS dataset. This provides a convenient reference within the R environment without needing to manually find and review the text file on the BLS website.
#'
#' @param series_id Character string. The BLS series identifier (e.g., "ln", "cu", "ap")
#' @param display_method Character string. How to display the overview: 
#'   "viewer" (default), "console", or "popup"
#' @param base_url Character string. Base URL for BLS data (default uses official BLS site)
#'
#' @return Invisibly returns the text content. Function is called to use the viewer, console, or as a popup, depending on the 'display_method' argument.
#' 
#' @export
#' 
#' @importFrom httr GET add_headers stop_for_status content
#' @importFrom htmltools HTML
#' @importFrom htmltools htmlEscape
#' @importFrom rstudioapi isAvailable
#'
#' @examples
#' \donttest{
#' if(interactive()){
#' # Display Average Price Data overview
#' bls_overview("ap")
#' 
#' # Display consumer price index overview  
#' bls_overview("cu")
#' 
#' # Display in console instead of viewer
#' bls_overview("ap", display_method = "console")
#' }
#' }
bls_overview <- function(series_id, 
                         display_method = "viewer",
                         base_url = "https://download.bls.gov/pub/time.series") {
  
  # Validate inputs
  if (!is.character(series_id) || length(series_id) != 1) {
    stop("series_id must be a single character string")
  }
  
  display_method <- match.arg(display_method, c("viewer", "console", "popup"))
  
  # Construct URL
  url <- file.path(base_url, series_id, paste0(series_id, ".txt"))
  
  # Fetch content with proper headers (similar to fread_bls)
  tryCatch({
    headers <- get_bls_headers()
    
    response <- httr::GET(url, httr::add_headers(.headers = headers))
    httr::stop_for_status(response)
    
    content_text <- httr::content(response, as = "text", encoding = "UTF-8")
    
    # Display based on method
    switch(display_method,
           "viewer" = display_in_viewer(content_text, series_id),
           "console" = display_in_console(content_text, series_id),
           "popup" = display_in_popup(content_text, series_id)
    )
    
    invisible(content_text)
    
  }, error = function(e) {
    stop(sprintf("Could not fetch overview for series '%s'. URL: %s\nError: %s", 
                 series_id, url, e$message))
  })
}

#' Display text content in Viewer window.
#'
#' Helper function used to display content from 'bls_overview' in the HTML viewer.
#' 
#' @param content Character. Text content to display
#' @param series_id Two-letter series ID for a BLS time series to render in the display.
#'
#' @return No object returned, called to render content in HTML viewer.
display_in_viewer <- function(content, series_id) {
  if (!requireNamespace("htmltools", quietly = TRUE)) {
    stop("Package 'htmltools' is required for viewer display. Install with: install.packages('htmltools')")
  }
  
  # Create HTML content
  html_content <- htmltools::HTML(sprintf("
    <html>
    <head>
      <title>BLS Overview: %s</title>
      <style>
        body { 
          font-family: 'Courier New', monospace; 
          margin: 20px; 
          line-height: 1.4;
          background-color: #f8f9fa;
        }
        .header { 
          background-color: #007bff; 
          color: white; 
          padding: 15px; 
          margin: -20px -20px 20px -20px;
          border-radius: 0;
        }
        .content { 
          white-space: pre-wrap; 
          background-color: white;
          padding: 20px;
          border: 1px solid #dee2e6;
          border-radius: 5px;
        }
      </style>
    </head>
    <body>
      <div class='header'>
        <h1>BLS Dataset Overview: %s</h1>
        <p>Source: https://download.bls.gov/pub/time.series/%s/%s.txt</p>
      </div>
      <div class='content'>%s</div>
    </body>
    </html>
  ", toupper(series_id), toupper(series_id), series_id, series_id, 
                                          htmltools::htmlEscape(content)))
  
  # Create temporary file and display
  temp_file <- tempfile(fileext = ".html")
  writeLines(as.character(html_content), temp_file)
  
  if (rstudioapi::isAvailable()) {
    rstudioapi::viewer(temp_file)
  } else {
    utils::browseURL(temp_file)
  }
}




#' Display text content in console.
#'
#' Helper function used to display content from 'bls_overview' in the console..
#' 
#' @param content Character. Text content to display
#' @param series_id Two-letter series ID for a BLS time series to render in the display.
#'
#' @return No object returned, called to render content in console only..
display_in_console <- function(content, series_id) {
  cat(sprintf("\n=== BLS Dataset Overview: %s ===\n", toupper(series_id)))
  cat(sprintf("Source: https://download.bls.gov/pub/time.series/%s/%s.txt\n", series_id, series_id))
  cat(paste(rep("=", 50), collapse = ""), "\n\n")
  cat(content, "\n\n")
}


#' Display text content in popup window.
#'
#' Helper function used to display content from 'bls_overview' in a popup window.
#' 
#' @param content Character. Text content to display
#' @param series_id Two-letter series ID for a BLS time series to render in the display.
#'
#' @return No object returned, called to render content in popup.
display_in_popup <- function(content, series_id) {
  if (rstudioapi::isAvailable() && rstudioapi::hasFun("showDialog")) {
    # Truncate content if too long for dialog
    display_content <- content
    if (nchar(content) > 2000) {
      display_content <- paste(substr(content, 1, 2000), "\n\n[Content truncated - use viewer method for full text]")
    }
    
    rstudioapi::showDialog(
      title = paste("BLS Overview:", toupper(series_id)),
      message = display_content
    )
  } else {
    message("Popup not available, displaying in console instead")
    display_in_console(content, series_id)
  }
}