class OneDisplayFinancial {
    constructor(container, options = {}) {
      this.container = container;
      this.instanceId = `financial-instance-${Math.random().toString(36).substr(2, 9)}`;
      this.containerHeight = options.containerHeight || 0; // Used to calculate margin-top for marquee
      this.fontSize = options.fontSize || 16; // Used to calculate margin-top for marquee
      this.apiKey = options.apiKey || '';
      this.symbols = options.symbols || ['^GSPC', '^DJI', '^IXIC', 'GC=F', 'CL=F', 'BTC-USD'];
      this.refreshInterval = options.refreshInterval || 60000;
      this.theme = options.theme || 'light';
      this.marquee = options.marquee || false;
      this.marqueeSpeed = options.marqueeSpeed || 150;
      this.data = [];
      this.marqueeElements = [];


      
      this.injectStyles();
      this.initContainer();
      
    }
  
    initContainer() {
      this.container.innerHTML = '';
      this.loadingIndicator = document.createElement('div');
      this.loadingIndicator.className = `${this.instanceId} loading`;
      this.loadingIndicator.textContent = 'Loading market data...';
      this.container.appendChild(this.loadingIndicator);
  
      this.widgetContainer = document.createElement('div');
      this.widgetContainer.className = `${this.instanceId} financial-widget ${this.marquee ? 'marquee-container' : ''}`;
      this.container.appendChild(this.widgetContainer);
      
      if (this.marquee) {
        this.marqueeContent = document.createElement('div');
        this.marqueeContent.className = `${this.instanceId} marquee-content`;
        this.widgetContainer.appendChild(this.marqueeContent);
      }
    }
  
    injectStyles() {
      const style = document.createElement('style');
      style.innerHTML = `
        .${this.instanceId} * {
          box-sizing: border-box;
          margin: 0;
          padding: 0;
          font-family: Arial, sans-serif;
        }
          .poop {
            background-color: red !important;
          }
  
        .${this.instanceId} .financial-widget {
          width: 100%;
          height: 100%;
          background: ${this.theme === 'dark' ? '#222' : '#f5f5f5'};
          border-radius: 8px;
          padding: 15px;
          overflow: hidden;
        }

        
/* Target both possible class combinations */
    .${this.instanceId}.marquee-container,
    .${this.instanceId}.financial-widget.marquee-container {
      overflow: hidden;
      white-space: nowrap;
      position: relative;
      width: 100%;
      -webkit-mask-image: linear-gradient(
        to right,
        transparent 0%,
        black 50px,
        black calc(100% - 50px),
        transparent 100%
      );
      mask-image: linear-gradient(
        to right,
        transparent 0%,
        black 50px,
        black calc(100% - 50px),
        transparent 100%
      );
    }
    
        .${this.instanceId} .marquee-content {
          display: inline-block;
          white-space: nowrap;
          will-change: transform; /* Optimize for animation */
        }
        
        .${this.instanceId} .marquee-item {
          display: inline-block;
          margin-right: 40px;
          white-space: nowrap;
          margin-top: ${(this.containerHeight - (this.fontSize * 1.2)) / 2}px;
        }
        
        .${this.instanceId} .marquee-item .financial-name,
        .${this.instanceId} .marquee-item .financial-price,
        .${this.instanceId} .marquee-item .financial-change-container {
          display: inline-block;
          margin-right: 10px;
        }
  
        .${this.instanceId} .financial-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 0;
          border-bottom: 1px solid ${this.theme === 'dark' ? '#444' : '#ddd'};
        }
  
        .${this.instanceId} .financial-name {
          color: ${this.theme === 'dark' ? '#eee' : '#333'};
          font-weight: bold;
          
        }

        .${this.instanceId} .financial-name.list {
          min-width: 120px;
          padding-left: 10px;
          width: 40%; 
        }
  
        .${this.instanceId} .financial-price {
          color: ${this.theme === 'dark' ? '#eee' : '#333'};
          font-family: 'Courier New', monospace;
          
          text-align: right;
          padding-right: 10px;
          font-weight: bold;
        }

        .${this.instanceId} .financial-price.list {
          width: 30%;
        }


        .${this.instanceId} .financial-price.positive {
          color: #0a0;
        }
  
        .${this.instanceId} .financial-price.negative {
          color: #a00;
        }
  
        .${this.instanceId} .financial-change-container {
          
          text-align: right;
        }
        .${this.instanceId} .financial-change-container.list {
          width: 30%;
          min-width: 150px;
          padding-right: 10px;
        }

  
        .${this.instanceId} .financial-change {
          font-size: 0.8em;
          padding: 0px 8px;
          border-radius: 8px;
          display: inline-block;
          text-align: center;
          min-width: 150px;
        }
  
        .${this.instanceId} .financial-change.positive {
          color: #0a0;
          background-color: ${this.theme === 'dark' ? '#0a03' : '#dfd'};
          background-opacity: 0.5;
        }
  
        .${this.instanceId} .financial-change.negative {
          color: #a00;
          background-color: ${this.theme === 'dark' ? '#a003' : '#fdd'};
          background-opacity: 0.5;
        }
  
        .${this.instanceId} .loading {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
          color: ${this.theme === 'dark' ? '#ccc' : '#666'};
        }

        
      `;
      document.head.appendChild(style);
    }
  
    async fetchData() {
      try {
        const symbolsParam = this.symbols.join(',');
        const response = await fetch(
          `https://api.onedisplay.se/yahoo2json?symbols=${symbolsParam}`
        );
    
        const data = await response.json();
    
        // Ensure data is in expected format
        if (!Array.isArray(data)) {
          throw new Error('Invalid data format');
        }
    
        this.data = data;
        if(this.marqueeContent) {
          this.marqueeContent.style.display = 'block';
        }
    
        // Clear previous error if any
        // Remove any existing error message safely
    const existingError = this.widgetContainer.querySelector(`.${this.instanceId}.error`);
    if (existingError) {
      existingError.remove();
    }
        
        this.renderData();
      } catch (error) {
        console.error('Error fetching financial data:', error);
        this.showError('Failed to load market data');
      } finally {
        this.loadingIndicator.style.display = 'none';
        this.widgetContainer.style.display = 'block';
      }
    }
  
    renderData() {
      if (this.marquee) {
        this.renderMarquee();
      } else {
        this.renderList();
      }
    }
    
    renderList() {
      this.widgetContainer.innerHTML = '';
      
      this.data.forEach(item => {
        const itemElement = this.createFinancialItem(item, false);
        this.widgetContainer.appendChild(itemElement);
      });
    }
    
    renderMarquee() {
      this.marqueeContent.innerHTML = '';
      
      this.data.forEach(item => {
        const itemElement = this.createFinancialItem(item, true);
        this.marqueeContent.appendChild(itemElement);
      });
      
      this.startMarqueeAnimation();
    }
    
    createFinancialItem(item, isMarquee) {
      const change = item.change;
      const changePercent = item.changePercent;
      const isPositive = change >= 0;
      
      if (isMarquee) {
        // Create inline marquee item
        const itemElement = document.createElement('div');
        itemElement.className = `${this.instanceId} marquee-item`;
        
        const nameElement = document.createElement('span');
        nameElement.className = `${this.instanceId} financial-name`;
        nameElement.textContent = item.name;
        itemElement.appendChild(nameElement);
        
        const priceElement = document.createElement('span');
        priceElement.className = `${this.instanceId} financial-price ${isPositive ? 'positive' : 'negative'}`;
        priceElement.textContent = '$' + item.price.toFixed(2) + `(${isPositive ? '+' : ''}${changePercent.toFixed(2)}%)`;
        itemElement.appendChild(priceElement);
        
        return itemElement;
      } else {
        // Create regular list item
        const itemElement = document.createElement('div');
        itemElement.className = `${this.instanceId} financial-item list`;
        
        const nameElement = document.createElement('div');
        nameElement.className = `${this.instanceId} financial-name list`;
        nameElement.textContent = item.name;
        itemElement.appendChild(nameElement);
        
        const priceElement = document.createElement('div');
        priceElement.className = `${this.instanceId} financial-price list`;
        priceElement.textContent = `$${item.price.toFixed(2)}`;
        itemElement.appendChild(priceElement);
        
        const changeContainer = document.createElement('div');
        changeContainer.className = `${this.instanceId} financial-change-container list`;
        
        const changeElement = document.createElement('div');
        changeElement.className = `${this.instanceId} financial-change ${isPositive ? 'positive' : 'negative'}`;
        changeElement.textContent = `${isPositive ? '+' : ''}${change.toFixed(2)} (${isPositive ? '+' : ''}${changePercent.toFixed(2)}%)`;
        changeContainer.appendChild(changeElement);
        
        itemElement.appendChild(changeContainer);
        return itemElement;
      }
    }


      startMarqueeAnimation() {
        // Cancel any existing animation
        if (this.transitionEndListener) {
          this.marqueeContent.removeEventListener('transitionend', this.transitionEndListener);
        }
        
        const containerWidth = this.widgetContainer.clientWidth;
        const contentWidth = this.marqueeContent.scrollWidth;
        
        // If content is smaller than container, no need to animate
        if (contentWidth <= containerWidth) {
          this.marqueeContent.style.transform = 'translateX(0)';
          return;
        }
        
        // Reset position to right side
        this.marqueeContent.style.transition = 'none';
        this.marqueeContent.style.transform = `translateX(${containerWidth}px)`;
        
        // Force reflow
        this.marqueeContent.offsetHeight;
        
        // Calculate duration based on speed (distance/speed = time)
        const duration = (contentWidth + containerWidth) / this.marqueeSpeed;
        
        // Start animation
        this.marqueeContent.style.transition = `transform ${duration}s linear`;
        this.marqueeContent.style.transform = `translateX(-${contentWidth}px)`;
        
        // Set up looping
        this.transitionEndListener = () => {
          this.startMarqueeAnimation(); // Restart the animation
        };
        this.marqueeContent.addEventListener('transitionend', this.transitionEndListener);
      }
  
      showError(message) {
        if(this.marqueeContent) {
          this.marqueeContent.style.display = 'none';
        }
        // Avoid appending duplicate error messages
        const existingError = this.widgetContainer.querySelector(`.${this.instanceId}.error`);
        if (existingError) return;
      
        const errorElement = document.createElement('div');
        errorElement.className = `${this.instanceId} error`;
        errorElement.style.textAlign = 'center';
        errorElement.style.color = this.theme === 'dark' ? '#fff' : '#000';
        errorElement.textContent = message;
      
        this.widgetContainer.appendChild(errorElement);
      }
  
    start() {
      this.fetchData();
      this.intervalId = setInterval(() => this.fetchData(), this.refreshInterval);
    }
  
    stop() {
      clearInterval(this.intervalId);
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
      }

      if (this.transitionEndListener) {
        this.marqueeContent.removeEventListener('transitionend', this.transitionEndListener);
      }
    }
  }