import { useEffect, useRef, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';

export const copyToClipboard = async ( text ) => {
	try {
		await window.navigator.clipboard.writeText( text );
		return true;
	} catch ( error ) {
		// Clipboard API needs a secure context; fall back to the legacy textarea approach.
		const element = document.createElement( 'textarea' );
		element.value = text;
		document.body.appendChild( element );
		element.select();
		const copied = document.execCommand( 'copy' );
		document.body.removeChild( element );
		return copied;
	}
};

/**
 * Legacy `.ssgs-clipboard`: a read-only field plus a Copy button with a status tooltip.
 *
 * @param {Object}   props
 * @param {string}   props.id          Input ID.
 * @param {string}   props.value       Displayed value.
 * @param {string}   props.label       Accessible label for the field.
 * @param {string}   props.buttonLabel Button text.
 * @param {string}   props.copiedText  Tooltip text after copying.
 * @param {string}   props.className   Extra wrapper class ('medium' in step 4).
 * @param {Function} props.onCopy      Performs the copy; resolves to true on success.
 */
const CopyField = ( { id, value, label, buttonLabel, copiedText, className = '', onCopy } ) => {
	const [ copied, setCopied ] = useState( false );
	const timer = useRef( null );

	useEffect( () => () => clearTimeout( timer.current ), [] );

	const handleCopy = async ( event ) => {
		event.preventDefault();
		if ( await onCopy() ) {
			setCopied( true );
			clearTimeout( timer.current );
			timer.current = setTimeout( () => setCopied( false ), 3000 );
		}
	};

	return (
		<div className={ `ssgs-clipboard ${ className }`.trim() }>
			<input type="text" readOnly value={ value } className="ssgs-input" id={ id } aria-label={ label } onClick={ handleCopy } />
			<span className="ssgs-tooltip text">
				<button type="button" className="ssgs-btn" onClick={ handleCopy } onMouseOver={ () => setCopied( false ) } onFocus={ () => setCopied( false ) }>
					{ buttonLabel }
				</button>
				<span className="text" role="status">
					{ copied ? copiedText : __( 'Copy to clipboard', TEXT_DOMAIN ) }
				</span>
			</span>
		</div>
	);
};

export default CopyField;
