← back to Boomer Calculator

components/ScientificCalculator.tsx

94 lines

'use client'

import { useState } from 'react'

export default function ScientificCalculator() {
  const [display, setDisplay] = useState('0')
  const [showResult, setShowResult] = useState(false)
  const [celebrating, setCelebrating] = useState(false)

  const buttons = [
    ['C', '(', ')', '/'],
    ['7', '8', '9', '*'],
    ['4', '5', '6', '-'],
    ['1', '2', '3', '+'],
    ['0', '.', 'sin', '='],
  ]

  const handleClick = (value: string) => {
    if (value === 'C') {
      setDisplay('0')
      setShowResult(false)
      setCelebrating(false)
    } else if (value === '=') {
      setDisplay('Calculating...')
      setTimeout(() => {
        setDisplay('67')
        setShowResult(true)
        setCelebrating(true)
        setTimeout(() => setCelebrating(false), 2000)
      }, 500)
    } else {
      if (display === '0' || showResult) {
        setDisplay(value)
        setShowResult(false)
      } else {
        setDisplay(display + value)
      }
    }
  }

  return (
    <div className="bg-white rounded-xl shadow-2xl p-3 sm:p-4 max-w-2xl mx-auto">
      <div className="mb-3 sm:mb-4">
        <div className="bg-gray-900 text-white p-4 sm:p-5 rounded-lg">
          <div
            className={`text-3xl sm:text-4xl md:text-5xl font-bold font-mono transition-all px-2 text-center break-words ${
              celebrating ? 'rainbow-animation scale-110' : ''
            }`}
          >
            {display}
          </div>
        </div>
        {showResult && (
          <div className="mt-2 text-center text-green-600 font-bold animate-pulse text-base sm:text-lg">
            ✨ Perfect! ✨
          </div>
        )}
      </div>

      <div className="grid grid-cols-4 gap-2 sm:gap-3">
        {buttons.flat().map((btn, idx) => (
          <button
            key={idx}
            onClick={(e) => {
              e.preventDefault();
              handleClick(btn);
            }}
            onTouchEnd={(e) => {
              e.preventDefault();
              handleClick(btn);
            }}
            className={`p-4 sm:p-5 md:p-6 rounded-lg font-bold text-xl sm:text-2xl md:text-3xl select-none cursor-pointer shadow-lg ${
              btn === '='
                ? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white col-span-1'
                : btn === 'C'
                ? 'bg-red-500 text-white'
                : ['+', '-', '*', '/'].includes(btn)
                ? 'bg-blue-500 text-white'
                : 'bg-gray-200'
            }`}
            style={{ WebkitTapHighlightColor: 'transparent' }}
          >
            {btn}
          </button>
        ))}
      </div>

      <div className="mt-3 text-center text-sm sm:text-base text-gray-600 font-semibold">
        <p>Easy Calculator</p>
      </div>
    </div>
  )
}