<template>
	<cdx-dialog
		v-model:open="wrappedOpen"
		class="mw-oathauth-passkeydialog"
		:title="$i18n( 'oathauth-passkey-dialog-title' )"
		:primary-action="primaryAction"
		:default-action="defaultAction"
		@primary="createPasskey"
		@default="close"
	>
		<template #header>
			<div class="mw-oathauth-passkeydialog__image"></div>
			<h2 class="cdx-dialog__header__title">
				{{ $i18n( 'oathauth-passkey-dialog-title' ) }}
			</h2>
		</template>

		<!-- v-html is safe because this data is generated by the server-side wikitext parser -->
		<!-- eslint-disable-next-line vue/no-v-html -->
		<div v-html="passkeyDialogTextHtml"></div>

		<template v-if="errorMessage" #footer-text>
			<cdx-message type="error">
				{{ errorMessage }}
			</cdx-message>
		</template>
	</cdx-dialog>
</template>

<script>
const { defineComponent, ref, toRef } = require( 'vue' );
const { CdxDialog, CdxMessage, useModelWrapper } = require( './codex.js' );
const { passkeyDialogTextHtml } = require( './data.json' );

module.exports = exports = defineComponent( {
	components: {
		CdxDialog,
		CdxMessage
	},
	props: {
		open: {
			type: Boolean,
			default: false
		}
	},
	setup( props, { emit } ) {
		const wrappedOpen = useModelWrapper( toRef( () => props.open ), emit, 'update:open' );
		const errorMessage = ref( '' );
		const primaryAction = {
			label: mw.msg( 'oathauth-passkey-dialog-add' ),
			actionType: 'progressive'
		};
		const defaultAction = {
			label: mw.msg( 'oathauth-passkey-dialog-back' )
		};

		function createPasskey() {
			const registrator = new mw.ext.webauthn.Registrator( '', null, true );
			return registrator.register()
				.then( ( credential ) => new mw.Api().postWithToken( 'csrf', {
					action: 'webauthn',
					func: 'register',
					credential: JSON.stringify( credential ),
					passkeyMode: true
				} ) ).then(
					() => {
						window.location.reload();
					},
					( error ) => {
						if ( error === 'webauthn-reauthenticate' ) {
							// The user's authentication has expired, and they need to
							// reauthenticate. Reload the page, which will automatically redirect
							// the user to the reauthentication flow.
							window.location.reload();
						}
						errorMessage.value = mw.message( error ).exists() ?
							mw.message( error ).text() :
							error;
					}
				);
		}

		function close() {
			wrappedOpen.value = false;
			errorMessage.value = '';
		}

		return {
			wrappedOpen,
			primaryAction,
			defaultAction,
			createPasskey,
			close,
			passkeyDialogTextHtml,
			errorMessage
		};
	}
} );
</script>

<style lang="less">
@import 'mediawiki.skin.variables';

.mw-oathauth-passkeydialog {
	&__image {
		width: @size-800;
		height: @size-800;
		margin-left: auto;
		margin-right: auto;
		background: url( passkey.svg ) no-repeat center;
	}
}
</style>
