← back to Boomer Calculator

components/ScientificCalculator.tsx

84 lines

'use client'

import { useState } from 'react'
import { evaluateExpression } from '@/lib/calculations'

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

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

  const handleClick = (value: string) => {
    setError('')
    if (value === 'C') {
      setDisplay('0')
      setShowResult(false)
    } else if (value === '=') {
      try {
        setDisplay(String(Number(evaluateExpression(display).toPrecision(12))))
        setShowResult(true)
      } catch (err) {
        setError((err as Error).message)
      }
    } else {
      const token = value === 'sin' ? 'sin(' : value
      const continueResult = ['+', '-', '*', '/'].includes(value)
      setDisplay((display === '0' || showResult) && !continueResult ? token : display + token)
      setShowResult(false)
    }
  }

  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
            role="status"
            aria-label="Calculator display"
            className="text-3xl sm:text-4xl md:text-5xl font-bold font-mono px-2 text-center break-words"
          >
            {display}
          </div>
        </div>
        {error && <p role="alert" className="mt-2 text-center text-red-700">{error}</p>}
      </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);
            }}
            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>Arithmetic and sine · sin uses degrees</p>
      </div>
    </div>
  )
}