1import React, { useState } from 'react';
2
3const MIN_VALUE = -50;
4const MAX_VALUE = 100;
5
6export default function StepCounter() {
7 const [count, setCount] = useState(0);
8 const [step, setStep] = useState(1);
9 const [history, setHistory] = useState([]);
10
11 // Helper to log actions
12 const logAction = (action, prevVal, nextVal) => {
13 const entry = {
14 id: Date.now(),
15 time: new Date().toLocaleTimeString(),
16 description: `${action} (from ${prevVal} to ${nextVal})`
17 };
18 setHistory((prev) => [entry, ...prev.slice(0, 9)]); // Keep last 10 entries
19 };
20
21 // Handlers
22 const handleIncrement = () => {
23 setCount((prev) => {
24 const next = Math.min(prev + step, MAX_VALUE);
25 logAction(`Incremented by ${step}`, prev, next);
26 return next;
27 });
28 };
29
30 const handleDecrement = () => {
31 setCount((prev) => {
32 const next = Math.max(prev - step, MIN_VALUE);
33 logAction(`Decremented by ${step}`, prev, next);
34 return next;
35 });
36 };
37
38 const handleReset = () => {
39 logAction('Reset to zero', count, 0);
40 setCount(0);
41 };
42
43 const handleStepChange = (e) => {
44 const parsed = parseInt(e.target.value, 10);
45 setStep(isNaN(parsed) || parsed < 1 ? 1 : parsed);
46 };
47
48 const isAtMin = count <= MIN_VALUE;
49 const isAtMax = count >= MAX_VALUE;
50
51 return (
52 <div className="counter-container">
53 <h2>Interactive Step Counter</h2>
54
55 {/* Main Display */}
56 <div className={`count-badge ${count > 0 ? 'positive' : count < 0 ? 'negative' : 'neutral'}`}>
57 <span className="count-number">{count}</span>
58 </div>
59
60 {/* Limit Warnings */}
61 {isAtMax && <p className="warning-text">Reached maximum limit of {MAX_VALUE}!</p>}
62 {isAtMin && <p className="warning-text">Reached minimum limit of {MIN_VALUE}!</p>}
63
64 {/* Controls */}
65 <div className="controls-box">
66 <label>
67 Step Size:
68 <input
69 type="number"
70 min="1"
71 max="25"
72 value={step}
73 onChange={handleStepChange}
74 className="step-input"
75 />
76 </label>
77
78 <div className="button-row">
79 <button onClick={handleDecrement} disabled={isAtMin} className="btn btn-secondary">
80 - {step}
81 </button>
82 <button onClick={handleReset} className="btn btn-outline">
83 Reset
84 </button>
85 <button onClick={handleIncrement} disabled={isAtMax} className="btn btn-primary">
86 + {step}
87 </button>
88 </div>
89 </div>
90
91 {/* Audit History Log */}
92 {history.length > 0 && (
93 <div className="history-section">
94 <h4>Recent Activity</h4>
95 <ul className="history-list">
96 {history.map((item) => (
97 <li key={item.id}>
98 <span className="timestamp">[{item.time}]</span> {item.description}
99 </li>
100 ))}
101 </ul>
102 </div>
103 )}
104 </div>
105 );
106}