"""Template tags for the Bookmark viewer."""
from django import template
from django.utils.safestring import mark_safe

register = template.Library()


@register.filter
def media_grid_class(media_count):
    """Return the CSS grid class for a media block based on item count."""
    n = int(media_count or 0)
    if n <= 1:
        return 'one'
    if n == 2:
        return 'two'
    if n == 3:
        return 'three'
    return 'four'


@register.filter
def ms_to_duration(ms):
    """Convert milliseconds to a short M:SS duration string."""
    try:
        secs = int(int(ms) / 1000)
    except (TypeError, ValueError):
        return ''
    if secs >= 3600:
        h = secs // 3600
        m = (secs % 3600) // 60
        s = secs % 60
        return f'{h}:{m:02d}:{s:02d}'
    m = secs // 60
    s = secs % 60
    return f'{m}:{s:02d}'


@register.simple_tag
def bookmark_chip(flag, label, count, request_get):
    """Render a filter chip button that toggles a boolean query param,
    preserving the current `q` search query."""
    active = False
    val = ''
    try:
        val = request_get.get(flag)
    except AttributeError:
        val = None
    if val is not None:
        active = True
    q = ''
    try:
        q = request_get.get('q') or ''
    except AttributeError:
        q = ''
    base = 'inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium border cursor-pointer select-none transition '
    cls = base + ('bg-blue-600 text-white border-blue-600'
                  if active else 'bg-white text-gray-600 border-gray-300 hover:bg-gray-100')
    # When active, clicking the chip goes to a URL with that flag removed
    # (toggle off). When inactive, clicking adds the flag=on.
    params = []
    if q:
        params.append(('q', q))
    # keep other flag params
    KEEP = ('has_video', 'has_photo', 'has_card', 'is_quote', 'is_retweet')
    for k in KEEP:
        if k == flag:
            continue
        v = None
        try:
            v = request_get.get(k)
        except AttributeError:
            v = None
        if v:
            params.append((k, 'on'))
    if not active:
        params.append((flag, 'on'))
    href = '?' + '&'.join(f'{k}={v}' for k, v in params) if params else './'
    return mark_safe(
        f'<a href="{href}" hx-get="?{"&".join(f"{k}={v}" for k,v in params)}" '
        f'hx-target="#bm-content" hx-swap="innerHTML" hx-push-url="true" '
        f'class="{cls}"><span>{label}</span>'
        f'<span class="opacity-75">{count}</span></a>'
    )