export default () => (
  <section>
    <h1>SSE Demo</h1>

    <div id="status">Connecting...</div>
    <div id="time" style="font-size: 2em; font-family: monospace;"></div>
    <div id="count">Events received: 0</div>

    <p style="margin-top: 2em;">
      <a href="/">Back to Home</a>
    </p>

    <script dangerouslySetInnerHTML={{
      __html: `
      const statusEl = document.getElementById('status')
      const timeEl = document.getElementById('time')
      const countEl = document.getElementById('count')
      let count = 0

      const events = new EventSource('/api/time')

      events.onopen = () => {
        statusEl.textContent = 'Connected'
        statusEl.style.color = 'green'
      }

      events.onmessage = (e) => {
        const data = JSON.parse(e.data)
        timeEl.textContent = new Date(data.time).toLocaleTimeString()
        count++
        countEl.textContent = 'Events received: ' + count
      }

      events.onerror = () => {
        statusEl.textContent = 'Disconnected'
        statusEl.style.color = 'red'
      }
    `}} />
  </section>
)
