/* eslint-disable no-console */
import { useState } from 'react'
import { UserStore } from '../../../../shared-state'
import { chatWithUs } from '../assets'
import { Box, styled } from '@mui/material'

export default function FreshChatButton() {
  const _window = window as any
  const { user } = UserStore.useState()

  var openWidget = function () {
    const el = document.getElementById('fc_frame')
    if (el) {
      el.style.visibility = 'visible'
    }
    _window.fcWidget.open()
    initEvents()
  }
  var initEvents = function () {
    const el = document.getElementById('custom_fc_button')
    _window.fcWidget.on('widget:opened', function (resp) {
      if (el) {
        el.style.visibility = 'hidden'
      }
    })
    _window.fcWidget.on('widget:closed', function (resp) {
      if (el) {
        el.style.visibility = 'visible'
      }
    })
  }

  if (!user) return null
  return (
    <Box
      id="custom_fc_button"
      sx={{
        position: 'fixed',
        right: 0,
        bottom: '18px',
        cursor: 'pointer',
        '@media print': {
          display: 'none',
        },
      }}
    >
      <a id="open_fc_widget" onClick={openWidget} style={{ cursor: 'pointer' }}>
        <StyledImg src={chatWithUs} />
      </a>
    </Box>
  )
}

const StyledImg = styled('img')(({ theme }) => ({
  width: '35px',
  height: 'auto',
  '&:hover': {
    width: '50px',
  },
  transition: 'width 0.3s',
}))
