# Load necessary libraries
library(sf)
library(tigris)
library(dplyr)
library(leaflet)
library(RColorBrewer)
library(htmltools)
# Set tigris options to use simplified geometries and cache data
options(tigris_use_cache = TRUE)
options(tigris_class = "sf")

# Load US state shapefile with simplified boundaries to reduce file size
us_states <- states(cb = TRUE, resolution = "20m") %>%
  st_as_sf() %>%
  st_transform(4326) %>%  # Transform to WGS84 for leaflet compatibility
  st_simplify(dTolerance = 0.01) # Simplify geometries to reduce file size
##   |                                                                              |                                                                      |   0%  |                                                                              |======                                                                |   9%  |                                                                              |============                                                          |  17%  |                                                                              |==================                                                    |  26%  |                                                                              |========================                                              |  35%  |                                                                              |===============================                                       |  44%  |                                                                              |=====================================                                 |  52%  |                                                                              |===========================================                           |  61%  |                                                                              |=======================================================               |  79%  |                                                                              |===================================================================   |  96%  |                                                                              |======================================================================| 100%
# Define states and their statuses
states <- c(
  "Alabama", "Alaska", "Arizona", "Arkansas", "California", 
  "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", 
  "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", 
  "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", 
  "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", 
  "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", 
  "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", 
  "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", 
  "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", 
  "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"
)

# Define legality status
legality <- c(
  "Illegal", "Legal", "Legal", "Illegal", "Legal", 
  "Legal", "Legal", "Legal", "Illegal", "Illegal", 
  "Legal", "Illegal", "Legal", "Illegal", "Illegal", 
  "Illegal", "Illegal", "Illegal", "Legal", "Legal", 
  "Legal", "Legal", "Illegal", "Medical", "Legal", 
  "Legal", "Illegal", "Legal", "Legal", "Legal", 
  "Legal", "Legal", "Illegal", "Illegal", "Legal", 
  "Illegal", "Legal", "Legal", "Legal", "Illegal", 
  "Illegal", "Illegal", "Illegal", "Illegal", "Legal", 
  "Legal", "Legal", "Illegal", "Illegal", "Illegal"
)

# Define detailed status
status <- c(
  "Medical Only", "Recreational", "Recreational", "Medical Only", "Recreational", 
  "Recreational", "Recreational", "Recreational", "Medical Only", "CBD Only", 
  "Recreational", "Fully Illegal", "Recreational", "CBD Only", "Medical CBD Only", 
  "CBD Only", "Medical Only", "Medical Only", "Recreational", "Recreational", 
  "Recreational", "Recreational", "Medical Only", "Medical Only", "Recreational", 
  "Recreational", "CBD Only", "Recreational", "Medical Only", "Recreational", 
  "Recreational", "Recreational", "Medical CBD Only", "Medical Only", "Recreational", 
  "Medical Only", "Recreational", "Medical Only", "Recreational", "CBD Only", 
  "Medical Only", "CBD Only", "Medical CBD Only", "Medical Only", "Recreational", 
  "Recreational", "Recreational", "Medical Only", "Medical CBD Only", "CBD Only"
)

# Create the cannabis legality dataframe
cannabis_legality <- data.frame(
  state = states,
  legality = legality,
  status = status
)

# Create a lookup table for state abbreviations
state_abbr <- c(
  "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", 
  "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", 
  "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", 
  "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", 
  "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"
)

state_lookup <- data.frame(
  STUSPS = state_abbr,
  state = states
)

# Join data - only keep necessary columns to reduce memory usage
cannabis_state_data <- cannabis_legality %>%
  inner_join(state_lookup, by = "state")

# Select only needed columns from us_states to reduce size
us_states <- us_states %>%
  select(GEOID, NAME, STUSPS, geometry) %>%
  left_join(cannabis_state_data, by = "STUSPS")

# Create color palette
status_colors <- colorFactor(
  palette = c("darkgreen", "lightgreen", "orange", "darkorange", "red"),
  domain = c("Recreational", "Medical Only", "Medical CBD Only", "CBD Only", "Fully Illegal")
)
# Create simplified popup content
popup_content <- paste(
  "<strong>", us_states$NAME, "</strong>",
  "<br>Status: ", us_states$status
)

# Create interactive map with minimal tile loading
leaflet(us_states) %>%
  setView(-96, 37.8, 4) %>%
  # Use a lightweight tile provider
  addProviderTiles("CartoDB.Positron", options = providerTileOptions(
    minZoom = 2, maxZoom = 6, updateWhenZooming = FALSE)) %>%
  addPolygons(
    fillColor = ~status_colors(status),
    weight = 1,
    opacity = 1,
    color = "white",
    fillOpacity = 0.7,
    label = ~NAME,
    popup = ~popup_content,
    # Disable some interactive features to reduce file size
    highlightOptions = highlightOptions(
      weight = 2,
      color = "#666",
      fillOpacity = 0.7,
      bringToFront = TRUE)
  ) %>%
  addLegend(
    position = "bottomright",
    pal = status_colors,
    values = ~status,
    title = "Legal Status",
    opacity = 0.7
  )
# Create a static version with lower resolution
library(ggplot2)

ggplot(us_states) +
  geom_sf(aes(fill = status), color = "white", size = 0.2) +
  scale_fill_manual(values = c(
    "Recreational" = "darkgreen", 
    "Medical Only" = "lightgreen", 
    "Medical CBD Only" = "orange", 
    "CBD Only" = "darkorange", 
    "Fully Illegal" = "red"
  )) +
  labs(
    title = "Cannabis Legality in the United States",
    subtitle = "Status by State - 2025",
    fill = "Legal Status"
  ) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    plot.title = element_text(face = "bold")
  )