// Page Creation - Auto-generate slugs from titles

const DIACRITICS_REGEX = new RegExp('[\\u0300-\\u036f]', 'g');

function slugify(text: string): string {
    return text
        .toLowerCase()
        .normalize('NFD')
        .replace(DIACRITICS_REGEX, '')
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '');
}

const titleInput = document.getElementById('title') as HTMLInputElement | null;
const slugInput = document.getElementById('slug') as HTMLInputElement | null;
const titleEnInput = document.getElementById('titleEn') as HTMLInputElement | null;
const slugEnInput = document.getElementById('slugEn') as HTMLInputElement | null;

// A slug field stops auto-following its title once the user types directly
// into it — tracked separately from `.value` since that's non-empty as soon
// as it's been auto-generated once.
let slugTouched = false;
let slugEnTouched = false;

if (slugInput) {
    slugInput.addEventListener('input', () => {
        slugTouched = true;
    });
}

if (slugEnInput) {
    slugEnInput.addEventListener('input', () => {
        slugEnTouched = true;
    });
}

if (titleInput && slugInput) {
    titleInput.addEventListener('input', (e: Event): void => {
        const target = e.target as HTMLInputElement;
        const slug = slugify(target.value);

        if (!slugTouched) {
            slugInput.value = slug;
        }
        if (!slugEnTouched && titleEnInput && !titleEnInput.value && slugEnInput) {
            slugEnInput.value = slug;
        }
    });
}

if (titleEnInput && slugEnInput) {
    titleEnInput.addEventListener('input', (e: Event): void => {
        const target = e.target as HTMLInputElement;
        if (!slugEnTouched) {
            slugEnInput.value = slugify(target.value);
        }
    });
}
