package com.example.mystictale.resources.components.dateComponents

import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation

fun dateOfBirthVisualTransformation() = VisualTransformation { text ->
    val trimmed = if (text.text.length >= 8) text.text.substring(0..7) else text.text
    val formatted = buildString {
        for (i in trimmed.indices) {
            if (i == 2 || i == 4) append('.')
            append(trimmed[i])
        }
    }
    TransformedText(
        text = AnnotatedString(formatted),
        offsetMapping = object : OffsetMapping {
            override fun originalToTransformed(offset: Int): Int {
                return when {
                    offset <= 2 -> offset
                    offset <= 4 -> offset + 1
                    offset <= 8 -> offset + 2
                    else -> 10
                }
            }

            override fun transformedToOriginal(offset: Int): Int {
                return when {
                    offset <= 2 -> offset
                    offset <= 5 -> offset - 1
                    offset <= 10 -> offset - 2
                    else -> 8
                }
            }
        }
    )
}