class OneDisplayRSS {
    constructor(container, options = {}) {
      this.container = container; // Use the passed container directly
      this.instanceId = `rss-instance-${Math.random().toString(36).substr(2, 9)}`; // Unique ID for each instance
      this.url = options.url || '';
      this.refreshInterval = options.refreshInterval || 30000; // 30 seconds
      this.itemDisplayTime = options.timeout * 1000 || 10000; // 10 seconds per item
      this.maxItems = options.maxItems * 1000 || 10; // Maximum number of items
      this.theme = options.theme;
      this.currentItemIndex = 0;
      this.items = [];
      this.transitionInterval = null;
      this.resizeTimeout = null;

      this.loadingIndicator = document.createElement('div');
      this.loadingIndicator.className = `${this.instanceId} loading`;
      this.loadingIndicator.textContent = 'Loading news...';
      this.container.appendChild(this.loadingIndicator);

      this.itemsContainer = document.createElement('div');
      this.itemsContainer.className = `${this.instanceId} rss-items-container`;
      this.container.appendChild(this.itemsContainer);

      // Inject scoped CSS for this instance
      this.injectStyles();
    }

    // Inject unique styles for this specific instance
    injectStyles() {
      const style = document.createElement('style');
      style.innerHTML = `
        .${this.instanceId} * {
          box-sizing: border-box;
          margin: 0;
          padding: 0;
          font-family: Arial, sans-serif;
        }

        .${this.instanceId} .rss-widget {
          width: 100%;
          height: 100%;
          overflow: hidden;
          position: relative;
          background: #f5f5f5;
          border-radius: 8px;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .${this.instanceId} .rss-item {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          padding: 20px;
          display: flex;
          opacity: 0;
          transition: opacity 0.8s ease-in-out;
          background: transparent;
          overflow-y: hidden;
        }

        .${this.instanceId} .rss-item.active {
          opacity: 1;
          z-index: 1;
        }

        .${this.instanceId} .rss-item.portrait {
          flex-direction: column;
        }

        .${this.instanceId} .rss-item.landscape {
          flex-direction: row;
        }

        .${this.instanceId} .rss-image-container {
          flex-shrink: 0;
          overflow: hidden;
          border-radius: 4px;
        }

        .${this.instanceId} .rss-item.landscape .rss-image-container {
          width: 40%;
          height: 100%;
          margin-right: 15px;
        }

        .${this.instanceId} .rss-item.portrait .rss-image-container {
          width: 100%;
          height: auto;
          max-height: 50%;
          margin-bottom: 15px;
        }

        .${this.instanceId} .rss-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          display: block;
        }

        .${this.instanceId} .rss-content {
        font-size: ${this.fontSize}px;
            display: flex;
            flex-direction: column;
            overflow-y: hidden;
            position: relative;
          }

        .${this.instanceId} .rss-item.landscape .rss-content {
          width: 60%;
          height: 100%;
          padding-left: 10px;
          mask-image: linear-gradient(to bottom, 
            black calc(100% - 4em), 
            transparent);
          -webkit-mask-image: linear-gradient(to bottom, 
            black calc(100% - 4em), 
            transparent);
        }

        .${this.instanceId} .rss-item.portrait .rss-content {
          width: 100%;
          padding-top: 10px;
          flex: 1;
          overflow-y: hidden;
          mask-image: linear-gradient(to bottom, 
            black calc(100% - 4em), 
            transparent);
          -webkit-mask-image: linear-gradient(to bottom, 
            black calc(100% - 4em), 
            transparent);
        }

        .${this.instanceId} .rss-item.landscape .rss-content-full {
          width: 100%;
          height: 100%;
          padding-left: 10px;
          mask-image: linear-gradient(to bottom, 
            black calc(100% - 4em), 
            transparent);
          -webkit-mask-image: linear-gradient(to bottom, 
            black calc(100% - 4em), 
            transparent);
        }

        .${this.instanceId} .rss-title {
          font-weight: bold;
          margin-bottom: 5px;
          color: ${this.theme == 'dark' ? '#fff' : '#000'};
          line-height: 1.2;
          variable: ${this.theme};
        }

        .${this.instanceId} .rss-description {
          color: ${this.theme == 'dark' ? '#fefefe' : '#2f2f2f'};
          line-height: 1.4;
          margin-bottom: 10px;
          overflow: hidden;
          flex-grow: 1;
        }

        .${this.instanceId} .rss-date {
          font-size: 0.8em;
          color: ${this.theme == 'dark' ? '#fefefe' : '#666'};
        }

        .${this.instanceId} .rss-nav {
          position: absolute;
          bottom: 10px;
          left: 0;
          width: 100%;
          display: flex;
          justify-content: center;
          z-index: 2;
        }

        .${this.instanceId} .rss-dot {
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background: rgba(0, 0, 0, 0.2);
          margin: 0 5px;
          cursor: pointer;
          transition: background 0.3s;
        }

        .${this.instanceId} .rss-dot.active {
          background: rgba(0, 0, 0, 0.6);
        }
      `;
      document.head.appendChild(style);
    }

    async fetchAndDisplayFeed() {
      try {
        //this.loadingIndicator.style.display = 'flex';
        const response = await axios.get(this.url);
        const feed = response.data;

        if (!feed.items || feed.items.length === 0) {
          throw new Error('No items in feed');
        }
        this.items = feed.items.slice(0, this.maxItems);
        this.renderFeed();
        this.startTransitionCycle();
      } catch (error) {
        console.error('Error fetching RSS feed:', error);
        this.showError('Failed to load news feed. Please try again later.');
      } finally {
        this.loadingIndicator.style.display = 'none';
      }
    }

    renderFeed() {
      // Clear previous content
      this.itemsContainer.innerHTML = '';

      const parent = this.container.parentElement;
      const containerWidth = parent.offsetWidth;
      const containerHeight = parent.offsetHeight;

      // Get container dimensions and determine layout (landscape/portrait)
      //const containerWidth = this.container.offsetWidth;
      //const containerHeight = this.container.offsetHeight;
      const isLandscape = containerWidth > containerHeight;

      this.items.forEach((item, index) => {
        const itemElement = document.createElement('div');
        itemElement.className = `${this.instanceId} rss-item`;
        itemElement.dataset.index = index;
        itemElement.classList.add(isLandscape ? 'landscape' : 'portrait');

        // Add image if available
        let hasImage = false;
        if (item.enclosure && item.enclosure.type.startsWith('image/')) {
          const imageContainer = document.createElement('div');
          imageContainer.className = `${this.instanceId} rss-image-container`;
          const image = document.createElement('img');
          image.className = `${this.instanceId} rss-image`;
          image.src = item.enclosure.url;
          image.alt = item.title;
          imageContainer.appendChild(image);
          itemElement.appendChild(imageContainer);
          hasImage = true;
        }

        // Add content (title, description, date)
        const content = document.createElement('div');
        content.className = `${this.instanceId} ${hasImage ? 'rss-content' : 'rss-content-full'}`;
        const title = document.createElement('div');
        title.className = `${this.instanceId} rss-title`;
        title.innerHTML = item.title;
        content.appendChild(title);

        if (item.description) {
          const description = document.createElement('div');
          description.className = `${this.instanceId} rss-description`;
          description.innerHTML = this.stripHtml(item.description);
          content.appendChild(description);
        }
        /* if (item.pubDate) {
          const date = document.createElement('div');
          date.className = `${this.instanceId} rss-date`;
          date.innerHTML = this.formatDate(item.pubDate);
          content.appendChild(date);
        } */

        itemElement.appendChild(content);
        this.itemsContainer.appendChild(itemElement);
      });

      // Add navigation dots if there are multiple items
      /* if (this.items.length > 1) {
        const nav = document.createElement('div');
        nav.className = `${this.instanceId} rss-nav`;
        this.items.forEach((_, index) => {
          const dot = document.createElement('div');
          dot.className = `${this.instanceId} rss-dot`;
          dot.dataset.index = index;
          dot.addEventListener('click', () => this.goToItem(index));
          nav.appendChild(dot);
        });
        this.itemsContainer.appendChild(nav);
      } */

      // Activate the first item by default
      const activeItem = this.itemsContainer.querySelector(`.${this.instanceId} .rss-item[data-index="${this.currentItemIndex}"]`);
      if (activeItem) activeItem.classList.add('active');
    }

    stripHtml(html)
    {
      let tmp = document.createElement("DIV");
      tmp.innerHTML = html;
      return tmp.textContent || tmp.innerText || "";
    }

    startTransitionCycle() {
      clearInterval(this.transitionInterval);
      if (this.items.length > 1) {
        this.transitionInterval = setInterval(() => this.nextItem(), this.itemDisplayTime);
      }
    }

    nextItem() {
      const nextIndex = (this.currentItemIndex + 1) % this.items.length;
      this.goToItem(nextIndex);
    }

    goToItem(index) {
      if (index < 0 || index >= this.items.length) return;

      const currentActive = document.querySelector(`.${this.instanceId} .rss-item.active`);
      if (currentActive) currentActive.classList.remove('active');
      const currentDot = document.querySelector(`.${this.instanceId} .rss-dot.active`);
      if (currentDot) currentDot.classList.remove('active');

      this.currentItemIndex = index;
      const itemElements = document.querySelectorAll(`.${this.instanceId} .rss-item`);
      if (itemElements[index]) itemElements[index].classList.add('active');
      const dots = document.querySelectorAll(`.${this.instanceId} .rss-dot`);
      if (dots[index]) dots[index].classList.add('active');

      this.startTransitionCycle();
    }

    showError(message) {
      this.itemsContainer.innerHTML = '';
      const errorElement = document.createElement('div');
      errorElement.className = `${this.instanceId} error`;
      errorElement.textContent = message;
      this.itemsContainer.appendChild(errorElement);
    }

    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString(undefined, {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    }

    handleResize() {
      clearTimeout(this.resizeTimeout);
      this.resizeTimeout = setTimeout(() => {
        this.renderFeed();
      }, 200);
    }

    start() {
      this.fetchAndDisplayFeed();
      setInterval(() => this.fetchAndDisplayFeed(), this.refreshInterval);
      window.addEventListener('resize', () => this.handleResize());
    }

    stop() {
      clearInterval(this.transitionInterval);
      window.removeEventListener('resize', this.handleResize);
      this.itemsContainer.innerHTML = '';
    }
  }

