'use client';
import { useState } from 'react';
import { formatPrice } from '@/lib/money';
interface DiscountPanelProps {
/** Unit price in cents of the selected item. */
unitPriceCents: number;
/** Called when a discount is applied. */
onApply: (discountCents: number) => void;
onClose: () => void;
}
export default function DiscountPanel({ unitPriceCents, onApply, onClose }: DiscountPanelProps) {
const [mode, setMode] = useState<'percent' | 'fixed'>('percent');
const [value, setValue] = useState('');
const [error, setError] = useState('');
const numericValue = Number(value.replace(',', '.'));
const discountCents = Number.isFinite(numericValue)
? mode === 'percent'
? Math.round((numericValue / 100) * unitPriceCents)
: Math.round(numericValue * 100)
: 0;
const handleApply = () => {
if (!value || numericValue <= 0) return;
if (discountCents > unitPriceCents) { setError('Descuento mayor al precio'); return; }
onApply(discountCents);
onClose();
};
return (
Aplicar descuento
{ setValue(e.target.value); setError(''); }}
placeholder={mode === 'percent' ? 'Porcentaje (%)' : 'Cantidad (€), ej. 3,50'}
className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl text-lg focus:border-[#2D6A4F] outline-none"
aria-label={mode === 'percent' ? 'Porcentaje de descuento' : 'Descuento en euros'}
autoFocus
/>
{error &&
{error}
}
Precio original{formatPrice(unitPriceCents)}
Descuento-{formatPrice(discountCents)}
Precio final{formatPrice(unitPriceCents - discountCents)}
);
}