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

function Mirai_cloudTypes() {
    static $types = null;
    if ($types !== null) return $types;
    $base = Mirai_cloudAssetUrl();
    $types = [
        'bd'      => ['name' => '百度网盘',  'svg' => $base.'baidu.svg'],
        'lz'      => ['name' => '蓝奏云',    'svg' => $base.'lanzou.svg'],
        'alipan'  => ['name' => '阿里云盘',  'svg' => $base.'alyp.svg'],
        'ty'      => ['name' => '天翼云',    'svg' => $base.'tianyi.svg'],
        'wy'      => ['name' => '微云',      'svg' => $base.'weiyun.svg'],
        'onedrive'=> ['name' => 'OneDrive',  'svg' => $base.'OneDrive.svg'],
        'ct'      => ['name' => '城通网盘',  'svg' => $base.'cloud.svg'],
        'xunlei'  => ['name' => '迅雷云盘',  'svg' => $base.'xunlei.svg'],
        'quark'   => ['name' => '夸克网盘',  'svg' => $base.'quark.svg'],
        'pan123'  => ['name' => '123云盘',   'svg' => $base.'123.svg'],
        'github'  => ['name' => 'GitHub',    'svg' => $base.'github.svg'],
        'gitee'   => ['name' => 'Gitee',     'svg' => $base.'gitee.svg'],
        'default' => ['name' => '其他网盘',  'svg' => $base.'cloud.svg'],
    ];
    return $types;
}

function Mirai_cloudAssetUrl() {
    if (function_exists('Mirai_getThemeUrl')) {
        return Mirai_getThemeUrl() . '/assets/images/cloud/';
    }
    return '/usr/themes/Mirai/assets/images/cloud/';
}

function Mirai_cloudDetectType($url) {
    if (empty($url)) return 'default';
    $map = [
        'bd'       => ['pan.baidu.com', 'baidu'],
        'lz'       => ['lanzou', 'lanzoui', 'lanzoub', 'lanzoux'],
        'alipan'   => ['alipan.com', 'aliyundrive.com'],
        'ty'       => ['.189.cn', 'cloud.189.cn'],
        'wy'       => ['weiyun.com'],
        'onedrive' => ['onedrive.live.com', 'sharepoint.com', '1drv.ms'],
        'ct'       => ['ctfile.com'],
        'xunlei'   => ['pan.xunlei.com'],
        'quark'    => ['pan.quark.cn'],
        'pan123'   => ['123pan.com', '123865.com', '123912.com'],
        'github'   => ['github.com'],
        'gitee'    => ['gitee.com'],
    ];
    $urlLower = strtolower($url);
    foreach ($map as $type => $keywords) {
        foreach ($keywords as $kw) {
            if (strpos($urlLower, $kw) !== false) return $type;
        }
    }
    return 'default';
}

function Mirai_cloudParseAttrs($attrStr) {
    $attrs = [];
    $attrStr = trim($attrStr);
    if ($attrStr === '') return $attrs;
    preg_match_all('/(\w+)\s*=\s*"([^"]*)"/', $attrStr, $m, PREG_SET_ORDER);
    foreach ($m as $match) { $attrs[$match[1]] = $match[2]; }
    preg_match_all("/(\w+)\s*=\s*'([^']*)'/", $attrStr, $m2, PREG_SET_ORDER);
    foreach ($m2 as $match) { $attrs[$match[1]] = $match[2]; }
    preg_match_all('/(\w+)\s*=\s*([^\s\]]+)/', $attrStr, $m3, PREG_SET_ORDER);
    foreach ($m3 as $match) {
        if (!isset($attrs[$match[1]])) $attrs[$match[1]] = $match[2];
    }
    return $attrs;
}

function Mirai_cloudRenderOne($attrs) {
    $types = Mirai_cloudTypes();
    $type = isset($attrs['type']) ? trim($attrs['type']) : '';
    $url  = isset($attrs['url'])  ? trim($attrs['url'])  : '';
    if (empty($url)) return '';

    if (empty($type) || !isset($types[$type])) {
        $type = Mirai_cloudDetectType($url);
    }
    $cfg  = isset($types[$type]) ? $types[$type] : $types['default'];
    $title    = !empty($attrs['title'])    ? $attrs['title']    : '资源下载';
    $password = !empty($attrs['password']) ? $attrs['password'] : '';
    $svgUrl   = $cfg['svg'];
    $name     = $cfg['name'];

    $metaText = $name;
    if ($password) {
        $metaText .= ' · 提取码：<span class="mirai-cloud__pwd">' . htmlspecialchars($password, ENT_QUOTES, 'UTF-8') . '</span>';
    }

    $downloadSvg = Mirai_cloudAssetUrl() . 'download.svg';

    $copyBtn = '';
    if ($password) {
        $copyBtn = '<button class="mirai-cloud__copy" type="button" data-pwd="' . htmlspecialchars($password, ENT_QUOTES, 'UTF-8') . '" aria-label="复制提取码" title="复制提取码"><i class="ri-file-copy-line"></i><span class="copy-text">复制</span></button>';
    }

    return '<div class="mirai-cloud" data-type="' . htmlspecialchars($type, ENT_QUOTES, 'UTF-8') . '">'
         . '<img class="mirai-cloud__icon no-lightbox" src="' . htmlspecialchars($svgUrl, ENT_QUOTES, 'UTF-8') . '" alt="" width="32" height="32" loading="lazy" decoding="async">'
         . '<div class="mirai-cloud__info">'
         . '<div class="mirai-cloud__title">' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</div>'
         . '<div class="mirai-cloud__meta">' . $metaText . $copyBtn . '</div>'
         . '</div>'
         . '<a class="mirai-cloud__btn" href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer nofollow" aria-label="下载"><img class="no-lightbox" src="' . htmlspecialchars($downloadSvg, ENT_QUOTES, 'UTF-8') . '" alt="" width="16" height="16"></a>'
         . '</div>';
}

function Mirai_cloudFilterContent($content) {
    $content = (string)$content;
    if (strpos($content, '{cloud') === false) return $content;

    $content = preg_replace_callback('/\[\[(cloud(?:\s+[^\]]*)?)\]\]/i', function($m) {
        return "\x00MIRAI_CLOUD_ESCAPED_" . $m[1] . "\x00";
    }, $content);

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

    $content = preg_replace_callback('/\{cloud([^}]*)\/\}/i', function($matches) {
        $attrs = Mirai_cloudParseAttrs($matches[1]);
        return Mirai_cloudRenderOne($attrs);
    }, $content);

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

    $content = preg_replace_callback('/\x00MIRAI_CLOUD_ESCAPED_(cloud(?:\s+[^\]\x00]*)?)\x00/i', function($m) {
        return '{' . $m[1] . '/}';
    }, $content);

    return $content;
}

function Mirai_cloudTypesForJs() {
    $types = Mirai_cloudTypes();
    $base = Mirai_cloudAssetUrl();
    $result = [];
    foreach ($types as $value => $cfg) {
        $svg = isset($cfg['svg']) ? str_replace($base, '', $cfg['svg']) : 'cloud.svg';
        $result[] = ['value' => $value, 'label' => $cfg['name'], 'svg' => $svg];
    }
    return $result;
}

function Mirai_cloudHasShortcode($content) {
    return strpos((string)$content, '{cloud') !== false;
}