// Copyright © 2026 Cold Bore Ballistics LLC. Proprietary and Confidential. All rights reserved.
package com.coldboreballisticsllc.scopedope.ui.screens.splash

import android.app.Activity
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import com.coldboreballisticsllc.scopedope.BuildConfig
import com.coldboreballisticsllc.scopedope.R
import com.coldboreballisticsllc.scopedope.ui.theme.ColorAmber
import com.coldboreballisticsllc.scopedope.ui.theme.ColorBackground
import com.coldboreballisticsllc.scopedope.ui.theme.ColorSurface
import com.coldboreballisticsllc.scopedope.ui.theme.ColorTextMuted
import com.coldboreballisticsllc.scopedope.ui.theme.ColorTextPrimary
import com.coldboreballisticsllc.scopedope.ui.theme.PlexMono

private const val BETA_EXPIRY_MS = 45L * 24 * 60 * 60 * 1000

@Composable
fun SplashScreen(onComplete: () -> Unit) {
    val isBeta    = BuildConfig.VERSION_NAME.contains("beta", ignoreCase = true)
    val isExpired = isBeta && (System.currentTimeMillis() - BuildConfig.BUILD_TIMESTAMP) > BETA_EXPIRY_MS

    LaunchedEffect(Unit) {
        if (!isExpired) {
            delay(1800L)
            onComplete()
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(ColorBackground),
    ) {
        // ── BETA diagonal watermark ─────────────────────────────────────────
        if (isBeta) {
            Box(
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(top = 56.dp, end = 10.dp)
                    .rotate(30f)
                    .border(1.dp, ColorAmber.copy(alpha = 0.5f), RoundedCornerShape(3.dp))
                    .padding(horizontal = 12.dp, vertical = 5.dp),
                contentAlignment = Alignment.Center,
            ) {
                Text(
                    text  = "BETA",
                    style = TextStyle(
                        fontFamily    = PlexMono,
                        fontWeight    = FontWeight.Bold,
                        fontSize      = 13.sp,
                        letterSpacing = 4.sp,
                        color         = ColorAmber.copy(alpha = 0.65f),
                    ),
                )
            }
        }

        // ── Main identity block ─────────────────────────────────────────────
        Column(
            modifier            = Modifier
                .align(Alignment.Center)
                .padding(bottom = 80.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(0.dp),
        ) {
            Image(
                painter            = painterResource(R.drawable.ic_launcher_foreground),
                contentDescription = null,
                modifier           = Modifier.size(192.dp),
            )
            Spacer(Modifier.height(24.dp))
            ScopeDopeWordmark()
            Spacer(Modifier.height(6.dp))
            Text(
                text  = "COLD BORE BALLISTICS",
                style = TextStyle(
                    fontFamily    = PlexMono,
                    fontWeight    = FontWeight.Normal,
                    fontSize      = 11.sp,
                    letterSpacing = 4.sp,
                    color         = Color(0xFF5A5048),
                ),
            )
            Spacer(Modifier.height(12.dp))
            Text(
                text  = "v${BuildConfig.VERSION_NAME}",
                style = TextStyle(
                    fontFamily = PlexMono,
                    fontSize   = 13.sp,
                    color      = ColorTextMuted,
                ),
            )
        }

        // ── Tagline — bottom ─────────────────────────────────────────────────
        Column(
            modifier            = Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 48.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            HorizontalDivider(
                modifier  = Modifier
                    .fillMaxWidth(0.46f)
                    .padding(bottom = 20.dp),
                color     = ColorAmber.copy(alpha = 0.35f),
                thickness = 1.dp,
            )
            Text(
                text      = buildAnnotatedString {
                    withStyle(SpanStyle(color = ColorTextMuted, fontWeight = FontWeight.Light)) { append("Precision's ") }
                    withStyle(SpanStyle(color = ColorAmber,     fontWeight = FontWeight.Bold))  { append("NEW ")         }
                    withStyle(SpanStyle(color = ColorTextMuted, fontWeight = FontWeight.Light)) { append("Best Friend!") }
                },
                style     = TextStyle(fontFamily = PlexMono, fontSize = 16.sp),
                textAlign = TextAlign.Center,
            )
        }
    }

    if (isExpired) {
        val activity = LocalContext.current as? Activity
        AlertDialog(
            onDismissRequest  = {},
            title             = { Text("Beta Expired") },
            text              = { Text("This beta build expired 45 days after it was created. Please update to the latest release.") },
            confirmButton     = {
                TextButton(onClick = { activity?.finishAffinity() }) {
                    Text("Close App", color = ColorAmber)
                }
            },
            containerColor    = ColorSurface,
            titleContentColor = ColorTextPrimary,
            textContentColor  = ColorTextPrimary,
        )
    }
}

// ── "Scope" + "D" + reticle-as-O + "PE" wordmark ─────────────────────────────

@Composable
private fun ScopeDopeWordmark() {
    Row(
        verticalAlignment     = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center,
    ) {
        // "Scope" — light weight, primary color
        Text(
            text  = "Scope",
            style = TextStyle(
                fontFamily  = PlexMono,
                fontWeight  = FontWeight.Light,
                fontSize    = 48.sp,
                color       = ColorTextPrimary,
            ),
        )
        // "D" — amber bold
        Text(
            text  = "D",
            style = TextStyle(
                fontFamily  = PlexMono,
                fontWeight  = FontWeight.Bold,
                fontSize    = 48.sp,
                color       = ColorAmber,
            ),
        )
        // Scope-reticle favicon as "O"
        ReticleFavicon(size = 42.dp)
        // "PE" — amber bold
        Text(
            text  = "PE",
            style = TextStyle(
                fontFamily  = PlexMono,
                fontWeight  = FontWeight.Bold,
                fontSize    = 48.sp,
                color       = ColorAmber,
            ),
        )
    }
}

@Composable
private fun ReticleFavicon(size: androidx.compose.ui.unit.Dp) {
    androidx.compose.foundation.Canvas(
        modifier = Modifier
            .size(size)
            .padding(horizontal = 1.dp),
    ) {
        val cx = this.size.width / 2f
        val cy = this.size.height / 2f
        val r  = cx * 0.92f
        val sw = 2.5.dp.toPx()
        val tsw = 1.5.dp.toPx()
        val gap = r * 0.26f

        // Outer circle
        drawCircle(color = Color.White, radius = r, center = Offset(cx, cy), style = Stroke(sw))
        // Red diamond (scope reticle center marker)
        val d = r * 0.44f
        val diamond = androidx.compose.ui.graphics.Path().apply {
            moveTo(cx, cy - d)
            lineTo(cx + d * 0.87f, cy)
            lineTo(cx, cy + d)
            lineTo(cx - d * 0.87f, cy)
            close()
        }
        drawPath(diamond, Color(0xFFCC2200))
        // Crosshairs (white, gap in center)
        drawLine(Color.White, Offset(cx - r * 0.9f, cy), Offset(cx - gap, cy), tsw)
        drawLine(Color.White, Offset(cx + gap, cy), Offset(cx + r * 0.9f, cy), tsw)
        drawLine(Color.White, Offset(cx, cy - r * 0.9f), Offset(cx, cy - gap), tsw)
        drawLine(Color.White, Offset(cx, cy + gap), Offset(cx, cy + r * 0.9f), tsw)
    }
}
