package com.example.shiftalarm

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.activity.enableEdgeToEdge
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.shiftalarm.databinding.ActivityManualBinding

class ManualActivity : AppCompatActivity() {
    private lateinit var binding: ActivityManualBinding

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

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

        setupManual()
        
        binding.btnCloseManual.setOnClickListener {
            finish()
        }
    }

    private fun setupManual() {
        try {
            val versionName = try {
                packageManager.getPackageInfo(packageName, 0).versionName
            } catch (e: Exception) { "0.7.1" }
            
            binding.manualVersionText.text = "교대링(Shiftring) v$versionName"

            val rawContent = assets.open("MANUAL.md").bufferedReader().use { it.readText() }
            
            // Premium Styling logic
            val styledContent = rawContent
                .replace(Regex("^# (.*)", RegexOption.MULTILINE), "<br><big><big><b>$1</b></big></big><br>")
                .replace(Regex("^## (.*)", RegexOption.MULTILINE), "<br><br><font color='#00897B'><b>$1</b></font><br>")
                .replace(Regex("^### (.*)", RegexOption.MULTILINE), "<br><br><b>$1</b><br>")
                .replace(Regex("^- (.*)", RegexOption.MULTILINE), " • $1")
                .replace("\n", "<br>")
            
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                binding.manualContent.text = android.text.Html.fromHtml(styledContent, android.text.Html.FROM_HTML_MODE_LEGACY)
            } else {
                @Suppress("DEPRECATION")
                binding.manualContent.text = android.text.Html.fromHtml(styledContent)
            }
        } catch (e: Exception) {
            binding.manualContent.text = "설명서를 불러오지 못했습니다."
        }
    }
}
