import Foundation

/// Thread-safe running byte total for download progress (mutated from the
/// URLSession thread, read from the actor).
final class ByteCounter: @unchecked Sendable {
  private let lock = NSLock()
  private var total: Int64 = 0

  @discardableResult
  func add(_ delta: Int64) -> Int64 {
    lock.lock(); defer { lock.unlock() }
    total += delta
    return total
  }

  var value: Int64 {
    lock.lock(); defer { lock.unlock() }
    return total
  }
}

/// Builds a complete, offline MapLibre style JSON string whose only source
/// is the territory's local PMTiles file (`pmtiles://` protocol). Kept
/// minimal and self-contained — it renders with the radios off. The app's
/// MapLibre view supplies the pmtiles protocol handler.
enum MapStyle {
  static func json(pmtilesPath: String, dark: Bool) -> String {
    let background = dark ? "#1c1b1f" : "#fffbfe"
    let land = dark ? "#242329" : "#f2eef6"
    let water = dark ? "#22303a" : "#a8c8e8"
    let road = dark ? "#3a3940" : "#ffffff"
    let roadCasing = dark ? "#0a4b19" : "#0a4b19"
    let text = dark ? "#e7e0ec" : "#1c1b1f"

    let style: [String: Any] = [
      "version": 8,
      "name": "MapMap \(dark ? "Dark" : "Light")",
      "glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
      "sources": [
        "mapmap": [
          "type": "vector",
          "url": "pmtiles://\(pmtilesPath)",
        ],
      ],
      "layers": [
        ["id": "background", "type": "background",
         "paint": ["background-color": background]],
        ["id": "landcover", "type": "fill", "source": "mapmap",
         "source-layer": "landcover", "paint": ["fill-color": land]],
        ["id": "water", "type": "fill", "source": "mapmap",
         "source-layer": "water", "paint": ["fill-color": water]],
        ["id": "roads-casing", "type": "line", "source": "mapmap",
         "source-layer": "transportation",
         "paint": ["line-color": roadCasing, "line-width": 3.0]],
        ["id": "roads", "type": "line", "source": "mapmap",
         "source-layer": "transportation",
         "paint": ["line-color": road, "line-width": 2.0]],
        ["id": "place-labels", "type": "symbol", "source": "mapmap",
         "source-layer": "place",
         "layout": ["text-field": ["get", "name"], "text-size": 12.0],
         "paint": ["text-color": text]],
      ],
    ]

    guard
      let data = try? JSONSerialization.data(withJSONObject: style, options: [.sortedKeys]),
      let json = String(data: data, encoding: .utf8)
    else {
      return "{\"version\":8,\"sources\":{},\"layers\":[]}"
    }
    return json
  }
}
