<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가

if(!function_exists('vpn_grade_badge_html')) {
    function vpn_grade_badge_html($grade) {
        $grade = strtoupper(trim((string)$grade));
        if($grade === '') return '';
        $c = array('BASIC'=>'#6c757d','PLUS'=>'#0d6efd','PRO'=>'#198754','ULTRA'=>'#6f42c1','MAX'=>'#dc3545');
        $bg = isset($c[$grade]) ? $c[$grade] : '#555';
        return '<span class="vpn-grade-badge" style="display:inline-block;padding:1px 8px;border-radius:0;font-size:11px;font-weight:700;letter-spacing:.4px;background:'.$bg.';color:#fff;margin-right:4px;vertical-align:middle;">'.htmlspecialchars($grade,ENT_QUOTES).'</span>';
    }
}
if(!function_exists('vpn_category_badge_html')) {
    function vpn_category_badge_html($spec_os) {
        $parts = explode('-', trim((string)$spec_os));
        $cat = strtoupper(trim($parts[0]));
        if($cat === '') return '';
        return '<span class="vpn-category-badge" style="display:inline-block;padding:1px 8px;border-radius:0;font-size:11px;font-weight:700;letter-spacing:.4px;background:#0891b2;color:#fff;margin-right:4px;vertical-align:middle;">'.htmlspecialchars($cat,ENT_QUOTES).'</span>';
    }
}

require_once(G5_PATH.'/mylib/rpc_grade.lib.php');

//자동높이조절
apms_script('imagesloaded');
apms_script('height');

// add_stylesheet('css 구문', 출력순서); 숫자가 작을 수록 먼저 출력됨
add_stylesheet('<link rel="stylesheet" href="'.$list_skin_url.'/style.css" media="screen">', 0);

// 버튼컬러
$btn1 = (isset($wset['btn1']) && $wset['btn1']) ? $wset['btn1'] : 'black';
$btn2 = (isset($wset['btn2']) && $wset['btn2']) ? $wset['btn2'] : 'color';

// 썸네일
$thumb_w = (isset($wset['thumb_w']) && $wset['thumb_w'] > 0) ? $wset['thumb_w'] : 400;
$thumb_h = (isset($wset['thumb_h']) && $wset['thumb_h'] > 0) ? $wset['thumb_h'] : 540;
$img_h = apms_img_height($thumb_w, $thumb_h, '135');

$wset['line'] = (isset($wset['line']) && $wset['line'] > 0) ? $wset['line'] : 2;
$line_height = 20 * $wset['line'];

// 간격
$gap_right = (isset($wset['gap']) && ($wset['gap'] > 0 || $wset['gap'] == "0")) ? $wset['gap'] : 15;
$minus_right = ($gap_right > 0) ? '-'.$gap_right : 0;

$gap_bottom = (isset($wset['gapb']) && ($wset['gapb'] > 0 || $wset['gapb'] == "0")) ? $wset['gapb'] : 30;
$minus_bottom = ($gap_bottom > 0) ? '-'.$gap_bottom : 0;

// 가로수
$item = (isset($wset['item']) && $wset['item'] > 0) ? $wset['item'] : 4;

// 반응형
if(_RESPONSIVE_) {
	$lg = (isset($wset['lg']) && $wset['lg'] > 0) ? $wset['lg'] : 3;
	$md = (isset($wset['md']) && $wset['md'] > 0) ? $wset['md'] : 3;
	$sm = (isset($wset['sm']) && $wset['sm'] > 0) ? $wset['sm'] : 2;
	$xs = (isset($wset['xs']) && $wset['xs'] > 0) ? $wset['xs'] : 2;
}

// 새상품
$is_new = (isset($wset['new']) && $wset['new']) ? $wset['new'] : 'red';
$new_item = ($wset['newtime']) ? $wset['newtime'] : 24;

// DC
$is_dc = (isset($wset['dc']) && $wset['dc']) ? $wset['dc'] : 'orangered';

// 그림자
$shadow_in = '';
$shadow_out = (isset($wset['shadow']) && $wset['shadow']) ? apms_shadow($wset['shadow']) : '';
if($shadow_out && isset($wset['inshadow']) && $wset['inshadow']) {
	$shadow_in = '<div class="in-shadow">'.$shadow_out.'</div>';
	$shadow_out = '';
}

$list_cnt = count($list);

include_once($list_skin_path.'/category.skin.php');
?>

<style>
	.list-wrap { margin-right:<?php echo $minus_right;?>px; margin-bottom:<?php echo $minus_bottom;?>px; }
	.list-wrap .item-row { width:<?php echo apms_img_width($item);?>%; }
	.list-wrap .item-list { margin-right:<?php echo $gap_right;?>px; margin-bottom:<?php echo $gap_bottom;?>px; }
	.list-wrap .item-name { height:<?php echo $line_height;?>px; }
	/* .list-wrap .img-wrap { padding-bottom:<?php echo $img_h;?>%; } */
	<?php if(_RESPONSIVE_) { // 반응형일 때만 작동 ?>
		<?php if($lg) { ?>
		@media (max-width:1199px) {
			.responsive .list-wrap .item-row { width:<?php echo apms_img_width($lg);?>%; }
		}
		<?php } ?>
		<?php if($md) { ?>
		@media (max-width:991px) {
			.responsive .list-wrap .item-row { width:<?php echo apms_img_width($md);?>%; }
		}
		<?php } ?>
		<?php if($sm) { ?>
		@media (max-width:767px) {
			.responsive .list-wrap .item-row { width:<?php echo apms_img_width($sm);?>%; }
		}
		<?php } ?>
		<?php if($xs) { ?>
		@media (max-width:480px) {
			.responsive .list-wrap .item-row { width:<?php echo apms_img_width($xs);?>%; }
		}
		<?php } ?>
	<?php } ?>
</style>

<style>
	/* Item Card Style */
	.item-card {
		border: 1px solid #eee;
		border-radius: 0;
		background: #fff;
		box-shadow: 0 4px 6px rgba(0,0,0,0.02);
		transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
		overflow: hidden;
		display: flex;
		flex-direction: row;
		height: 135px;
	}
	.item-card:hover {
		box-shadow: 0 10px 20px rgba(0,0,0,0.12);
		border-color: #ddd;
	}
	.item-card .item-image {
		width: 135px;
		flex: 0 0 135px;
		height: 135px;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fbfbfb;
		overflow: hidden;
	}
	.item-card .item-image > a {
		width: 100%;
		height: 100%;
		display: block;
	}
	.item-card .item-image .img-wrap {
		height: 100% !important;
		padding-bottom: 0 !important;
		position: relative;
	}
	.img-wrap.has-auction-overlay .label-tack { top: 36px; }
	/* 모던 배지 스타일 */
	.badge-stack {
		display: flex;
		flex-direction: column;
		gap: 3px;
		left: 0;
		top: 10px;
		z-index: 10;
		position: absolute;
	}
	.img-wrap.has-auction-overlay .badge-stack { top: 34px; }
	/* 경매 정보 바 (상태 + 타이머 한 줄 flex) */
	.auction-info-bar {
		position: absolute;
		top: 0; left: 0;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: rgba(0,0,0,0.58);
		padding: 4px 7px;
		box-sizing: border-box;
		z-index: 6;
		gap: 6px;
	}
	.auction-status-label {
		color: #4ade80;
		font-size: 1.05rem;
		font-weight: 700;
		text-shadow: 0 1px 3px rgba(0,0,0,0.9);
		white-space: nowrap;
		flex-shrink: 0;
	}
	.auction-info-bar .auction_remain_timer {
		color: #cbd5e1;
		font-size: 1rem;
		font-weight: normal;
		text-shadow: 0 1px 2px rgba(0,0,0,0.9);
		text-align: right;
		min-width: 0;
		white-space: nowrap;
	}
	.it-badge {
		display: inline-block;
		font-size: 11px;
		font-weight: 700;
		letter-spacing: 0.4px;
		padding: 3px 8px 3px 5px;
		border-radius: 0 4px 4px 0;
		line-height: 1.4;
		color: #fff;
		text-shadow: 0 1px 2px rgba(0,0,0,0.25);
		box-shadow: 1px 1px 4px rgba(0,0,0,0.22);
		white-space: nowrap;
	}
	.badge-soldout { background: linear-gradient(135deg,#64748b,#475569); }
	.badge-rec     { background: linear-gradient(135deg,#2563eb,#1d4ed8); }
	.badge-new     { background: linear-gradient(135deg,#059669,#047857); }
	.badge-best    { background: linear-gradient(135deg,#d97706,#b45309); }
	.badge-dc      { background: linear-gradient(135deg,#dc2626,#b91c1c); }
	.badge-cp      { background: linear-gradient(135deg,#7c3aed,#6d28d9); }
	.badge-hit     { background: linear-gradient(135deg,#db2777,#be185d); }
	.item-card .item-image .img-item {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-card .item-image img {
		max-width: 100%;
		max-height: 100%;
		width: auto;
		height: auto;
		object-fit: contain;
	}
	.item-card .item-content {
		flex: 1;
		padding: 7px 10px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		min-width: 0;
		max-width: calc(100% - 135px);		max-height: 135px;		overflow: hidden;
	}
	.item-card .item-name {
		margin-bottom: 0;
		font-size: 15px;
		line-height: 1.3;
		display: none;
	}
	.item-name-overlay {
		position: absolute;
		top: 10px;
		left: 50%;
		transform: translateX(-50%);
		text-align: center;
		font-weight: bold;
		font-size: 16px;
		color: #fff;
		z-index: 5;
		text-shadow: 1px 1px 3px rgba(0,0,0,0.8);
		white-space: nowrap;
	}

	.list-specs {
		flex: 1;
		min-height: 0;
		overflow: hidden;
	}
	.list-specs a, .list-specs a:focus, .list-specs a:active { outline: none; }
	.item-specs-table {
		width: 100%;
		margin: 0;
		border-collapse: collapse;
		font-size: 11.5px;
		color: #444;
		table-layout: auto;
	}
	.item-specs-table th, .item-specs-table td {
		padding: 0;
		border-bottom: 1px solid #f0f0f0;
		text-align: left;
		vertical-align: middle;
		line-height: 1.2;
	}
	.item-specs-table.vpn-item tr:not(:first-child) th,
	.item-specs-table.vpn-item tr:not(:first-child) td {
		padding: 0;
		line-height: 1.6;
	}
	.item-specs-table th {
		font-weight: 600;
		color: #777;
		font-size: 9px;
		text-transform: uppercase;
		letter-spacing: 0.3px;
		white-space: nowrap;
	}
	.item-specs-table th.spec-label {
		width: 1%;
		padding-right: 6px;
		white-space: nowrap;
	}
	.item-specs-table td {
		text-align: left;
		color: #222;
		font-weight: 500;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	.item-specs-table .spec-full {
		text-align: left;
		padding: 0;
		color: #111;
		font-weight: 700;
		font-size: 11.5px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	.item-specs-table .spec-title-with-location {
		display: flex;
		align-items: center;
		gap: 8px;
		flex-wrap: nowrap;
	}
	.item-specs-table .spec-location {
		display: inline-flex;
		align-items: center;
		gap: 4px;
		font-size: 11.5px;
		font-weight: 500;
		color: #555;
		white-space: nowrap;
		flex-shrink: 0;
	}
	.item-specs-table tr:last-child th, .item-specs-table tr:last-child td {
		border-bottom: none;
	}

	/* Price Section */
	.item-card .item-price {
		margin-top: 2px;
		padding-top: 3px;
		border-top: 2px solid #f0f0f0;
		text-align: left;
		flex-shrink: 0;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		min-width: 0;
		max-width: 100%;
	}
	.item-card .item-price b {
		font-size: 13.5px;
		font-weight: 700;
		color: #0063ff;
		letter-spacing: -0.3px;
	}
	.item-card .item-price small {
		font-size: 10px;
		color: #888;
		margin-left: 2px;
		font-weight: 400;
	}
	.item-card .item-price .item-sp {
		display: inline-block;
		margin-left: 3px;
		font-size: 9px;
		line-height: 1.2;
		padding: 1px 3px;
		border-radius: 0;
		background: #f8f9fa;
		cursor: help;
	}
	.item-card .item-price .item-sp.blue {
		background: #e3f2fd;
		color: #1976d2;
	}
	.item-card .item-price .item-sp.green {
		background: #e8f5e9;
		color: #388e3c;
	}
	.item-card .item-price .item-sp.darkgray {
		background: #f5f5f5;
		color: #666;
	}
	.item-card .item-price .product-price-usage {
		margin-bottom: 4px;
	}

	.item-card .item-content .item-star {
		display: none;
	}
	.item-card .item-details {
		display: none;
	}
	.item-card .item-price {
		margin-top: 0 !important;
	}

	.nation_flag_img2 {
		width: 20px;
		height: 14px;
		margin-left: 0;
		margin-right: 4px;
		vertical-align: middle;
		border-radius: 0;
		box-shadow: 0 1px 2px rgba(0,0,0,0.1);
	}

	@media screen and (max-width: 991px) {
		.item-card {
			height: 120px;
		}
		.item-card .item-image {
			width: 120px;
			flex: 0 0 120px;
			height: 120px;
		}
		.item-specs-table {
			font-size: 11px;
		}
		.item-card .item-price b {
			font-size: 15px;
		}
	}

	@media screen and (max-width: 767px) {
		.item-card {
			height: 110px;
		}
		.item-card .item-image {
			width: 110px;
			flex: 0 0 110px;
			height: 110px;
		}
		.item-card .item-content {
			padding: 8px 10px;
		}
		.item-specs-table {
			font-size: 10px;
		}
		.item-specs-table th.spec-label {
			width: 42px;
		}
		.item-card .item-price b {
			font-size: 14px;
		}
		.nation_flag_img2 {
			width: 18px;
			height: 12px;
		}
	}
</style>
<?php
$_is_auction_list = ($list_cnt > 0 && isset($list[0]['ca_id']) && $list[0]['ca_id'] == '20')
                 || (isset($ca_id) && $ca_id == '20');
if($_is_auction_list): ?>
<style>
/* ── 통합 경매 컨트롤 패널 (list-sort 스타일 일치) ── */
#auction-ctrl-panel {
    display:flex; align-items:center; flex-wrap:wrap; gap:6px;
    width:100%; box-sizing:border-box;
    border-top:1px solid #edf2f8; padding-top:10px; margin-top:4px;
}
.acp-row-1 {
    display:flex; align-items:center; justify-content:space-between;
    flex-wrap:wrap; gap:8px;
    padding-bottom:10px;
    border-bottom:1px solid #edf2f8;
    margin-bottom:8px;
}
.acp-nav-group { display:flex; flex-wrap:wrap; gap:6px; }
.acp-sort-group { display:flex; align-items:center; align-self:center; gap:6px; flex-wrap:wrap; margin-left:auto; }
/* 내 입찰만 체크박스 — 차별화 스타일 */
.acp-mybid-lbl {
    display:inline-flex !important; align-items:center; align-self:center; gap:5px;
    height:28px; padding:0 11px; box-sizing:border-box; margin:0;
    border:1.5px solid #4c6fa7;
    background:#edf4ff; color:#2d5fa7;
    font-size:12px; font-weight:700;
    cursor:pointer; user-select:none; white-space:nowrap;
    transition:all .15s;
}
.acp-mybid-lbl:hover { background:#dce9ff; }
.acp-mybid-lbl input[type="checkbox"] {
    width:13px; height:13px; cursor:pointer;
    accent-color:#4c6fa7; margin:0; flex-shrink:0;
}
.acp-mybid-lbl:has(input:checked) {
    background:#4c6fa7; border-color:#4c6fa7; color:#fff;
}
/* nav 버튼: oi-sort-chip 동일 스타일 */
.acp-nav-btn {
    display:inline-flex; align-items:center;
    padding:4px 10px; border:1px solid #d8e0ec; border-radius:0;
    background:#fff; color:#4b5f79;
    font-size:12px; font-weight:600; line-height:1.3;
    cursor:pointer; transition:all .16s ease; white-space:nowrap;
}
.acp-nav-btn:hover { background:#eef4ff; border-color:#9db2d7; color:#2d4a78; }
.acp-nav-btn.anb-list   {}
.acp-nav-btn.anb-active {}
.acp-nav-btn.anb-ending {}
.acp-nav-btn.anb-mybids {}
/* 정렬 칩: oi-sort-chip 동일 */
.acp-sort-chip {
    display:inline-flex; align-items:center;
    padding:4px 10px; border:1px solid #d8e0ec; border-radius:0;
    background:#fff; color:#4b5f79;
    font-size:12px; font-weight:600; line-height:1.3;
    text-decoration:none; transition:all .16s ease; white-space:nowrap;
    cursor:pointer;
}
.acp-sort-chip:hover { background:#eef4ff; border-color:#9db2d7; color:#2d4a78; text-decoration:none; }
.acp-sort-chip.on { background:#4c6fa7; border-color:#4c6fa7; color:#fff !important; font-weight:700; box-shadow:0 2px 8px rgba(62,94,150,.22); }
    /* 정렬 페어 버튼 (라벨 + ▲▼) */
    .acp-sort-pair {
        display:inline-flex; align-items:stretch;
        height:28px; box-sizing:border-box;
        border:1px solid #d8e0ec;
        font-size:12px; font-weight:600; color:#4b5f79;
        white-space:nowrap;
    }
    .acp-sp-label {
        display:flex; align-items:center;
        padding:0 5px 0 9px;
        background:#fff; user-select:none;
    }
    .acp-sp-tris {
        display:flex; flex-direction:row;
        border-left:1px solid #e5eaf2;
    }
    .asp-t {
        display:flex; align-items:center; justify-content:center;
        background:#fff; border:none; cursor:pointer;
        color:#c4ccd8; font-size:8px; line-height:1;
        padding:0 4px; margin:0; text-decoration:none;
        transition:color .12s, background .12s;
    }
    .asp-t:first-child { border-right:1px solid #e5eaf2; }
    .asp-t:hover { color:#4c6fa7; background:#eef3fc; }
    .asp-t.on { color:#fff; background:#4c6fa7; }
/* 상태 필터 바: oi-plan-chip 동일 */
#auction-filter-bar {
    display:flex; align-items:center; align-self:center; flex-wrap:nowrap; gap:6px;
    height:28px; padding:0; margin:0; border-bottom:none;
}
#auction-filter-bar .af-title {
    color:#4a5568; font-weight:700; font-size:13px;
    margin-right:2px; white-space:nowrap;
}
.af-btn {
    display:inline-flex; align-items:center; gap:4px;
    height:28px; padding:0 10px; box-sizing:border-box;
    border:1px solid #cfd8e3; border-radius:0;
    background:#f9fbff; color:#40546e;
    font-size:12px; font-weight:600;
    cursor:pointer; transition:all .16s ease; white-space:nowrap;
}
.af-btn:hover { border-color:#96abd1; background:#eef4ff; color:#2e4466; }
.af-btn.active { background:#4c6fa7; border-color:#4c6fa7; color:#fff; font-weight:700; }
.af-btn.active::before { content:'✓ '; font-size:11px; }
.af-btn.active .af-count { background:rgba(255,255,255,.23); color:#fff; }
.af-btn[data-status="경매진행중"].active  { background:#4c6fa7; border-color:#4c6fa7; }
.af-btn[data-status="경매시작전"].active  { background:#4c6fa7; border-color:#4c6fa7; }
.af-btn[data-status="경매종료[낙찰]"].active { background:#4c6fa7; border-color:#4c6fa7; }
.af-btn[data-status="경매종료[유찰]"].active { background:#4c6fa7; border-color:#4c6fa7; }
.af-count {
    display:inline-flex; align-items:center; justify-content:center;
    min-width:20px; height:20px; padding:0 6px; border-radius:0;
    background:#edf1f7; color:#4b627f;
    font-size:11px; font-weight:700;
}
#af-no-result {
    display:none; width:100%; padding:30px;
    text-align:center; color:#9ca3af; font-size:14px;
}
@media(max-width:767px) {
    #auction-ctrl-panel { gap:4px; }
    .acp-sort-group { justify-content:flex-end; margin-left:0; }
}
/* ── 경매 컨트롤 패널 다크모드 ── */
[data-site-theme="dark"] #auction-ctrl-panel { border-top-color:#3a3a42; }
[data-site-theme="dark"] .acp-row-1 { border-bottom-color:#3a3a42; }
[data-site-theme="dark"] .acp-mybid-lbl { background:#1e2a3a; border-color:#4c6fa7; color:#90afd4; }
[data-site-theme="dark"] .acp-mybid-lbl:hover { background:#253348; }
[data-site-theme="dark"] .acp-mybid-lbl:has(input:checked) { background:#3b5fa3; border-color:#3b5fa3; color:#fff; }
[data-site-theme="dark"] .acp-nav-btn { background:#252528; border-color:#3a3a42; color:#a1a1aa; }
[data-site-theme="dark"] .acp-nav-btn:hover { background:#2c2c3a; border-color:#4a5a6e; color:#c4c4cc; }
[data-site-theme="dark"] .acp-sort-chip { background:#252528; border-color:#3a3a42; color:#a1a1aa; }
[data-site-theme="dark"] .acp-sort-chip:hover { background:#2c2c3a; border-color:#4a5a6e; color:#c4c4cc; }
[data-site-theme="dark"] .acp-sort-chip.on { background:#3b5fa3; border-color:#3b5fa3; color:#fff !important; }
[data-site-theme="dark"] .acp-sort-pair { border-color:#3a3a42; color:#a1a1aa; }
[data-site-theme="dark"] .acp-sp-label { background:#252528; color:#a1a1aa; }
[data-site-theme="dark"] .acp-sp-tris { border-left-color:#3a3a42; }
[data-site-theme="dark"] .asp-t { background:#252528; color:#52525e; border-color:#3a3a42; }
[data-site-theme="dark"] .asp-t:first-child { border-right-color:#3a3a42; }
[data-site-theme="dark"] .asp-t:hover { background:#2c2c3a; color:#90afd4; }
[data-site-theme="dark"] .asp-t.on { background:#3b5fa3; color:#fff; }
[data-site-theme="dark"] #auction-filter-bar .af-title { color:#a1a1aa; }
[data-site-theme="dark"] .af-btn { background:#252528; border-color:#3a3a42; color:#a1a1aa; }
[data-site-theme="dark"] .af-btn:hover { background:#2c2c3a; border-color:#4a5a6e; color:#c4c4cc; }
[data-site-theme="dark"] .af-btn.active { background:#3b5fa3; border-color:#3b5fa3; color:#fff; }
[data-site-theme="dark"] .af-count { background:#2d2d34; color:#8899aa; }
[data-site-theme="dark"] .af-btn.active .af-count { background:rgba(255,255,255,.2); color:#fff; }
</style>
<?php
$_acp_get = $_GET;
unset($_acp_get['sort'], $_acp_get['sortodr'], $_acp_get['page']);
$_acp_sort_href = '?' . (empty($_acp_get) ? '' : http_build_query($_acp_get) . '&') . 'sort=';
$_acp_sort    = isset($sort)    ? $sort    : (isset($_GET['sort'])    ? $_GET['sort']    : '');
$_acp_sortodr = isset($sortodr) ? $sortodr : (isset($_GET['sortodr']) ? $_GET['sortodr'] : 'desc');
// 경매 등급/종류 필터 변수 (category.skin.php에서 주입됨, 없으면 기본값)
if (!isset($oi_grade_filter))    $oi_grade_filter    = '';
if (!isset($oi_grade_options))   $oi_grade_options   = array('' => '등급 전체', 'BASIC' => 'BASIC', 'PLUS' => 'PLUS', 'PRO' => 'PRO', 'ULTRA' => 'ULTRA', 'MAX' => 'MAX');
if (!isset($oi_grade_colors))    $oi_grade_colors    = array('BASIC' => '#6c757d', 'PLUS' => '#0d6efd', 'PRO' => '#198754', 'ULTRA' => '#6f42c1', 'MAX' => '#dc3545');
if (!isset($oi_grade_counts))    $oi_grade_counts    = array();
if (!isset($oi_subtype_filter))  $oi_subtype_filter  = '';
if (!isset($oi_subtype_options)) $oi_subtype_options = array();
if (!isset($oi_subtype_counts))  $oi_subtype_counts  = array();
$_acp_grade_href_base = '?';
$_acp_grade_params = $_GET;
unset($_acp_grade_params['grade'], $_acp_grade_params['page']);
if (!empty($_acp_grade_params)) $_acp_grade_href_base .= http_build_query($_acp_grade_params) . '&';
$_acp_subtype_href_base = '?';
$_acp_subtype_params = $_GET;
unset($_acp_subtype_params['subtype'], $_acp_subtype_params['page']);
if (!empty($_acp_subtype_params)) $_acp_subtype_href_base .= http_build_query($_acp_subtype_params) . '&';
?>
<div class="list-sort">
<?php if (count($oi_subtype_options) > 1): ?>
<div class="oi-subtype-filter-inline" style="border-top:none; margin-top:0; padding-top:0;">
    <span class="oi-grade-label">상품종류</span>
    <?php foreach ($oi_subtype_options as $sk => $sl) {
        $sis = ($oi_subtype_filter === (string)$sk);
        $scount = isset($oi_subtype_counts[$sk]) ? (int)$oi_subtype_counts[$sk] : 0;
        $s_href = ($sk === '')
            ? $_acp_subtype_href_base . 'ca_id=' . urlencode(isset($ca_id) ? $ca_id : '')
            : $_acp_subtype_href_base . 'ca_id=' . urlencode(isset($ca_id) ? $ca_id : '') . '&subtype=' . urlencode($sk);
    ?>
    <a class="oi-grade-chip<?php echo $sis ? ' is-active' : ''; ?>" href="<?php echo htmlspecialchars($s_href, ENT_QUOTES); ?>">
        <span><?php echo htmlspecialchars($sl, ENT_QUOTES); ?></span>
        <span class="oi-menu-count-badge"><?php echo number_format($scount); ?></span>
    </a>
    <?php } ?>
</div>
<?php endif; ?>
<div class="oi-grade-filter-inline"<?php if (count($oi_subtype_options) <= 1) echo ' style="border-top:none;margin-top:0;padding-top:0;"'; ?>>
    <span class="oi-grade-label">상품등급</span>
    <?php foreach ($oi_grade_options as $agk => $agl) {
        $ag_is = ($oi_grade_filter === $agk);
        $ag_count = isset($oi_grade_counts[$agk]) ? (int)$oi_grade_counts[$agk] : 0;
        $ag_href = $agk === '' ? $_acp_grade_href_base . 'ca_id=' . urlencode(isset($ca_id) ? $ca_id : '') : $_acp_grade_href_base . 'ca_id=' . urlencode(isset($ca_id) ? $ca_id : '') . '&grade=' . urlencode($agk);
        $ag_active_style = '';
        if ($ag_is && $agk !== '' && isset($oi_grade_colors[$agk])) {
            $gc = $oi_grade_colors[$agk];
            $ag_active_style = ' style="background:'.$gc.';border-color:'.$gc.';"';
        }
    ?>
    <a class="oi-grade-chip<?php echo $ag_is ? ' is-active' : ''; ?>" href="<?php echo htmlspecialchars($ag_href, ENT_QUOTES); ?>"
       <?php echo $ag_active_style; ?>>
        <?php if ($agk !== '' && isset($oi_grade_colors[$agk])) echo '<span class="grade-dot" style="background:'.htmlspecialchars($oi_grade_colors[$agk],ENT_QUOTES).';"></span>'; ?>
        <span><?php echo htmlspecialchars($agl, ENT_QUOTES); ?></span>
        <span class="oi-menu-count-badge"><?php echo number_format($ag_count); ?></span>
    </a>
    <?php } ?>
    <span class="oi-grade-guide-btn" id="oi-grade-guide-btn-acp"
          onclick="(function(){var w=document.getElementById('oi-grade-info-wrap-acp');var b=document.getElementById('oi-grade-guide-btn-acp');var o=w.classList.toggle('open');b.classList.toggle('open',o);b.innerHTML=o?'✕ 닫기':'ⓘ 등급 안내';})();">ⓘ 등급 안내</span>
</div>
<?php if (isset($_gi_grades) && is_array($_gi_grades)): ?>
<div class="oi-grade-info-wrap" id="oi-grade-info-wrap-acp">
    <div class="oi-grade-info-card">
        <div class="ogi-header">
            <span class="ogi-title">📊 상품등급 안내</span>
            <span class="ogi-criteria">📌 <?php echo htmlspecialchars(isset($_gi_criteria) ? $_gi_criteria : '', ENT_QUOTES); ?></span>
        </div>
        <div class="ogi-flow">
            <?php $gi_first2 = true; foreach ($_gi_grades as $gk2 => $gv2) { ?>
            <?php if (!$gi_first2) echo '<span class="ogi-arrow">›</span>'; $gi_first2 = false; ?>
            <div class="ogi-step">
                <span class="ogi-badge" style="background:<?php echo $gv2['color']; ?>;"><?php echo htmlspecialchars($gk2, ENT_QUOTES); ?></span>
                <span class="ogi-kor"><?php echo htmlspecialchars($gv2['kor'], ENT_QUOTES); ?></span>
                <span class="ogi-desc"><?php echo htmlspecialchars($gv2['desc'], ENT_QUOTES); ?></span>
            </div>
            <?php } ?>
        </div>
        <div class="ogi-direction">
            <span class="ogi-dir-low">낮음 ◀</span>
            <div class="ogi-dir-bar"></div>
            <span class="ogi-dir-high">▶ 높음</span>
        </div>
        <div class="ogi-note">※ RPC 경매 상품등급은 CPU 성능 · RAM 용량 · SSD/HDD 저장 용량 등 하드웨어 사양을 기준으로 자동 산정됩니다.</div>
    </div>
</div>
<?php endif; ?>
<div id="auction-ctrl-panel">
    <label class="acp-mybid-lbl" for="chk-my-bid">
        <input type="checkbox" id="chk-my-bid"> 내 입찰만
    </label>
    <div id="auction-filter-bar">
        <button class="af-btn af-all active" data-status="all">전체&nbsp;<span class="af-count" id="afc-all">0</span></button>
        <button class="af-btn" data-status="경매진행중">진행중&nbsp;<span class="af-count" id="afc-prog">0</span></button>
        <button class="af-btn" data-status="경매시작전">시작전&nbsp;<span class="af-count" id="afc-wait">0</span></button>
        <button class="af-btn" data-status="경매종료[낙찰]">낙찰&nbsp;<span class="af-count" id="afc-win">0</span></button>
        <button class="af-btn" data-status="경매종료[유찰]">유찰&nbsp;<span class="af-count" id="afc-lose">0</span></button>
        <button class="af-btn" data-status="경매취소">취소&nbsp;<span class="af-count" id="afc-cancel">0</span></button>
    </div>
    <div class="acp-sort-group">
        <div class="acp-sort-pair">
            <span class="acp-sp-label">최근순</span>
            <div class="acp-sp-tris">
                <a class="asp-t<?php echo ($_acp_sort==='it_update_time' && $_acp_sortodr==='desc') ? ' on' : ''; ?>" href="<?php echo $_acp_sort_href; ?>it_update_time&sortodr=desc" id="asort-recent-desc">▲</a>
                <a class="asp-t<?php echo ($_acp_sort==='it_update_time' && $_acp_sortodr==='asc') ? ' on' : ''; ?>" href="<?php echo $_acp_sort_href; ?>it_update_time&sortodr=asc" id="asort-recent-asc">▼</a>
            </div>
        </div>
        <div class="acp-sort-pair">
            <span class="acp-sp-label">마감 임박</span>
            <div class="acp-sp-tris">
                <button class="asp-t" id="asort-deadline-desc" type="button">▲</button>
                <button class="asp-t" id="asort-deadline-asc"  type="button">▼</button>
            </div>
        </div>
        <div class="acp-sort-pair">
            <span class="acp-sp-label">시작가</span>
            <div class="acp-sp-tris">
                <button class="asp-t" id="asort-origin-desc" type="button">▲</button>
                <button class="asp-t" id="asort-origin-asc"  type="button">▼</button>
            </div>
        </div>
        <div class="acp-sort-pair">
            <span class="acp-sp-label">현재가</span>
            <div class="acp-sp-tris">
                <button class="asp-t" id="asort-cur-desc" type="button">▲</button>
                <button class="asp-t" id="asort-cur-asc"  type="button">▼</button>
            </div>
        </div>
        <div class="acp-sort-pair">
            <span class="acp-sp-label">즉시구매가</span>
            <div class="acp-sp-tris">
                <button class="asp-t" id="asort-buynow-desc" type="button">▲</button>
                <button class="asp-t" id="asort-buynow-asc"  type="button">▼</button>
            </div>
        </div>
    </div>
</div>
</div>
<?php endif; ?>
<div class="list-wrap">
	<?php
	// 리스트
	for ($i=0; $i < $list_cnt; $i++) {

		// 경매상품이면 상품상세페이지 URL이 다르므로 변경시켜 줌 convertUrl() 함수는 이 파일 하단에 있음 JSLEE {
		if ($list[$i]['ca_id'] == '20') {
			$list[$i]['href'] = convertUrl($list[$i]['href']);
		}
		// 경매상품이면 상품상세페이지 URL이 다르므로 변경시켜 줌 convertUrl() 함수는 이 파일 하단에 있음 JSLEE }

		// DC
		$cur_price = $dc_per = '';
		if($list[$i]['it_cust_price'] > 0 && $list[$i]['it_price'] > 0) {
			$cur_price = '<strike>&nbsp;'.number_format($list[$i]['it_cust_price']).'&nbsp;</strike>';
			$dc_per = round((($list[$i]['it_cust_price'] - $list[$i]['it_price']) / $list[$i]['it_cust_price']) * 100);
		}

		// 라벨 (모던 배지 스팬)
		$item_label = '';
		if($dc_per || $list[$i]['it_type5']) {
			$item_label = '<span class="it-badge badge-dc">DC</span>';
		} else if($list[$i]['it_type3'] || $list[$i]['pt_num'] >= (G5_SERVER_TIME - ($new_item * 3600))) {
			$item_label = '<span class="it-badge badge-new">New</span>';
		}

		// 아이콘 (모던 배지 — item_label 스팬과 합쳐서 하나의 badge-stack으로 출력)
		$_raw_icon = item_icon($list[$i]);
		$_badge_map = [
			'icon_hit.gif'      => ['인기', 'badge-hit'],
			'icon_rec.gif'      => ['추천', 'badge-rec'],
			'icon_new.gif'      => ['NEW',  'badge-new'],
			'icon_best.gif'     => ['BEST', 'badge-best'],
			'icon_discount.gif' => ['DC',   'badge-dc'],
			'icon_cp.gif'       => ['쿠폰', 'badge-cp'],
			'icon_soldout.gif'  => ['품절', 'badge-soldout'],
		];
		$_badges = $item_label; // label(DC/New) 먼저
		foreach ($_badge_map as $_gif => $_bi) {
			if ($list[$i]['ca_id'] == '20' && $_gif === 'icon_soldout.gif') continue;
			if (strpos($_raw_icon, $_gif) !== false)
				$_badges .= '<span class="it-badge '.$_bi[1].'">'.$_bi[0].'</span>';
		}
		$item_icon = $_badges ? '<div class="label-tack badge-stack">'.$_badges.'</div>' : '';
		$item_label = ''; // badge-stack에 합쳤으므로 개별 출력 불필요

		// 이미지
		$img = apms_it_thumbnail($list[$i], $thumb_w, $thumb_h, false, true);

	?>
		<div class="item-row"<?php if($list[$i]['ca_id']=='20' && !empty($list[$i]['last_auction_status'])) { echo ' data-auction-status="'.htmlspecialchars($list[$i]['last_auction_status']).'"'; echo ' data-start-price="'.intval($list[$i]['last_auction_price']).'"'; echo ' data-origin-price="'.intval($list[$i]['origin_start_price']).'"'; echo ' data-buynow-price="'.intval($list[$i]['buy_it_now_price']).'"'; echo ' data-my-bid="'.intval($list[$i]['my_bid']).'"'; } ?>>
			<div class="item-list item-card">
				<div class="item-image">
					<a href="<?php echo $list[$i]['href'];?>">
						<div class="img-wrap<?php echo $list[$i]['rpc_auction_expire_date'] ? ' has-auction-overlay' : ''; ?>">
							<?php echo $shadow_in;?>
							<?php echo $item_label;?>
							<?php echo $item_icon;?>
							<div class="img-item">
								<img src="<?php echo $img['src'];?>" alt="<?php echo $img['alt'];?>">
								<?php if ($list[$i]['rpc_auction_expire_date']) { ?>
									<div class="auction-info-bar">
										<span class="auction-status-label"><?php echo $list[$i]['last_auction_status_display']?></span>
										<span class="auction_remain_timer" data-expire-time="<?php echo $list[$i]['rpc_auction_term_stop'] ?>"></span>
									</div>
									<!--
									<div class="overlay-text" style="position: absolute; top: 35px; left: 50%; transform: translate(-50%, -50%); color: silver; font-size: 0.9rem; font-weight: normal; text-shadow: 2px 2px 4px rgba(0, 0, 0, 1); white-space: nowrap; text-align:center; width:98%;">
										<?php
											$auction_hours = (int)(isset($list[$i]['rpc_rental_hours']) ? $list[$i]['rpc_rental_hours'] : $list[$i]['rpc_rental_days']);
											echo "즉시구매가 ".number_format($list[$i]['buy_it_now_price'])." Point / ".apms_contract_hours_text($auction_hours);
										?>
									</div>
									-->
									<div class="overlay-text" style="position: absolute; bottom: -10px; left: 50%; transform: translate(-50%, -50%); color: silver; font-size: 0.9rem; font-weight: normal; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); white-space: nowrap; text-align:left; width:98%; padding:2px 5px;">
										<?php echo get_pt_seller_name($list[$i]['pt_id']); ?>
									</div>
									<div class="overlay-text" style="position: absolute; bottom: -10px; left: 50%; transform: translate(-50%, -50%); color: silver; font-size: 0.9rem; font-weight: normal; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); white-space: nowrap; text-align:right; width:98%; padding:2px 5px;">
										<?php // echo "매너온도 " . get_pt_manner_temperature($list[$i]['pt_id']); ?>
										<?php echo apms_get_star($list[$i]['it_use_avg'], $wset['star']); ?>

									</div>
								<?php } else { ?>
									<div class="overlay-text" style="position: absolute; bottom: -10px; left: 50%; transform: translate(-50%, -50%); color: silver; font-size: 0.9rem; font-weight: normal; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); white-space: nowrap; text-align:left; width:98%; padding:2px 5px;">
										<?php echo get_pt_seller_name($list[$i]['pt_id']); ?>
									</div>
									<div class="overlay-text" style="position: absolute; bottom: -10px; left: 50%; transform: translate(-50%, -50%); color: silver; font-size: 0.9rem; font-weight: normal; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); white-space: nowrap; text-align:right; width:98%; padding:2px 5px;">
										<?php // echo "매너온도 " . get_pt_manner_temperature($list[$i]['pt_id']); ?>
										<?php echo apms_get_star($list[$i]['it_use_avg'], $wset['star']); ?>
									</div>
								<?php } ?>
							</div>
						</div>
					</a>
					<?php // echo $shadow_out;?>
				</div>
				<div class="item-content">
					<?php if($wset['star']) { /* ?>
						<div class="item-star" style="font-size:1.25rem;">
							<?php echo get_pt_seller_name($list[$i]['pt_id']) . " " . apms_get_star($list[$i]['it_use_avg'], $wset['star']); //평균별점 ?>
						</div>
					<?php */ } ?>

					<div class="list-specs">
						<a href="<?php echo $list[$i]['href'];?>">
							<table class="item-specs-table">
								<?php
								$is_vpn_item = (stripos(trim($list[$i]['it_name']), 'VPN') === 0) || (stripos(trim($list[$i]['it_id']), 'VPN') === 0) || (isset($api_data) && stripos(trim($api_data['it_name']), 'VPN') === 0);
								if($is_vpn_item){
									$headers = ["", "요금제"];
								}else{
									$headers = ["", "CPU", "GPU", "IP", "RAM", "SSD", "HDD", "USB"];
								}
								$rows = [];

								$result_api_data = sql_query("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id='{$list[$i]['it_id']}' ORDER BY it_id DESC LIMIT 1");
								while($api_data = sql_fetch_array($result_api_data)){
									$it_id = $api_data['it_id'];
									$it_origin_mgr_from_api = $api_data['it_origin_mgr_from_api'];
									$M_storeid = explode("Ž",$api_data['it_origin_mgr_from_api'])[0]." ".explode("Ž",$api_data['it_origin_mgr_from_api'])[1];
									$M_storename = explode("Ž",$api_data['it_origin_mgr_from_api'])[2];
									// $extIP = $api_data['extIP'];
									// JSON 데이터
									$jsonData_it_spec_remote_sw = $api_data['it_spec_remote_sw'];

									// JSON 데이터를 배열로 디코드
									$dataArray_it_spec_remote_sw = json_decode($jsonData_it_spec_remote_sw, true);

									// RemoteIP 값을 추출하여 $extIP 변수에 저장
									$extIP = isset($dataArray_it_spec_remote_sw[0]['RemoteIP__0']) ? $dataArray_it_spec_remote_sw[0]['RemoteIP__0'] : null;
									$remote_ip_org = explode(" ", $extIP)[0];
									$remote_ip_parts = explode(".", $remote_ip_org); // IP 주소를 점(.)으로 분리
									// 각 부분을 3자리로 맞추기 위해 앞에 0을 추가
									foreach ($remote_ip_parts as &$part) {
										$part = str_pad($part, 3, '0', STR_PAD_LEFT);
									}
									// 마스킹할 부분을 선택
									$remote_ip_parts[1] = '***';
									$remote_ip_parts[3] = '***';
									// 마스킹된 IP 주소를 다시 조합
									$masked_ip = implode(".", $remote_ip_parts);
									$remote_ip = $masked_ip; // 출력: 111.***.022.***

									$remote_ip_country_code = strtolower($dataArray_it_spec_remote_sw[0]['RemoteIP_CountryCode__0']);
									$remote_ip_country_name = $dataArray_it_spec_remote_sw[0]['RemoteIP_CountryName__0'];
									$remote_ip_city_name = $dataArray_it_spec_remote_sw[0]['RemoteIP_City__0'];
									$remote_ip_country_flag = "<img src='" . G5_DATA_URL . "/item/img_nation_flag/svg/{$remote_ip_country_code}.svg' class='nation_flag_img2'>";

									//$it_spec_cpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)", "Intel", "AMD", "with Radeon Graphics", "with Radeon Vega Graphics", "CPU", "Core ", " Cores", "Eight-Processor"), array("", "", "", "", "", "", "", "", "C", ""), $api_data['it_spec_cpu'])));
									$it_spec_cpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)", "with Radeon Graphics", "with Radeon Vega Graphics", "CPU", "Core ", "Eight-Processor"), array("", "", "", "", "", "", ""), $api_data['it_spec_cpu'])));
									if (count($it_spec_cpu_arr) == 1) {
										$it_spec_cpu = $it_spec_cpu_arr[0];
									} else if (count($it_spec_cpu_arr) == 2) {
										$it_spec_cpu = "[Dual] " . $it_spec_cpu_arr[0];
									} else if (count($it_spec_cpu_arr) == 3) {
										$it_spec_cpu = "[Triple] " . $it_spec_cpu_arr[0];
									} else if (count($it_spec_cpu_arr) == 4) {
										$it_spec_cpu = "[Quad] " . $it_spec_cpu_arr[0];
									}
									if (stripos($it_spec_cpu, 'intel') !== false) {
										$logo_cpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_intel.png' class='cpu_logo_img2'>";
									} else if (stripos($it_spec_cpu, 'amd') !== false) {
										$logo_cpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_amd.png' class='cpu_logo_img2'>";
									} else {
										$logo_cpu = "";
									}

									// CPU 데이터
									$cpu_data = $api_data['it_spec_cpu'];

									// 정규식을 사용하여 괄호 속에 "Cores"라는 단어가 포함된 숫자를 추출
									if (preg_match('/\((\d+) Cores\)/', $cpu_data, $matches)) {
										// 추출된 숫자를 $cpu_core 변수에 저장
										$cpu_core = $matches[1];
									} else {
										// "Cores"가 포함된 문자열이 없는 경우
										$cpu_core = null;
									}
									$it_spec_mainboard = $api_data['it_spec_mainboard'];
									$it_spec_ram = $api_data['it_spec_ram'];
									$it_spec_ram_type = $api_data['it_spec_ram_type'];
									//$SSDinfo = $api_data['SSDinfo'];
									$it_spec_ssd =  $api_data['it_spec_ssd'] === "0 GB" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : $api_data['it_spec_ssd'];
									$it_spec_ssd_type = $api_data['it_spec_ssd_type'];
									//$SSD = $api_data['SSD'];
									//$HDDinfo = $api_data['HDDinfo'];
									$it_spec_hdd = $api_data['it_spec_hdd'] === "0 GB" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : $api_data['it_spec_hdd'];
									$it_spec_hdd_type = $api_data['it_spec_hdd_type'];
									//$HDD = $api_data['HDD'];
									$it_spec_gpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)"), array("", ""), $api_data['it_spec_gpu'])));
									if (count($it_spec_gpu_arr) == 1) {
										$it_spec_gpu = $it_spec_gpu_arr[0];
									} else if (count($it_spec_gpu_arr) > 1) {
										if ((strpos($it_spec_gpu_arr[0], "NVIDIA") !== false) || (strpos($it_spec_gpu_arr[0], "AMD") !== false)) {
											$it_spec_gpu = $it_spec_gpu_arr[0];
										} else if ((strpos($it_spec_gpu_arr[1], "NVIDIA") !== false) || (strpos($it_spec_gpu_arr[1], "AMD") !== false)) {
											$it_spec_gpu = $it_spec_gpu_arr[1];
										} else {
											$it_spec_gpu = $it_spec_gpu_arr[0] . "<br>" . $it_spec_gpu_arr[1];
										}
									}
									if (stripos($it_spec_gpu, 'nvidia') !== false) {
										$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia.png' class='gpu_logo_img2'>";
									}
									if (stripos($it_spec_gpu, 'quadro') !== false) {
										$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia_quadro.png' class='gpu_logo_img2'>";
									} else if (stripos($it_spec_gpu, 'geforce') !== false) {
										$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia_geforce.png' class='gpu_logo_img2'>";
									}

									if (stripos($it_spec_gpu, 'radeon') !== false) {
										$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_amd_radeon.png' class='gpu_logo_img2'>";
									} else {
										$logo_gpu = "";
									}

									//$gpu_ram = $api_data['gpu_ram'];

									//$it_spec_os = trim(str_ireplace(array("Microsoft", "Windows", "(64Bit)"), array("", "Win", ""), $api_data['it_spec_os']));
									$it_spec_os = trim($api_data['it_spec_os']);
									$it_spec_os = str_replace(array("Microsoft"), array(""), $it_spec_os);
									if (stripos($it_spec_os, 'Windows 11') !== false || stripos($it_spec_os, 'Windows11') !== false) {
										//$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "MS " . $it_spec_os;
										$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows11.png' class='os_img2'>";
									} else if (stripos($it_spec_os, 'Windows 10') !== false || stripos($it_spec_os, 'Windows10') !== false) {
										//$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "MS " . $it_spec_os;
										$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows10.png' class='os_img2'>";
									} else if (stripos($it_spec_os, 'Windows 8') !== false || stripos($it_spec_os, 'Windows8') !== false) {
										//$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "MS " . $it_spec_os;
										$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows8.png' class='os_img2'>";
									} else if (stripos($it_spec_os, 'Windows 7') !== false || stripos($it_spec_os, 'Windows7') !== false) {
										//$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "MS " . $it_spec_os;
										$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows7.png' class='os_img2'>";
									} else if (stripos($it_spec_os, 'Windows Server 2016') !== false) {
										//$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "MS " . $it_spec_os;
										$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/WindowsServer2016.png' class='os_img2'>";
									} else {
										$OS_flag = "";
									}

									// OS화면표시언어를 $it_spec_os 변숭에 추가함
									$it_spec_os_disp_lang = $api_data['it_spec_os_disp_lang'];
									if ($it_spec_os_disp_lang != "") {
										$os_country_disp = array_search($it_spec_os_disp_lang, $countries);
										if ($os_country_disp === false) {
											$os_country_disp = "Unknown";
										}
										$it_spec_os .= " (" . $os_country_disp . ")";
									}

									$rantal_fee_type = $api_data['rantal_fee_type'];
									$rental_fee = $api_data['rental_fee'];
									$rental_setting_fee = $api_data['it_install_price'];
									$rental_fee_first_daily = round(($rental_fee + $rental_setting_fee) / 30);
									$rental_fee_ext_daily = round(($rental_fee) / 30);
									$rental_stat = $api_data['rental_stat'];
									$client_number = $api_data['client_number'];
									$cpu_clock = $api_data['cpu_clock'];
									$AppVer = $api_data['AppVer'];
									$it_billing_plan = isset($api_data['it_billing_plan']) ? $api_data['it_billing_plan'] : ''; // Billing plan added by AI
									$it_billing_traffic_cost = isset($api_data['it_billing_traffic_cost']) ? $api_data['it_billing_traffic_cost'] : 0;
									$it_billing_time_cost = isset($api_data['it_billing_time_cost']) ? $api_data['it_billing_time_cost'] : 0;

									// Initialize the array
									$it_spec_device_arr = [];

									// Check if $it_spec_keyboard is not empty and add to array
									if (!empty(trim($api_data['it_spec_keyboard']))) {
										$it_spec_device_arr[] = "KEYBOARD";
									}

									// Check if $it_spec_mouse is not empty and add to array
									if (!empty(trim($api_data['it_spec_mouse']))) {
										$it_spec_device_arr[] = "MOUSE";
									}

									// Join array elements with a comma if there are multiple elements
									$it_spec_devices = (count($it_spec_device_arr) > 0) ? implode(', ', $it_spec_device_arr) : "-";

									if($is_vpn_item){
										// Location string
										$location_str = !empty(trim($remote_ip_country_name)) ? $remote_ip_country_flag . " " . $remote_ip_country_name : "";
										// Product name
										$product_name = $list[$i]['it_name'];
										$_grade_badge = vpn_category_badge_html(isset($api_data['it_spec_os']) ? $api_data['it_spec_os'] : '').vpn_grade_badge_html(isset($api_data['it_spec_grade']) ? $api_data['it_spec_grade'] : '');
										echo "<tr><td colspan='4' class='spec-full' style='padding-bottom:2px;'><div class='spec-title-with-location'><span style='font-weight:700;'>{$_grade_badge}{$product_name}</span>";
										if(!empty($location_str)) echo "<span class='spec-location'>{$location_str}</span>";
										echo "</div></td></tr>";
										// 요금제 목록
										$_v_labels = array();
										if (function_exists('apms_allowed_pricing_units_from_item')) {
											$_v_allowed = apms_allowed_pricing_units_from_item($api_data);
											if (!empty($_v_allowed['hour']))  $_v_labels[] = '1시간';
											if (!empty($_v_allowed['day']))   $_v_labels[] = '1일';
											if (!empty($_v_allowed['month'])) $_v_labels[] = '1개월';
											if (!empty($_v_allowed['year']))  $_v_labels[] = '1년';
											if (!empty($_v_allowed['usage'])) $_v_labels[] = '종량제';
										}
										$_v_plan_str = !empty($_v_labels) ? implode(' / ', $_v_labels) . ' 이용권' : '-';
										// 주문가능기간
										$_v_max_hours = function_exists('apms_buy_qty_to_hours') ? (int)apms_buy_qty_to_hours($api_data['it_buy_max_qty']) : 0;
										$_v_max_text  = ($_v_max_hours > 0 && function_exists('apms_contract_hours_text')) ? '최대 '.apms_contract_hours_text($_v_max_hours) : '최대 365일';
										// 개통비/설치비
										$_v_setup = isset($api_data['it_install_price']) ? (int)$api_data['it_install_price'] : 0;
										$_v_setup_str = $_v_setup > 0 ? number_format($_v_setup).' P' : '없음';
										echo "<tr><th class='spec-label'>요금제</th><td colspan='3'>{$_v_plan_str}</td></tr>";
										echo "<tr><th class='spec-label'>주문기간</th><td colspan='3'>{$_v_max_text}</td></tr>";
										echo "<tr><th class='spec-label'>개통비</th><td colspan='3'>{$_v_setup_str}</td></tr>";
										echo "<tr><th class='spec-label'>프로토콜</th><td colspan='3'>IKEv2 <span style='color:#888;font-size:10px;'>Win / Mac / Linux / Android / iOS</span></td></tr>";

									} else {
										$location_str = !empty(trim($remote_ip_country_name)) ? $remote_ip_country_flag . " " . $remote_ip_country_name : "";

										// Product Name with Location in same line
										$product_name = $list[$i]['it_name'];
										// 자동 등급 산정 및 저장 (미설정 시)
										$_rpc_cur_grade = isset($api_data['it_spec_grade']) ? (string)$api_data['it_spec_grade'] : '';
										$_rpc_grade = rpc_ensure_grade(
											$api_data['it_id'],
											$_rpc_cur_grade,
											$api_data['it_spec_cpu'],
											$api_data['it_spec_ram'],
											$api_data['it_spec_ssd'],
											$api_data['it_spec_hdd']
										);
										$_grade_badge = rpc_category_badge_html($list[$i]['ca_id']).rpc_grade_badge_html($_rpc_grade);
										echo "<tr><td colspan='4' class='spec-full' style='padding-bottom:2px;'><div class='spec-title-with-location'><span style='font-weight:700;'>{$_grade_badge}{$product_name}</span>";
										if(!empty($location_str)) echo "<span class='spec-location'>{$location_str}</span>";
										echo "</div></td></tr>";
										// CPU
										echo "<tr><th class='spec-label'>CPU</th><td colspan='3'>{$it_spec_cpu}</td></tr>";
										// GPU
										echo "<tr><th class='spec-label'>GPU</th><td colspan='3'>{$it_spec_gpu}</td></tr>";

										// 개통비 변수 (가격행 우측 표시용)
										$_rpc_setup_fee = isset($api_data['it_install_price']) ? (int)$api_data['it_install_price'] : 0;
										$_rpc_setup_str = $_rpc_setup_fee > 0 ? number_format($_rpc_setup_fee).' P' : '없음';

										// RAM + SSD + HDD + USB 한 행
										$hdd_empty = (stripos($it_spec_hdd, '0') !== false || stripos($it_spec_hdd, 'Not installed') !== false || empty($it_spec_hdd));
										$usb_empty = ($it_spec_devices == '-' || empty($it_spec_devices));
										$_hdd_part = (!$hdd_empty) ? " <span style='color:#888;font-weight:500;margin-left:8px;margin-right:2px;'>HDD</span> {$it_spec_hdd}" : '';
										$_usb_part = (!$usb_empty) ? " <span style='color:#888;font-weight:500;margin-left:8px;margin-right:2px;'>USB</span> {$it_spec_devices}" : '';
										echo "<tr><th class='spec-label'>RAM</th><td colspan='3'>{$it_spec_ram} <span style='color:#888;font-weight:500;margin-left:6px;margin-right:2px;'>SSD</span> {$it_spec_ssd}{$_hdd_part}{$_usb_part}</td></tr>";
										// 렌탈 기간
										$_rpc_rental_h = (int)(isset($list[$i]['rpc_rental_hours']) ? $list[$i]['rpc_rental_hours'] : 0);
										if($_rpc_rental_h > 0) {
											$_rd=floor($_rpc_rental_h/24); $_rh=$_rpc_rental_h%24;
											$_rs=($_rd>0?$_rd.'일':'').($_rh>0?($_rd>0?' ':'').$_rh.'시간':''); if(!$_rs)$_rs=$_rpc_rental_h.'시간';
											$_ext11 = isset($list[$i]['it_11']) ? $list[$i]['it_11'] : '';
											$_ext_badge = ($_ext11 === '1')
												? "&nbsp;<span style='display:inline-block;font-size:10px;font-weight:600;color:#fff;background:#3b82f6;border-radius:3px;padding:1px 5px;'>연장가능</span>"
												: "&nbsp;<span style='display:inline-block;font-size:10px;font-weight:600;color:#fff;background:#9ca3af;border-radius:3px;padding:1px 5px;'>기간 연장 불가</span>";
											echo "<tr><th class='spec-label'>이용 기간</th><td colspan='3' style='font-weight:800;color:#1273ea;'>{$_rs}&nbsp;<small style='color:#888;font-size:10px;font-weight:400;'>낙찰즉시 이용가능</small>{$_ext_badge}</td></tr>";
										}
									}
								// save price data before $api_data is overwritten by loop exit
								$_saved_hour_price = (isset($api_data['it_is_hour_sale_price']) && (int)$api_data['it_is_hour_sale_price'] > 0) ? (int)$api_data['it_is_hour_sale_price'] : 0;
								$_saved_hour_sale  = isset($api_data['it_is_hour_sale']) ? $api_data['it_is_hour_sale'] : '0';
								}
								?>
							</table>
						</a>
					</div>

					<div class="item-price en" style="margin-top:10px;">
						<?php if($list[$i]['it_tel_inq']) { ?>
							<b>Call</b>
						<?php } else { ?>
							<?php echo $cur_price;?>
							<?php if ($list[$i]['ca_id'] == '20') { ?>
								<b><!--<i class="fa fa-krw"></i>--><?php echo number_format($list[$i]['last_auction_price']);?> P</b><small>/ 최종입찰</small>
								<?php if(isset($_rpc_setup_str)): ?>
								<span style="float:right;font-size:10px;color:#888;font-weight:500;margin-top:2px;">설치비/개통비&nbsp;<b style="color:#555;"><?php echo $_rpc_setup_str; ?></b></span>
								<?php endif; ?>
							<?php } else { ?>

								<?php if (isset($is_vpn_item) && $is_vpn_item && $it_billing_plan == 'usage') { /* Usage Plan Display */ ?>
									<div style="line-height:1.4; text-align:left;">
										<b><?php echo number_format($it_billing_traffic_cost);?> P</b><small> / GB</small>
										<span style="color:#aaa; font-weight:normal;">+</span>
										<b><?php echo number_format($it_billing_time_cost);?> P</b><small> / 시간</small>
									</div>
									<div class="item-sp darkgray" style="margin-top:5px; text-align:left;">
										<i class="fa fa-clock-o"></i> 유효기간 없음 (No Expiration)
									</div>
								<?php } else { /* Usage Plan Display End */ ?>

									<?php
										$vpn_hourly_price = ($_saved_hour_price > 0) ? $_saved_hour_price : (int)$list[$i]['it_price'];
										if ($vpn_hourly_price < 0) $vpn_hourly_price = 0;
										$_price_unit_label = ($_saved_hour_sale === '1' || $_saved_hour_price > 0) ? '/ 1시간' : '/ 1일';
									?>
									<b><!--<i class="fa fa-krw"></i>--><?php echo number_format($vpn_hourly_price);?> P</b><small><?php echo $_price_unit_label; ?></small>
									<?php $min_contract_hours = apms_buy_qty_to_hours($list[$i]['it_buy_min_qty']); ?>
									<span class="item-sp darkgray">
										<i class="fa fa-bolt"></i>
										<?php echo apms_contract_hours_text($min_contract_hours); ?> 이상 주문가능
									</span>
								<?php } ?>
							<?php } ?>

							<!-- Moved from details -->
							<?php if ($list[$i]['ca_id'] == '20') { ?>
								<span class="item-sp blue">
									<i class="fa fa-tags"></i>
								<?php echo round((1 - ($list[$i]['last_auction_price'] / $list[$i]['buy_it_now_price'])) * 100) . "% 할인";?>
								</span>
							<?php } else { ?>
								<?php if($list[$i]['it_point']) { ?>
									<span class="item-sp green">
										<i class="fa fa-gift"></i>
									<?php echo ($list[$i]['it_point_type'] == 2) ? $list[$i]['it_point'].'% 포인트 적립' : number_format(get_item_point($list[$i])).' 포인트 적립';?>
									</span>
								<?php } ?>
							<?php } ?>

							<?php if($dc_per) { ?>
								<span class="item-sp orangered">
									<i class="fa fa-bolt"></i>
									<?php echo $dc_per;?>% DC
								</span>
							<?php } ?>
						<?php } ?>
					</div>
					<div class="item-details en">
						<?php if($wset['cmt'] && $list[$i]['pt_comment']) { ?>
							<span class="item-sp red">
								<i class="fa fa-comment"></i>
								<?php echo number_format($list[$i]['pt_comment']);?>
							</span>
						<?php } ?>
						<?php if($wset['buy'] && $list[$i]['it_sum_qty']) { ?>
							<span class="item-sp blue">
								<i class="fa fa-shopping-cart"></i>
								<?php echo number_format($list[$i]['it_sum_qty']);?>
							</span>
						<?php } ?>
						<?php if($wset['hit'] && $list[$i]['it_hit']) { ?>
							<span class="item-sp gray">
								<i class="fa fa-eye"></i>
								<?php echo number_format($list[$i]['it_hit']);?>
							</span>
						<?php } ?>
					</div>
				</div>
				<?php if($wset['sns']) { ?>
					<div class="item-sns">
						<?php
							$sns_url  = G5_SHOP_URL.'/item.php?it_id='.$list[$i]['it_id'];
							$sns_title = get_text($list[$i]['it_name']);
							$sns_img = $list_skin_url.'/img';
							echo  get_sns_share_link('facebook', $sns_url, $sns_title, $sns_img.'/sns_fb.png').' ';
							echo  get_sns_share_link('twitter', $sns_url, $sns_title, $sns_img.'/sns_twt.png').' ';
							echo  get_sns_share_link('googleplus', $sns_url, $sns_title, $sns_img.'/sns_goo.png').' ';
							echo  get_sns_share_link('kakaostory', $sns_url, $sns_title, $sns_img.'/sns_kakaostory.png').' ';
							echo  get_sns_share_link('kakaotalk', $sns_url, $sns_title, $sns_img.'/sns_kakao.png').' ';
							echo  get_sns_share_link('naverband', $sns_url, $sns_title, $sns_img.'/sns_naverband.png').' ';
						?>
					</div>
				<?php } ?>
			</div>
		</div>
	<?php } // end for ?>
	<?php if(!$list_cnt) { ?>
		<div class="list-none">등록된 상품이 없습니다.</div>
	<?php } ?>
	<div class="clearfix"></div>
</div>
<script>
$(document).ready(function(){
	$('.list-wrap').imagesLoaded(function(){
		$('.list-wrap .item-content').matchHeight();
	});
});
</script>
<div class="list-btn">
	<div class="list-page pull-left">
		<ul class="pagination pagination-sm en">
			<?php echo apms_paging($write_pages, $page, $total_page, $list_page); ?>
		</ul>
		<div class="clearfix"></div>
	</div>
	<div class="pull-right">
		<div class="btn-group">
			<?php if ($is_event) { ?>
				<a class="btn btn-<?php echo $btn2;?> btn-sm" href="./event.php"><i class="fa fa-gift"></i> 이벤트</a>
			<?php } ?>
			<?php if ($write_href) { ?>
				<a class="btn btn-<?php echo $btn1;?> btn-sm" href="<?php echo $write_href;?>"><i class="fa fa-upload"></i><span class="hidden-xs"> 등록</span></a>
			<?php } ?>
			<?php if ($admin_href) { ?>
				<a class="btn btn-<?php echo $btn1;?> btn-sm" href="<?php echo $admin_href;?>"><i class="fa fa-th-large"></i><span class="hidden-xs"> 관리</span></a>
			<?php } ?>
			<?php if ($config_href) { ?>
				<a class="btn btn-<?php echo $btn1;?> btn-sm" href="<?php echo $config_href;?>"><i class="fa fa-cog"></i><span class="hidden-xs"> 설정</span></a>
			<?php } ?>
			<?php if($setup_href) { ?>
				<a class="btn btn-<?php echo $btn1;?> btn-sm win_memo" href="<?php echo $setup_href;?>"><i class="fa fa-cogs"></i><span class="hidden-xs"> 스킨설정</span></a>
			<?php } ?>
			<?php if ($rss_href) { ?>
				<a class="btn btn-<?php echo $btn2;?> btn-sm" title="카테고리 RSS 구독하기" href="<?php echo $rss_href;?>" target="_blank"><i class="fa fa-rss fa-lg"></i></a>
			<?php } ?>
		</div>
	</div>
	<div class="clearfix"></div>
</div>


<?php
// 경매상품이면 상품상세페이지 URL이 다르므로 변경시켜 주는 함수 JSLEE {
function convertUrl($url) {
	global $g5;

    // URL을 파싱하여 쿼리 문자열을 추출
    $parsedUrl = parse_url($url);
    parse_str($parsedUrl['query'], $queryParams);

    // it_id 값을 추출
    $it_id = $queryParams['it_id'];

	// write_auction_table 에서 wr_id 확인
	$row = sql_fetch("SELECT * FROM {$g5['write_auction_table']} WHERE pcnum = '$it_id' ");
    // 새로운 URL을 생성
    $newUrl = G5_BBS_URL . "/board.php?bo_table=auction&wr_id=" . $row['wr_id'] . "&s=&pcnum=" . $it_id;

    return $newUrl;
}
// 경매상품이면 상품상세페이지 URL이 다르므로 변경시켜 주는 함수 JSLEE }
?>

<script>
(function(){
    var filterBar = document.getElementById('auction-filter-bar');
    if(!filterBar) return;

    var rows = document.querySelectorAll('.item-row[data-auction-status]');
    if(!rows.length) return;

    var selected = new Set(); // 비어있으면 전체 표시

    // 빈 결과 표시 div
    var noResult = document.createElement('div');
    noResult.id = 'af-no-result';
    noResult.textContent = '선택한 입찰 현황에 해당하는 경매 상품이 없습니다.';
    var listWrap = document.querySelector('.list-wrap');
    if(listWrap) listWrap.after(noResult);

    function applyFilter(){
        var chk = document.getElementById('chk-my-bid');
        var myBidOnly = chk && chk.checked;
        var visible = 0;
        rows.forEach(function(r){
            var statusOk = (selected.size === 0) || selected.has(r.getAttribute('data-auction-status'));
            var myBidOk  = !myBidOnly || r.getAttribute('data-my-bid') === '1';
            var show = statusOk && myBidOk;
            r.style.display = show ? '' : 'none';
            if(show) visible++;
        });
        noResult.style.display = visible===0 ? '' : 'none';
        /* 카운트 업데이트 (내 입찰만 체크 반영) */
        var fc = {}; var ft = 0;
        rows.forEach(function(r){
            if(!myBidOnly || r.getAttribute('data-my-bid')==='1'){
                var s=r.getAttribute('data-auction-status'); fc[s]=(fc[s]||0)+1; ft++;
            }
        });
        var cm={'afc-all':ft,'afc-prog':fc['경매진행중']||0,'afc-wait':fc['경매시작전']||0,
                'afc-win':fc['경매종료[낙찰]'||0]||0,'afc-lose':fc['경매종료[유찰]'||0]||0,'afc-cancel':fc['경매취소']||0};
        cm['afc-win']  = fc['경매종료[낙찰]']||0;
        cm['afc-lose'] = fc['경매종료[유찰]']||0;
        Object.keys(cm).forEach(function(id){ var el=document.getElementById(id); if(el) el.textContent=cm[id]; });
        var cancelBtn=document.querySelector('.af-btn[data-status="경매취소"]');
        if(cancelBtn) cancelBtn.style.display=(fc['경매취소']||0)===0?'none':'';
    }

    function syncButtons(){
        var allBtn = document.querySelector('.af-btn[data-status="all"]');
        document.querySelectorAll('.af-btn[data-status]').forEach(function(btn){
            var st = btn.getAttribute('data-status');
            if(st==='all') btn.classList.toggle('active', selected.size===0);
            else           btn.classList.toggle('active', selected.has(st));
        });
    }

    document.querySelectorAll('.af-btn[data-status]').forEach(function(btn){
        btn.addEventListener('click', function(){
            var st = this.getAttribute('data-status');
            if(st==='all'){
                selected.clear();
            } else {
                if(selected.has(st)){ selected.delete(st); }
                else                { selected.add(st); }
            }
            syncButtons();
            applyFilter();
        });
    });

    /* 아이템 클릭 시 현재 필터 상태 저장 */
    document.querySelectorAll('.item-row a, .item-row').forEach(function(el){
        el.addEventListener('click', function(){
            var active = [];
            selected.forEach(function(v){ active.push(v); });
            sessionStorage.setItem('auction_shop_filter', active.join(','));
        });
    });

    syncButtons();
    applyFilter();

    /* JS 가격 정렬 공통 함수 */
    function _sortByAttr(attr, btnId, asc) {
        var allRows = Array.from(document.querySelectorAll('.item-row[' + attr + ']'));
        allRows.sort(function(a, b) {
            var va = parseInt(a.getAttribute(attr) || '0', 10);
            var vb = parseInt(b.getAttribute(attr) || '0', 10);
            return asc ? va - vb : vb - va;
        });
        var ul = allRows.length && allRows[0].parentNode;
        if (ul) allRows.forEach(function(r) { ul.appendChild(r); });
        document.querySelectorAll('.asp-t').forEach(function(b){ b.classList.remove('on'); });
        var btn = document.getElementById(btnId);
        if (btn) btn.classList.add('on');
    }

    /* 마감 임박 정렬 (asc=true: 임박순▲, asc=false: 여유순▼) */
    function _sortByEndTime(asc) {
        var rows = Array.from(document.querySelectorAll('.item-row[data-end-ts]'));
        rows.sort(function(a,b){
            var ta = parseInt(a.getAttribute('data-end-ts')||'9999999999',10);
            var tb = parseInt(b.getAttribute('data-end-ts')||'9999999999',10);
            return asc ? ta - tb : tb - ta;
        });
        var ul = rows.length && rows[0].parentNode;
        if(ul) rows.forEach(function(r){ ul.appendChild(r); });
        document.querySelectorAll('.asp-t').forEach(function(b){ b.classList.remove('on'); });
        var btn = document.getElementById(asc ? 'asort-deadline-asc' : 'asort-deadline-desc');
        if(btn) btn.classList.add('on');
    }

    /* sort chip 버튼 이벤트 */
    var _sbDeadlineAsc  = document.getElementById('asort-deadline-asc');
    var _sbDeadlineDesc = document.getElementById('asort-deadline-desc');
    var _sbOriginDesc   = document.getElementById('asort-origin-desc');
    var _sbOriginAsc    = document.getElementById('asort-origin-asc');
    var _sbCurDesc      = document.getElementById('asort-cur-desc');
    var _sbCurAsc       = document.getElementById('asort-cur-asc');
    var _asortBuynowDesc = document.getElementById('asort-buynow-desc');
    var _asortBuynowAsc  = document.getElementById('asort-buynow-asc');
    if (_sbDeadlineAsc)  _sbDeadlineAsc.addEventListener('click',  function(){ _sortByEndTime(true);  });
    if (_sbDeadlineDesc) _sbDeadlineDesc.addEventListener('click', function(){ _sortByEndTime(false); });
    if (_sbOriginDesc)   _sbOriginDesc.addEventListener('click',   function(){ _sortByAttr('data-origin-price', 'asort-origin-desc', false); });
    if (_sbOriginAsc)    _sbOriginAsc.addEventListener('click',    function(){ _sortByAttr('data-origin-price', 'asort-origin-asc',  true);  });
    if (_sbCurDesc)      _sbCurDesc.addEventListener('click',      function(){ _sortByAttr('data-start-price',  'asort-cur-desc',    false); });
    if (_sbCurAsc)       _sbCurAsc.addEventListener('click',       function(){ _sortByAttr('data-start-price',  'asort-cur-asc',     true);  });
    if (_asortBuynowDesc) _asortBuynowDesc.addEventListener('click', function(){ _sortByAttr('data-buynow-price', 'asort-buynow-desc', false); });
    if (_asortBuynowAsc)  _asortBuynowAsc.addEventListener('click',  function(){ _sortByAttr('data-buynow-price', 'asort-buynow-asc',  true);  });

    /* 내 입찰만 체크박스 */
    var chkMyBidEl = document.getElementById('chk-my-bid');
    if(chkMyBidEl) chkMyBidEl.addEventListener('change', function(){
        applyFilter();
    });

    /* URL 파라미터 ast= 자동 필터 적용 */
    (function(){
        var params = new URLSearchParams(window.location.search);
        var ast    = params.get('ast');
        var asort  = params.get('asort');
        if (!ast) return;

        /* 숫자코드 → shop status 문자열 매핑 */
        var statusMap = {
            '0': '경매시작전',
            '1': '경매진행중',
            '2': '경매종료[낙찰]',
            '3': '경매종료[유찰]'
        };

        selected.clear();
        if (ast === 'my') {
            /* 내 입찰만 체크박스 활성화 */
            var _chk = document.getElementById('chk-my-bid');
            if(_chk) _chk.checked = true;
        } else {
            ast.split(',').forEach(function(v){
                var mapped = statusMap[v] || v;
                selected.add(mapped);
            });
        }
        syncButtons();
        applyFilter();

        /* 마감 임박 정렬: data-end-ts 기준 오름차순 */
        if (asort === 'end' || asort === 'end-asc') { _sortByEndTime(true); }
        if (asort === 'end-desc') { _sortByEndTime(false); }
    })();
})();
</script>
<script>
	document.addEventListener("DOMContentLoaded", function() {
		function updateAuctionTime() {
			const elements = document.querySelectorAll('.auction_remain_timer');
			elements.forEach(function(element) {
				const expireTime = parseInt(element.getAttribute('data-expire-time'), 10);
				const currentTime = new Date().getTime();
				const timeRemaining = expireTime - currentTime;

				if (timeRemaining > 0) {
					const seconds = Math.floor((timeRemaining / 1000) % 60);
					const minutes = Math.floor((timeRemaining / (1000 * 60)) % 60);
					const hours = Math.floor((timeRemaining / (1000 * 60 * 60)) % 24);
					const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));

					const hh = ('0' + hours).slice(-2);
					const mm = ('0' + minutes).slice(-2);
					const ss = ('0' + seconds).slice(-2);
					let displayTime;
					if (days > 0) displayTime = days + '일 ' + hh + ':' + mm + ':' + ss;
					else if (hours > 0) displayTime = hh + ':' + mm + ':' + ss;
					else displayTime = mm + ':' + ss;
					element.textContent = displayTime;
				} else {
					element.textContent = "종료";
				}
			});
		}

		// 매 1초마다 남은 시간을 업데이트
		setInterval(updateAuctionTime, 1000);

		// 페이지 로드 후 즉시 시간 업데이트
		updateAuctionTime();
	});
</script>