<?php
/**
 * 炎酷CMS - 在线编辑（可视化设置：模板卡片选择 + 主题色实时预览，所见即所得）
 * 支持 首页 / 首页区块 / 文章列表 / 文章内容 / 单页面 五种类型。
 * 右侧 iframe 加载前台真实页面（带 yk_preview=1 参数），预览不写库，保存后生效。
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';
require SITE_PATH . '/inc/render.php'; // theme_var_map() 与前台预览参数保持一致

$page_title = '在线编辑';
$active = 'visual';

/* ---------------- 全站模板分组（编号 => [短名, 描述]） ---------------- */
$tplGroups = array(
    'tpl_header' => array('顶部导航模板', array(
        1 => array('样式1 经典企业', '顶部信息条（电话/邮箱）+ 白底LOGO居左、导航居右'),
        2 => array('样式2 居中大气', 'LOGO居上、导航居中，上下细分割线'),
        3 => array('样式3 深色科技', '深色背景、青色高亮、导航下划线动画'),
        4 => array('样式4 全宽色带', '主色满宽背景、白色导航文字'),
        5 => array('样式5 悬浮胶囊', '圆角悬浮导航条、吸顶跟随，胶囊形选中项'),
    )),
    'tpl_banner' => array('顶部广告条模板', array(
        1 => array('样式1 大图轮播', '全宽大图轮播'),
        2 => array('样式2 固定单图', '固定单图 + 标题'),
        3 => array('样式3 公告条', '纯公告滚动条（无图片）'),
        4 => array('样式4 左图右公告', '左图右公告组合'),
        5 => array('样式5 左右分屏', '左侧渐变文案区 + 右侧图片轮播'),
        6 => array('样式6 通栏公告', '低矮公告横幅 + 右侧小图点缀'),
        7 => array('样式7 多图网格', '一大图 + 多小图拼版，悬停放大'),
        8 => array('样式8 卡片轮播', '大圆角卡片轮播 + 卡片下方公告'),
    )),
    'kefu_style' => array('客服浮动条样式', array(
        1 => array('样式1 细长竖条', '右侧电话/微信图标按钮，悬停展开'),
        2 => array('样式2 胶囊竖排', '右侧圆角胶囊竖排，图标 + 文字'),
        3 => array('样式3 卡片式', '右侧卡片：标题 + 大号电话 + 二维码'),
    )),
    'tpl_footer' => array('底部模板', array(
        1 => array('样式1 深色三栏', '导航 | 公司信息 | 联系版权'),
        2 => array('样式2 简洁居中', '简洁居中单行风格（白字）'),
    )),
);

/* ---------------- 首页区块模板（按模块类型区分，各 5 套） ---------------- */
$blockTplNames = array(
    'about'   => array(
        1 => array('样式1 左图右文', '图片居左、文字居右'),
        2 => array('样式2 右图左文色块', '图片居右、左侧色块文字'),
        3 => array('样式3 上图下文卡片', '图片居上、文字居下的卡片'),
        4 => array('样式4 纯文字居中', '无图，文字居中排版'),
        5 => array('样式5 图片背景浮层', '整幅背景图 + 文字浮层'),
    ),
    'article' => array(
        1 => array('样式1 左图右文列表', '缩略图居左、标题摘要居右'),
        2 => array('样式2 纯文字日期列表', '无图，标题 + 日期行式'),
        3 => array('样式3 首条大图+列表', '第一条大图展示 + 其余列表'),
        4 => array('样式4 两列卡片', '两列图文卡片网格'),
        5 => array('样式5 横向滚动卡片', '卡片横向排列，可滑动'),
    ),
    'product' => array(
        1 => array('样式1 四列网格图卡', '四列等宽图片卡片'),
        2 => array('样式2 标题遮罩图卡', '图片上标题遮罩浮层'),
        3 => array('样式3 大小图混排', '一大图 + 多小图混排'),
        4 => array('样式4 圆角阴影卡片', '圆角带阴影的图卡'),
        5 => array('样式5 左图右简介列表', '图片居左、简介居右行式'),
    ),
);
$blockModNames = array('about' => '关于模块', 'article' => '文章模块', 'product' => '产品模块');
$titleStyleNames = array(
    1 => array('样式1 左侧竖线', '标题左侧竖向色条'),
    2 => array('样式2 底部下划线', '标题下方短下划线'),
    3 => array('样式3 居中两侧横线', '标题居中、两侧横线装饰'),
    4 => array('样式4 底色块', '标题整体带底色块'),
    5 => array('样式5 菱形前缀', '标题前菱形符号'),
);

/* ---------------- 列表 / 内容页 / 单页模板（按栏目或单页存储） ---------------- */
$listTplNames = array(
    1 => array('样式1 左图右文', '经典左缩略图右文字列表（分割线）'),
    2 => array('样式2 卡片网格', '两列卡片网格（上图下文）'),
    3 => array('样式3 纯文字', '标题居左、日期居右，悬停变色'),
    4 => array('样式4 大图通栏', '一列大图 + 摘要'),
    5 => array('样式5 新闻列表', '日期方块 + 标题摘要 + 阅读量'),
    6 => array('样式6 紧凑表格', '序号 / 标题 / 日期 行式'),
    7 => array('样式7 杂志头条', '第一条大图头条 + 其余小列表'),
    8 => array('样式8 序号排行', '左侧序号排行列表'),
    9 => array('样式9 三列图网格', '图下标题 + 日期'),
    10 => array('样式10 极简文字', '无图、大留白、分割线'),
    11 => array('样式11 标签卡片', '圆角卡片、标签色块'),
    12 => array('样式12 图文交错', '奇数行图左、偶数行图右'),
);
$contentTplNames = array(
    1 => array('样式1 居中经典', '居中窄栏经典排版'),
    2 => array('样式2 左文右卡', '左侧正文 + 右侧信息卡（栏目/日期/阅读量/上下篇）'),
    3 => array('样式3 宽屏色块', '宽屏大标题头部色块 + 正文'),
);
$pageTplNames = array(
    1 => array('样式1 标题横幅', '经典关于我们：顶部标题横幅 + 居中正文'),
    2 => array('样式2 左右分栏', '左侧渐变装饰面板（单页名+slogan），右侧正文'),
    3 => array('样式3 色块标题', '全宽色块标题 + 窄栏正文（最大宽度 800px 居中）'),
    4 => array('样式4 侧边联系卡', '正文居左、右侧固定卡片（电话/地址/邮箱）'),
    5 => array('样式5 大字封面', '顶部超大标题渐变区 + 正文卡片浮上去'),
    6 => array('样式6 企业文化', '顶部标语带 + 正文分两栏排版'),
    7 => array('样式7 极简窄栏', '超窄正文栏、大留白、细分割线'),
    8 => array('样式8 发展历程', '左侧竖向装饰线 + 正文（时间轴氛围边框）'),
    9 => array('样式9 荣誉墙', '标题 + 正文 + 下方渐变“资质”色块网格'),
    10 => array('样式10 深色风', '深色背景区标题 + 白色正文卡片'),
);

/* ---------------- 主题色字段（键 => [标签, 提示]） ---------------- */
$themeFields = array(
    'theme_nav_bg'        => array('导航条背景色', ''),
    'theme_nav_color'     => array('导航条文字色', ''),
    'theme_nav_active'    => array('导航点击文字色', '鼠标滑过与当前选中导航的文字颜色'),
    'theme_nav_active_bg' => array('导航点击背景色', '当前选中导航项的背景颜色'),
    'theme_accent'        => array('全局强调色', '链接高亮、按钮、标题装饰等（默认红色 #e63946）'),
    'theme_footer_bg'     => array('底部背景色', ''),
    'theme_footer_color'  => array('底部文字色', ''),
    'theme_side_bg'       => array('侧栏标题背景色', ''),
    'theme_side_color'    => array('侧栏标题文字色', ''),
);

/* ---------------- 页面类型与预览目标 ---------------- */
$tabs = array('home' => '首页', 'block' => '首页区块', 'list' => '文章列表', 'art' => '文章内容', 'page' => '单页面');
$tab  = isset($_GET['tab']) && isset($tabs[$_GET['tab']]) ? $_GET['tab'] : 'home';
$colId  = isset($_GET['col']) ? (int)$_GET['col'] : 0;
$pageId = isset($_GET['pid']) ? (int)$_GET['pid'] : 0;
$blockId = isset($_GET['bid']) ? (int)$_GET['bid'] : 0;

// 栏目下拉（列表/内容页标签用）
$colOptions = array();
if ($tab === 'list' || $tab === 'art') {
    column_options(0, 0, $colOptions);
    if ($colId <= 0 && $colOptions) {
        $colId = (int)$colOptions[0]['id'];
    }
}
// 单页下拉
$pageOptions = array();
if ($tab === 'page') {
    $pageOptions = db_all('SELECT id, name, flag FROM ' . DB_PREFIX . 'page WHERE status = 1 ORDER BY sort ASC, id ASC');
    if ($pageId <= 0 && $pageOptions) {
        $pageId = (int)$pageOptions[0]['id'];
    }
}
// 首页区块下拉（友情链接模块无模板，排除）
$blockOptions = array();
$curBlock = null;
if ($tab === 'block') {
    $blockOptions = db_all("SELECT id, name, mod_type FROM " . DB_PREFIX . "index_block WHERE mod_type != 'link' ORDER BY sort ASC, id ASC");
    if ($blockId <= 0 && $blockOptions) {
        $blockId = (int)$blockOptions[0]['id'];
    }
    if ($blockId > 0) {
        $curBlock = db_one('SELECT * FROM ' . DB_PREFIX . 'index_block WHERE id = ?', array($blockId));
    }
}

/* ---------------- 保存 ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    // 全站模板与主题色：字段在表单中才保存（仅首页标签页带全站模板字段）
    foreach ($tplGroups as $key => $g) {
        if (isset($_POST[$key])) {
            $max = max(array_keys($g[1]));
            config_set($key, (string)max(1, min($max, (int)$_POST[$key])));
        }
    }
    if (isset($_POST['kefu_on'])) {
        config_set('kefu_on', $_POST['kefu_on'] === '1' ? '1' : '0');
    }
    foreach (array_keys($themeFields) as $k) {
        if (isset($_POST[$k])) {
            config_set($k, trim($_POST[$k]));
        }
    }
    // 区块 / 栏目 / 单页级模板
    $detail = array();
    if ($tab === 'block' && $blockId > 0 && $curBlock) {
        $sets = array();
        $args = array();
        $logs = array();
        if (isset($_POST['block_tpl'])) {
            $sets[] = 'tpl_id = ?';
            $args[] = max(1, min(5, (int)$_POST['block_tpl']));
            $logs[] = '模板样式=' . $args[count($args) - 1];
        }
        if (isset($_POST['block_title_style'])) {
            $sets[] = 'title_style = ?';
            $args[] = max(1, min(5, (int)$_POST['block_title_style']));
            $logs[] = '标题样式=' . $args[count($args) - 1];
        }
        if ($sets) {
            $args[] = $blockId;
            db_exec('UPDATE ' . DB_PREFIX . 'index_block SET ' . implode(', ', $sets) . ' WHERE id = ?', $args);
            $detail[] = '模块#' . $blockId . ' ' . implode(' ', $logs);
        }
    }
    if ($tab === 'list' && $colId > 0 && isset($_POST['list_tpl'])) {
        $v = max(1, min(12, (int)$_POST['list_tpl']));
        db_exec('UPDATE ' . DB_PREFIX . 'column SET list_tpl = ? WHERE id = ?', array($v, $colId));
        $detail[] = '栏目#' . $colId . ' 列表模板=' . $v;
    }
    if ($tab === 'art' && $colId > 0 && isset($_POST['content_tpl'])) {
        $v = max(1, min(3, (int)$_POST['content_tpl']));
        db_exec('UPDATE ' . DB_PREFIX . 'column SET content_tpl = ? WHERE id = ?', array($v, $colId));
        $detail[] = '栏目#' . $colId . ' 内容页模板=' . $v;
    }
    if ($tab === 'page' && $pageId > 0 && isset($_POST['page_tpl'])) {
        $v = max(1, min(10, (int)$_POST['page_tpl']));
        db_exec('UPDATE ' . DB_PREFIX . 'page SET page_tpl = ? WHERE id = ?', array($v, $pageId));
        $detail[] = '单页#' . $pageId . ' 页面模板=' . $v;
    }
    admin_log('在线编辑', '更新' . $tabs[$tab] . '可视化设置' . ($detail ? '（' . implode('；', $detail) . '）' : ''));
    flash_set('已保存，前台已生效');
    header('Location: visual.php?tab=' . $tab . '&col=' . $colId . '&pid=' . $pageId . '&bid=' . $blockId);
    exit;
}

$cfg = site_config();
function ykv_cfg($cfg, $key, $default = '') {
    return isset($cfg[$key]) && $cfg[$key] !== '' ? $cfg[$key] : $default;
}

/* ---------------- 计算预览 URL 与当前标签页的模板卡片组 ---------------- */
$previewBase = rtrim(SITE_URL, '/') . '/';
$previewHint = '';
$tabGroups = array();   // 当前标签页要显示的模板卡片组
$curMap = array();      // 各卡片组当前已保存的模板编号

if ($tab === 'home') {
    $tabGroups = $tplGroups;
    foreach (array_keys($tplGroups) as $k) {
        $curMap[$k] = (int)ykv_cfg($cfg, $k, '1');
    }
} elseif ($tab === 'block') {
    if ($curBlock) {
        $mod = isset($blockTplNames[$curBlock['mod_type']]) ? $curBlock['mod_type'] : 'article';
        $tabGroups = array(
            'block_tpl' => array('模块模板样式（' . $blockModNames[$mod] . '，按模块保存）', $blockTplNames[$mod]),
            'block_title_style' => array('模块标题样式（按模块保存）', $titleStyleNames),
        );
        $curMap = array('block_tpl' => (int)$curBlock['tpl_id'], 'block_title_style' => (int)$curBlock['title_style']);
        // 预览首页，仅覆盖当前模块（block_id 由 JS 拼接进预览 URL）
    } else {
        $previewHint = '暂无首页模块，请先到“首页区块”添加';
    }
} elseif ($tab === 'list') {
    $tabGroups = array('list_tpl' => array('文章列表模板（按栏目保存）', $listTplNames));
    if ($colId > 0) {
        $curMap = array('list_tpl' => (int)db_val('SELECT list_tpl FROM ' . DB_PREFIX . 'column WHERE id = ?', array($colId)));
        $previewBase .= '?col=' . $colId;
    } else {
        $previewHint = '暂无栏目，请先到“栏目管理”创建';
    }
} elseif ($tab === 'art') {
    $tabGroups = array('content_tpl' => array('文章内容页模板（按栏目保存）', $contentTplNames));
    if ($colId > 0) {
        $curMap = array('content_tpl' => (int)db_val('SELECT content_tpl FROM ' . DB_PREFIX . 'column WHERE id = ?', array($colId)));
        $artId = (int)db_val('SELECT id FROM ' . DB_PREFIX . 'article WHERE col_id = ? AND status = 1 ORDER BY id DESC LIMIT 1', array($colId));
        if ($artId > 0) {
            $previewBase .= '?art=' . $artId;
        } else {
            $previewHint = '该栏目暂无文章，无法预览内容页';
        }
    } else {
        $previewHint = '暂无栏目，请先到“栏目管理”创建';
    }
} elseif ($tab === 'page') {
    $tabGroups = array('page_tpl' => array('单页面模板（按单页保存）', $pageTplNames));
    if ($pageId > 0) {
        $prow = db_one('SELECT page_tpl, flag FROM ' . DB_PREFIX . 'page WHERE id = ?', array($pageId));
        if ($prow) {
            $curMap = array('page_tpl' => (int)$prow['page_tpl']);
            $previewBase .= '?page=' . urlencode($prow['flag']);
        } else {
            $previewHint = '单页不存在';
        }
    } else {
        $previewHint = '暂无单页，请先到“单页管理”创建';
    }
}
foreach ($curMap as $k => $v) {
    if ($v < 1) $curMap[$k] = 1;
}

// 当前标签页的模板卡片组键（JS 拼预览 URL 用）
$tabTplKeys = array_keys($tabGroups);

require dirname(__DIR__) . '/inc/header.php';
?>
<style>
.ykv-wrap{display:flex;gap:20px;align-items:flex-start}
.ykv-panel{width:420px;flex-shrink:0;background:#fff;border-radius:12px;padding:20px 22px;box-shadow:0 2px 14px rgba(31,45,61,.06);border:1px solid rgba(234,238,242,.7);max-height:calc(100vh - 130px);overflow-y:auto}
.ykv-panel h4{font-size:14px;color:#1f2d3d;margin:18px 0 10px;padding-left:10px;position:relative}
.ykv-panel h4::before{content:"";position:absolute;left:0;top:2px;bottom:2px;width:4px;border-radius:2px;background:linear-gradient(180deg,#3b82f6,#2563eb)}
.ykv-cards{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.ykv-card{border:2px solid #e5eaf1;border-radius:8px;padding:9px 11px;cursor:pointer;transition:all .15s;background:#fafbfc}
.ykv-card:hover{border-color:#93c0f5}
.ykv-card.on{border-color:#2563eb;background:#eff5ff;box-shadow:0 2px 8px rgba(37,99,235,.15)}
.ykv-card .nm{font-size:13px;font-weight:600;color:#1f2d3d}
.ykv-card .ds{font-size:12px;color:#8a94a6;margin-top:3px;line-height:1.5}
.ykv-color{display:flex;align-items:center;gap:8px;margin-bottom:10px}
.ykv-color .lb{width:110px;flex-shrink:0;font-size:13px;color:#5c6a7d}
.ykv-color input[type=color]{width:42px;height:30px;padding:2px;border:1px solid #d5dae3;border-radius:4px;cursor:pointer}
.ykv-color input[type=text]{flex:1;padding:6px 10px;border:1px solid #dbe2ec;border-radius:6px;font-size:13px;font-family:inherit}
.ykv-color input[type=text]:focus{border-color:#3b82f6;outline:none}
.ykv-tip{font-size:12px;color:#999;margin:-6px 0 10px 120px}
.ykv-sel{width:100%;padding:7px 10px;border:1px solid #dbe2ec;border-radius:6px;font-size:13px;margin-bottom:6px}
.ykv-stage{flex:1;min-width:0;position:sticky;top:86px}
.ykv-bar{display:flex;align-items:center;gap:10px;margin-bottom:10px}
.ykv-bar .dev button{padding:5px 14px;border:1px solid #dbe2ec;background:#fff;border-radius:6px;cursor:pointer;font-size:13px;color:#5c6a7d}
.ykv-bar .dev button.on{background:linear-gradient(90deg,#3b82f6,#2563eb);color:#fff;border-color:#2563eb}
.ykv-bar .hint{font-size:12px;color:#999}
.ykv-framebox{margin:0 auto;background:#fff;border:1px solid #dbe2ec;border-radius:10px;overflow:hidden;box-shadow:0 4px 18px rgba(31,45,61,.1);transition:max-width .25s}
.ykv-framebox iframe{display:block;width:100%;height:calc(100vh - 210px);border:0}
.ykv-save{margin-top:16px;padding-top:14px;border-top:1px solid #f0f2f5}
.ykv-empty{padding:60px 20px;text-align:center;color:#999;background:#fff;border:1px dashed #dbe2ec;border-radius:10px}
@media(max-width:1100px){.ykv-wrap{flex-direction:column}.ykv-panel{width:100%;max-height:none}.ykv-stage{position:static;width:100%}}
</style>

<div class="yk-tabs" style="margin-bottom:14px">
  <?php foreach ($tabs as $k => $label): ?>
  <a href="visual.php?tab=<?php echo $k; ?>"<?php echo $tab === $k ? ' class="on"' : ''; ?>><?php echo e($label); ?></a>
  <?php endforeach; ?>
</div>

<div class="ykv-wrap">
  <div class="ykv-panel">
    <form method="post" action="visual.php?tab=<?php echo $tab; ?>&col=<?php echo $colId; ?>&pid=<?php echo $pageId; ?>&bid=<?php echo $blockId; ?>" id="ykvForm">
      <?php echo csrf_field(); ?>

      <?php if ($tab === 'list' || $tab === 'art'): ?>
      <h4>预览栏目</h4>
      <select class="ykv-sel" onchange="location.href='visual.php?tab=<?php echo $tab; ?>&col='+this.value">
        <?php foreach ($colOptions as $co): ?>
        <option value="<?php echo (int)$co['id']; ?>"<?php echo (int)$co['id'] === $colId ? ' selected' : ''; ?>><?php echo str_repeat('　', $co['depth']) . e($co['name']); ?></option>
        <?php endforeach; ?>
      </select>
      <?php elseif ($tab === 'page'): ?>
      <h4>预览单页</h4>
      <select class="ykv-sel" onchange="location.href='visual.php?tab=page&pid='+this.value">
        <?php foreach ($pageOptions as $po): ?>
        <option value="<?php echo (int)$po['id']; ?>"<?php echo (int)$po['id'] === $pageId ? ' selected' : ''; ?>><?php echo e($po['name']); ?></option>
        <?php endforeach; ?>
      </select>
      <?php elseif ($tab === 'block'): ?>
      <h4>预览模块</h4>
      <select class="ykv-sel" onchange="location.href='visual.php?tab=block&bid='+this.value">
        <?php foreach ($blockOptions as $bo): ?>
        <option value="<?php echo (int)$bo['id']; ?>"<?php echo (int)$bo['id'] === $blockId ? ' selected' : ''; ?>><?php echo e($bo['name']); ?>（<?php echo e(isset($blockModNames[$bo['mod_type']]) ? $blockModNames[$bo['mod_type']] : $bo['mod_type']); ?>）</option>
        <?php endforeach; ?>
      </select>
      <?php endif; ?>

      <?php foreach ($tabGroups as $key => $g): $cur = isset($curMap[$key]) ? $curMap[$key] : 1; ?>
      <h4><?php echo e($g[0]); ?></h4>
      <input type="hidden" name="<?php echo e($key); ?>" id="f_<?php echo e($key); ?>" value="<?php echo $cur; ?>">
      <div class="ykv-cards">
        <?php foreach ($g[1] as $id => $n): ?>
        <div class="ykv-card<?php echo $cur === $id ? ' on' : ''; ?>" data-group="<?php echo e($key); ?>" data-id="<?php echo $id; ?>" onclick="ykvPick(this)">
          <div class="nm"><?php echo e($n[0]); ?></div>
          <div class="ds"><?php echo e($n[1]); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endforeach; ?>

      <?php if ($tab === 'home'): ?>
      <h4>客服浮动条开关</h4>
      <div class="yk-check" style="margin-bottom:6px">
        <label><input type="radio" name="kefu_on" value="1"<?php echo ykv_cfg($cfg, 'kefu_on', '0') === '1' ? ' checked' : ''; ?> onchange="ykvReload()"> 开启</label>
        <label><input type="radio" name="kefu_on" value="0"<?php echo ykv_cfg($cfg, 'kefu_on', '0') !== '1' ? ' checked' : ''; ?> onchange="ykvReload()"> 关闭</label>
      </div>
      <?php endif; ?>

      <h4>主题颜色（全站）</h4>
      <?php foreach ($themeFields as $key => $f): $val = ykv_cfg($cfg, $key); $picker = preg_match('/^#[0-9a-fA-F]{6}$/', $val) ? $val : '#ffffff'; ?>
      <div class="ykv-color">
        <span class="lb"><?php echo e($f[0]); ?></span>
        <input type="color" id="<?php echo e($key); ?>_picker" value="<?php echo e($picker); ?>" oninput="ykvColor('<?php echo e($key); ?>', this.value)">
        <input type="text" name="<?php echo e($key); ?>" id="<?php echo e($key); ?>" value="<?php echo e($val); ?>" placeholder="#ffffff（留空用模板默认色）" oninput="ykvColorText('<?php echo e($key); ?>', this.value)">
      </div>
      <?php if ($f[1] !== ''): ?><div class="ykv-tip"><?php echo e($f[1]); ?></div><?php endif; ?>
      <?php endforeach; ?>

      <div class="ykv-save">
        <button class="yk-btn" type="submit">保存并生效</button>
        <a href="index.php" style="margin-left:12px;font-size:13px">返回站点设置</a>
      </div>
    </form>
  </div>

  <div class="ykv-stage">
    <div class="ykv-bar">
      <div class="dev">
        <button type="button" id="devPc" class="on" onclick="ykvDevice('pc')">电脑</button>
        <button type="button" id="devMobile" onclick="ykvDevice('mobile')">手机</button>
      </div>
      <button type="button" class="yk-btn gray sm" onclick="ykvReload()">刷新预览</button>
      <span class="hint">预览为临时效果，不写数据库；点左侧“保存并生效”后前台正式更新</span>
    </div>
    <?php if ($previewHint !== ''): ?>
    <div class="ykv-empty"><?php echo e($previewHint); ?></div>
    <?php else: ?>
    <div class="ykv-framebox" id="ykvBox">
      <iframe id="ykvFrame" src="about:blank"></iframe>
    </div>
    <?php endif; ?>
  </div>
</div>

<script>
var YKV_BASE = <?php echo json_encode($previewBase); ?>;
var YKV_BLOCK_ID = <?php echo $tab === 'block' ? $blockId : 0; ?>;
var YKV_THEME_VAR = <?php echo json_encode(theme_var_map()); ?>;
var YKV_TPL_KEYS = <?php echo json_encode($tabTplKeys); ?>;
var YKV_HAS_FRAME = <?php echo $previewHint === '' ? 'true' : 'false'; ?>;

// 依据面板当前状态拼预览 URL（模板走 URL 参数，主题色也带上保证刷新后一致）
function ykvUrl() {
    var q = ['yk_preview=1'];
    if (YKV_BLOCK_ID > 0) q.push('block_id=' + YKV_BLOCK_ID);
    YKV_TPL_KEYS.forEach(function (k) {
        q.push(k + '=' + encodeURIComponent(document.getElementById('f_' + k).value));
    });
    var kefuOn = document.querySelector('input[name="kefu_on"]:checked');
    q.push('kefu_on=' + (kefuOn ? kefuOn.value : '0'));
    for (var k in YKV_THEME_VAR) {
        q.push(k + '=' + encodeURIComponent(document.getElementById(k).value));
    }
    return YKV_BASE + (YKV_BASE.indexOf('?') >= 0 ? '&' : '?') + q.join('&');
}

function ykvReload() {
    if (YKV_HAS_FRAME) document.getElementById('ykvFrame').src = ykvUrl();
}

// 模板卡片单选
function ykvPick(el) {
    var group = el.getAttribute('data-group');
    document.getElementById('f_' + group).value = el.getAttribute('data-id');
    document.querySelectorAll('.ykv-card[data-group="' + group + '"]').forEach(function (c) { c.classList.remove('on'); });
    el.classList.add('on');
    ykvReload();
}

// 颜色：免刷新实时预览（postMessage 改 iframe 内 CSS 变量）
function ykvSendColor(key, val) {
    if (!YKV_HAS_FRAME) return;
    var cssVar = YKV_THEME_VAR[key];
    var frame = document.getElementById('ykvFrame');
    if (frame.contentWindow) {
        var vars = {};
        vars[cssVar] = val;
        frame.contentWindow.postMessage({ykTheme: 1, vars: vars}, '*');
    }
}
function ykvColor(key, val) {
    document.getElementById(key).value = val;
    ykvSendColor(key, val);
}
function ykvColorText(key, val) {
    if (/^#[0-9a-fA-F]{6}$/.test(val)) {
        document.getElementById(key + '_picker').value = val;
    }
    ykvSendColor(key, val);
}

// 设备切换
function ykvDevice(dev) {
    document.getElementById('ykvBox').style.maxWidth = dev === 'mobile' ? '414px' : '100%';
    document.getElementById('devPc').className = dev === 'pc' ? 'on' : '';
    document.getElementById('devMobile').className = dev === 'mobile' ? 'on' : '';
}

ykvReload();
</script>
<?php
require dirname(__DIR__) . '/inc/footer.php';
