<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function Mirai_musicFilterContent($content)
{
    $content = (string)$content;
    if (strpos($content, '{mp3') === false) return $content;

    $protectedAreas = [];
    $content = preg_replace_callback(
        '/(<(code|pre|kbd)[^>]*>[\s\S]*?<\/\2>|<table[\s\S]*?<\/table>)/i',
        function ($matches) use (&$protectedAreas) {
            $placeholder = "\x00MIRAI_MUSIC_PROTECTED_" . count($protectedAreas) . "\x00";
            $protectedAreas[] = $matches[0];
            return $placeholder;
        },
        $content
    );

    $content = preg_replace_callback('/\{mp3\s+([^}]*)\/\}/i', function ($matches) {
        $attrs = Mirai_musicParseAttrs($matches[1]);
        return Mirai_musicRenderMp3($attrs);
    }, $content);

    foreach ($protectedAreas as $index => $original) {
        $content = str_replace("\x00MIRAI_MUSIC_PROTECTED_" . $index . "\x00", $original, $content);
    }

    return $content;
}

function Mirai_musicParseAttrs($attrString)
{
    $attrs = [];
    preg_match_all('/(\w+)="([^"]*)"/', $attrString, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
        $attrs[$match[1]] = $match[2];
    }
    return $attrs;
}

function Mirai_musicRenderMp3($attrs)
{
    $name = isset($attrs['name']) ? $attrs['name'] : '';
    $url = isset($attrs['url']) ? trim($attrs['url']) : '';
    $artist = isset($attrs['artist']) ? $attrs['artist'] : '';
    $cover = isset($attrs['cover']) ? $attrs['cover'] : '';
    $theme = isset($attrs['theme']) ? $attrs['theme'] : '#007fff';
    $autoplay = !empty($attrs['autoplay']) ? '1' : '0';

    if (empty($url)) {
        return '<p style="color:#e74c3c;text-align:center;padding:1em;">音频地址未填写</p>';
    }

    return '<div class="mirai-mp3" data-name="' . htmlspecialchars($name) . '" data-url="' . htmlspecialchars($url) . '" data-artist="' . htmlspecialchars($artist) . '" data-cover="' . htmlspecialchars($cover) . '" data-theme="' . htmlspecialchars($theme) . '" data-autoplay="' . $autoplay . '"></div>';
}
