import { useState } from 'react'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Link from '@mui/material/Link'
import Typography from '@mui/material/Typography'
import { Link as RouterLink } from 'react-router-dom'

const STORAGE_KEY = 'cookie-consent-accepted'

function wasAccepted(): boolean {
  try {
    return localStorage.getItem(STORAGE_KEY) === '1'
  } catch {
    return false
  }
}

function markAccepted() {
  try {
    localStorage.setItem(STORAGE_KEY, '1')
  } catch {
    // ignore
  }
}

export function CookieConsentBanner() {
  const [visible, setVisible] = useState(!wasAccepted())

  if (!visible) return null

  return (
    <Box
      sx={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        zIndex: 1300,
        bgcolor: 'background.paper',
        borderTop: 1,
        borderColor: 'divider',
        px: 2,
        py: 1.5,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 2,
        flexWrap: 'wrap',
        boxShadow: 3,
      }}
    >
      <Typography variant="body2" color="text.secondary">
        Мы используем cookie для поддержания сессии. Продолжая использовать сайт, вы принимаете{' '}
        <Link component={RouterLink} to="/privacy" underline="hover">
          Политику обработки персональных данных
        </Link>
        .
      </Typography>
      <Button
        variant="contained"
        size="small"
        onClick={() => {
          markAccepted()
          setVisible(false)
        }}
      >
        Понятно
      </Button>
    </Box>
  )
}
