import { useState } from 'react'

/**
 * Check localStorage to determine if this device has been seen before.
 * Returns "original" if this is the same device that submitted the vote,
 * the stored OTP if this device was used for a previous check, or null if it's a new device. And stores the new OTP for future checks.
 */
export function getAlreadySeenDevice(election_id: string, auth_token: string, otp: string): null | string {
  if (typeof window === 'undefined') return null

  // Check if this is the original voting device
  if (localStorage.getItem(`voter-${election_id}-${auth_token}`)) return 'original'

  // Check if this device was used for a previous malware check
  const malwareCheckKey = `malware-check-${election_id}-${auth_token}`
  const storedOtp = localStorage.getItem(malwareCheckKey)
  if (storedOtp) return storedOtp

  // New device - store current OTP for future checks
  localStorage.setItem(malwareCheckKey, otp)
  return null
}

export function SameDeviceWarning({ alreadySeenDevice }: { alreadySeenDevice: null | string }) {
  const [dismissed, setDismissed] = useState(false)

  if (!alreadySeenDevice || dismissed) return null

  return (
    <div className="p-4 mb-6 text-yellow-800 bg-yellow-50 rounded-lg border-2 border-yellow-400">
      <div className="flex justify-between items-start mb-2 text-lg">
        <h3 className="font-semibold">⚠️ Same Device Warning</h3>
        <button className="text-yellow-600 hover:text-yellow-800" onClick={() => setDismissed(true)} type="button">
          ×
        </button>
      </div>

      {alreadySeenDevice === 'original' ? (
        <p>You&apos;re using the same device & browser used to submit your vote.</p>
      ) : (
        <p>
          This device was already used for a previous malware check.
          <span className="block text-xs opacity-70">ID: {alreadySeenDevice}</span>
        </p>
      )}

      <p className="mt-3 text-sm">For cross-device security verification, consider using a separate device.</p>
    </div>
  )
}
