/**
 * 多比比 — 设计系统共享 UI 组件 (与 screenshots/html/_base.css 的 token 对齐)。
 *
 * - [PlatformAvatar]: 风格化品牌徽章 —— 圆角方块 + 品牌主色渐变 + 单个中文字符。
 *                     刻意不复刻任何平台 logo,商店审核明确禁用未授权第三方 logo。
 * - [PriceGauge]:     简化双色价格水位条(neutral 底 + teal 填 + 深色标记三角)。css `.gauge`。
 * - [SummaryBar]:     纯 teal-dark hero 横幅(全网最低 / 省 ¥X)。css `.sumbar`。
 * - [TagChip]:        小号方角彩色标签 (本机/最低 等)。css `.tag`。
 * - [DbbProgressBar]: 迷你水平进度条 (css `.bar`)。
 */
package com.jishisongfu.duobibi.ui

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.EmojiEvents
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jishisongfu.duobibi.ui.theme.DbbColors

// --- 平台品牌色 (取自 css .pbadge.jd/.tb/.pdd/.dy/.mt/.elm) ---
// 渐变上下两色让方块徽章有"App icon"质感,与真实平台 logo 形态不同。
private data class BrandStyle(val top: Color, val bottom: Color, val ch: String, val fg: Color = Color.White)

private fun platformBrand(platform: String): BrandStyle = when (platform) {
    "京东" -> BrandStyle(Color(0xFFE1251B), Color(0xFFB91C1C), "京")
    "淘宝" -> BrandStyle(Color(0xFFFF7A22), Color(0xFFE15500), "淘")
    "拼多多" -> BrandStyle(Color(0xFFE02E24), Color(0xFFB91C1C), "拼")
    "抖音" -> BrandStyle(Color(0xFF3A3A3A), Color(0xFF0F172A), "抖")
    "美团", "美团外卖" -> BrandStyle(Color(0xFFFFCB1F), Color(0xFFF0B400), if (platform == "美团外卖") "外" else "美", Color(0xFF3A2C00))
    "饿了么" -> BrandStyle(Color(0xFF1E88FF), Color(0xFF0066CC), "饿")
    else -> BrandStyle(Color(0xFF64748B), Color(0xFF334155), platform.firstOrNull()?.toString() ?: "?")
}

/**
 * 风格化平台徽章 —— 圆角方块 + 品牌主色渐变 + 单个中文字符。`small=true` 紧凑场景用。
 * 名字保留 PlatformAvatar 以避免现有调用点全改;视觉上是新设计语言里的 .pbadge。
 */
@Composable
fun PlatformAvatar(
    platform: String,
    modifier: Modifier = Modifier,
    small: Boolean = false,
) {
    val style = platformBrand(platform)
    val sizeDp = if (small) 18.dp else 22.dp
    val fs = if (small) 10.sp else 11.sp
    val cornerDp = if (small) 5.dp else 6.dp
    Box(
        modifier = modifier
            .size(sizeDp)
            .clip(RoundedCornerShape(cornerDp))
            .background(Brush.verticalGradient(listOf(style.top, style.bottom))),
        contentAlignment = Alignment.Center,
    ) {
        Text(style.ch, color = style.fg, fontSize = fs, fontWeight = FontWeight.Bold)
    }
}

/**
 * 平台名圆角胶囊 —— 整名字躺在一个浅灰胶囊里(参考主流比价 App)。
 *
 * 跟 [PlatformAvatar] 的分工:
 *  - PlatformAvatar:小方块图标(22dp),只放单字,作为缩略图用(商品组卡 / 引导页平台列阵)
 *  - PlatformChip:**长胶囊**,放整个平台名("淘宝闪购"/"京东到家"/"饿了么"),
 *    用在对比表格行 —— 避免"图标 + 重复一遍平台名 Text"的双重视觉
 *
 * `isLowest = true` 时切换到品牌主色实心胶囊 + 白字,作为"最低"高亮。
 * `onClick` 可选,提供时整个胶囊可点(对应"点行去搜")。
 */
@Composable
fun PlatformChip(
    name: String,
    modifier: Modifier = Modifier,
    isLowest: Boolean = false,
    onClick: (() -> Unit)? = null,
) {
    val bg = if (isLowest) DbbColors.Teal else DbbColors.Fill
    val fg = if (isLowest) Color.White else DbbColors.InkSec
    val shape = RoundedCornerShape(8.dp)
    Box(
        modifier = modifier
            .clip(shape)
            .background(bg)
            .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
            .padding(horizontal = 10.dp, vertical = 5.dp),
    ) {
        Text(
            name,
            color = fg,
            fontSize = 12.sp,
            fontWeight = if (isLowest) FontWeight.Bold else FontWeight.Medium,
        )
    }
}

/**
 * 价格水位条:浅灰底 + Teal 填充到 marker 位置 + 深色三角标记。
 * 一般约定:min=全网最低价, max=最高价, marker=市场常见价 — 让用户一眼看到"现价水位"。
 * 不再用彩虹渐变(色彩太多),改成双色更克制。
 */
@Composable
fun PriceGauge(
    min: Double,
    max: Double,
    marker: Double,
    modifier: Modifier = Modifier,
) {
    val range = (max - min).coerceAtLeast(0.0001)
    val frac = ((marker - min) / range).coerceIn(0.0, 1.0).toFloat()
    BoxWithConstraints(modifier.fillMaxWidth().height(14.dp)) {
        // Track:浅灰底
        Box(
            Modifier
                .fillMaxWidth()
                .height(6.dp)
                .align(Alignment.BottomStart)
                .clip(RoundedCornerShape(3.dp))
                .background(DbbColors.Fill),
        )
        // Fill:teal 填到 marker
        Box(
            Modifier
                .fillMaxWidth(frac)
                .height(6.dp)
                .align(Alignment.BottomStart)
                .clip(RoundedCornerShape(3.dp))
                .background(DbbColors.Teal),
        )
        // 标记三角
        val markerLeft = (maxWidth * frac) - 5.dp
        Canvas(
            modifier = Modifier
                .size(width = 10.dp, height = 8.dp)
                .offset(x = markerLeft, y = 0.dp),
        ) {
            val path = Path().apply {
                moveTo(size.width / 2f, size.height)
                lineTo(0f, 0f)
                lineTo(size.width, 0f)
                close()
            }
            drawPath(path, color = Color(0xFF0F172A))
        }
    }
}

/**
 * Hero 横幅(纯 teal-dark)。从渐变 teal→sky 改成纯色,减少屏幕上的色彩数量。
 * 典型用法:"全网最低 · 京东 ¥7799 较常见价省 ¥500"。
 */
@Composable
fun SummaryBar(
    label: String,
    bigText: String,
    subText: String,
    modifier: Modifier = Modifier,
    leadingIcon: ImageVector = Icons.Filled.EmojiEvents,
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(13.dp))
            .background(DbbColors.TealDark)
            .padding(horizontal = 13.dp, vertical = 11.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(leadingIcon, contentDescription = null, tint = Color.White, modifier = Modifier.size(22.dp))
        Spacer(Modifier.width(9.dp))
        Column {
            Text(label, color = Color.White.copy(alpha = 0.85f), fontSize = 11.sp)
            Row(verticalAlignment = Alignment.Bottom) {
                Text(bigText, color = Color.White, fontSize = 19.sp, fontWeight = FontWeight.ExtraBold)
                Spacer(Modifier.width(6.dp))
                Text(
                    subText,
                    color = Color.White.copy(alpha = 0.9f),
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Medium,
                )
            }
        }
    }
}

/** 小号方角彩色标签 (如 "本机" / "最低")。css `.tag`。 */
@Composable
fun TagChip(text: String, bg: Color, fg: Color, modifier: Modifier = Modifier) {
    Box(
        modifier
            .clip(RoundedCornerShape(5.dp))
            .background(bg)
            .padding(horizontal = 6.dp, vertical = 2.dp),
    ) { Text(text, color = fg, fontSize = 10.sp, fontWeight = FontWeight.Bold) }
}

/** 迷你水平进度条 (css `.bar`)。fraction 0..1,默认 teal 色,可换 save/up。 */
@Composable
fun DbbProgressBar(
    fraction: Float,
    modifier: Modifier = Modifier,
    color: Color = DbbColors.Teal,
) {
    val f = fraction.coerceIn(0f, 1f)
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(6.dp)
            .clip(RoundedCornerShape(3.dp))
            .background(DbbColors.Fill),
    ) {
        Box(
            Modifier
                .fillMaxWidth(f)
                .height(6.dp)
                .clip(RoundedCornerShape(3.dp))
                .background(color),
        )
    }
}
