<?php
/**
 * /www/artists.php  —  아티스트 목차(허브)
 * ------------------------------------------------------------------
 *  artists 테이블의 활성 팀을 그리드로 노출. 각 팀 → /list.php?artist={slug}
 *  헤더 ARTIST 메뉴의 도착지(스크롤 대신 페이지 이동 통일).
 * ------------------------------------------------------------------
 */

require_once __DIR__ . '/includes/config.php';   // $pdo, 세션, won(), e()
require_once __DIR__ . '/includes/page_head.php'; // kp_page_head() 공통 제목

$st = $pdo->query("SELECT id, name, name_en, slug FROM artists WHERE is_active = 1 ORDER BY sort_order, name");
$artists = $st->fetchAll();

/* 각 팀의 상품 수 (있으면 표시) */
$counts = [];
try {
    $cst = $pdo->query("SELECT artist_id, COUNT(*) AS c FROM products WHERE is_active = 1 AND artist_id IS NOT NULL GROUP BY artist_id");
    foreach ($cst->fetchAll() as $r) $counts[(int)$r['artist_id']] = (int)$r['c'];
} catch (Throwable $e) {}

/* 상단 알파벳 인덱스: 존재하는 이니셜 집합 (#=비알파벳 맨 뒤로) */
$ixSet = [];
foreach ($artists as $a) {
    $en = trim((string)($a['name_en'] ?? '')); $kr = trim((string)$a['name']);
    $c  = $en !== '' ? strtoupper($en[0]) : (function_exists('mb_substr') ? mb_substr($kr, 0, 1, 'UTF-8') : '#');
    $c  = preg_match('/[A-Z]/', $c) ? $c : '#';
    $ixSet[$c] = true;
}
ksort($ixSet);
if (isset($ixSet['#'])) { unset($ixSet['#']); $ixSet['#'] = true; }
$ixList = array_keys($ixSet);

$page_title  = 'ARTIST | KPOPPOCA';
$active_menu = 'artist';
include __DIR__ . '/includes/header.php';
?>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.css">

<style>
.ar-wrap{ max-width:1120px; margin:0 auto; padding:18px 18px 90px; font-family:'Pretendard',sans-serif; color:#141414; word-break:keep-all; }
.ar-head{ text-align:center; margin-bottom:34px; }
.ar-eyebrow{ font-family:'Unbounded',sans-serif; font-size:12px; font-weight:700; letter-spacing:.18em; color:#FF1488; }
.ar-title{ font-family:'Unbounded',sans-serif; font-weight:800; font-size:clamp(26px,4vw,34px); margin:8px 0 6px; }
.ar-desc{ font-size:14px; color:#888; }

.ar-grid{ display:grid; grid-template-columns:repeat(auto-fill,minmax(min(100%,150px),1fr)); gap:clamp(12px,1.6vw,18px); }
.ar-card{ display:flex; flex-direction:column; align-items:center; gap:11px; text-decoration:none; color:inherit;
  padding:22px 12px; border:1.5px solid #f0eef2; border-radius:16px; background:#fff; transition:.18s; }
.ar-card:hover{ border-color:#FF1488; transform:translateY(-4px); box-shadow:0 14px 30px rgba(255,20,136,.13); }
.ar-ava{ width:74px; height:74px; border-radius:50%; display:grid; place-items:center;
  background:linear-gradient(145deg,#FFE3F0,#FFF0F6); color:#FF1488;
  font-family:'Unbounded',sans-serif; font-weight:800; font-size:26px; }
.ar-card:hover .ar-ava{ background:linear-gradient(145deg,#FF1488,#FF5BA8); color:#fff; }
.ar-en{ font-family:'Unbounded',sans-serif; font-weight:700; font-size:13.5px; text-align:center; line-height:1.25; letter-spacing:.01em; }
.ar-kr{ font-size:12px; color:#9a9aa3; margin-top:-4px; }
.ar-cnt{ font-size:11px; font-weight:700; color:#FF1488; }

.ar-empty{ text-align:center; padding:70px 20px; color:#999; }

.ar-index{ display:flex; flex-wrap:wrap; justify-content:center; gap:4px 6px; margin-bottom:28px; }
.ar-ix{ border:none; background:none; cursor:pointer; font-family:'Unbounded',sans-serif; font-weight:700;
  font-size:13px; color:#bdbdc6; padding:6px 11px; border-radius:9px; transition:.15s; letter-spacing:.02em; }
.ar-ix:hover{ color:#FF1488; }
.ar-ix.on{ color:#FF1488; background:#FFE3F0; }
</style>

<?php kp_page_head('BROWSE BY ARTIST', 'ARTIST', '아티스트별 공식 포토카드 · 굿즈를 만나보세요'); ?>

<div class="ar-wrap">

  <?php if ($artists): ?>
    <div class="ar-index">
      <button type="button" class="ar-ix on" data-ix="all">전체</button>
      <?php foreach ($ixList as $L): ?>
        <button type="button" class="ar-ix" data-ix="<?= e($L) ?>"><?= e($L) ?></button>
      <?php endforeach; ?>
    </div>
    <div class="ar-grid">
      <?php foreach ($artists as $a):
        $en   = trim((string)($a['name_en'] ?? ''));
        $kr   = trim((string)$a['name']);
        $slug = trim((string)$a['slug']);
        $disp = $en !== '' ? $en : $kr;
        $init = $en !== '' ? strtoupper($en[0])
              : (function_exists('mb_substr') ? mb_substr($kr, 0, 1, 'UTF-8') : '♪');
        $cnt  = $counts[(int)$a['id']] ?? 0;
        $ix   = preg_match('/[A-Za-z]/', (string)$init) ? strtoupper((string)$init) : '#';
      ?>
        <a class="ar-card" data-initial="<?= e($ix) ?>" href="/list.php?artist=<?= e($slug) ?>">
          <div class="ar-ava"><?= e($init) ?></div>
          <div class="ar-en"><?= e($disp) ?></div>
          <?php if ($en !== '' && $kr !== '' && $en !== $kr): ?>
            <div class="ar-kr"><?= e($kr) ?></div>
          <?php endif; ?>
          <?php if ($cnt > 0): ?><div class="ar-cnt"><?= $cnt ?>개 상품</div><?php endif; ?>
        </a>
      <?php endforeach; ?>
    </div>
  <?php else: ?>
    <div class="ar-empty">등록된 아티스트가 아직 없어요.</div>
  <?php endif; ?>
</div>

<script>
(function(){
  var bar = document.querySelector('.ar-index'); if(!bar) return;
  var cards = document.querySelectorAll('.ar-card');
  bar.addEventListener('click', function(ev){
    var b = ev.target.closest('.ar-ix'); if(!b) return;
    var ix = b.getAttribute('data-ix');
    bar.querySelectorAll('.ar-ix').forEach(function(x){ x.classList.toggle('on', x === b); });
    cards.forEach(function(c){
      c.style.display = (ix === 'all' || c.getAttribute('data-initial') === ix) ? '' : 'none';
    });
  });
})();
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
