package com.fabledsword.minstrel.shared.widgets

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
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.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Dp
import com.fabledsword.minstrel.theme.FabledSwordFlatTokens

/**
 * Shared cover artwork tile: clipped, optionally backgrounded `Box`
 * with a [ServerImage] inside and a per-caller [fallback] icon. Used
 * by `AlbumCard`, `ArtistCard`, `PlaylistCard` — they vary on size /
 * shape / fallback icon / background, but the surrounding Box +
 * ServerImage + fallback structure was identical at all three sites.
 *
 * [overlay] is a `BoxScope` slot for things drawn on top of the cover
 * (e.g. the `VariantPill` system-playlist label, the play button) —
 * callers can use `Modifier.align(...)` inside it. The overlay sits on
 * an outer, UN-clipped box so corner-anchored widgets are not cut off by
 * [shape]: a `BottomEnd` play button on a `CircleShape` avatar falls in
 * the square's corner, outside the circle, and would otherwise be clipped
 * away. Only the artwork + background are clipped to [shape].
 */
@Composable
fun CoverTile(
    url: String?,
    contentDescription: String?,
    size: Dp,
    fallback: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    shape: Shape = RoundedCornerShape(FabledSwordFlatTokens.radiusSm),
    background: Color = Color.Transparent,
    overlay: @Composable BoxScope.() -> Unit = {},
) {
    Box(
        modifier = modifier.size(size),
        contentAlignment = Alignment.Center,
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .clip(shape)
                .background(background),
            contentAlignment = Alignment.Center,
        ) {
            ServerImage(
                url = url,
                contentDescription = contentDescription,
                modifier = Modifier.fillMaxSize(),
            ) {
                fallback()
            }
        }
        overlay()
    }
}
