// functions, first
var mmopened = false;
var guidevolumetimerid = 0;
var guidefullscreentimerid = 0;
var guidefullscreen = false;
var volume = 10;

function showmobilemenu() {
  var mobilemenu = document.getElementById("mmenu");

  if (mmopened == false) {
    mobilemenu.setAttribute("style", "transform: translateY(0%);");
    mmopened = true;
  } else {
    mobilemenu.setAttribute("style", "transform: translateY(-100%);");
    mmopened = false;
  }
}

function volumepopup() {
  clearTimeout(guidevolumetimerid);
  var volumeoverlay = document.getElementById("guidevolumeoverlay");
  var guidevideo = document.getElementById("guidevideo");
  var volumetext = document.getElementById("guidevolumetext");
  volumetext.textContent = "Volume: " + Math.ceil(guidevideo.volume * 100);
  volumeoverlay.style.display = "block";
  guidevolumetimerid = setTimeout(() => {
    volumeoverlay.style.display = "none";
  }, 1500);
}

function guidevolumechange(state) {
  var video = document.getElementById("guidevideo");
  if (state == "up") {
    if (volume < 10) {
      volume += 1;
    }
  }
  if (state == "down") {
    if (volume > 0) {
      volume -= 1;
    }
  }
  video.volume = (volume * 0.1).toFixed(1);
  volumepopup();
}

function theatermode() {
  var curPlay = document.getElementById("guidecurrentlyplaying");
  var guideVidPlayer = document.getElementById("guidevideoplayer");
  var guidevideooverlay = document.getElementById("guidevideooverlay");
  var guidechannelslist = document.getElementById("guidechannelslist");
  var guidevideo = document.getElementById("guidevideo");

  curPlay.classList.toggle("theater");
  guideVidPlayer.classList.toggle("theater");
  guidevideooverlay.classList.toggle("theater");
  guidechannelslist.classList.toggle("theater");
  guidevideo.classList.toggle("theater");
}

function unmutevideo() {
  var unmuteoverlay = document.getElementById("guideunmuteoverlay");
  var guidevideo = document.getElementById("guidevideo");

  unmuteoverlay.style.display = "none";
  guidevideo.muted = !guidevideo.muted;
  guidevideo.play();
}

function fullscreenoverlay() {
  console.log("1");
  if (guidefullscreen) {
    console.log("2");
    var guidefullscreenoverlay = document.getElementById(
      "guidefullscreenoverlay"
    );
    if (guidefullscreen) {
      console.log("3 and here's the overlay!");
      clearTimeout(guidefullscreentimerid);
      guidefullscreenoverlay.classList.remove("hidden");
      guidefullscreentimerid = setTimeout(() => {
        guidefullscreenoverlay.classList.add("hidden");
      }, 4500);
    }
  }
}

function fullscreen() {
  var header = document.getElementById("header");
  var guideVidPlayer = document.getElementById("guidevideoplayer");
  var curPlay = document.getElementById("guidecurrentlyplaying");
  var guidechannelslist = document.getElementById("guidebottomhalf");
  var guidecontrols = document.getElementById("guidecontrols");
  var guidefullscreenoverlay = document.getElementById(
    "guidefullscreenoverlay"
  );
  var mmenu = document.getElementById("mmenu");

  guidecontrols.classList.toggle("fullscreen");
  header.classList.toggle("hidden");
  curPlay.classList.toggle("theater");
  guidechannelslist.classList.toggle("hidden");

  guideVidPlayer.classList.toggle("fullscreen");
  mmenu.classList.toggle("hidden");

  if (guidefullscreen) {
    document.exitFullscreen();
    guideVidPlayer.removeEventListener("mousemove", function () {
      fullscreenoverlay();
    });
    guideVidPlayer.removeEventListener("touchstart", function () {
      fullscreenoverlay();
    });
    guideVidPlayer.removeEventListener("touchmove", function () {
      fullscreenoverlay();
    });
    guidefullscreenoverlay.classList.add("hidden");
    guidefullscreen = false;
  } else {
    guideVidPlayer.addEventListener("mousemove", function () {
      fullscreenoverlay();
    });
    guideVidPlayer.addEventListener("touchstart", function () {
      fullscreenoverlay();
    });
    guideVidPlayer.addEventListener("touchmove", function () {
      fullscreenoverlay();
    });
    guideVidPlayer.requestFullscreen();
    guidefullscreen = true;
  }

  fullscreenoverlay();
}

function setchannel(channelid) {
  var guidetitle = document.getElementById("guidetitle");
  var guidecount = document.getElementById("guideviewcount");
  var guidedescription = document.getElementById("guidedescription");
  var backgroundinfo = document.getElementById("backgroundinfo");
  var video = document.getElementById("guidevideo");
  var guidecurrentlyplayingtitle = document.getElementById(
    "guidecurrentlyplayingtitle"
  );
  var guidecurrentlyplayingdescription = document.getElementById(
    "guidecurrentlyplayingdescription"
  );
  var guidefullscctitle = document.getElementById("guidefullscctitle");
  var guidefullschantitle = document.getElementById("guidefullschantitle");
  var guidefullsicon = document.getElementById("guidefullsicon");
  var videoSrc =
    "https://watch.mistweather.com/hls/" + channelid + "/index.m3u8";

  publicchannels.forEach((channel) => {
    if (channel.id == channelid) {
      guidetitle.textContent = channel.title;
      guidefullschantitle.textContent = channel.title;
    }
  });

  guidefullsicon.setAttribute(
    "src",
    "https://live.mistweather.com/channels/logos/" + channelid + ".jpg"
  );
  guidedescription.textContent =
    "Hello! This is the description for this channel known as " +
    channelid +
    "! Because we have yet to have April add channel descriptions, this is a generic placeholder and will NOT be the final product.";

  guidecount.textContent = "👁 69 | " + "Unknown | " + channelid;

  guidecurrentlyplayingtitle.textContent = "Something's playing alright!";
  guidecurrentlyplayingdescription.textContent =
    "However we currently don't know what's playing? Maybe the streamer has to yet set what's currently playing right now?";
  guidefullscctitle.textContent = "Something's playing alright!";

  video.setAttribute(
    "poster",
    cacheBustingUrl(
      "https://capture.mistweather.com/snapshots/" + channelid + ".jpg"
    )
  );

  if (Hls.isSupported()) {
    var hls = new Hls();
    hls.loadSource(videoSrc);
    hls.attachMedia(video);
  }

  var channelelement = document.getElementById(channelid);
  Array.from(document.getElementsByClassName("guidechannelselected")).forEach(
    (channel) => {
      channel.classList.remove("guidechannelselected");
    }
  );
  channelelement.classList.add("guidechannelselected");
}

// guide channels

var publicchannels = [
  {
    id: "zachnet-ch1",
    title: "WeatherNow | zachNet TV",
  },
  {
    id: "zachnet-ch2",
    title: "Weatherscan v1 - Columbus, GA | zachNet TV 2",
  },
  {
    id: "zachnet-ch3",
    title: "Project Plus / Weatherscan Local - Columbus, GA | zachNet TV 3",
  },
  {
    id: "ksfw_ch01",
    title: "KSFW IP (coming soon)",
  },
  {
    id: "rfnet",
    title: "RFNet | Local Forecasts On The 8s",
  },
  {
    id: "skycastsoftware",
    title: "NO MEDIA INSERTED. DOWNLOADING [**--------] 20% ",
  },
  {
    id: "a32bitweather",
    title: "Pandastar 2XD |32bitpanda Weather",
  },
  {
    id: "lafayettenetwork01",
    title: "The LafayetteNETwork",
  },
  {
    id: "kxou_dt01",
    title: "KXOU – Your Destination for Music, Movies, TV, Weather, and More!",
  },
  {
    id: "coconut_tv",
    title: "UFEI MASS STORAGE-LOADING [||--------------]",
  },
  {
    id: "nettv_peak",
    title: "NET+ TV | The finest of stations",
  },
  {
    id: "twstvch01",
    title: "TWS - TV",
  },
  {
    id: "skycastwthrscnwx_ch01",
    title: "Weather Now Network HD 2",
  },
  {
    id: "newenglandweather_ch01",
    title: "We are coming back soon (hosted on digital ocean Singapore)",
  },
  {
    id: "cwxch01",
    title: "KCWX - Local forecasts for Bellingham, WA and surrounding",
  },
  {
    id: "wrok",
    title: "Rocky Weather Network - WROK TV",
  },
  {
    id: "dalk8",
    title: "The Freaky Network",
  },
  {
    id: "asrn_channel01",
    title: "ASRN - Weatherscan Local for Omaha, NE",
  },
  {
    id: "clementine_wx01",
    title: "Clementine Weather Network",
  },
  {
    id: "colster",
    title: "WCOL-7",
  },
  {
    id: "ntnch01",
    title: "ntn: ntn Radio - relaxing music / https://ntn-requests.surge.sh",
  },
  {
    id: "highland-networks-ch1",
    title: "24/7 Hyper-Local Weather For Asheville, NC - Highland Weather",
  },
  {
    id: "tmcweathermd",
    title: "Your Maryland Weather - Hosted by Tanner Cero",
  },
  {
    id: "kwsf01",
    title: "WeatherHDS for portions of WA + zagreb for some reason",
  },
  {
    id: "localscope_weather",
    title: "CameraScope",
  },
  {
    id: "scope_extras",
    title: "Scope Extras - these are the most retro bunnies of all time",
  },
  {
    id: "mcenetworks01",
    title: "The Immortal Channel | IMMORTAL NOT INVINCIBLE Season 2",
  },
  {
    id: "spcplainfieldtv",
    title: "SPCPlainfield",
  },
  {
    id: "spcplainfieldtv-2",
    title: "SPCPlainfield Weatherscan",
  },
  {
    id: "wmce",
    title: "[krowtenecm] | I2Jr for the LaGrange Area",
  },
  {
    id: "sspwxr01",
    title: "METEOchannel: ❄️🌨️ 24/7 IntelliStar 2 xD for Saskatoon, SK, Canada",
  },
  {
    id: "sspwxr02",
    title: "METEOchannel SD: ❄️🌨️ 24/7 Canadian Weather",
  },
  {
    id: "sspwxr03",
    title: "METEOchannel 3K: 24/7 Weather in the WeatherStar 3000 format",
  },
  {
    id: "thebrochannel",
    title: "The Brother Channel (Colchester)",
  },
  {
    id: "ctrlplusgeek",
    title: "Cil's Cilly World :3",
  },
  {
    id: "bloxeleste1",
    title: "Bloxeleste1 - WBLX-TV 13.1",
  },
  {
    id: "lcn_plus",
    title: "LCN",
  },
  {
    id: "bloxeleste2",
    title: "Bloxeleste2 - WBLX-TV 13.2",
  },
  {
    id: "bloxeleste_music",
    title: "BloxelesteMusic - WBLX-TV 13.3",
  },
  {
    id: "corn_tv",
    title: "CornTV, Broadcasting online and CH10 NTSC!",
  },
  {
    id: "piceboi01",
    title: "PicelBoi Broadcasting - Jeremy IntelliStar 2 XD",
  },
  {
    id: "zonexero-vent01",
    title: "WeatherZone | Tampa Bay",
  },
  {
    id: "zonexero-vent02",
    title: "WeatherZone | Chattanooga",
  },
  {
    id: "blisstar-ch01",
    title: "BlissSTAR",
  },
  {
    id: "lynxch01",
    title: "Lynx Television (UK)",
  },
  {
    id: "ziptv",
    title: ">zip.",
  },
  {
    id: "wtsc01",
    title: "Local 8 News",
  },
];

async function grabchannels() {
  publicchannels = await fetch(
    "https://portal.mistweather.com/mist-streaming/api2/public-channels"
  );
  publicchannels = await publicchannels.json();

  console.log(publicchannels);
}

// Cache Busting for Screenshot of Streams (from MapGuy11)
function cacheBustingUrl(url) {
  return url + "?v=" + new Date().getTime();
}

// once document is ready

document.addEventListener("DOMContentLoaded", function () {
  var guide = document.getElementById("guide");
  if (guide) {
    var guidechannelslist = document.getElementById("guidechannels");
    var volumecontrol = document.getElementById("guidevolume");
    var video = document.getElementById("guidevideo");
    guidechannelslist.innerHTML = "";

    try {
      grabchannels();
    } catch {
      console.error(
        "Apparently there was an error grabbing the public channels. Oh well!"
      );
    }

    // for each channel add html
    publicchannels.forEach((channel) => {
      guidechannelslist.innerHTML +=
        '<a class="areset" onclick="setchannel(' +
        "'" +
        channel.id +
        "'" +
        ')">' +
        "<section " +
        'class="guidechannel"' +
        'id="' +
        channel.id +
        '"' +
        'style="' +
        "background: linear-gradient(" +
        "#ffffffaa," +
        "#00000080," +
        "#00000080," +
        "#00000080," +
        "#00000080," +
        "#00000080," +
        "#00000080," +
        "#00000080," +
        "#00000080," +
        "#ffffffaa" +
        ")," +
        "url(/images/global/bgs/mttrenderearly2025.avif);" +
        "background-position: center;" +
        "background-size: cover;" +
        '"' +
        ">" +
        "<img " +
        'src="https://live.mistweather.com/channels/logos/' +
        channel.id +
        '.jpg"' +
        'alt="Channel icon"' +
        'class="guidechannelicon"' +
        "/>" +
        '<section class="guidechannelthumbnail">' +
        '<section class="guidechannelthumbnailshadow"></section>' +
        "<img " +
        'src="' +
        cacheBustingUrl(
          "https://capture.mistweather.com/snapshots/" + channel.id + ".jpg"
        ) +
        '"alt="" class="guidechannelthumbnailactual"' +
        "/>" +
        "</section>" +
        '<section class="guidechannelinfo">' +
        '<h2 class="guidechannelname">' +
        channel["title"] +
        "</h2>" +
        '<h3 class="guidechannelinfotext">👁 69 | ' +
        channel["id"] +
        " |&nbsp;</h3>" +
        '<h3 class="guidechanneldescription">Test test</h3>' +
        "</section>" +
        "</section></a" +
        ">";
    });

    volumecontrol.addEventListener("change", function () {
      if (video) {
        value = (+volumecontrol.value / 10).toFixed(1);
        video.volume = value;
        console.log(video.volume);
        console.log(value);
        volumepopup();
      }
    });
  }
});

document.addEventListener("fullscreenchange", function () {
  if (document.fullscreenElement == null) {
    if (guidefullscreen) {
      fullscreen();
    }
  }
});
