'use client'

import { useState, useEffect } from 'react'
import { Heart } from 'lucide-react'

interface Props {
  listingId: string
  saveLabel: string
  savedLabel: string
}

export default function SaveButton({ listingId, saveLabel, savedLabel }: Props) {
  const [isSaved, setIsSaved] = useState(false)

  useEffect(() => {
    try {
      const stored = localStorage.getItem('savedListingIds')
      if (stored) {
        const ids = JSON.parse(stored) as string[]
        setIsSaved(ids.includes(listingId))
      }
    } catch (e) {
      console.error('Error reading localStorage:', e)
    }
  }, [listingId])

  const toggleSave = () => {
    try {
      const stored = localStorage.getItem('savedListingIds')
      let ids: string[] = stored ? JSON.parse(stored) : []
      if (ids.includes(listingId)) {
        ids = ids.filter(id => id !== listingId)
        setIsSaved(false)
      } else {
        ids.push(listingId)
        setIsSaved(true)
      }
      localStorage.setItem('savedListingIds', JSON.stringify(ids))
      window.dispatchEvent(new Event('favorites-updated'))
    } catch (err) {
      console.error('Error writing localStorage:', err)
    }
  }

  return (
    <button
      onClick={toggleSave}
      className={`flex items-center justify-center gap-2 border font-bold text-xs py-3.5 px-4 rounded-xl transition ${
        isSaved 
          ? 'bg-bougainvillea/5 border-bougainvillea/20 text-bougainvillea' 
          : 'bg-paper border-pine/15 hover:bg-stone text-pine'
      }`}
    >
      <Heart className={`w-4 h-4 ${isSaved ? 'fill-bougainvillea text-bougainvillea' : 'text-pine/70'}`} />
      {isSaved ? savedLabel : saveLabel}
    </button>
  )
}
