// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.onboarding

import android.graphics.Typeface
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.databinding.ActivityOnboardingBinding
import xyz.apiote.bimba.czwek.settings.ServerChooserActivity

class OnboardingActivity : AppCompatActivity() {
	private var _binding: ActivityOnboardingBinding? = null
	private val binding get() = _binding!!

	private val activityLauncher =
		registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
			if (!FirstRunActivity.getFirstRun(this)) {
				finish()
			}
		}

	override fun onCreate(savedInstanceState: Bundle?) {
		enableEdgeToEdge()
		super.onCreate(savedInstanceState)
		_binding = ActivityOnboardingBinding.inflate(layoutInflater)
		setContentView(binding.root)

		ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, windowInsets ->
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			v.updatePadding(right = insets.right, left = insets.left, bottom = insets.bottom)
			windowInsets
		}

		prepareButton(
			binding.buttonSimple,
			getString(R.string.onboarding_simple),
			getString(R.string.onboarding_simple_action),
			true
		)
		prepareButton(
			binding.buttonAdvanced,
			getString(R.string.onboarding_advanced),
			getString(R.string.onboarding_advanced_action),
			false
		)
	}

	private fun prepareButton(button: Button, title: String, description: String, simple: Boolean) {
		button.text = SpannableStringBuilder().apply {
			append(
				title,
				StyleSpan(Typeface.BOLD),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
			)
			append("\n")
			append(
				description,
				RelativeSizeSpan(.75f),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
			)
		}
		button.setOnClickListener {
			moveOn(simple)
		}
	}

	private fun moveOn(simple: Boolean) {
		activityLauncher.launch(ServerChooserActivity.getIntent(this, simple))
	}
}