import React, { useState, useEffect } from 'react';
import './ChainlinkDemo.css';

// Mock data for demonstration purposes
const mockTokenData = {
  networkStats: {
    totalTokens: 1000000,
    circulatingSupply: 350000,
    reservedPool: 650000,
    tokenPrice: 2.75,
    marketCap: 962500,
    stakeholders: 1250,
    chargingHubs: 36,
    totalTransactions: 15782
  },
  userWallet: {
    balance: 45,
    stakingRewards: 3.2,
    acquisitionHistory: [
      { date: "Apr 1, 2025", amount: 15, source: "Monthly Subscription", price: 2.65 },
      { date: "Mar 1, 2025", amount: 15, source: "Monthly Subscription", price: 2.58 },
      { date: "Feb 1, 2025", amount: 15, source: "Monthly Subscription", price: 2.42 }
    ],
    transactionHistory: [
      { date: "Mar 15, 2025", type: "Staking", amount: 20, status: "Active" },
      { date: "Mar 10, 2025", type: "Charging Credit", amount: 5, status: "Completed" },
      { date: "Feb 22, 2025", type: "Governance Vote", amount: 0, status: "Completed" }
    ]
  },
  assetOwnership: {
    totalOwnership: 0.0045, // percentage of network
    hubs: [
      { id: 101, name: "Springfield Downtown", ownership: 0.0012, status: "Operational", monthlyRevenue: 0.32 },
      { id: 102, name: "Champaign-Urbana Hub", ownership: 0.0018, status: "Construction", monthlyRevenue: 0 },
      { id: 103, name: "Bloomington-Normal", ownership: 0.0015, status: "Planning", monthlyRevenue: 0 }
    ],
    projectedReturns: [
      { year: 2025, quarter: 2, returns: 0.45 },
      { year: 2025, quarter: 3, returns: 0.68 },
      { year: 2025, quarter: 4, returns: 0.92 },
      { year: 2026, quarter: 1, returns: 1.25 }
    ]
  },
  tokenomics: {
    distribution: [
      { category: "Subscriber Rewards", percentage: 35, color: "#00E0FF" },
      { category: "Infrastructure Development", percentage: 25, color: "#35F2DB" },
      { category: "Operations", percentage: 15, color: "#FFC107" },
      { category: "Community Governance", percentage: 10, color: "#FF5555" },
      { category: "Partnerships", percentage: 10, color: "#9C27B0" },
      { category: "Reserve", percentage: 5, color: "#607D8B" }
    ],
    utilityFunctions: [
      { function: "Charging Credits", description: "Redeem tokens for charging credits at The Link hubs" },
      { function: "Subscription Discounts", description: "Apply tokens toward Unity Fleet subscription fees" },
      { function: "Governance Rights", description: "Vote on network expansion and feature development" },
      { function: "Revenue Sharing", description: "Earn a portion of network revenue based on token holdings" },
      { function: "Asset Ownership", description: "Tokens represent fractional ownership in physical infrastructure" }
    ],
    valueDrivers: [
      { driver: "Network Expansion", impact: "High", description: "Each new charging hub increases token utility and demand" },
      { driver: "EV Adoption Rate", impact: "High", description: "Accelerating EV adoption drives charging demand and token usage" },
      { driver: "Subscription Growth", impact: "Medium", description: "New subscribers receive tokens, increasing distribution and usage" },
      { driver: "Energy Efficiency", impact: "Medium", description: "Optimized energy usage improves hub profitability and token value" },
      { driver: "Governance Decisions", impact: "Low", description: "Community governance ensures alignment with token holder interests" }
    ]
  },
  marketData: {
    priceHistory: [
      { month: "Jan", price: 2.25 },
      { month: "Feb", price: 2.42 },
      { month: "Mar", price: 2.58 },
      { month: "Apr", price: 2.75 }
    ],
    volumeHistory: [
      { month: "Jan", volume: 15000 },
      { month: "Feb", volume: 22500 },
      { month: "Mar", volume: 28000 },
      { month: "Apr", volume: 35000 }
    ],
    projections: [
      { quarter: "Q2 2025", lowEstimate: 2.85, highEstimate: 3.25 },
      { quarter: "Q3 2025", lowEstimate: 3.10, highEstimate: 3.75 },
      { quarter: "Q4 2025", lowEstimate: 3.50, highEstimate: 4.50 },
      { quarter: "Q1 2026", lowEstimate: 4.00, highEstimate: 5.25 }
    ]
  }
};

function ChainlinkDemo() {
  const [activeTab, setActiveTab] = useState('overview');
  const [loading, setLoading] = useState(true);
  const [selectedAsset, setSelectedAsset] = useState(null);
  const [tokenAction, setTokenAction] = useState(null);
  const [tokenAmount, setTokenAmount] = useState(1);
  const [showConfirmation, setShowConfirmation] = useState(false);
  const [animateTokenFlow, setAnimateTokenFlow] = useState(false);

  useEffect(() => {
    // Simulate loading
    const timer = setTimeout(() => {
      setLoading(false);
    }, 1500);
    
    return () => clearTimeout(timer);
  }, []);

  const handleAssetSelect = (asset) => {
    setSelectedAsset(asset);
  };

  const handleTokenActionSelect = (action) => {
    setTokenAction(action);
    setShowConfirmation(false);
  };

  const handleTokenAmountChange = (amount) => {
    setTokenAmount(Math.max(1, Math.min(mockTokenData.userWallet.balance, amount)));
  };

  const handleActionConfirm = () => {
    setShowConfirmation(true);
  };

  const handleTokenFlowDemo = () => {
    setAnimateTokenFlow(true);
    setTimeout(() => {
      setAnimateTokenFlow(false);
    }, 5000);
  };

  // Helper function to render the network overview
  const renderOverview = () => {
    const { networkStats, tokenomics } = mockTokenData;
    
    return (
      <div className="overview-tab">
        <div className="network-stats">
          <div className="stats-card token-supply">
            <h3>Token Supply & Distribution</h3>
            <div className="token-supply-chart">
              <div className="supply-chart-container">
                <div className="supply-chart">
                  <div 
                    className="supply-segment circulating" 
                    style={{ 
                      transform: `rotate(0deg) skew(${90 - (networkStats.circulatingSupply / networkStats.totalTokens) * 360}deg)` 
                    }}
                  ></div>
                  <div 
                    className="supply-segment reserved" 
                    style={{ 
                      transform: `rotate(${(networkStats.circulatingSupply / networkStats.totalTokens) * 360}deg) skew(${90 - (networkStats.reservedPool / networkStats.totalTokens) * 360}deg)` 
                    }}
                  ></div>
                  <div className="supply-inner">
                    <div className="supply-value">{networkStats.totalTokens.toLocaleString()}</div>
                    <div className="supply-label">Total Tokens</div>
                  </div>
                </div>
              </div>
              <div className="supply-legend">
                <div className="legend-item">
                  <div className="legend-color circulating"></div>
                  <div className="legend-label">Circulating Supply</div>
                  <div className="legend-value">{networkStats.circulatingSupply.toLocaleString()} tokens</div>
                </div>
                <div className="legend-item">
                  <div className="legend-color reserved"></div>
                  <div className="legend-label">Reserved Pool</div>
                  <div className="legend-value">{networkStats.reservedPool.toLocaleString()} tokens</div>
                </div>
              </div>
            </div>
          </div>
          
          <div className="stats-card network-metrics">
            <h3>Network Metrics</h3>
            <div className="metrics-grid">
              <div className="metric-item">
                <div className="metric-icon">💰</div>
                <div className="metric-value">${networkStats.tokenPrice.toFixed(2)}</div>
                <div className="metric-label">Token Price</div>
              </div>
              <div className="metric-item">
                <div className="metric-icon">📊</div>
                <div className="metric-value">${networkStats.marketCap.toLocaleString()}</div>
                <div className="metric-label">Market Cap</div>
              </div>
              <div className="metric-item">
                <div className="metric-icon">👥</div>
                <div className="metric-value">{networkStats.stakeholders.toLocaleString()}</div>
                <div className="metric-label">Stakeholders</div>
              </div>
              <div className="metric-item">
                <div className="metric-icon">🔌</div>
                <div className="metric-value">{networkStats.chargingHubs}</div>
                <div className="metric-label">Charging Hubs</div>
              </div>
            </div>
          </div>
        </div>
        
        <div className="token-distribution">
          <h3>Token Distribution</h3>
          <div className="distribution-chart">
            <div className="pie-chart-container">
              <div className="pie-chart">
                {tokenomics.distribution.map((segment, index) => {
                  const previousSegments = tokenomics.distribution
                    .slice(0, index)
                    .reduce((sum, item) => sum + item.percentage, 0);
                  
                  return (
                    <div 
                      key={index}
                      className="pie-segment"
                      style={{ 
                        transform: `rotate(${previousSegments * 3.6}deg) skew(${90 - segment.percentage * 3.6}deg)`,
                        background: segment.color
                      }}
                    ></div>
                  );
                })}
                <div className="pie-inner">
                  <div className="pie-icon">⬡</div>
                </div>
              </div>
            </div>
            <div className="distribution-legend">
              {tokenomics.distribution.map((segment, index) => (
                <div key={index} className="legend-item">
                  <div className="legend-color" style={{ backgroundColor: segment.color }}></div>
                  <div className="legend-label">{segment.category}</div>
                  <div className="legend-value">{segment.percentage}%</div>
                </div>
              ))}
            </div>
          </div>
        </div>
        
        <div className="token-utility">
          <h3>Token Utility Functions</h3>
          <div className="utility-grid">
            {tokenomics.utilityFunctions.map((utility, index) => (
              <div key={index} className="utility-card">
                <div className="utility-header">
                  <div className="utility-icon">⬡</div>
                  <h4>{utility.function}</h4>
                </div>
                <p>{utility.description}</p>
              </div>
            ))}
          </div>
        </div>
        
        <div className="value-drivers">
          <h3>Value Drivers</h3>
          <div className="drivers-table">
            <div className="table-header">
              <div className="driver-column">Driver</div>
              <div className="impact-column">Impact</div>
              <div className="description-column">Description</div>
            </div>
            {tokenomics.valueDrivers.map((driver, index) => (
              <div key={index} className="table-row">
                <div className="driver-column">{driver.driver}</div>
                <div className={`impact-column impact-${driver.impact.toLowerCase()}`}>{driver.impact}</div>
                <div className="description-column">{driver.description}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  };

  // Helper function to render the wallet tab
  const renderWallet = () => {
    const { userWallet } = mockTokenData;
    
    return (
      <div className="wallet-tab">
        <div className="wallet-overview">
          <div className="wallet-card balance">
            <div className="wallet-icon">⬡</div>
            <div className="wallet-balance">{userWallet.balance}</div>
            <div className="wallet-label">Available Tokens</div>
            <div className="wallet-value">${(userWallet.balance * mockTokenData.networkStats.tokenPrice).toFixed(2)}</div>
          </div>
          
          <div className="wallet-card staking">
            <div className="staking-header">
              <h3>Staking Rewards</h3>
              <div className="staking-apy">8.5% APY</div>
            </div>
            <div className="staking-metrics">
              <div className="staking-metric">
                <div className="metric-label">Monthly Rewards</div>
                <div className="metric-value">{userWallet.stakingRewards} tokens</div>
                <div className="metric-value-usd">${(userWallet.stakingRewards * mockTokenData.networkStats.tokenPrice).toFixed(2)}</div>
              </div>
              <div className="staking-metric">
                <div className="metric-label">Staked Amount</div>
                <div className="metric-value">20 tokens</div>
                <div className="metric-value-usd">${(20 * mockTokenData.networkStats.tokenPrice).toFixed(2)}</div>
              </div>
            </div>
            <button className="staking-button">Manage Staking</button>
          </div>
          
          <div className="wallet-card actions">
            <h3>Token Actions</h3>
            <div className="action-buttons">
              <button 
                className={`action-button ${tokenAction === 'redeem' ? 'active' : ''}`}
                onClick={() => handleTokenActionSelect('redeem')}
              >
                Redeem for Credits
              </button>
              <button 
                className={`action-button ${tokenAction === 'stake' ? 'active' : ''}`}
                onClick={() => handleTokenActionSelect('stake')}
              >
                Stake Tokens
              </button>
              <button 
                className={`action-button ${tokenAction === 'vote' ? 'active' : ''}`}
                onClick={() => handleTokenActionSelect('vote')}
              >
                Governance Vote
              </button>
            </div>
            
            {tokenAction && (
              <div className="token-action-form">
                <div className="form-header">
                  <h4>
                    {tokenAction === 'redeem' ? 'Redeem Tokens for Credits' : 
                     tokenAction === 'stake' ? 'Stake Tokens for Rewards' : 
                     'Use Tokens for Governance Vote'}
                  </h4>
                </div>
                
                <div className="form-content">
                  <div className="amount-selector">
                    <label>Token Amount</label>
                    <div className="amount-controls">
                      <button 
                        className="amount-button decrease"
                        onClick={() => handleTokenAmountChange(tokenAmount - 1)}
                        disabled={tokenAmount <= 1}
                      >
                        -
                      </button>
                      <input 
                        type="number" 
                        value={tokenAmount} 
                        onChange={(e) => handleTokenAmountChange(parseInt(e.target.value) || 1)}
                        min="1"
                        max={userWallet.balance}
                      />
                      <button 
                        className="amount-button increase"
                        onClick={() => handleTokenAmountChange(tokenAmount + 1)}
                        disabled={tokenAmount >= userWallet.balance}
                      >
                        +
                      </button>
                    </div>
                  </div>
                  
                  <div className="conversion-preview">
                    {tokenAction === 'redeem' && (
                      <div className="conversion-detail">
                        <span className="detail-label">Charging Credits:</span>
                        <span className="detail-value">{tokenAmount * 10} credits</span>
                      </div>
                    )}
                    {tokenAction === 'stake' && (
                      <div className="conversion-detail">
                        <span className="detail-label">Monthly Rewards:</span>
                        <span className="detail-value">{(tokenAmount * 0.085 / 12).toFixed(2)} tokens</span>
                      </div>
                    )}
                    {tokenAction === 'vote' && (
                      <div className="conversion-detail">
                        <span className="detail-label">Voting Power:</span>
                        <span className="detail-value">{tokenAmount} votes</span>
                      </div>
                    )}
                    <div className="conversion-detail">
                      <span className="detail-label">Token Value:</span>
                      <span className="detail-value">${(tokenAmount * mockTokenData.networkStats.tokenPrice).toFixed(2)}</span>
                    </div>
                  </div>
                  
                  <button 
                    className="confirm-action-button"
                    onClick={handleActionConfirm}
                  >
                    Confirm {tokenAction === 'redeem' ? 'Redemption' : tokenAction === 'stake' ? 'Staking' : 'Vote'}
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
        
        <div className="transaction-history">
          <h3>Transaction History</h3>
          <div className="history-tabs">
            <button 
              className={`history-tab ${!selectedAsset ? 'active' : ''}`}
              onClick={() => setSelectedAsset(null)}
            >
              All Transactions
            </button>
            <button 
              className={`history-tab ${selectedAsset === 'acquisition' ? 'active' : ''}`}
              onClick={() => handleAssetSelect('acquisition')}
            >
              Token Acquisition
            </button>
            <button 
              className={`history-tab ${selectedAsset === 'usage' ? 'active' : ''}`}
              onClick={() => handleAssetSelect('usage')}
            >
              Token Usage
            </button>
          </div>
          
          <div className="history-table">
            <div className="table-header">
              <div className="date-column">Date</div>
              <div className="type-column">Type</div>
              <div className="amount-column">Amount</div>
              <div className="status-column">Status</div>
            </div>
            
            {!selectedAsset && (
              <>
                {userWallet.acquisitionHistory.map((transaction, index) => (
                  <div key={`acq-${index}`} className="table-row acquisition">
                    <div className="date-column">{transaction.date}</div>
                    <div className="type-column">{transaction.source}</div>
                    <div className="amount-column">+{transaction.amount} tokens</div>
                    <div className="status-column">Completed</div>
                  </div>
                ))}
                {userWallet.transactionHistory.map((transaction, index) => (
                  <div key={`tx-${index}`} className="table-row usage">
                    <div className="date-column">{transaction.date}</div>
                    <div className="type-column">{transaction.type}</div>
                    <div className="amount-column">{transaction.amount > 0 ? `-${transaction.amount} tokens` : 'N/A'}</div>
                    <div className="status-column">{transaction.status}</div>
                  </div>
                ))}
              </>
            )}
            
            {selectedAsset === 'acquisition' && (
              <>
                {userWallet.acquisitionHistory.map((transaction, index) => (
                  <div key={index} className="table-row acquisition">
                    <div className="date-column">{transaction.date}</div>
                    <div className="type-column">{transaction.source}</div>
                    <div className="amount-column">+{transaction.amount} tokens</div>
                    <div className="status-column">Completed</div>
                  </div>
                ))}
              </>
            )}
            
            {selectedAsset === 'usage' && (
              <>
                {userWallet.transactionHistory.map((transaction, index) => (
                  <div key={index} className="table-row usage">
                    <div className="date-column">{transaction.date}</div>
                    <div className="type-column">{transaction.type}</div>
                    <div className="amount-column">{transaction.amount > 0 ? `-${transaction.amount} tokens` : 'N/A'}</div>
                    <div className="status-column">{transaction.status}</div>
                  </div>
                ))}
              </>
            )}
          </div>
        </div>
      </div>
    );
  };

  // Helper function to render the asset ownership tab
  const renderAssetOwnership = () => {
    const { assetOwnership } = mockTokenData;
    
    return (
      <div className="ownership-tab">
        <div className="ownership-overview">
          <div className="ownership-card summary">
            <h3>Your Network Ownership</h3>
            <div className="ownership-percentage">
              <div className="percentage-value">{(assetOwnership.totalOwnership * 100).toFixed(4)}%</div>
              <div className="percentage-label">of The Link Network</div>
            </div>
            <div className="ownership-details">
              <div className="detail-item">
                <div className="detail-label">Token Holdings</div>
                <div className="detail-value">{mockTokenData.userWallet.balance} tokens</div>
              </div>
              <div className="detail-item">
                <div className="detail-label">Network Value</div>
                <div className="detail-value">${(mockTokenData.networkStats.marketCap).toLocaleString()}</div>
              </div>
              <div className="detail-item">
                <div className="detail-label">Your Share Value</div>
                <div className="detail-value">
                  ${(mockTokenData.networkStats.marketCap * assetOwnership.totalOwnership).toFixed(2)}
                </div>
              </div>
            </div>
          </div>
          
          <div className="ownership-card projections">
            <h3>Projected Returns</h3>
            <div className="returns-chart">
              <div className="chart-bars">
                {assetOwnership.projectedReturns.map((quarter, index) => (
                  <div key={index} className="chart-bar-container">
                    <div className="bar-label">{`Q${quarter.quarter} ${quarter.year}`}</div>
                    <div className="bar-wrapper">
                      <div 
                        className="bar"
                        style={{ height: `${quarter.returns * 50}%` }}
                      ></div>
                    </div>
                    <div className="bar-value">${quarter.returns.toFixed(2)}</div>
                  </div>
                ))}
              </div>
            </div>
            <div className="returns-note">
              Projected returns based on current token holdings and network growth forecasts.
            </div>
          </div>
        </div>
        
        <div className="asset-holdings">
          <h3>Your Infrastructure Holdings</h3>
          <div className="holdings-grid">
            {assetOwnership.hubs.map((hub, index) => (
              <div key={index} className={`holding-card ${hub.status.toLowerCase()}`}>
                <div className="holding-header">
                  <h4>{hub.name}</h4>
                  <div className={`holding-status ${hub.status.toLowerCase()}`}>
                    {hub.status}
                  </div>
                </div>
                <div className="holding-details">
                  <div className="holding-item">
                    <div className="item-label">Ownership Stake</div>
                    <div className="item-value">{(hub.ownership * 100).toFixed(4)}%</div>
                  </div>
                  <div className="holding-item">
                    <div className="item-label">Monthly Revenue</div>
                    <div className="item-value">
                      {hub.monthlyRevenue > 0 ? `$${hub.monthlyRevenue.toFixed(2)}` : 'Pending'}
                    </div>
                  </div>
                  <div className="holding-item">
                    <div className="item-label">Token Allocation</div>
                    <div className="item-value">
                      {Math.round(mockTokenData.userWallet.balance * (hub.ownership / assetOwnership.totalOwnership))} tokens
                    </div>
                  </div>
                </div>
                <div className="holding-actions">
                  <button className="view-details-button">View Details</button>
                </div>
              </div>
            ))}
          </div>
        </div>
        
        <div className="network-growth">
          <h3>Network Growth Opportunities</h3>
          <div className="opportunities-grid">
            <div className="opportunity-card">
              <div className="opportunity-icon">🏙️</div>
              <h4>Urban Hub Expansion</h4>
              <p>New charging hubs planned for Chicago metro area in Q3 2025.</p>
              <div className="opportunity-metrics">
                <div className="metric">
                  <div className="metric-label">Projected ROI</div>
                  <div className="metric-value">12.5%</div>
                </div>
                <div className="metric">
                  <div className="metric-label">Min. Investment</div>
                  <div className="metric-value">50 tokens</div>
                </div>
              </div>
              <button className="opportunity-button">Express Interest</button>
            </div>
            
            <div className="opportunity-card">
              <div className="opportunity-icon">🛣️</div>
              <h4>I-55 Corridor</h4>
              <p>Strategic corridor deployment connecting Chicago to St. Louis.</p>
              <div className="opportunity-metrics">
                <div className="metric">
                  <div className="metric-label">Projected ROI</div>
                  <div className="metric-value">9.8%</div>
                </div>
                <div className="metric">
                  <div className="metric-label">Min. Investment</div>
                  <div className="metric-value">25 tokens</div>
                </div>
              </div>
              <button className="opportunity-button">Express Interest</button>
            </div>
            
            <div className="opportunity-card">
              <div className="opportunity-icon">🔋</div>
              <h4>Battery Storage Upgrade</h4>
              <p>Technology upgrade for existing hubs to increase capacity.</p>
              <div className="opportunity-metrics">
                <div className="metric">
                  <div className="metric-label">Projected ROI</div>
                  <div className="metric-value">7.2%</div>
                </div>
                <div className="metric">
                  <div className="metric-label">Min. Investment</div>
                  <div className="metric-value">10 tokens</div>
                </div>
              </div>
              <button className="opportunity-button">Express Interest</button>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Helper function to render the market data tab
  const renderMarketData = () => {
    const { marketData } = mockTokenData;
    
    return (
      <div className="market-tab">
        <div className="market-overview">
          <div className="market-card price">
            <h3>Token Price</h3>
            <div className="current-price">
              <div className="price-value">${mockTokenData.networkStats.tokenPrice.toFixed(2)}</div>
              <div className="price-change positive">+6.6% (30d)</div>
            </div>
            <div className="price-chart">
              <div className="chart-lines">
                {marketData.priceHistory.map((month, index) => (
                  <div key={index} className="chart-point" style={{ left: `${index * 33}%`, bottom: `${(month.price / 3) * 100}%` }}>
                    <div className="point-dot"></div>
                    {index > 0 && (
                      <div 
                        className="point-line" 
                        style={{ 
                          width: `33%`, 
                          transform: `rotate(${Math.atan2(
                            (month.price - marketData.priceHistory[index - 1].price) / 3, 
                            0.33
                          ) * (180 / Math.PI)}deg)`,
                          transformOrigin: 'left center'
                        }}
                      ></div>
                    )}
                  </div>
                ))}
              </div>
              <div className="chart-labels">
                {marketData.priceHistory.map((month, index) => (
                  <div key={index} className="chart-label" style={{ left: `${index * 33}%` }}>
                    {month.month}
                  </div>
                ))}
              </div>
            </div>
          </div>
          
          <div className="market-card volume">
            <h3>Trading Volume</h3>
            <div className="volume-chart">
              {marketData.volumeHistory.map((month, index) => (
                <div key={index} className="volume-bar-container">
                  <div className="bar-label">{month.month}</div>
                  <div className="bar-wrapper">
                    <div 
                      className="volume-bar"
                      style={{ height: `${(month.volume / 40000) * 100}%` }}
                    ></div>
                  </div>
                  <div className="bar-value">{month.volume.toLocaleString()}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
        
        <div className="price-projections">
          <h3>Price Projections</h3>
          <div className="projections-chart">
            <div className="chart-bars">
              {marketData.projections.map((quarter, index) => (
                <div key={index} className="projection-bar-container">
                  <div className="bar-label">{quarter.quarter}</div>
                  <div className="bar-wrapper">
                    <div 
                      className="projection-range"
                      style={{ 
                        height: `${(quarter.highEstimate / 6) * 100}%`,
                        bottom: `${(quarter.lowEstimate / 6) * 100}%`
                      }}
                    ></div>
                    <div 
                      className="projection-line"
                      style={{ 
                        bottom: `${((quarter.highEstimate + quarter.lowEstimate) / 2 / 6) * 100}%`
                      }}
                    ></div>
                  </div>
                  <div className="range-values">
                    <div className="high-value">${quarter.highEstimate.toFixed(2)}</div>
                    <div className="low-value">${quarter.lowEstimate.toFixed(2)}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="projections-note">
            Projections based on network growth, EV adoption rates, and infrastructure expansion plans.
            Actual results may vary.
          </div>
        </div>
        
        <div className="market-insights">
          <h3>Market Insights</h3>
          <div className="insights-grid">
            <div className="insight-card">
              <div className="insight-header">
                <div className="insight-icon">📈</div>
                <h4>Growth Drivers</h4>
              </div>
              <ul className="insight-list">
                <li>Illinois EV adoption projected to reach 7.8% by end of 2025</li>
                <li>State incentives for charging infrastructure increasing by 25%</li>
                <li>Phase 2 expansion adding 8 new charging hubs in Q3 2025</li>
                <li>Corporate fleet partnerships expected to drive token demand</li>
              </ul>
            </div>
            
            <div className="insight-card">
              <div className="insight-header">
                <div className="insight-icon">⚖️</div>
                <h4>Risk Factors</h4>
              </div>
              <ul className="insight-list">
                <li>Regulatory changes in tokenized asset classification</li>
                <li>Competition from other charging networks</li>
                <li>Supply chain constraints for charging equipment</li>
                <li>Potential delays in infrastructure deployment timeline</li>
              </ul>
            </div>
            
            <div className="insight-card">
              <div className="insight-header">
                <div className="insight-icon">🔮</div>
                <h4>Future Developments</h4>
              </div>
              <ul className="insight-list">
                <li>Token governance system launching in Q3 2025</li>
                <li>Secondary market for token trading in development</li>
                <li>Enhanced staking rewards program planned for Q4 2025</li>
                <li>Cross-network partnerships with other mobility tokens</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // Helper function to render the token flow visualization
  const renderTokenFlow = () => {
    return (
      <div className="token-flow-tab">
        <div className="flow-visualization">
          <h3>Token Flow Visualization</h3>
          <div className="flow-container">
            <div className={`flow-diagram ${animateTokenFlow ? 'animate' : ''}`}>
              <div className="flow-node subscribers">
                <div className="node-icon">👤</div>
                <div className="node-label">Subscribers</div>
                <div className="node-value">1,250 users</div>
              </div>
              
              <div className="flow-node network">
                <div className="node-icon">⬡</div>
                <div className="node-label">Token Network</div>
                <div className="node-value">1M tokens</div>
              </div>
              
              <div className="flow-node infrastructure">
                <div className="node-icon">🔌</div>
                <div className="node-label">Charging Hubs</div>
                <div className="node-value">36 locations</div>
              </div>
              
              <div className="flow-node revenue">
                <div className="node-icon">💰</div>
                <div className="node-label">Revenue Pool</div>
                <div className="node-value">$125K monthly</div>
              </div>
              
              <div className="flow-path subscription">
                <div className="path-label">Monthly Subscription</div>
                <div className="token-particle"></div>
                <div className="token-particle"></div>
                <div className="token-particle"></div>
              </div>
              
              <div className="flow-path redemption">
                <div className="path-label">Token Redemption</div>
                <div className="token-particle"></div>
                <div className="token-particle"></div>
              </div>
              
              <div className="flow-path investment">
                <div className="path-label">Infrastructure Investment</div>
                <div className="token-particle"></div>
                <div className="token-particle"></div>
                <div className="token-particle"></div>
              </div>
              
              <div className="flow-path returns">
                <div className="path-label">Revenue Distribution</div>
                <div className="token-particle"></div>
                <div className="token-particle"></div>
              </div>
            </div>
          </div>
          <div className="flow-controls">
            <button className="animate-flow-button" onClick={handleTokenFlowDemo}>
              Animate Token Flow
            </button>
          </div>
        </div>
        
        <div className="flow-explanation">
          <h3>How ChainLink Tokens Work</h3>
          <div className="explanation-steps">
            <div className="step">
              <div className="step-number">1</div>
              <div className="step-content">
                <h4>Token Distribution</h4>
                <p>
                  Unity Fleet subscribers earn ChainLink tokens monthly as part of their subscription.
                  These tokens represent fractional ownership in The Link charging infrastructure.
                </p>
              </div>
            </div>
            
            <div className="step">
              <div className="step-number">2</div>
              <div className="step-content">
                <h4>Token Utility</h4>
                <p>
                  Tokens can be redeemed for charging credits, applied to subscription discounts,
                  or held as an investment in the growing charging network.
                </p>
              </div>
            </div>
            
            <div className="step">
              <div className="step-number">3</div>
              <div className="step-content">
                <h4>Infrastructure Expansion</h4>
                <p>
                  Token value is backed by physical charging infrastructure. As the network grows,
                  token holders benefit from increased utility and potential value appreciation.
                </p>
              </div>
            </div>
            
            <div className="step">
              <div className="step-number">4</div>
              <div className="step-content">
                <h4>Revenue Sharing</h4>
                <p>
                  Charging revenue is distributed to token holders proportional to their ownership stake,
                  creating a sustainable economic model that aligns all stakeholders.
                </p>
              </div>
            </div>
          </div>
        </div>
        
        <div className="token-benefits">
          <h3>Benefits of Tokenization</h3>
          <div className="benefits-grid">
            <div className="benefit-card">
              <div className="benefit-icon">🔄</div>
              <h4>Circular Economy</h4>
              <p>
                Creates a closed-loop system where subscribers become stakeholders,
                aligning incentives across the ecosystem.
              </p>
            </div>
            
            <div className="benefit-card">
              <div className="benefit-icon">📊</div>
              <h4>Transparent Ownership</h4>
              <p>
                Blockchain-based tokens provide clear, verifiable ownership records
                and automated distribution of benefits.
              </p>
            </div>
            
            <div className="benefit-card">
              <div className="benefit-icon">🌱</div>
              <h4>Sustainable Funding</h4>
              <p>
                Tokenization creates a sustainable funding model for infrastructure
                development without relying solely on external investment.
              </p>
            </div>
            
            <div className="benefit-card">
              <div className="benefit-icon">🔐</div>
              <h4>Community Governance</h4>
              <p>
                Token holders can participate in network decisions, ensuring
                the system evolves to meet community needs.
              </p>
            </div>
          </div>
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="chainlink-demo loading">
        <div className="loading-logo">
          <img src="/images/unity_fleet_logo.png" alt="Unity Fleet" />
          <div className="loading-pulse"></div>
        </div>
        <p>Loading ChainLink Tokenization Demo...</p>
      </div>
    );
  }

  return (
    <div className="chainlink-demo">
      <header className="demo-header">
        <div className="demo-title">
          <h1>ChainLink Tokenization</h1>
          <span className="demo-subtitle">Unity Fleet Ownership Model</span>
        </div>
        
        <div className="token-stats">
          <div className="token-price">
            <span className="price-label">Token Price:</span>
            <span className="price-value">${mockTokenData.networkStats.tokenPrice.toFixed(2)}</span>
            <span className="price-change positive">+6.6%</span>
          </div>
          <div className="token-market-cap">
            <span className="cap-label">Market Cap:</span>
            <span className="cap-value">${mockTokenData.networkStats.marketCap.toLocaleString()}</span>
          </div>
        </div>
      </header>
      
      <div className="demo-navigation">
        <button 
          className={`nav-button ${activeTab === 'overview' ? 'active' : ''}`}
          onClick={() => setActiveTab('overview')}
        >
          Network Overview
        </button>
        <button 
          className={`nav-button ${activeTab === 'wallet' ? 'active' : ''}`}
          onClick={() => setActiveTab('wallet')}
        >
          Token Wallet
        </button>
        <button 
          className={`nav-button ${activeTab === 'ownership' ? 'active' : ''}`}
          onClick={() => setActiveTab('ownership')}
        >
          Asset Ownership
        </button>
        <button 
          className={`nav-button ${activeTab === 'market' ? 'active' : ''}`}
          onClick={() => setActiveTab('market')}
        >
          Market Data
        </button>
        <button 
          className={`nav-button ${activeTab === 'flow' ? 'active' : ''}`}
          onClick={() => setActiveTab('flow')}
        >
          Token Flow
        </button>
      </div>
      
      <main className="demo-content">
        {activeTab === 'overview' && renderOverview()}
        {activeTab === 'wallet' && renderWallet()}
        {activeTab === 'ownership' && renderAssetOwnership()}
        {activeTab === 'market' && renderMarketData()}
        {activeTab === 'flow' && renderTokenFlow()}
      </main>
      
      {showConfirmation && (
        <div className="token-confirmation-modal">
          <div className="modal-content">
            <h3>Confirm Token Action</h3>
            
            <div className="confirmation-details">
              <div className="confirmation-item">
                <span className="item-label">Action:</span>
                <span className="item-value">
                  {tokenAction === 'redeem' ? 'Redeem Tokens for Credits' : 
                   tokenAction === 'stake' ? 'Stake Tokens for Rewards' : 
                   'Use Tokens for Governance Vote'}
                </span>
              </div>
              <div className="confirmation-item">
                <span className="item-label">Amount:</span>
                <span className="item-value">{tokenAmount} tokens</span>
              </div>
              <div className="confirmation-item">
                <span className="item-label">Value:</span>
                <span className="item-value">${(tokenAmount * mockTokenData.networkStats.tokenPrice).toFixed(2)}</span>
              </div>
              {tokenAction === 'redeem' && (
                <div className="confirmation-item">
                  <span className="item-label">Credits:</span>
                  <span className="item-value">{tokenAmount * 10} charging credits</span>
                </div>
              )}
              {tokenAction === 'stake' && (
                <div className="confirmation-item">
                  <span className="item-label">Monthly Reward:</span>
                  <span className="item-value">{(tokenAmount * 0.085 / 12).toFixed(2)} tokens</span>
                </div>
              )}
            </div>
            
            <div className="confirmation-actions">
              <button className="cancel-button" onClick={() => setShowConfirmation(false)}>Cancel</button>
              <button className="confirm-button">Confirm</button>
            </div>
          </div>
        </div>
      )}
      
      <footer className="demo-footer">
        <div className="footer-info">
          <span>ChainLink Tokenization Demo</span>
          <span>Powered by Atlas Intelligence</span>
        </div>
        <div className="footer-links">
          <a href="#" className="footer-link">Token Whitepaper</a>
          <a href="#" className="footer-link">Legal Disclosure</a>
          <a href="#" className="footer-link">FAQ</a>
        </div>
      </footer>
    </div>
  );
}

export default ChainlinkDemo;
