<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Radio By Peter</title>
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;700&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.1.6/purify.min.js"></script>
  <script src="https://hammerjs.github.io/dist/hammer.min.js"></script>
  
  @keyframes spinAndColor {
  0% {
    transform: rotate(0deg);
    color: #4CAF50;
    text-shadow: 0 0 10px #4CAF50;
  }
  50% {
    transform: rotate(180deg);
    color: #F44336;
    text-shadow: 0 0 15px #F44336;
  }
  100% {
    transform: rotate(360deg);
    color: #4CAF50;
    text-shadow: 0 0 10px #4CAF50;
  }
}

.radio-icon {
  animation: spinAndColor 3s infinite ease-in-out;
  transition: all 0.3s ease;
}

body {
  margin: 0;
  padding: 0;
  font-family: 'Cairo', sans-serif;
  color: white;
  background: linear-gradient(135deg, #1a1a1a 0%, #212121 50%, #2c2c2c 100%);
  height: 100vh;
  overflow-y: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  touch-action: none;
  box-shadow: inset 0 0 100px rgba(0, 0, 0, 0.5);
}

*:focus {
  outline: none;
  box-shadow: 0 0 12px rgba(76, 175, 80, 0.7), 0 0 20px rgba(76, 175, 80, 0.3);
}

/* AppBar */
.app-bar {
  background: linear-gradient(135deg, #212121 0%, #1a1a1a 100%);
  width: 100%;
  padding: 16px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4), 0 2px 4px rgba(76, 175, 80, 0.1);
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.app-bar h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #4CAF50;
  text-transform: uppercase;
  display: flex;
  align-items: center;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.radio-icon {
  font-size: 24px;
  margin-right: 8px;
  vertical-align: middle;
}

.radio-icon.playing {
  animation: spin-radio 2s linear infinite;
}

@keyframes spin-radio {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* الـ Wrapper */
.wrapper {
  width: 100%; /* Ensure it takes full available width */
  max-width: 800px; /* Limits the overall width on larger screens */
  /* Remove direct padding here, we'll manage it inside for better scrollbar control */
  /* padding: 20px; */ /* REMOVE THIS LINE */

  flex: 1;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding-bottom: 70px; /* Keep this for space above footer */
  min-height: calc(100vh - 70px);
  margin: 0 auto; /* This centers the wrapper */
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  overflow-y: auto; /* This is essential for the scrollbar */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);

  /* Crucial for scrollbar containment, especially in RTL */
  padding-right: 20px; /* Keep padding on the right for content */
  /* We will create "internal padding" for the scrollbar on the left */
  padding-left: 0; /* Reset or remove padding-left directly on wrapper if it's causing issues */

  /* Scrollbar styling for Firefox */
  scrollbar-width: thin;
  scrollbar-color: #4CAF50 #303030;
}

/* Add a new inner container for padding to push content away from the scrollbar */
#stationsList {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 50vh;
  overflow-y: auto; /* Keep this, but we'll apply internal padding for it */
  margin-bottom: 16px;
  padding: 8px;
  animation: fadeIn 0.7s ease-in-out;
  touch-action: pan-y;
  width: 100%;

  /* This is the key change for #stationsList */
  padding-left: 20px; /* Add padding here to push content away from the left edge (where scrollbar is in RTL) */
  padding-right: 20px; /* Add padding for consistency on the right */
  box-sizing: border-box; /* Ensure padding is included in its width */
}


/* Webkit scrollbar styling (Chrome, Safari, Edge) */
.wrapper::-webkit-scrollbar {
  width: 8px; /* Width of the vertical scrollbar */
  background: transparent; /* Make the scrollbar area transparent */
}

.wrapper::-webkit-scrollbar-track {
  background: #303030; /* Color of the scrollbar track */
  border-radius: 10px;
}

.wrapper::-webkit-scrollbar-thumb {
  background-color: #4CAF50; /* Color of the scrollbar thumb */
  border-radius: 10px;
  border: 2px solid #303030; /* Add a border to the thumb to create inner spacing */
}

/* You might want to apply the same scrollbar styling to #stationsList if it also has overflow */
#stationsList::-webkit-scrollbar {
  width: 8px;
  background: transparent;
}

#stationsList::-webkit-scrollbar-track {
  background: #303030;
  border-radius: 10px;
}

#stationsList::-webkit-scrollbar-thumb {
  background-color: #4CAF50;
  border-radius: 10px;
  border: 2px solid #303030;
}

#now-playing {
  background: rgba(76, 175, 80, 0.15);
  padding: 12px;
  margin-bottom: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #4CAF50;
  text-align: center;
  border-radius: 12px;
  border: 1px solid rgba(76, 175, 80, 0.5);
  opacity: 0;
  transform: translateY(-10px);
  transition: opacity 0.5s ease, transform 0.5s ease, box-shadow 0.3s ease;
}

#now-playing.visible {
  opacity: 1;
  transform: translateY(0);
  box-shadow: 0 0 15px rgba(76, 175, 80, 0.3);
}

#errorMessage {
  position: fixed;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%);
  background: #F44336;
  padding: 12px 20px;
  font-size: 16px;
  font-weight: 500;
  color: white;
  text-align: center;
  border-radius: 12px;
  z-index: 1002;
  opacity: 0;
  transition: opacity 0.3s ease, box-shadow 0.3s ease;
  display: block;
}

#errorMessage.show {
  opacity: 1;
  box-shadow: 0 0 10px rgba(244, 67, 54, 0.5);
}

#searchInput {
  width: 100%;
  padding: 12px 40px 12px 16px;
  margin-bottom: 16px;
  margin-top: 8px;
  border-radius: 12px;
  border: 1px solid #4CAF50;
  background: #424242;
  color: white;
  font-size: 16px;
  font-family: 'Cairo', sans-serif;
  box-sizing: border-box;
  transition: border-color 0.3s ease, box-shadow 0.3s ease, transform 0.2s ease;
  position: relative;
  display: none;
}

#searchInput.visible {
  display: block;
}

#searchInput:focus {
  border-color: #66BB6A;
  box-shadow: 0 0 12px rgba(76, 175, 80, 0.7);
  transform: scale(1.02);
}

#searchInput::placeholder {
  color: #B0BEC5;
}

.tabs {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-bottom: 16px;
}

.tab {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.3s ease;
}

.tab:hover {
  background: #66BB6A;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.tab.active {
  background: #FF9800;
  box-shadow: 0 0 15px rgba(255, 152, 0, 0.5);
}

#stationsList {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 50vh;
  overflow-y: auto;
  margin-bottom: 16px;
  padding: 8px;
  animation: fadeIn 0.7s ease-in-out;
  touch-action: pan-y;
  width: 100%;
}

@keyframes fadeIn {
  0% { opacity: 0; transform: translateY(10px); }
  100% { opacity: 1; transform: translateY(0); }
}

.station-item {
  background: #303030;
  padding: 12px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background 0.3s ease, box-shadow 0.3s ease, transform 0.2s ease;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.1);
}

.station-item:hover {
  background: #424242;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3), 0 3px 6px rgba(0, 0, 0, 0.2);
  transform: translateY(-2px);
}

.station-item.playing {
  background: #FF9800;
  box-shadow: 0 0 20px rgba(255, 152, 0, 0.7), 0 4px 8px rgba(255, 152, 0, 0.3);
}

.station-item img {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  margin-left: 12px;
  object-fit: cover;
  aspect-ratio: 1/1;
  transition: transform 0.3s ease;
}

.station-item:hover img {
  transform: scale(1.1);
}

.station-item span {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: white;
  transition: color 0.3s ease;
}

.station-item:hover span {
  color: #66BB6A;
}

.station-play-btn, .player-control-btn, #audio-player-control {
  background: linear-gradient(135deg, #388E3C 0%, #4CAF50 100%);
  border: none;
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 12px;
  transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.3s ease;
  font-family: 'Material Icons';
  font-size: 24px;
  position: relative;
  overflow: hidden;
}

.station-play-btn::before, .player-control-btn::before, #audio-player-control::before {
  content: 'play_arrow';
  font-family: 'Material Icons';
  font-size: 24px;
  position: relative;
  z-index: 2;
}

.station-play-btn.playing::before, .player-control-btn.playing::before, #audio-player-control.playing::before {
  content: 'pause';
}

.station-play-btn:hover, .player-control-btn:hover, #audio-player-control:hover {
  background: linear-gradient(135deg, #66BB6A 0%, #81C784 100%);
  box-shadow: 0 0 15px rgba(76, 175, 80, 0.8);
}

.station-play-btn.playing, .player-control-btn.playing, #audio-player-control.playing {
  background: linear-gradient(135deg, #FF9800 0%, #FFB300 100%);
}

.station-play-btn.playing:hover, .player-control-btn.playing:hover, #audio-player-control.playing:hover {
  background: linear-gradient(135deg, #FFB300 0%, #FFCA28 100%);
}

#audio-player-dummy, #video-player-dummy {
  width: 100%;
  margin-bottom: 16px;
  border-radius: 12px;
  background: linear-gradient(135deg, #424242 0%, #303030 100%);
  opacity: 0;
  transform: scale(0.95);
  transition: opacity 0.5s ease, transform 0.5s ease, box-shadow 0.3s ease;
  display: none;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 60px;
  align-items: center;
}

#audio-player-dummy.visible, #video-player-dummy.visible {
  opacity: 1;
  transform: scale(1);
  box-shadow: 0 0 25px rgba(76, 175, 80, 0.6);
  display: flex;
}

.player-img {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-left: 12px;
  object-fit: cover;
  aspect-ratio: 1/1;
  transition: transform 0.3s ease;
}

.player-img:hover {
  transform: scale(1.1);
}

.player-wave {
  position: absolute;
  top: 50%;
  right: 70px;
  transform: translateY(-50%);
  display: flex;
  gap: 4px;
}

.player-wave span {
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
  border-radius: 2px;
  animation: wave 1.2s infinite ease-in-out;
  display: none;
  box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
}

.player-wave span:nth-child(2) { animation-delay: 0.3s; }
.player-wave span:nth-child(3) { animation-delay: 0.6s; }
.player-wave span:nth-child(4) { animation-delay: 0.9s; }

#audio-player-dummy.visible .player-wave span, #video-player-dummy.visible .player-wave span {
  display: block;
}

.station-name {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #4CAF50;
  margin: 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.3s ease, text-shadow 0.3s ease;
}

.station-name:hover {
  color: #66BB6A;
  text-shadow: 0 0 10px rgba(76, 175, 80, 0.5);
}

@keyframes wave {
  0%, 100% { height: 12px; transform: translateY(0); }
  50% { height: 24px; transform: translateY(-5px); }
}

.player-control-btn, #audio-player-control {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
}

#player {
  display: none !important;
}

#toggleMenu, #retryButton {
  background: linear-gradient(135deg, #388E3C 0%, #4CAF50 100%);
  border: none;
  padding: 12px 24px;
  color: white;
  font-size: 16px;
  font-family: 'Cairo', sans-serif;
  cursor: pointer;
  margin-bottom: 16px;
  border-radius: 12px;
  width: 100%;
  transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

#toggleMenu:hover, #retryButton:hover {
  background: linear-gradient(135deg, #66BB6A 0%, #81C784 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(76, 175, 80, 0.4);
}

#video-placeholder, #hidden-video-iframe, #toggle-dailymotion {
  display: none !important;
}

footer {
  background: linear-gradient(135deg, #1a1a1a 0%, #000000 100%);
  width: 100%;
  padding: 12px;
  text-align: center;
  color: #4CAF50;
  font-size: 14px;
  font-family: 'Cairo', sans-serif;
  font-weight: 600;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.3);
}

/* شريط التنقل السفلي */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100vw;
  background: linear-gradient(135deg, #212121 0%, #1a1a1a 100%);
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.4);
  z-index: 1001;
  box-sizing: border-box;
  transition: background 0.5s ease, box-shadow 0.3s ease;
}

.bottom-nav button {
  background: transparent;
  border: none;
  font-family: 'Material Icons';
  font-size: 24px;
  cursor: pointer;
  padding: 10px;
  color: #4CAF50;
  transition: color 0.3s ease, transform 0.2s ease, box-shadow 0.3s ease;
  position: relative;
  overflow: hidden;
}

.bottom-nav button:hover {
  color: #66BB6A;
  transform: scale(1.2);
  box-shadow: 0 0 15px rgba(76, 175, 80, 0.5);
}

.bottom-nav button.active {
  color: #FF9800;
  box-shadow: 0 0 20px rgba(255, 152, 0, 0.7);
}

.bottom-nav button::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 0;
  left: 0;
  background: #FF9800;
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.bottom-nav button.active::after {
  transform: scaleX(1);
}

#favoritesCount {
  font-size: 12px;
  background: #FF9800;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  margin-right: 4px;
  transition: transform 0.3s ease;
}

.bottom-nav button:hover #favoritesCount {
  transform: scale(1.2);
}

/* تنسيق الساعة الديجيتال */
#clock-placeholder {
  width: 100%;
  margin-bottom: 16px;
  border-radius: 12px;
  background: linear-gradient(135deg, #4CAF50 0%, #388E3C 100%);
  padding: 10px;
  box-sizing: border-box;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2), 0 0 15px rgba(76, 175, 80, 0.3);
  direction: ltr;
  transition: background 0.5s ease, box-shadow 0.3s ease;
}

/* حجب الإعلانات */
iframe[src*="ads"], iframe[src*="doubleclick"],
div[id^="ad-"], div[class^="ad-"],
div[id^="ads-"], div[class^="ads-"],
div[id*="sponsor"], div[class*="sponsor"],
div[id*="promoted"], div[class*="promoted"],
div[id*="banner"], div[class*="banner"],
div[id*="advert"], div[class*="advert"],
div[id*="advertisement"], div[class*="advertisement"] {
  display: none !important;
  visibility: hidden !important;
  max-height: 0 !important;
  overflow: hidden !important;
}

/* الوضع النهاري */
body.light-mode {
  background: linear-gradient(135deg, #E6F0FA 0%, #F8FAFC 50%, #FFFFFF 100%);
  color: #1A1A1A;
  box-shadow: inset 0 0 100px rgba(255, 255, 255, 0.3);
}

body.light-mode .app-bar {
  background: linear-gradient(135deg, #FFFFFF 0%, #F1F5F9 100%);
}

body.light-mode .station-item {
  background: #F1F5F9;
}

body.light-mode .station-item:hover {
  background: #E2E8F0;
}

body.light-mode .station-item span {
  color: #1A1A1A;
}

body.light-mode #searchInput {
  background: #FFFFFF;
  border-color: #4CAF50;
}

body.light-mode .bottom-nav {
  background: linear-gradient(135deg, #FFFFFF 0%, #F1F5F9 100%);
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

body.light-mode #clock-placeholder {
  background: linear-gradient(135deg, #424242 0%, #303030 100%); /* نفس لون الـ Dummy Player */
  color: #FFD700; /* لون النص بقى كده عشان يظهر واضح على الخلفية الداكنة */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1), 0 0 15px rgba(66, 66, 66, 0.3); /* تعديل الظلال */
}

/* زر المفضلة */
.fav-btn {
  background: #FFD700;
  color: #333;
  border: none;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  cursor: pointer;
  margin-left: 8px;
  transition: background 0.3s ease, box-shadow 0.3s ease, transform 0.2s ease;
  font-family: 'Material Icons';
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.fav-btn:hover {
  box-shadow: 0 0 15px rgba(255, 215, 0, 0.8);
  transform: rotate(15deg) scale(1.1);
}

.fav-btn.favorited {
  background: #FFA500;
}

.fav-btn::before {
  content: 'star';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: transform 0.3s ease;
}

.fav-btn:hover::before {
  transform: translate(-50%, -50%) scale(1.2);
}

/* إشعار منبثق */
.toast {
  position: fixed;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%);
  background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
  color: white;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  opacity: 0;
  transition: opacity 0.3s ease, transform 0.3s ease, box-shadow 0.3s ease;
  z-index: 1002;
}

.toast.show {
  opacity: 1;
  transform: translateX(-50%) scale(1.05);
  box-shadow: 0 0 15px rgba(76, 175, 80, 0.5);
}

/* وضع توفير الطاقة */
body.power-save .player-wave,
body.power-save .station-item:hover,
body.power-save #audio-player-dummy,
body.power-save #video-player-dummy {
  animation: none;
  box-shadow: none;
}

/* Responsive للتلفزيون */
@media screen and (min-width: 768px) {
  .app-bar h1 {
    font-size: 40px;
  }
  .radio-icon {
    font-size: 32px;
  }
  #now-playing, #errorMessage, #searchInput {
    font-size: 26px;
  }
  .station-item img {
    width: 80px;
    height: 80px;
  }
  .station-item span {
    font-size: 26px;
  }
  .station-play-btn, .player-control-btn, #audio-player-control {
    width: 48px;
    height: 48px;
    font-size: 22px;
  }
  .fav-btn {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }
  #toggleMenu, #retryButton {
    font-size: 24px;
    padding: 20px 40px;
  }
  footer {
    font-size: 20px;
  }
  .player-wave span {
    width: 6px;
    height: 30px;
  }
  .station-name {
    font-size: 25px;
  }
  .bottom-nav button {
    font-size: 28px;
    padding: 12px;
  }
  #clock-placeholder {
    font-size: 24px;
  }
  .wrapper {
    padding: 10px;
    max-width: 1000px;
  }
  .player-img {
    width: 48px;
    height: 48px;
  }
}

/* تمركز الواجهة على الموبايل */
@media screen and (max-width: 768px) {
  .wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 10px;
    width: 100%;
    max-width: 100%;
  }
  .app-bar, #stationsList, #now-playing, #errorMessage, #searchInput,
  #audio-player-dummy, #video-player-dummy, #toggleMenu, #retryButton, footer, #clock-placeholder {
    width: 100%;
    margin: 0 auto;
    padding-left: 0;
    padding-right: 0;
  }
  .bottom-nav {
    height: 60px;
    box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.15);
  }
  .bottom-nav button {
    padding: 12px;
    font-size: 26px;
  }
  .station-item img {
    width: 40px;
    height: 40px;
  }
}

/* تغيير الخلفية بناءً على الوقت */
@supports (prefers-color-scheme: dark) {
  @media (prefers-color-scheme: dark) {
    body {
      background: linear-gradient(135deg, #1a1a1a 0%, #212121 50%, #2c2c2c 100%);
    }
  }
  @media (prefers-color-scheme: light) {
    body {
      background: linear-gradient(135deg, #E6F0FA 0%, #F8FAFC 50%, #FFFFFF 100%);
      color: #1A1A1A;
    }
  }
}
  
  <!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Radio By Peter</title>
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;700&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.1.6/purify.min.js"></script>
  <script src="https://hammerjs.github.io/dist/hammer.min.js"></script>
</head>
<body>
  <div class="app-bar">
    <h1>Radio By Peter <span class="radio-icon material-icons">radio</span></h1>
  </div>
  <div class="wrapper">
    <div id="now-playing"></div>
    <input type="text" id="searchInput" placeholder="ابحث عن محطة..." />
    <div id="errorMessage" style="display: none;">حدث خطأ في تشغيل المحطة، الرجاء المحاولة مرة أخرى.</div>
    <audio id="player" controlsList="nodownload nofullscreen noremoteplayback"></audio>
    <div id="audio-player-dummy">
      <button id="audio-player-control" class="player-control-btn"></button>
      <img class="player-img" src="" alt="شعار المحطة"/>
      <span class="station-name"></span>
      <div class="player-wave">
        <span></span><span></span><span></span><span></span>
      </div>
    </div>
    <div id="video-player-dummy">
      <button class="player-control-btn" id="video-player-control"></button>
      <img class="player-img" src="" alt="شعار المحطة"/>
      <span class="station-name"></span>
      <div class="player-wave">
        <span></span><span></span><span></span><span></span>
      </div>
    </div>
    <div id="clock-placeholder">00:00:00</div>
    <div id="video-placeholder">
      <iframe id="hidden-video-iframe"></iframe>
    </div>
    <button id="toggle-dailymotion" style="display: none;">تشغيل</button>
    <div class="tabs">
    </div>
    <button id="toggleMenu">عرض/إخفاء المحطات</button>
    <div id="stationsList"></div>
    <button id="retryButton" style="display: none;">إعادة المحاولة</button>
    <footer>Peter © 2025</footer>
  </div>
  <div class="bottom-nav">
    <button id="searchBtn" class="material-icons" aria-label="البحث">🔍</button>
    <button id="showFavorites" class="material-icons" aria-label="عرض المفضلة">⭐<span id="favoritesCount">0</span></button>
    <button id="toggleTheme" class="material-icons" aria-label="تبديل الوضع النهاري">brightness_6</button>
    <button id="homeBtn" class="material-icons" aria-label="الصفحة الرئيسية">🏠</button>
    <button id="powerSaveBtn" class="material-icons" aria-label="وضع توفير الطاقة">battery_saver</button>
  </div>

  <script>
    let currentVideoStation = null;
    let isVideoLoaded = false;
    let isPlaying = false;
    let iframe = null;
    let messageListener = null;
    let loadedStations = null;
    let customStations = [];
    let isShowingFavorites = false;
    let searchTimeout = null;
    let focusedIndex = 0;

    const stations = [
      { name: "شعبى اف ام 95", url: "https://radio95.radioca.st/stream/1/", type: "audio", img: "", "data-src": "https://source.boomplaymusic.com/group10/M00/04/08/1c2e6cdcd3f94c78beca54c5e2adc408H300W300_320_320.jpeg" },
      { name: "الراديو 9090", url: "https://9090streaming.mobtada.com/9090FMEGYPT", type: "audio", img: "", "data-src": "https://upload.wikimedia.org/wikipedia/commons/a/a7/El_Radio_9090.png" },
      { name: "NRJ مصر 92.1", url: "https://nrjstreaming.ahmed-melege.com/nrjegypt", type: "audio", img: "", "data-src": "https://cdn-profiles.tunein.com/s291274/images/logog.jpg" },
      { name: "راديو هيتس 88.2", url: "https://radiohits882.radioca.st/;", type: "audio", img: "", "data-src": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Radio_Hits.png/420px-Radio_Hits.png" },
      { name: "نجوم إف إم 100.6", url: "https://audio.nrpstream.com/listen/nogoumfm/radio.mp3", type: "audio", img: "", "data-src": "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjh_SSTkrI6XJAV0k4LrM2ifN8MXhyNqN9g6gPH35EQdHn_MaibYUJsKYJaqD_IyfNxdAlu-B5tP9gXH1evsMHwn-ZlGyCaKL8IvUQAiehyphenhypheniGw68JFL4XVSWSdF1hyphenhyphenQ7FMr80MBuUE4/s550/nogoum-fm.jpg" },
      { name: "ميجا إف إم 92.7", url: "http://nebula.shoutca.st:8211/mp3", type: "audio", img: "", "data-src": "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6SLaZnuhpxj-ZWyuYlhPbjPCsK8QsTN3WiP-Afq__eSs9KqJxkM7DdxF1-0OuSj718hjTXhJypJ_s8iuS915zjEJy4Ke_nnf8ufCNskaqvg5-2zvo3oKJrL2kG7o9DByny3G8eMuqmZQ9gLNIgLI-q9vZYpkORRTMWpzqPm9zunZefkVhxdHLD7NI/s480/megafm.jpg" },
      { name: "نغم إف إم 105.3", url: "https://ahmsamir.radioca.st/stream", type: "audio", img: "", "data-src": "https://upload.wikimedia.org/wikipedia/commons/f/f6/Nagham_FM.png" },
      { name: "محطة مصر أونلاين", url: "https://s3.radio.co:80/s9cb11828c/listen", type: "audio", img: "", "data-src": "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYB6kH_v3HHCfQqdMwyuiwlzjjiVFthHP0PF0tQRgwMiTgpgBI9kgb5W5FiIw3Pwr-PKmUHlK8sdmvOjRyez-aOwmtx-UH8ilBMY009osoGq9UchKavayGB9t_HwSvp2OT3qgEnDe_6QD/s1600/radio-mahatet-masr-live.jpg" },
      { name: "راديو 90s FM", url: "https://eu1.fastcast4u.com/proxy/prontofm?mp=/1", type: "audio", img: "", "data-src": "https://i0.wp.com/news.ninetiesfm.com/wp-content/uploads/2020/09/New-Project.png" },
      { name: "إذاعة الأغاني المصرية 105.8", url: "https://geo.dailymotion.com/player.html?video=x8n6dyz&muted=0&ads=0", type: "dailymotion", img: "", "data-src": "https://radio.qassimy.com/wp-content/uploads/2023/03/%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D9%85%D8%A7%D8%B9-%D8%A7%D9%84%D9%89-%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9-%D8%B1%D8%A7%D8%AF%D9%8A%D9%88-%D8%A7%D8%B0%D8%A7%D8%B9%D8%A9-%D8%A7%D9%84%D8%A3%D8%BA%D8%A7%D9%86%D9%8A-105.8-%D8%A7%D9%81-%D8%A7%D9%85-%D9%81%D9%8A-%D9%85%D8%B5%D8%B1-%D8%A8%D8%AB-%D9%85%D8%A8%D8%A7%D8%B4%D8%B1-%D8%A7%D9%88%D9%86-%D9%84%D8%A7%D9%8A%D9%86.jpg" },
      { name: "راديو مصر", url: "https://geo.dailymotion.com/player.html?video=x8n6dpk&muted=0&ads=0", type: "dailymotion", img: "", "data-src": "https://www.maspero.eg/images/live_channels_logos/1667483775.jpg" },
      { name: "يوتيوب - أغنية جديدة", url: "https://www.youtube.com/watch?v=8nX2n8UKbWA", type: "youtube", img: "", "data-src": "https://upload.wikimedia.org/wikipedia/commons/0/09/YouTube_full-color_icon_%282017%29.svg" },
      { name: "فيميو - عينة فيديو", url: "https://vimeo.com/76979871", type: "vimeo", img: "", "data-src": "https://upload.wikimedia.org/wikipedia/commons/9/95/Vimeo_logo.svg" }
    ];

    const defaultStations = stations;
    const jsonUrl = 'https://raw.githubusercontent.com/vinogans/json/main/stations.json';

    const stationsList = document.getElementById("stationsList");
    const player = document.getElementById("player");
    const audioPlayerDummy = document.getElementById("audio-player-dummy");
    const audioPlayerControl = document.getElementById("audio-player-control");
    const videoPlayerDummy = document.getElementById("video-player-dummy");
    const videoPlayerControl = document.getElementById("video-player-control");
    const nowPlaying = document.getElementById("now-playing");
    const toggleMenu = document.getElementById("toggleMenu");
    const searchInput = document.getElementById("searchInput");
    const retryButton = document.getElementById("retryButton");
    const errorMessage = document.getElementById("errorMessage");
    const videoPlaceholder = document.getElementById("video-placeholder");
    const clockPlaceholder = document.getElementById("clock-placeholder");
    const searchBtn = document.getElementById("searchBtn");
    const showFavorites = document.getElementById("showFavorites");
    const toggleTheme = document.getElementById("toggleTheme");
    const homeBtn = document.getElementById("homeBtn");
    const powerSaveBtn = document.getElementById("powerSaveBtn");

    showError(false);

    function updateClock() {
      const now = new Date();
      let hours = now.getHours();
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const ampm = hours >= 12 ? 'PM' : 'AM';
      
      hours = hours % 12;
      hours = hours ? hours : 12;
      hours = String(hours).padStart(2, '0');
      
      clockPlaceholder.textContent = `${hours}:${minutes}:${seconds} ${ampm}`;
    }

    updateClock();
    setInterval(updateClock, 1000);

    function createIframe(videoUrl, platform) {
      iframe = document.createElement("iframe");
      iframe.id = "hidden-video-iframe";
      iframe.setAttribute("allow", "autoplay; fullscreen; accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture");
      iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-popups allow-forms");
      iframe.setAttribute("loading", "eager");
      iframe.style.width = "100%";
      iframe.style.height = "100%";
      iframe.style.border = "none";
      iframe.style.display = "none";

      let finalUrl = videoUrl;
      try {
        if (platform === 'youtube') {
          const urlObj = new URL(videoUrl);
          let videoId = urlObj.searchParams.get("v");
          if (!videoId && videoUrl.includes("youtu.be")) {
            videoId = urlObj.pathname.split('/').pop();
          }
          if (videoId) {
            finalUrl = `https://www.youtube.com/embed/${videoId}?autoplay=1&muted=0&controls=0&enablejsapi=1&origin=${window.location.origin}&rel=0`;
          } else {
            throw new Error("Failed to extract YouTube video ID");
          }
        } else if (platform === 'dailymotion') {
          const urlObj = new URL(videoUrl);
          let videoId = urlObj.searchParams.get("video") || urlObj.pathname.split('/').pop().split('?')[0];
          if (videoId) {
            finalUrl = `https://geo.dailymotion.com/player.html?video=${videoId}&autoplay=1&muted=0&ads=0&queue-enable=false`;
          } else {
            throw new Error("Failed to extract Dailymotion video ID");
          }
        } else if (platform === 'vimeo') {
          const urlObj = new URL(videoUrl);
          const videoId = urlObj.pathname.split('/').pop();
          if (videoId) {
            finalUrl = `https://player.vimeo.com/video/${videoId}?autoplay=1&muted=0&controls=0`;
          } else {
            throw new Error("Failed to extract Vimeo video ID");
          }
        }
      } catch (e) {
        console.error(`${platform}: Invalid URL format:`, videoUrl, e);
        return null;
      }

      iframe.src = finalUrl;
      videoPlaceholder.innerHTML = '';
      videoPlaceholder.appendChild(iframe);
      return iframe;
    }

    function setupMessageListener() {
      if (messageListener) {
        window.removeEventListener('message', messageListener);
      }
      messageListener = (event) => {
        if (event.origin.startsWith('https://www.youtube.com') && currentVideoStation && currentVideoStation.type === "youtube") {
          try {
            const data = JSON.parse(event.data);
            if (!iframe || event.source !== iframe.contentWindow || !currentVideoStation) return;
            if (data.event === 'onReady') {
              isVideoLoaded = true;
              if (isPlaying) {
                iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
              }
            } else if (data.event === 'onStateChange') {
              if (data.info === 1) {
                isPlaying = true;
                nowPlaying.textContent = `تشغيل: ${currentVideoStation.name}`;
                nowPlaying.classList.add('visible');
                updateStationButtons();
              } else if (data.info === 2 || data.info === 0) {
                isPlaying = false;
                nowPlaying.textContent = `متوقف: ${currentVideoStation.name}`;
                updateStationButtons();
              }
            } else if (data.event === 'onError') {
              console.error('YouTube error:', data.info);
              showError(true);
              nowPlaying.textContent = `خطأ في محطة YouTube (كود: ${data.info})`;
              isPlaying = false;
              isVideoLoaded = false;
              stopAllPlayback();
            }
          } catch (e) {
            console.log("YouTube: Non-JSON message received, ignoring:", event.data);
          }
        } else if (event.origin.startsWith('https://geo.dailymotion.com') && currentVideoStation && currentVideoStation.type === "dailymotion") {
          try {
            const data = JSON.parse(event.data);
            if (!iframe || event.source !== iframe.contentWindow || !currentVideoStation) return;
            if (data.event === 'apiready') {
              isVideoLoaded = true;
              if (isPlaying) {
                iframe.contentWindow.postMessage('{"method":"play"}', '*');
                iframe.contentWindow.postMessage('{"method":"unmute"}', '*');
              }
            } else if (data.event === 'play') {
              isPlaying = true;
              nowPlaying.textContent = `تشغيل: ${currentVideoStation.name}`;
              nowPlaying.classList.add('visible');
              updateStationButtons();
            } else if (data.event === 'pause' || data.event === 'ended') {
              isPlaying = false;
              nowPlaying.textContent = `متوقف: ${currentVideoStation.name}`;
              updateStationButtons();
            } else if (data.event === 'error') {
              console.error('Dailymotion error:', data.data);
              showError(true);
              nowPlaying.textContent = "خطأ في محطة Dailymotion";
              isPlaying = false;
              isVideoLoaded = false;
              stopAllPlayback();
            }
          } catch (e) {
            console.log("Dailymotion: Non-JSON message received, ignoring.");
          }
        } else if (event.origin.startsWith('https://player.vimeo.com') && currentVideoStation && currentVideoStation.type === "vimeo") {
          try {
            const data = JSON.parse(event.data);
            if (!iframe || event.source !== iframe.contentWindow || !currentVideoStation) return;
            if (data.event === 'ready') {
              isVideoLoaded = true;
              if (isPlaying) {
                iframe.contentWindow.postMessage({ method: 'play' }, '*');
              }
            } else if (data.event === 'play') {
              isPlaying = true;
              nowPlaying.textContent = `تشغيل: ${currentVideoStation.name}`;
              nowPlaying.classList.add('visible');
              updateStationButtons();
            } else if (data.event === 'pause' || data.event === 'ended') {
              isPlaying = false;
              nowPlaying.textContent = `متوقف: ${currentVideoStation.name}`;
              updateStationButtons();
            } else if (data.event === 'error') {
              console.error('Vimeo error:', data.data);
              showError(true);
              nowPlaying.textContent = "خطأ في محطة Vimeo";
              isPlaying = false;
              isVideoLoaded = false;
              stopAllPlayback();
            }
          } catch (e) {
            console.log("Vimeo: Non-JSON message received, ignoring.");
          }
        }
      };
      window.addEventListener('message', messageListener);
    }

    function stopAllPlayback() {
      player.pause();
      player.currentTime = 0;
      player.src = "";
      audioPlayerControl.classList.remove('playing');
      videoPlayerControl.classList.remove('playing');

      if (currentVideoStation) {
        if (currentVideoStation.type === "audio") {
          audioPlayerDummy.style.display = "flex";
          audioPlayerDummy.classList.add('visible');
          audioPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
          videoPlayerDummy.style.display = "none";
          videoPlayerDummy.classList.remove('visible');
        } else {
          videoPlayerDummy.style.display = "flex";
          videoPlayerDummy.classList.add('visible');
          videoPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
          audioPlayerDummy.style.display = "none";
          audioPlayerDummy.classList.remove('visible');
        }
        nowPlaying.textContent = `متوقف: ${currentVideoStation.name}`;
        nowPlaying.classList.add('visible');
      } else {
        audioPlayerDummy.style.display = "none";
        audioPlayerDummy.classList.remove('visible');
        videoPlayerDummy.style.display = "none";
        videoPlayerDummy.classList.remove('visible');
        nowPlaying.textContent = "اختر محطة للتشغيل";
        nowPlaying.classList.remove('visible');
      }

      if (iframe) {
        try {
          if (currentVideoStation.type === "dailymotion") {
            iframe.contentWindow.postMessage('{"method":"pause"}', '*');
          } else if (currentVideoStation.type === "youtube") {
            if (iframe.contentWindow) {
              iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
              iframe.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
            }
          } else if (currentVideoStation.type === "vimeo") {
            iframe.contentWindow.postMessage({ method: 'pause' }, '*');
          }
        } catch (e) {
          console.warn(`${currentVideoStation.type}: Failed to send pause command.`, e);
        }
        videoPlaceholder.innerHTML = '';
        iframe = null;
      }

      if (messageListener) {
        window.removeEventListener('message', messageListener);
        messageListener = null;
      }

      isVideoLoaded = false;
      isPlaying = false;
      const buttons = document.querySelectorAll('.station-play-btn');
      buttons.forEach(button => {
        button.classList.remove('playing');
        const stationItem = button.closest('.station-item');
        stationItem.classList.remove('playing');
      });
      showError(false);
      updateStationButtons();
    }

    async function syncStations(attempt = 0) {
      const maxAttempts = 3;
      try {
        const response = await fetch(jsonUrl, {
          method: 'GET',
          headers: { 'Accept': 'application/json' }
        });
        if (!response.ok) throw new Error(`فشل جلب القائمة: HTTP ${response.status}`);
        const fetchedStations = await response.json();
        if (!Array.isArray(fetchedStations) || fetchedStations.length === 0) throw new Error('قائمة المحطات فارغة');
        loadedStations = fetchedStations.map(station => {
          if (station.type === 'youtube') {
            let videoId;
            let url = station.url;

            if (!url.startsWith('http://') && !url.startsWith('https://')) {
              url = `https://${url}`;
            }

            try {
              if (url.includes('youtu.be')) {
                videoId = url.split('/').pop().split('?')[0];
              } else if (url.includes('youtube.com/watch')) {
                const urlObj = new URL(url);
                videoId = urlObj.searchParams.get('v') || urlObj.pathname.split('/').pop();
              } else if (url.includes('youtube.com/embed')) {
                videoId = url.split('/embed/')[1]?.split('?')[0];
              } else {
                videoId = url;
              }

              if (videoId && /^[a-zA-Z0-9_-]{11}$/.test(videoId)) {
                return { ...station, url: `https://www.youtube.com/watch?v=${videoId}` };
              } else {
                console.warn(`Invalid YouTube video ID for station ${station.name}: ${videoId}`);
                return station;
              }
            } catch (e) {
              console.error(`Error parsing YouTube URL for station ${station.name}: ${url}`, e);
              return station;
            }
          }
          return station;
        });
        localStorage.setItem('stations', JSON.stringify(loadedStations));
        displayStations();
        errorMessage.style.display = 'none';
        loadCustomStations();
      } catch (error) {
        console.error('خطأ في المزامنة:', error.message);
        if (attempt < maxAttempts) {
          setTimeout(() => syncStations(attempt + 1), 2000 * (attempt + 1));
        } else {
          loadedStations = JSON.parse(localStorage.getItem('stations') || '[]') || defaultStations;
          displayStations();
          errorMessage.textContent = `فشل تحديث المحطات: ${error.message}. يتم استخدام القائمة المحلية.`;
          errorMessage.style.display = 'block';
          loadCustomStations();
        }
      }
    }

    function loadCustomStations() {
      try {
        customStations = JSON.parse(localStorage.getItem('customStations') || '[]');
        displayStations();
      } catch (error) {
        console.error('خطأ في تحميل المحطات المخصصة:', error.message);
        customStations = [];
        displayStations();
      }
    }

    function displayStations(filteredStations = null) {
      stationsList.innerHTML = "";
      const allStations = [...(filteredStations || loadedStations || defaultStations), ...customStations];
      const stationsToDisplay = isShowingFavorites ? JSON.parse(localStorage.getItem('favorites') || '[]') : (filteredStations || allStations);
      if (stationsToDisplay.length === 0) {
        stationsList.innerHTML = '<div style="color: #F44336; text-align: center;">لا توجد محطات متاحة</div>';
        return;
      }
      stationsToDisplay.forEach((station, index) => {
        const item = document.createElement("div");
        item.tabIndex = 0;
        item.className = `station-item ${currentVideoStation && currentVideoStation.url === station.url && isPlaying ? 'playing' : ''}`;
        const isFavorited = JSON.parse(localStorage.getItem('favorites') || '[]').some(fav => fav.url === station.url);
        const isCustom = customStations.some((s, i) => i === index - (loadedStations?.length || 0));
        item.innerHTML = `
          <img src="${station['data-src'] || station.img || 'https://via.placeholder.com/40?text=No+Image'}" alt="${station.name}"/>
          <span>${station.name}</span>
          <button class="station-play-btn ${currentVideoStation && currentVideoStation.url === station.url && isPlaying ? 'playing' : ''}" aria-label="تشغيل أو إيقاف محطة ${station.name}"></button>
          <button class="fav-btn ${isFavorited ? 'favorited' : ''}" aria-label="${isFavorited ? 'إزالة من المفضلة' : 'إضافة إلى المفضلة'}">⭐</button>
          ${isCustom ? `
            <button class="edit-btn material-icons" aria-label="تعديل محطة ${station.name}" style="color: #4CAF50; background: none; border: none; cursor: pointer;">edit</button>
            <button class="delete-btn material-icons" aria-label="حذف محطة ${station.name}" style="color: #F44336; background: none; border: none; cursor: pointer;">delete</button>
          ` : ''}
        `;
        item.querySelector('.station-play-btn').onclick = (e) => {
          e.stopPropagation();
          if (currentVideoStation && currentVideoStation.url === station.url && isPlaying) stopAllPlayback();
          else playStation(station);
        };
        item.querySelector('.fav-btn').onclick = (e) => {
          e.stopPropagation();
          if (isFavorited) {
            removeFromFavorites(station);
            e.target.classList.remove('favorited');
            e.target.setAttribute('aria-label', 'إضافة إلى المفضلة');
          } else {
            addToFavorites(station);
            e.target.classList.add('favorited');
            e.target.setAttribute('aria-label', 'إزالة من المفضلة');
          }
          if (isShowingFavorites) displayStations();
        };
        if (isCustom) {
          const customIndex = index - (loadedStations?.length || 0);
          item.querySelector('.edit-btn').onclick = (e) => {
            e.stopPropagation();
            editStation(station, customIndex);
          };
          item.querySelector('.delete-btn').onclick = (e) => {
            e.stopPropagation();
            deleteStation(customIndex);
          };
        }
        item.onclick = () => {
          if (!(currentVideoStation && currentVideoStation.url === station.url && isPlaying)) playStation(station);
        };
        stationsList.appendChild(item);
      });
    }

    setInterval(() => {
      if (navigator.onLine) syncStations();
    }, 5 * 60 * 1000);

    if (window.requestIdleCallback) requestIdleCallback(() => syncStations());
    else syncStations();

    function updateStationButtons() {
      const buttons = document.querySelectorAll('.station-play-btn');
      buttons.forEach(button => {
        const stationItem = button.closest('.station-item');
        const stationName = stationItem.querySelector('span').textContent;
        if (currentVideoStation && currentVideoStation.name === stationName && isPlaying) {
          button.classList.add('playing');
          stationItem.classList.add('playing');
        } else {
          button.classList.remove('playing');
          stationItem.classList.remove('playing');
        }
      });
      if (currentVideoStation) {
        if (currentVideoStation.type === "audio") {
          if (isPlaying) audioPlayerControl.classList.add('playing');
          else audioPlayerControl.classList.remove('playing');
          audioPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
          const playerImg = audioPlayerDummy.querySelector('.player-img');
          playerImg.src = currentVideoStation['data-src'] || currentVideoStation.img || 'https://via.placeholder.com/40?text=No+Image';
          playerImg.alt = `شعار محطة ${currentVideoStation.name}`;
        } else {
          if (isPlaying) videoPlayerControl.classList.add('playing');
          else videoPlayerControl.classList.remove('playing');
          videoPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
          const playerImg = videoPlayerDummy.querySelector('.player-img');
          playerImg.src = currentVideoStation['data-src'] || currentVideoStation.img || 'https://via.placeholder.com/40?text=No+Image';
          playerImg.alt = `شعار محطة ${currentVideoStation.name}`;
        }
      }
    }

    function playStation(station) {
      stopAllPlayback();
      currentVideoStation = station;
      isPlaying = true;
      if (station.type.toLowerCase() === "audio") {
        playAudioStation(station);
      } else {
        playHiddenVideo(station);
      }
      updateStationButtons();
      displayStations();
    }

   function playAudioStation(station) {
    const hiddenIframe = videoPlaceholder.querySelector('#hidden-video-iframe');
    if (hiddenIframe) {
        hiddenIframe.style.display = "none";
    }
    videoPlayerDummy.style.display = "none";
    videoPlayerDummy.classList.remove('visible');
    audioPlayerDummy.style.display = "flex";
    audioPlayerDummy.classList.add('visible');
    audioPlayerDummy.querySelector('.station-name').textContent = station.name;
    const playerImg = audioPlayerDummy.querySelector('.player-img');
    const imgSrc = station['data-src'] || station.img || 'https://via.placeholder.com/40?text=No+Image';
    playerImg.src = imgSrc;
    playerImg.onerror = () => { playerImg.src = 'https://via.placeholder.com/40?text=Error'; playerImg.onerror = null; };
    playerImg.alt = `شعار محطة ${station.name}`;

    player.pause(); // أوقف التشغيل الحالي
    // لا حاجة لـ player.currentTime = 0; إذا كنت ستغير المصدر وتحمله

    const audioUrl = station.url;

    if (!audioUrl || audioUrl.trim() === "") {
        console.error("Invalid audio URL for station:", station.name);
        nowPlaying.textContent = `خطأ: رابط المحطة (${station.name}) غير صالح`;
        updateStationButtons();
        audioPlayerControl.classList.remove('playing');
        isPlaying = false;
        showError(true);
        return;
    }

    // دالة مساعدة للتشغيل بعد تحميل المصدر
    const playWhenReady = () => {
        player.play()
            .then(() => {
                isPlaying = true;
                nowPlaying.textContent = `تشغيل: ${station.name}`;
                nowPlaying.classList.add('visible');
                updateStationButtons();
                audioPlayerControl.classList.add('playing');
                showError(false);
                // إزالة المستمعين لتجنب تراكمهم
                player.removeEventListener('loadeddata', playWhenReady);
                player.removeEventListener('error', handleLoadError);
            })
            .catch(e => {
                console.error('Audio playback error:', e);
                nowPlaying.textContent = `خطأ في تشغيل: <span class="math-inline">\{station\.name\} \(</span>{e.message})`;
                updateStationButtons();
                audioPlayerControl.classList.remove('playing');
                isPlaying = false;
                showError(true);
                retryButton.style.display = "block"; // افترض أن لديك زر إعادة محاولة
                // إزالة المستمعين لتجنب تراكمهم
                player.removeEventListener('loadeddata', playWhenReady);
                player.removeEventListener('error', handleLoadError);
            });
    };

    // دالة مساعدة لمعالجة خطأ تحميل المصدر
    const handleLoadError = (err) => {
        console.error('Error loading audio source:', err, player.error);
        nowPlaying.textContent = `خطأ في تحميل مصدر الصوت لـ: ${station.name}`;
        updateStationButtons();
        audioPlayerControl.classList.remove('playing');
        isPlaying = false;
        showError(true);
        retryButton.style.display = "block";
        player.removeEventListener('loadeddata', playWhenReady);
        player.removeEventListener('error', handleLoadError);
    };

    if (player.src !== audioUrl) {
        player.src = audioUrl;
        player.currentTime = 0; // يمكن وضعها هنا بعد تغيير المصدر
        // أضف مستمعي الأحداث قبل استدعاء load
        player.addEventListener('loadeddata', playWhenReady);
        player.addEventListener('error', handleLoadError); // لمعالجة أخطاء تحميل المصدر نفسه
        player.load(); // اطلب تحميل المصدر الجديد
    } else {
        // إذا كان نفس المصدر، وكان متوقفًا، شغله مباشرة
        // تأكد من أن currentTime في البداية إذا كنت تريد إعادة التشغيل من البداية
        if (player.paused) {
             player.currentTime = 0; // إذا أردت أن يبدأ دائمًا من الصفر
             playWhenReady(); // حاول التشغيل
        } else {
             // إذا كان يعمل بالفعل بنفس المصدر، قد لا تحتاج لعمل شيء
             // أو يمكنك إعادة تعيين الحالة كما هو مطلوب
             nowPlaying.textContent = `تشغيل: ${station.name}`; // تحديث الواجهة
        }
    }
}

    function playHiddenVideo(station) {
      player.pause();
      player.currentTime = 0;
      player.src = "";
      audioPlayerDummy.style.display = "none";
      audioPlayerDummy.classList.remove('visible');
      videoPlayerDummy.style.display = "flex";
      videoPlayerDummy.classList.add('visible');
      videoPlayerDummy.querySelector('.station-name').textContent = station.name;
      const playerImg = videoPlayerDummy.querySelector('.player-img');
      const imgSrc = station['data-src'] || station.img || 'https://via.placeholder.com/40?text=No+Image';
      playerImg.src = imgSrc;
      playerImg.onerror = () => { playerImg.src = 'https://via.placeholder.com/40?text=Error'; playerImg.onerror = null; };
      playerImg.alt = `شعار محطة ${station.name}`;
      isVideoLoaded = false;
      isPlaying = true;

      currentVideoStation = station;
      const videoUrl = station.url;
      if (!videoUrl || videoUrl.trim() === "") {
        console.error(`${station.type}: Video URL missing for station:`, station.name);
        showError(true);
        nowPlaying.textContent = "خطأ في تحميل المحطة";
        isPlaying = false;
        updateStationButtons();
        return;
      }

      iframe = createIframe(videoUrl, station.type.toLowerCase());
      if (!iframe) {
        showError(true);
        nowPlaying.textContent = "خطأ في تحميل المحطة (رابط غير صالح)";
        isPlaying = false;
        updateStationButtons();
        return;
      }
      setupMessageListener();

      const loadTimeout = setTimeout(() => {
        console.warn(`${station.type}: Iframe load timeout`);
        showError(true);
        nowPlaying.textContent = "فشل تحميل المحطة";
        isVideoLoaded = false;
        isPlaying = false;
        stopAllPlayback();
      }, 20000);

      iframe.onload = () => {
        clearTimeout(loadTimeout);
        nowPlaying.textContent = `جاهز: ${station.name}`;
        nowPlaying.classList.add('visible');
        showError(false);
        if (isPlaying) {
          if (station.type === "youtube") {
            iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
          } else if (station.type === "dailymotion") {
            iframe.contentWindow.postMessage('{"method":"play"}', '*');
            iframe.contentWindow.postMessage('{"method":"unmute"}', '*');
          } else if (station.type === "vimeo") {
            iframe.contentWindow.postMessage({ method: 'play' }, '*');
          }
        }
      };

      iframe.onerror = () => {
        clearTimeout(loadTimeout);
        console.error(`${station.type}: Iframe failed to load`);
        showError(true);
        nowPlaying.textContent = "خطأ في تحميل المحطة";
        isPlaying = false;
        isVideoLoaded = false;
        stopAllPlayback();
      };
    }

    function toggleMenuClick(show) {
      stationsList.style.display = show === undefined ? (stationsList.style.display === "flex" ? "none" : "flex") : (show ? "flex" : "none");
    }
    toggleMenu.onclick = () => toggleMenuClick();

    searchInput.oninput = () => {
      clearTimeout(searchTimeout);
      searchTimeout = setTimeout(() => {
        const q = searchInput.value.toLowerCase();
        const filtered = [...(loadedStations || defaultStations), ...customStations].filter(s => s.name.toLowerCase().includes(q));
        displayStations(filtered);
      }, 300);
    };

    function showError(show) {
      errorMessage.style.display = show ? "block" : "none";
      retryButton.style.display = show ? "block" : "none";
    }

    function togglePlayback() {
      if (!currentVideoStation) return;
      if (currentVideoStation.type === "audio") {
        if (player.paused) {
          player.play().then(() => {
            isPlaying = true;
            nowPlaying.textContent = `تشغيل: ${currentVideoStation.name}`;
            updateStationButtons();
            audioPlayerControl.classList.add('playing');
            audioPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
          }).catch(e => {
            console.error('Audio playback error:', e);
            showError(true);
            audioPlayerControl.classList.remove('playing');
            audioPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
            isPlaying = false;
          });
        } else {
          player.pause();
          isPlaying = false;
          nowPlaying.textContent = `متوقف: ${currentVideoStation.name}`;
          updateStationButtons();
          audioPlayerControl.classList.remove('playing');
          audioPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
        }
      } else if (currentVideoStation.type === "dailymotion" || currentVideoStation.type === "youtube" || currentVideoStation.type === "vimeo") {
        if (!isPlaying) {
          if (!iframe || !iframe.contentWindow) {
            iframe = createIframe(currentVideoStation.url, currentVideoStation.type);
            if (!iframe) {
              showError(true);
              nowPlaying.textContent = "خطأ في تحميل المحطة (رابط غير صالح)";
              isPlaying = false;
              updateStationButtons();
              return;
            }
            setupMessageListener();
          }
          try {
            if (currentVideoStation.type === "dailymotion") {
              iframe.contentWindow.postMessage('{"method":"play"}', '*');
              iframe.contentWindow.postMessage('{"method":"unmute"}', '*');
            } else if (currentVideoStation.type === "youtube") {
              iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
            } else if (currentVideoStation.type === "vimeo") {
              iframe.contentWindow.postMessage({ method: 'play' }, '*');
            }
            isPlaying = true;
            nowPlaying.textContent = `تشغيل: ${currentVideoStation.name}`;
            nowPlaying.classList.add('visible');
            updateStationButtons();
            videoPlayerControl.classList.add('playing');
            videoPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
            videoPlayerDummy.querySelector('.player-img').src = currentVideoStation.img || currentVideoStation["data-src"];
            videoPlayerDummy.querySelector('.player-img').alt = `شعار محطة ${currentVideoStation.name}`;
            showError(false);
          } catch (e) {
            console.error(`${currentVideoStation.type}: Error sending play command:`, e);
            showError(true);
            isPlaying = false;
            videoPlayerControl.classList.remove('playing');
            videoPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
            updateStationButtons();
          }
        } else {
          if (!iframe || !iframe.contentWindow || !isVideoLoaded) {
            stopAllPlayback();
            return;
          }
          try {
            if (currentVideoStation.type === "dailymotion") iframe.contentWindow.postMessage('{"method":"pause"}', '*');
            else if (currentVideoStation.type === "youtube") iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
            else if (currentVideoStation.type === "vimeo") iframe.contentWindow.postMessage({ method: 'pause' }, '*');
            isPlaying = false;
            nowPlaying.textContent = `متوقف: ${currentVideoStation.name}`;
            nowPlaying.classList.add('visible');
            updateStationButtons();
            videoPlayerControl.classList.remove('playing');
            videoPlayerDummy.querySelector('.station-name').textContent = currentVideoStation.name;
            showError(false);
          } catch (e) {
            console.warn(`${currentVideoStation.type}: Failed to send pause command:`, e);
            stopAllPlayback();
          }
        }
      }
    }

    retryButton.onclick = () => {
      if (currentVideoStation) playStation(currentVideoStation);
      else if (player.src) player.play().catch(() => showError(true));
      else showError(true);
    };

    videoPlayerControl.onclick = () => {
      if (!currentVideoStation || !["dailymotion", "youtube", "vimeo"].includes(currentVideoStation.type)) return;
      togglePlayback();
      updateStationButtons();
    };

    audioPlayerControl.onclick = () => togglePlayback();

    player.onplay = () => {
      if (currentVideoStation && currentVideoStation.type === "audio") {
        isPlaying = true;
        nowPlaying.textContent = `تشغيل: ${currentVideoStation.name}`;
        nowPlaying.classList.add('visible');
        updateStationButtons();
        audioPlayerControl.classList.add('playing');
        videoPlayerDummy.style.display = "none";
        videoPlayerDummy.classList.remove('visible');
        if (iframe) {
          videoPlaceholder.innerHTML = '';
          iframe = null;
        }
        if (messageListener) {
          window.removeEventListener('message', messageListener);
          messageListener = null;
        }
        isVideoLoaded = false;
        showError(false);
        displayStations();
      }
    };

    player.onpause = () => {
      if (currentVideoStation && currentVideoStation.type === "audio") {
        isPlaying = false;
        nowPlaying.textContent = `متوقف: ${currentVideoStation.name}`;
        updateStationButtons();
        audioPlayerControl.classList.remove('playing');
      }
    };

    function focusStation(index) {
      const items = document.querySelectorAll(".station-item");
      if (items.length === 0) return;
      focusedIndex = (index + items.length) % items.length;
      items[focusedIndex].focus();
    }

    document.addEventListener("keydown", (e) => {
      if (e.key === "ArrowDown") focusStation(focusedIndex + 1);
      else if (e.key === "ArrowUp") focusStation(focusedIndex - 1);
      else if (e.key === "Enter") document.querySelectorAll(".station-item")[focusedIndex]?.click();
    });

    function addToFavorites(station) {
      const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
      if (!favorites.some(fav => fav.url === station.url)) {
        favorites.push(station);
        localStorage.setItem('favorites', JSON.stringify(favorites));
      }
    }

    function removeFromFavorites(station) {
      const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
      const updatedFavorites = favorites.filter(fav => fav.url !== station.url);
      localStorage.setItem('favorites', JSON.stringify(updatedFavorites));
    }

    // تعديل أحداث زراير الـ Bottom Navigation Bar
    homeBtn.onclick = (e) => {
      e.stopPropagation();
      console.log("Home button clicked");
      isShowingFavorites = false;
      showFavorites.classList.remove('active');
      searchInput.classList.remove('visible');
      searchInput.value = '';
      displayStations();
      homeBtn.classList.add('active');
      toggleTheme.classList.remove('active');
      showFavorites.classList.remove('active');
      searchBtn.classList.remove('active');
    };

    toggleTheme.onclick = (e) => {
      e.stopPropagation();
      console.log("Toggle Theme button clicked");
      document.body.classList.toggle('light-mode');
      toggleTheme.innerHTML = document.body.classList.contains('light-mode') ? '🌙' : '☀';
      toggleTheme.setAttribute('aria-label', document.body.classList.contains('light-mode') ? 'الوضع الليلي' : 'الوضع النهاري');
      toggleTheme.classList.add('active');
      homeBtn.classList.remove('active');
      showFavorites.classList.remove('active');
      searchBtn.classList.remove('active');
    };

    showFavorites.onclick = (e) => {
      e.stopPropagation();
      console.log("Show Favorites button clicked");
      isShowingFavorites = !isShowingFavorites;
      showFavorites.innerHTML = isShowingFavorites ? '📋' : '⭐';
      showFavorites.setAttribute('aria-label', isShowingFavorites ? 'عرض الكل' : 'عرض المفضلة');
      displayStations();
      showFavorites.classList.toggle('active');
      homeBtn.classList.remove('active');
      toggleTheme.classList.remove('active');
      searchBtn.classList.remove('active');
    };

    searchBtn.onclick = (e) => {
      e.stopPropagation();
      console.log("Search button clicked");
      searchInput.classList.toggle('visible');
      if (searchInput.classList.contains('visible')) searchInput.focus();
      else {
        searchInput.value = '';
        displayStations();
      }
      searchBtn.classList.toggle('active');
      homeBtn.classList.remove('active');
      toggleTheme.classList.remove('active');
      showFavorites.classList.remove('active');
    };

    powerSaveBtn.onclick = (e) => {
      e.stopPropagation();
      console.log("Power Save button clicked");
      // أضف وظيفة وضع توفير الطاقة إذا كنت عايز
      powerSaveBtn.classList.toggle('active');
    };

    const hammer = new Hammer(stationsList);
    hammer.on('swipeleft', () => focusStation(focusedIndex + 1));
    hammer.on('swiperight', () => focusStation(focusedIndex - 1));

    window.addEventListener('online', () => syncStations());
    window.addEventListener('offline', () => {
      errorMessage.textContent = 'غير متصل بالإنترنت. جرب المحطات المحفوظة.';
      errorMessage.style.display = 'block';
      displayStations(JSON.parse(localStorage.getItem('stations') || '[]'));
    });

    const bottomNav = document.querySelector('.bottom-nav');
    const addStationBtn = document.createElement('button');
    addStationBtn.id = 'addStationBtn';
    addStationBtn.className = 'material-icons';
    addStationBtn.setAttribute('aria-label', 'إضافة محطة جديدة');
    addStationBtn.textContent = 'add_circle';
    bottomNav.appendChild(addStationBtn);

    const addStationForm = document.createElement('div');
    addStationForm.style.display = 'none';
    addStationForm.style.position = 'fixed';
    addStationForm.style.top = '50%';
    addStationForm.style.left = '50%';
    addStationForm.style.transform = 'translate(-50%, -50%)';
    addStationForm.style.background = '#424242';
    addStationForm.style.padding = '20px';
    addStationForm.style.borderRadius = '12px';
    addStationForm.style.zIndex = '1003';
    addStationForm.style.color = 'white';
    addStationForm.style.width = '90%';
    addStationForm.style.maxWidth = '400px';
    addStationForm.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.3)';
    addStationForm.innerHTML = `
      <h3 style="margin-top: 0; text-align: center; color: #4CAF50;">إضافة محطة جديدة</h3>
      <label for="stationName">اسم المحطة:</label>
      <input type="text" id="stationName" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" placeholder="مثال: راديو جديد" required>
      <label for="stationId">معرف الفيديو (ID):</label>
      <input type="text" id="stationId" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" placeholder="مثال: 8nX2n8UKbWA (لليوتيوب)" required>
      <label for="stationType">نوع المحطة:</label>
      <select id="stationType" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" required>
        <option value="audio">صوت (Audio)</option>
        <option value="dailymotion">Dailymotion</option>
        <option value="youtube">YouTube</option>
        <option value="vimeo">Vimeo</option>
      </select>
      <label for="stationImg">رابط الصورة (اختياري):</label>
      <input type="url" id="stationImg" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" placeholder="مثال: https://example.com/image.jpg">
      <div style="display: flex; gap: 10px; justify-content: center;">
        <button id="saveStationBtn" style="background: #4CAF50; border: none; padding: 10px 20px; color: white; border-radius: 8px; cursor: pointer;">حفظ</button>
        <button id="cancelStationBtn" style="background: #F44336; border: none; padding: 10px 20px; color: white; border-radius: 8px; cursor: pointer;">إلغاء</button>
      </div>
    `;
    document.body.appendChild(addStationForm);

    const editStationForm = document.createElement('div');
    editStationForm.style.display = 'none';
    editStationForm.style.position = 'fixed';
    editStationForm.style.top = '50%';
    editStationForm.style.left = '50%';
    editStationForm.style.transform = 'translate(-50%, -50%)';
    editStationForm.style.background = '#424242';
    editStationForm.style.padding = '20px';
    editStationForm.style.borderRadius = '12px';
    editStationForm.style.zIndex = '1003';
    editStationForm.style.color = 'white';
    editStationForm.style.width = '90%';
    editStationForm.style.maxWidth = '400px';
    editStationForm.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.3)';
    editStationForm.innerHTML = `
      <h3 style="margin-top: 0; text-align: center; color: #4CAF50;">تعديل محطة</h3>
      <label for="editStationName">اسم المحطة:</label>
      <input type="text" id="editStationName" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" required>
      <label for="editStationId">معرف الفيديو (ID):</label>
      <input type="text" id="editStationId" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" required>
      <label for="editStationType">نوع المحطة:</label>
      <select id="editStationType" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" required>
        <option value="audio">صوت (Audio)</option>
        <option value="dailymotion">Dailymotion</option>
        <option value="youtube">YouTube</option>
        <option value="vimeo">Vimeo</option>
      </select>
      <label for="editStationImg">رابط الصورة (اختياري):</label>
      <input type="url" id="editStationImg" style="width: 100%; padding: 8px; margin-bottom: 10px; border-radius: 8px; border: 1px solid #4CAF50; background: #303030; color: white;" placeholder="مثال: https://example.com/image.jpg">
      <div style="display: flex; gap: 10px; justify-content: center;">
        <button id="updateStationBtn" style="background: #4CAF50; border: none; padding: 10px 20px; color: white; border-radius: 8px; cursor: pointer;">تحديث</button>
        <button id="cancelEditBtn" style="background: #F44336; border: none; padding: 10px 20px; color: white; border-radius: 8px; cursor: pointer;">إلغاء</button>
      </div>
    `;
    document.body.appendChild(editStationForm);

    addStationBtn.onclick = (e) => {
      e.stopPropagation();
      console.log("Add Station button clicked");
      addStationForm.style.display = 'block';
      document.getElementById('stationName').value = '';
      document.getElementById('stationId').value = '';
      document.getElementById('stationType').value = 'audio';
      document.getElementById('stationImg').value = '';

      document.getElementById('saveStationBtn').onclick = () => {
        const name = document.getElementById('stationName').value.trim();
        const id = document.getElementById('stationId').value.trim();
        const type = document.getElementById('stationType').value;
        const img = document.getElementById('stationImg').value.trim() || '';

        if (!name || (type !== 'audio' && !id)) {
          alert('يرجى ملء جميع الحقول المطلوبة!');
          return;
        }

        let url = id;
        if (type === 'youtube' && !validateYouTubeId(id)) {
          alert('معرف الفيديو غير صالح! يرجى إدخال معرف يوتيوب صحيح (11 حرفًا).');
          return;
        } else if (type === 'youtube') {
          url = `https://www.youtube.com/watch?v=${id}`;
        } else if (type === 'dailymotion') {
          url = `https://geo.dailymotion.com/player.html?video=${id}&muted=0&ads=0`;
        } else if (type === 'vimeo') {
          url = `https://vimeo.com/${id}`;
        } else if (type === 'audio') {
          url = id;
        }

        const newStation = { name, url, type, img: img || '', 'data-src': img || '' };
        customStations.push(newStation);
        localStorage.setItem('customStations', JSON.stringify(customStations));
        addStationForm.style.display = 'none';
        displayStations();
      };

      document.getElementById('cancelStationBtn').onclick = () => {
        addStationForm.style.display = 'none';
      };
    };

    function validateYouTubeId(id) {
      return /^[a-zA-Z0-9_-]{11}$/.test(id);
    }

    function editStation(station, index) {
      editStationForm.style.display = 'block';
      document.getElementById('editStationName').value = station.name;
      document.getElementById('editStationId').value = station.url.includes('youtube.com') ? station.url.split('v=')[1] : station.url;
      document.getElementById('editStationType').value = station.type;
      document.getElementById('editStationImg').value = station.img || station['data-src'] || '';

      document.getElementById('updateStationBtn').onclick = () => {
        const name = document.getElementById('editStationName').value.trim();
        const id = document.getElementById('editStationId').value.trim();
        const type = document.getElementById('editStationType').value;
        const img = document.getElementById('editStationImg').value.trim() || '';

        if (!name || (type !== 'audio' && !id)) {
          alert('يرجى ملء جميع الحقول المطلوبة!');
          return;
        }

        let url = id;
        if (type === 'youtube' && !validateYouTubeId(id)) {
          alert('معرف الفيديو غير صالح! يرجى إدخال معرف يوتيوب صحيح (11 حرفًا).');
          return;
        } else if (type === 'youtube') {
          url = `https://www.youtube.com/watch?v=${id}`;
        } else if (type === 'dailymotion') {
          url = `https://geo.dailymotion.com/player.html?video=${id}&muted=0&ads=0`;
        } else if (type === 'vimeo') {
          url = `https://vimeo.com/${id}`;
        } else if (type === 'audio') {
          url = id;
        }

        customStations[index] = { name, url, type, img: img || '', 'data-src': img || '' };
        localStorage.setItem('customStations', JSON.stringify(customStations));
        editStationForm.style.display = 'none';
        displayStations();
      };

      document.getElementById('cancelEditBtn').onclick = () => {
        editStationForm.style.display = 'none';
      };
    }

    function deleteStation(index) {
      customStations.splice(index, 1);
      localStorage.setItem('customStations', JSON.stringify(customStations));
      displayStations();
    }
  </script>
</body>
</html>