import re

def slugify(text, max_length=None):
    """Lowercase, replace non-alphanumerics with hyphens, collapse repeats.

    If max_length is set, truncate the slug to at most max_length characters,
    preferring to cut at a hyphen boundary and never leaving a trailing hyphen.
    max_length <= 0 yields an empty string. None (default) keeps current behavior.
    """
    text = text.lower()
    full = re.sub(r"[^a-z0-9]+", "-", text).strip("-")

    if max_length is None:
        return full
    if max_length <= 0:
        return ""
    if len(full) <= max_length:
        return full

    truncated = full[:max_length]

    # Mid-word cut: if the char just past the window is not a hyphen, retreat to
    # the last hyphen boundary inside the window (cut before it). If no hyphen
    # exists in the window, keep the partial word (no boundary to cut at).
    if full[max_length] != "-":
        hyphen_idx = truncated.rfind("-")
        if hyphen_idx != -1:
            truncated = truncated[:hyphen_idx]

    return truncated.rstrip("-")