"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeInput = void 0;
const jsx_runtime_1 = require("@emotion/react/jsx-runtime");
/*
 * Wire
 * Copyright (C) 2018 Wire Swiss GmbH
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 *
 */
const react_1 = require("react");
const React = __importStar(require("react"));
const Input_1 = require("./Input");
const Identity_1 = require("../Identity");
const util_1 = require("../util");
const CodeInputWrapper = (props) => ((0, jsx_runtime_1.jsx)("div", Object.assign({ css: {
        display: 'flex',
        justifyContent: 'center',
    } }, props)));
const digitInputStyle = (theme, props) => (Object.assign(Object.assign({}, (0, Input_1.inputStyle)(theme, props)), { '& + &': {
        marginLeft: 'min(19px, 2vw)',
    }, '&:hover': {
        boxShadow: `0 0 0 1px ${Identity_1.COLOR_V2.GRAY_60}`,
    }, fontSize: theme.fontSizes.extraLarge, lineHeight: '1.75rem', borderRadius: '12px', padding: 0, textAlign: 'center', width: 'min(48px, 13vw)', height: '56px' }));
const DigitInput = React.forwardRef((props, ref) => (0, jsx_runtime_1.jsx)("input", Object.assign({ ref: ref, css: (theme) => digitInputStyle(theme, props) }, props, { type: "tel" })));
DigitInput.displayName = 'DigitInput';
const CodeInput = ({ style, digits = 6, autoFocus = false, markInvalid, onCodeComplete = util_1.noop, disabled, }) => {
    const [values, setValues] = (0, react_1.useState)(Array(digits).fill(''));
    const inputs = Array(digits);
    const forceSelection = (event) => {
        const target = event.target;
        target.select();
    };
    const forceSelectionPreventDefault = (event) => {
        forceSelection(event);
        event.preventDefault();
    };
    const nextField = (currentFieldIndex) => {
        const nextFieldIndex = currentFieldIndex + 1;
        if (nextFieldIndex < digits) {
            inputs[nextFieldIndex].focus();
        }
    };
    const previousField = (currentFieldIndex) => {
        if (currentFieldIndex > 0) {
            inputs[currentFieldIndex - 1].focus();
        }
    };
    const setValue = (fieldIndex, value) => {
        if (/^[0-9]?$/.test(value)) {
            const valuesCopy = values.slice();
            valuesCopy[fieldIndex] = value;
            setValues(valuesCopy);
            if (value.length) {
                nextField(fieldIndex);
            }
        }
    };
    const handleKeyDown = (fieldIndex, { key }) => {
        switch (key) {
            case 'Backspace':
                setValue(fieldIndex, '');
                previousField(fieldIndex);
                break;
            case 'ArrowLeft':
                previousField(fieldIndex);
                break;
            case 'ArrowRight':
                nextField(fieldIndex);
                break;
        }
        if (/^[0-9]$/.test(key)) {
            setValue(fieldIndex, key);
        }
    };
    const handlePaste = (fieldIndex, event) => {
        const pastedValue = event.clipboardData.getData('Text');
        const cleanedPaste = pastedValue.replace(/[^0-9]/g, '');
        if (/^[0-9]+$/.test(cleanedPaste)) {
            setValues(values.slice(0, fieldIndex).concat(cleanedPaste.split('')).slice(0, digits));
        }
    };
    (0, react_1.useEffect)(() => {
        const completeCode = values.join('');
        if (completeCode.length === digits) {
            onCodeComplete(completeCode);
        }
    }, [values]);
    return ((0, jsx_runtime_1.jsx)(CodeInputWrapper, Object.assign({ style: style }, { children: Array.from({ length: digits }, (_, index) => ((0, jsx_runtime_1.jsx)(DigitInput
        // eslint-disable-next-line jsx-a11y/no-autofocus
        , { 
            // eslint-disable-next-line jsx-a11y/no-autofocus
            autoFocus: index === 0 && autoFocus, onPaste: event => handlePaste(index, event), onFocus: forceSelection, onMouseDown: forceSelectionPreventDefault, onTouchStart: forceSelectionPreventDefault, onKeyDown: event => handleKeyDown(index, event), onKeyUp: forceSelection, markInvalid: markInvalid, ref: node => (inputs[index] = node), value: values[index], onChange: () => { }, disabled: disabled }, index))) })));
};
exports.CodeInput = CodeInput;
