﻿
const ASSETS = 'assets/';

/* ─── GLASEES ICON SVG ─── */
function GlassesIcon({ size = 28, color = '#201713' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" fill={color}>
      <path d="M31.194 15.201h-0.319c-0.395-3.303-3.202-5.864-6.611-5.864-3.168 0-5.813 2.212-6.491 5.174l-1.526-0.797c-0.154-0.080-0.339-0.080-0.493 0l-1.526 0.797c-0.677-2.962-3.323-5.174-6.491-5.174-3.41 0-6.216 2.562-6.612 5.864h-0.319c-0.442 0-0.8 0.358-0.8 0.8 0 0.441 0.358 0.799 0.8 0.799h0.319c0.396 3.303 3.202 5.864 6.612 5.864 3.68 0 6.664-2.983 6.664-6.664 0-0.124-0.012-0.245-0.019-0.368l1.618-0.845 1.618 0.845c-0.007 0.122-0.019 0.244-0.019 0.368 0 3.68 2.984 6.664 6.664 6.664 3.409 0 6.215-2.561 6.611-5.864h0.319c0.442 0 0.8-0.358 0.8-0.8s-0.358-0.8-0.8-0.8zM7.737 21.598c-3.087 0-5.598-2.511-5.598-5.598s2.511-5.598 5.598-5.598c3.087 0 5.598 2.511 5.598 5.598s-2.511 5.598-5.598 5.598zM24.263 21.598c-3.087 0-5.598-2.511-5.598-5.598s2.511-5.597 5.598-5.597c3.087 0 5.598 2.511 5.598 5.597s-2.511 5.598-5.598 5.598z" />
    </svg>
  );
}

function routeKeyFromCategory(category) {
  switch (category) {
    case '안경':
    case '안경테':
      return 'glasses';
    case '선글라스':
      return 'sunglasses';
    case '누진다초점':
      return 'progressive';
    case '콘텍트렌즈':
    case '콘택트렌즈':
      return 'contact';
    case '특수안경':
      return 'special';
    default:
      return 'glasses';
  }
}

function pageHref(page) {
  return {
    landing: 'index.html',
    brand: 'brand.html',
    events: 'events.html',
    glasses: 'glasses.html',
    sunglasses: 'sunglasses.html',
    progressive: 'progressivelenses.html',
    contact: 'contactlenses.html',
    special: 'specialglasses.html'
  }[page] || 'index.html';
}

function getPageTitle(page, product) {
  const titleMap = {
    landing: '으뜸안경본데이',
    brand: '안경원 소개 | 으뜸안경본데이',
    events: '이달의 행사 | 으뜸안경본데이',
    glasses: '안경테 | 으뜸안경본데이',
    sunglasses: '선글라스 | 으뜸안경본데이',
    progressive: '누진다초점 | 으뜸안경본데이',
    contact: '콘택트렌즈 | 으뜸안경본데이',
    special: '특수안경 | 으뜸안경본데이'
  };

  if (page === 'detail' && product) {
    return `${product.brand} ${product.model} | 으뜸안경본데이`;
  }

  return titleMap[page] || '으뜸안경본데이';
}

function getCategoryImage(page) {
  const imageMap = {
    brand: `${ASSETS}sub_model1.png`,
    events: `${ASSETS}sub_model2.png`,
    glasses: `${ASSETS}sub_model3.png`,
    sunglasses: `${ASSETS}sub_model4.png`,
    progressive: 'https://jaypak-example-bucket.s3.ap-northeast-2.amazonaws.com/bonday/sub_model5.png',
    contact: 'https://jaypak-example-bucket.s3.ap-northeast-2.amazonaws.com/bonday/sub_model6.png',
    special: 'https://jaypak-example-bucket.s3.ap-northeast-2.amazonaws.com/bonday/sub_model7.png'
  };

  return imageMap[page] || `${ASSETS}sub_model1.png`;
}

function getSiteSettings() {
  const settings = window.BONDAY_SITE_SETTINGS && typeof window.BONDAY_SITE_SETTINGS === 'object'
    ? window.BONDAY_SITE_SETTINGS
    : {};

  return {
    eventsBannerText: String(settings.eventsBannerText || '').trim(),
  };
}

function mapProduct(item) {
  const utils = window.BONDAY_UTILS || {};
  const priceText = typeof utils.formatPrice === 'function'
    ? utils.formatPrice(item.priceSale)
    : `${Number(item.priceSale || 0).toLocaleString('ko-KR')}원`;
  const originalPriceText = typeof utils.formatPrice === 'function'
    ? utils.formatPrice(item.priceOriginal)
    : `${Number(item.priceOriginal || 0).toLocaleString('ko-KR')}원`;
  const discountText = typeof utils.calculateDiscount === 'function'
    ? utils.calculateDiscount(item.priceOriginal, item.priceSale)
    : '';
  const hasOriginalPrice = Boolean(item.priceOriginal) && item.priceOriginal !== item.priceSale;

  return {
    id: `${item.brand}-${item.model}`,
    brand: item.brand,
    model: item.model,
    tags: Array.isArray(item.tags) ? item.tags : [],
    description: String(item.description || '').trim(),
    discount: discountText,
    price: priceText,
    originalPrice: hasOriginalPrice ? originalPriceText : '',
    badge: item.priceOriginal && item.priceSale && item.priceSale < item.priceOriginal ? 'EVENT' : null,
    isSoldOut: Boolean(item.isSoldOut || item.is_sold_out),
    isMonthlyFeature: Boolean(item.isMonthlyFeature || item.is_monthly_feature),
    category: routeKeyFromCategory(item.category),
    images: Array.isArray(item.images) ? item.images.filter(Boolean) : []
  };
}

function getProducts() {
  const source = Array.isArray(window.BONDAY_PRODUCT_DATA) ? window.BONDAY_PRODUCT_DATA : [];
  return source.map(mapProduct);
}

function getProductByModel(model) {
  const source = Array.isArray(window.BONDAY_PRODUCT_DATA) ? window.BONDAY_PRODUCT_DATA : [];
  const raw = source.find(item => item.model === model);
  return raw ? mapProduct(raw) : null;
}

const NAV = [
  { id:'landing',    label:'홈' },
  { id:'brand',      label:'안경원 소개' },
  { id:'events',     label:'이달의 행사' },
  { id:'glasses',    label:'안경테' },
  { id:'sunglasses', label:'선글라스' },
  { id:'progressive',label:'누진다초점' },
  { id:'contact',    label:'콘택트렌즈' },
  { id:'special',    label:'특수안경' },
];

const CATS = [
  { id:'brand',       n:'01', label:'안경원 소개', img:getCategoryImage('brand'), scale:1.28, mobileScale:1.34, position:'60% 42%', mobilePosition:'60% 42%' },
  { id:'events',      n:'02', label:'이달의 행사', img:getCategoryImage('events'), scale:1.18, mobileScale:1.24, position:'50% 42%', mobilePosition:'50% 42%' },
  { id:'glasses',     n:'03', label:'안경테',      img:getCategoryImage('glasses'), scale:1.34, mobileScale:1.40, position:'50% 48%', mobilePosition:'50% 48%' },
  { id:'sunglasses',  n:'04', label:'선글라스',    img:getCategoryImage('sunglasses'), scale:1.26, mobileScale:1.32, position:'54% 42%', mobilePosition:'54% 42%' },
  { id:'progressive', n:'05', label:'누진다초점',  img:getCategoryImage('progressive'), scale:1.16, mobileScale:1.2, position:'50% 42%', mobilePosition:'50% 42%' },
  { id:'contact',     n:'06', label:'콘택트렌즈',  img:getCategoryImage('contact'), scale:1.16, mobileScale:1.2, position:'50% 42%', mobilePosition:'50% 42%' },
  { id:'special',     n:'07', label:'특수안경',    img:getCategoryImage('special'), scale:1.14, mobileScale:1.18, position:'50% 40%', mobilePosition:'50% 40%' },
];

/* ─── SHARED HEADER ─── */
function Header({ page }) {
  const [scrolled, setScrolled] = React.useState(false);
  const scrollLockRef = React.useRef(false);
  const scrolledRef = React.useRef(false);

  React.useEffect(() => {
    let unlockTimer = null;

    const unlockScrollToggle = () => {
      if (unlockTimer) {
        window.clearTimeout(unlockTimer);
      }

      unlockTimer = window.setTimeout(() => {
        scrollLockRef.current = false;
      }, 220);
    };

    const onScroll = () => {
      if (scrollLockRef.current) {
        return;
      }

      const nextScrolled = scrolledRef.current
        ? window.scrollY > 4
        : window.scrollY > 50;

      if (nextScrolled === scrolledRef.current) {
        return;
      }

      scrollLockRef.current = true;
      scrolledRef.current = nextScrolled;
      setScrolled(nextScrolled);
      unlockScrollToggle();
    };

    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });

    return () => {
      window.removeEventListener('scroll', onScroll);
      if (unlockTimer) {
        window.clearTimeout(unlockTimer);
      }
    };
  }, []);

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(245,244,242,0.96)',
      backdropFilter: 'blur(12px)',
      borderBottom: '1px solid rgba(66,43,29,0.10)',
    }}>
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '0 1.25rem' }}>
        {/* Logo — hides on scroll */}
        <div style={{
          overflow: 'hidden',
          maxHeight: scrolled ? 0 : 64,
          opacity: scrolled ? 0 : 1,
          transition: 'max-height 0.25s ease, opacity 0.2s ease',
          paddingTop: scrolled ? 0 : '0.85rem',
          paddingBottom: scrolled ? 0 : '0.5rem',
        }}>
          <a href={pageHref('landing')} style={{ display:'flex', alignItems:'center', gap:10, padding:0 }}>
            <GlassesIcon size={26} color="#201713" />
            <div style={{ fontFamily:"'Noto Serif KR',serif", fontSize:'1.05rem', fontWeight:700, letterSpacing:'-0.04em', color:'#201713' }}>으뜸안경본데이</div>
          </a>
        </div>

        {/* Nav — always visible, sticky */}
        <nav style={{ display:'flex', gap:0, overflowX:'auto', scrollbarWidth:'none', borderTop: `1px solid ${scrolled ? 'transparent' : 'rgba(66,43,29,0.08)'}` }}>
          {NAV.map(n => {
            const active = page === n.id;
            return (
              <a key={n.id} href={pageHref(n.id)} style={{
                position:'relative', flexShrink:0,
                padding: '0.8rem 0.9rem',
                fontSize:'0.88rem', fontWeight: active ? 900 : 600,
                color: active ? '#201713' : '#6d6158',
                whiteSpace:'nowrap', transition:'color 0.2s',
              }}>
                {n.label}
                {active && (
                  <span style={{ position:'absolute', bottom:0, left:0, right:0, height:2, background:'#201713', borderRadius:1 }} />
                )}
              </a>
            );
          })}
        </nav>
      </div>
    </header>
  );
}

/* ─── FOOTER ─── */
function Footer() {
  return (
    <footer style={{ background:'#0f0b09', color:'rgba(255,244,234,0.55)', padding:'2rem 0', textAlign:'center', fontSize:'0.82rem', lineHeight:1.9, width:'100%', marginTop:'auto' }}>
      <div style={{ maxWidth:1100, margin:'0 auto', padding:'0 1.25rem' }}>
        <p style={{ color:'rgba(255,244,234,0.85)', fontWeight:700, marginBottom:4 }}>으뜸안경본데이</p>
        <p>부산광역시 연제구 월드컵대로 229 (거제동, 1층) · 051-501-5010</p>
        <p>영업시간 10:00 ~ 20:00 / 매주 일요일 휴무</p>
        <p>Copyright © 으뜸안경본데이. All Rights Reserved.</p>
      </div>
    </footer>
  );
}

function EventBanner({ isMobile, tone = 'default' }) {
  const { eventsBannerText } = getSiteSettings();

  if (!eventsBannerText) {
    return null;
  }

  const background = tone === 'landing'
    ? 'linear-gradient(180deg, rgba(242,236,227,0.96) 0%, rgba(237,229,218,0.94) 100%)'
    : 'linear-gradient(180deg, rgba(248,244,238,0.92) 0%, rgba(240,236,229,0.9) 100%)';

  return (
    <section style={{
      borderTop:'1px solid rgba(66,43,29,0.06)',
      borderBottom:'1px solid rgba(66,43,29,0.08)',
      background
    }}>
      <div style={{ maxWidth:1100, margin:'0 auto', padding: isMobile ? '1rem 1.25rem' : '1.15rem 1.25rem' }}>
        <div style={{
          display:'flex',
          alignItems:'flex-start',
          gap:'0.8rem',
          flexDirection:'column'
        }}>
          <span style={{
            display:'inline-flex',
            alignItems:'center',
            justifyContent:'center',
            padding:'0.38rem 0.68rem',
            borderRadius:999,
            background:'#201713',
            color:'#fff9f2',
            fontSize:'0.68rem',
            fontWeight:800,
            letterSpacing:'0.18em',
            textTransform:'uppercase',
            flexShrink:0
          }}>
            Event
          </span>
          <p style={{
            margin:0,
            color:'#201713',
            fontSize:isMobile ? '0.92rem' : '0.98rem',
            fontWeight:700,
            lineHeight:1.7,
            letterSpacing:'-0.02em',
            whiteSpace:'pre-line'
          }}>
            {eventsBannerText}
          </p>
        </div>
      </div>
    </section>
  );
}

/* ─── LANDING PAGE ─── */
function LandingPage() {
  const W = window.innerWidth;
  const isMobile = W < 768;

  return (
    <div style={{ background:'#f5f4f2', display:'flex', flexDirection:'column', flex:1 }}>
      <EventBanner isMobile={isMobile} tone="landing" />

      {/* HERO — full-width model image, text overlay bottom-left */}
      <section style={{ position:'relative', background:'#f0ece5', overflow:'hidden' }}>
        {/* Image fills right half / full on mobile */}
        <div style={{
          display:'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
          minHeight: isMobile ? 'auto' : 660,
        }}>
          {/* Left: text */}
          <div style={{
            display:'flex', flexDirection:'column', justifyContent:'center',
            padding: isMobile ? '2.5rem 1.5rem 1.5rem' : '4rem 3rem 4rem 0',
            maxWidth: isMobile ? '100%' : 520,
            marginLeft: isMobile ? 0 : 'auto',
          }}>
            <p style={{ fontSize:'0.72rem', fontWeight:800, letterSpacing:'0.2em', textTransform:'uppercase', color:'#8d5b37', marginBottom:'0.9rem' }}>
              Premium Eyewear
            </p>
            <h1 style={{
              fontFamily:"'Noto Serif KR',serif",
              fontSize: isMobile ? '2.4rem' : '3.4rem',
              fontWeight:700, lineHeight:1.12, letterSpacing:'-0.05em', color:'#201713',
              margin:'0 0 1.2rem',
            }}>
              매일 쓰는 안경,<br />공간까지<br />기억에 남게.
            </h1>
            <p style={{ fontSize:'0.95rem', color:'#6d6158', lineHeight:1.85, marginBottom:'1.8rem', maxWidth:380 }}>
              부산 연제구 법조타운점. 프레임 셀렉션, 누진다초점 상담, <br />선글라스까지 한 곳에서.
            </p>
            <div style={{ display:'flex', gap:'0.7rem', flexWrap:'wrap' }}>
              <a href={pageHref('glasses')} style={{
                padding:'0.78rem 1.5rem', borderRadius:4,
                background:'#201713', color:'#fff9f2',
                fontSize:'0.9rem', fontWeight:800,
              }}>안경테 보러가기</a>
              <a href={pageHref('brand')} style={{
                padding:'0.78rem 1.5rem', borderRadius:4,
                background:'transparent', color:'#201713', border:'1px solid rgba(66,43,29,0.25)',
                fontSize:'0.9rem', fontWeight:700,
              }}>매장 소개</a>
            </div>
          </div>

          {/* Right: model image */}
          {!isMobile && (
            <div style={{ position:'relative', overflow:'hidden', background:'#f0ece5' }}>
              <img src={`${ASSETS}main_model.png`} alt="모델"
                style={{ width:'100%', height:'100%', objectFit:'contain', objectPosition:'center bottom' }} />
            </div>
          )}
          {isMobile && (
            <img src={`${ASSETS}main_model.png`} alt="모델"
              style={{ width:'100%', height:440, objectFit:'cover', objectPosition:'center top' }} />
          )}
        </div>


      </section>

      {/* CATEGORY GRID */}
      <section style={{ background:'#0f0b09', padding: isMobile ? '2.5rem 0' : '3.5rem 0' }}>
        <div style={{ maxWidth:1100, margin:'0 auto', padding:'0 1.25rem' }}>
          <div style={{
            display:'grid',
            gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)',
            gap:'10px',
            background:'rgba(255,255,255,0.06)',
            border:'1px solid rgba(255,255,255,0.06)',
          }}>
            {CATS.slice(0,isMobile?6:7).map((cat, i) => (
              <a key={cat.id} href={pageHref(cat.id)}
                style={{
                  position:'relative', overflow:'hidden',
                  aspectRatio: (i===0 && !isMobile) ? '1.6/1' : '1/1',
                  gridColumn: (i===0 && !isMobile) ? 'span 2' : 'span 1',
                  background:'#1a1210', display:'block',
                }}>
                <img src={cat.img} alt={cat.label}
                  style={{
                    width:'100%',
                    height:'100%',
                    objectFit:'cover',
                    objectPosition: isMobile ? (cat.mobilePosition || cat.position || 'center center') : (cat.position || 'center center'),
                    opacity:0.96,
                    filter:'brightness(1.18) saturate(1.04)',
                    display:'block',
                    transition:'opacity 0.3s, transform 0.4s',
                    transform: `scale(${isMobile ? (cat.mobileScale || cat.scale || 1) : (cat.scale || 1)})`
                  }} />
                <div style={{
                  position:'absolute', inset:0,
                  background:'linear-gradient(180deg, rgba(255,255,255,0.10) 0%, rgba(0,0,0,0.28) 100%)',
                }} />
                <div style={{ position:'absolute', bottom:0, left:0, right:0, padding: isMobile ? '1rem' : '1.4rem', textAlign:'left', color:'#fff' }}>
                  <div style={{ fontSize:'0.7rem', fontWeight:800, letterSpacing:'0.14em', color:'rgba(255,255,255,0.5)', marginBottom:4 }}>{cat.n}</div>
                  <div style={{ fontFamily:"'Noto Serif KR',serif", fontSize: isMobile ? '1.1rem' : (i===0 ? '1.55rem' : '1.25rem'), fontWeight:700, letterSpacing:'-0.03em' }}>{cat.label}</div>
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* CONTACT STRIP */}
      <section style={{ background:'#f0ece5', padding: isMobile ? '2rem 0' : '3rem 0' }}>
        <div style={{ maxWidth:1100, margin:'0 auto', padding:'0 1.25rem' }}>
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap:'1.5rem', alignItems:'center' }}>
            <div>
              <p style={{ fontSize:'0.72rem', fontWeight:800, letterSpacing:'0.2em', textTransform:'uppercase', color:'#8d5b37', marginBottom:'1.2rem' }}>Visit & Contact</p>
              <div style={{ display:'grid', gap:'0.65rem' }}>
                {[['주소','부산광역시 연제구 월드컵대로 229 (거제동, 1층)'],['영업','10:00 ~ 20:00 / 매주 일요일 휴무'],['전화','051-501-5010']].map(([k,v])=>(
                  <div key={k} style={{ display:'grid', gridTemplateColumns:'60px 1fr', gap:'0.5rem', fontSize:'0.9rem' }}>
                    <span style={{ fontWeight:800, color:'#8d5b37', fontSize:'0.75rem', letterSpacing:'0.08em', textTransform:'uppercase', paddingTop:1 }}>{k}</span>
                    <span style={{ color:'#201713', lineHeight:1.6 }}>{v}</span>
                  </div>
                ))}
              </div>
              <div style={{ display:'flex', gap:'0.7rem', marginTop:'1.5rem', flexWrap:'wrap' }}>
                <a href="https://naver.me/FkLzXOKu" target="_blank" style={{ padding:'0.72rem 1.3rem', background:'#201713', color:'#fff9f2', borderRadius:4, fontSize:'0.88rem', fontWeight:800 }}>지도로 보기</a>
                <a href="tel:0515015010" style={{ padding:'0.72rem 1.3rem', border:'1px solid rgba(66,43,29,0.25)', color:'#201713', borderRadius:4, fontSize:'0.88rem', fontWeight:700 }}>전화 문의</a>
              </div>
            </div>
            <div style={{ borderRadius:8, overflow:'hidden', boxShadow:'0 20px 40px rgba(34,22,14,0.12)' }}>
              <img src={`${ASSETS}map_image.png`} alt="지도" style={{ width:'calc(100% + 8px)', height: isMobile ? 208 : 288, margin:'-4px', objectFit:'cover', objectPosition:'center' }} />
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </div>
  );
}

/* ─── CATALOG PAGE ─── */
function CatalogPage({ category }) {
  const W = window.innerWidth;
  const isMobile = W < 768;
  const isEventsPage = category === 'events';
  const allItems = getProducts().filter(p => category === 'events'
    ? p.isMonthlyFeature
    : p.category === category);

  // Derive brands from available products for this category
  const brandList = ['전체', ...Array.from(new Set(allItems.map(p => p.brand)))];
  const [activeBrand, setActiveBrand] = React.useState('전체');
  const items = activeBrand === '전체' ? allItems : allItems.filter(p => p.brand === activeBrand);

  return (
    <div style={{ background:'#f5f4f2', display:'flex', flexDirection:'column', flex:1 }}>
      {isEventsPage && (
        <EventBanner isMobile={isMobile} />
      )}

      {/* Page header — COLLECTION kicker + brand filter chips */}
      <div style={{ borderBottom:'1px solid rgba(66,43,29,0.08)', padding: isMobile ? '1.2rem 0 0.9rem' : '1.6rem 0 1rem', background:'#f5f4f2' }}>
        <div style={{ maxWidth:1100, margin:'0 auto', padding:'0 1.25rem' }}>
          <p style={{ fontSize:'0.7rem', fontWeight:800, letterSpacing:'0.18em', textTransform:'uppercase', color:'#8d5b37', marginBottom:'0.8rem' }}>Collection</p>
          {/* Brand filter chips */}
          <div style={{ display:'flex', gap:'0.55rem', flexWrap:'nowrap', overflowX:'auto', scrollbarWidth:'none', paddingBottom:'0.2rem', WebkitOverflowScrolling:'touch' }}>
            {brandList.map(brand => {
              const isActive = activeBrand === brand;
              const count = brand === '전체' ? allItems.length : allItems.filter(p => p.brand === brand).length;
              return (
                <button key={brand} onClick={() => setActiveBrand(brand)} style={{
                  display:'inline-flex', alignItems:'center', gap:6,
                  padding: isMobile ? '0.55rem 0.85rem' : '0.65rem 1rem',
                  borderRadius:4, border: isActive ? 'none' : '1px solid rgba(66,43,29,0.15)',
                  background: isActive ? '#201713' : '#fff',
                  color: isActive ? '#fff9f2' : '#201713',
                  fontSize: isMobile ? '0.82rem' : '0.88rem', fontWeight: isActive ? 800 : 600,
                  fontFamily:'inherit', cursor:'pointer',
                  transition:'all 0.2s ease',
                  boxShadow: isActive ? '0 4px 14px rgba(32,23,19,0.18)' : 'none',
                  whiteSpace:'nowrap',
                  flexShrink:0,
                }}>
                  {brand}
                  <span style={{
                    fontSize:'0.68rem', fontWeight:800,
                    color: isActive ? 'rgba(255,249,242,0.7)' : '#8d5b37',
                    background: isActive ? 'rgba(255,255,255,0.12)' : 'rgba(141,91,55,0.09)',
                    padding:'0.15rem 0.42rem', borderRadius:2,
                  }}>{count}</span>
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Products */}
      <div style={{ maxWidth:1100, margin:'0 auto', padding: isMobile ? '1.5rem 1.25rem' : '2rem 1.25rem' }}>
        {items.length === 0 ? (
          <div style={{ padding:'4rem 0', textAlign:'center', color:'#6d6158' }}>
            <p style={{ fontFamily:"'Noto Serif KR',serif", fontSize:'1.5rem', marginBottom:'0.8rem' }}>준비 중입니다</p>
            <p style={{ fontSize:'0.9rem' }}>매장으로 직접 문의해 주세요. 051-501-5010</p>
          </div>
        ) : (
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(3,1fr)', gap: isMobile ? '1rem' : '1.4rem' }}>
            {items.map(p => <ProductCard key={p.id} product={p} currentPage={category} />)}
          </div>
        )}
      </div>

      <Footer />
    </div>
  );
}

function AnimatedTagRow({ tags }) {
  const containerRef = React.useRef(null);
  const trackRef = React.useRef(null);
  const rowRef = React.useRef(null);
  const animationRef = React.useRef(null);
  const contentKey = Array.isArray(tags) ? tags.join('|') : '';

  React.useEffect(() => {
    const container = containerRef.current;
    const track = trackRef.current;
    const row = rowRef.current;

    if (!container || !track || !row) {
      return undefined;
    }

    const stopAnimation = () => {
      if (animationRef.current) {
        animationRef.current.cancel();
        animationRef.current = null;
      }
      track.style.transform = 'translateX(0)';
    };

    const setupAnimation = () => {
      stopAnimation();

      const rowWidth = row.scrollWidth;
      const overflow = Math.max(0, rowWidth - container.clientWidth);
      const travel = overflow;

      if (travel > 8) {
        const duration = Math.max(2800, travel * 75);
        animationRef.current = track.animate(
          [
            { transform: 'translateX(0)' },
            { transform: `translateX(-${travel}px)` }
          ],
          {
            duration,
            direction: 'alternate',
            iterations: Infinity,
            easing: 'ease-in-out',
            fill: 'both'
          }
        );
      }
    };

    setupAnimation();

    const observer = typeof ResizeObserver !== 'undefined'
      ? new ResizeObserver(setupAnimation)
      : null;

    if (observer) {
      observer.observe(container);
      observer.observe(row);
    }

    return () => {
      if (observer) {
        observer.disconnect();
      }
      stopAnimation();
    };
  }, [contentKey]);

    if (!Array.isArray(tags) || !tags.length) {
      return null;
    }

  const chipStyle = {
    display:'inline-flex',
    alignItems:'center',
    fontSize:'0.72rem',
    fontWeight:700,
    color:'#6d6158',
    background:'rgba(66,43,29,0.06)',
    padding:'0.25rem 0.5rem',
    borderRadius:2,
    flexShrink:0
  };

  return (
    <div
      ref={containerRef}
      style={{
        marginBottom:'0.8rem',
        overflow:'hidden'
      }}
    >
      <div
        ref={trackRef}
        style={{
          display:'inline-flex',
          whiteSpace:'nowrap',
          willChange:'transform'
        }}
      >
        <div ref={rowRef} style={{ display:'inline-flex', gap:4, whiteSpace:'nowrap' }}>
          {tags.map(tag => (
            <span key={tag} style={chipStyle}>
              {tag}
            </span>
            ))}
          </div>
      </div>
    </div>
  );
}

function ProductCard({ product: p, currentPage }) {
  const [hover, setHover] = React.useState(false);
  const imageSrc = p.images.length ? p.images[0] : `${ASSETS}product_sample_image.png`;
  const detailHref = `detail.html?model=${encodeURIComponent(p.model)}&from=${encodeURIComponent(currentPage)}`;
  const badgeText = p.isSoldOut ? 'SOLD OUT' : (p.isMonthlyFeature ? 'EVENT' : null);
  return (
    <a href={detailHref}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        background:'#fff', border:'1px solid rgba(66,43,29,0.08)',
        borderRadius:8, overflow:'hidden', cursor:'pointer',
        boxShadow: hover ? '0 12px 32px rgba(34,22,14,0.12)' : '0 2px 8px rgba(34,22,14,0.06)',
        transform: hover ? 'translateY(-4px)' : 'translateY(0)',
        transition:'all 0.25s ease', textAlign:'left', padding:0,
      }}>
      {/* Image */}
      <div style={{ position:'relative', background:'#f5f4f2', display:'flex', alignItems:'center', justifyContent:'center', padding:'5px', aspectRatio:'1/1' }}>
        {badgeText && (
          <span style={{
            position:'absolute',
            top:10,
            left:10,
            background: p.isSoldOut ? '#8d3526' : '#201713',
            color:'#fff9f2',
            fontSize:'0.65rem',
            fontWeight:800,
            letterSpacing:'0.1em',
            padding:'0.3rem 0.6rem',
            borderRadius:2
          }}>
            {badgeText}
          </span>
        )}
        <img src={imageSrc} alt={p.model}
          style={{ width:'100%', height:'100%', maxWidth:'100%', maxHeight:'100%', objectFit:'contain', transition:'transform 0.3s ease', transform: hover ? 'scale(1.30)' : 'scale(1.22)', transformOrigin:'center center' }} />
      </div>
      {/* Info */}
      <div style={{ padding:'0.9rem 1rem 1.1rem' }}>
        <div style={{ fontSize:'0.72rem', fontWeight:800, letterSpacing:'0.14em', textTransform:'uppercase', color:'#8d5b37', marginBottom:'0.3rem' }}>{p.brand}</div>
        <div style={{ fontSize:'1rem', fontWeight:900, letterSpacing:'-0.02em', color:'#201713', marginBottom:'0.6rem' }}>{p.model}</div>
        <AnimatedTagRow tags={p.tags} />
        <div style={{ display:'grid', gap:'0.18rem' }}>
          {p.originalPrice && (
            <span style={{ fontSize:'0.72rem', color:'#8b847d', textDecoration:'line-through', textDecorationThickness:'1px' }}>
              {p.originalPrice}
            </span>
          )}
          <div style={{ display:'flex', alignItems:'baseline', gap:'0.5rem' }}>
            {p.discount && <span style={{ fontSize:'0.88rem', fontWeight:800, color:'#2f7f93' }}>{p.discount}</span>}
            <span style={{ fontSize:'1rem', fontWeight:900, color:'#201713' }}>{p.price}</span>
          </div>
        </div>
      </div>
    </a>
  );
}

/* ─── DETAIL PAGE ─── */
function DetailPage() {
  const W = window.innerWidth;
  const isMobile = W < 768;
  const canHover = !isMobile && window.matchMedia('(hover: hover) and (pointer: fine)').matches;
  const params = new URLSearchParams(window.location.search);
  const model = params.get('model');
  const from = params.get('from');
  const p = getProductByModel(model);
  const [slide, setSlide] = React.useState(0);
  const [imgHover, setImgHover] = React.useState(false);
  const [zoomOrigin, setZoomOrigin] = React.useState('50% 50%');

  React.useEffect(() => {
    setSlide(0);
  }, [model]);

  if (!p) {
    return (
      <div style={{ background:'#f5f4f2', minHeight:'100vh' }}>
        <div style={{ maxWidth:1100, margin:'0 auto', padding: isMobile ? '2rem 1.25rem' : '4rem 1.25rem' }}>
          <p style={{ fontFamily:"'Noto Serif KR',serif", fontSize: isMobile ? '2rem' : '2.6rem', marginBottom:'1rem', color:'#201713' }}>
            상품을 찾을 수 없습니다.
          </p>
          <a href={pageHref(from || 'glasses')} style={{ display:'inline-block', padding:'0.85rem 1.2rem', background:'#201713', color:'#fff9f2', borderRadius:4, fontWeight:800 }}>
            목록으로 돌아가기
          </a>
        </div>
        <Footer />
      </div>
    );
  }

  const images = p.images.length ? p.images : [`${ASSETS}product_sample_image.png`];
  const activeImage = images[slide] || images[0];
  const hasMultipleImages = images.length > 1;

  function moveSlide(direction) {
    setSlide(current => {
      const next = current + direction;

      if (next < 0) {
        return images.length - 1;
      }

      if (next >= images.length) {
        return 0;
      }

      return next;
    });
  }

  function handleZoomMove(event) {
    if (!canHover) {
      return;
    }

    const rect = event.currentTarget.getBoundingClientRect();
    const x = ((event.clientX - rect.left) / rect.width) * 100;
    const y = ((event.clientY - rect.top) / rect.height) * 100;
    setZoomOrigin(`${x}% ${y}%`);
  }

  return (
    <div style={{ background:'#f5f4f2', display:'flex', flexDirection:'column', flex:1 }}>
      <div style={{ maxWidth:1100, margin:'0 auto', padding: isMobile ? '1.5rem 1.25rem' : '2.5rem 1.25rem' }}>

        {/* Back */}
        <a href={pageHref(from || p.category)} style={{ display:'flex', alignItems:'center', gap:6, fontSize:'0.88rem', fontWeight:700, color:'#6d6158', marginBottom:'1.5rem' }}>
          ← 목록으로
        </a>

        <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? '1.5rem' : '3rem', alignItems:'start' }}>

          {/* Gallery — hover to zoom */}
          <div>
            <div
              onMouseMove={canHover ? handleZoomMove : undefined}
              onMouseEnter={canHover ? () => setImgHover(true) : undefined}
              onMouseLeave={() => {
                setImgHover(false);
                setZoomOrigin('50% 50%');
              }}
              style={{ position:'relative', background:'#f5f4f2', borderRadius:8, display:'flex', alignItems:'center', justifyContent:'center', padding:'2.5rem', aspectRatio:'1/1', marginBottom:'1rem', overflow:'hidden', cursor: canHover ? 'crosshair' : 'default' }}>
              {hasMultipleImages && (
                <button
                  type="button"
                  onClick={() => moveSlide(-1)}
                  aria-label="이전 이미지"
                  style={{
                    position:'absolute',
                    left:12,
                    top:'50%',
                    transform:'translateY(-50%)',
                    background:'transparent',
                    color:'rgba(32,23,19,0.72)',
                    fontSize:'2rem',
                    fontWeight:900,
                    zIndex:2,
                    lineHeight:1,
                    padding:0
                  }}
                >
                  ‹
                </button>
              )}
              <img src={activeImage} alt={p.model} draggable="false"
                style={{
                  width:'100%',
                  maxWidth:380,
                  height:320,
                  objectFit:'contain',
                  transition:'transform 0.25s ease',
                  transform: canHover && imgHover ? 'scale(1.55)' : 'scale(1.22)',
                  transformOrigin: zoomOrigin,
                  pointerEvents:'none',
                  userSelect:'none'
                }} />
              {hasMultipleImages && (
                <button
                  type="button"
                  onClick={() => moveSlide(1)}
                  aria-label="다음 이미지"
                  style={{
                    position:'absolute',
                    right:12,
                    top:'50%',
                    transform:'translateY(-50%)',
                    background:'transparent',
                    color:'rgba(32,23,19,0.72)',
                    fontSize:'2rem',
                    fontWeight:900,
                    zIndex:2,
                    lineHeight:1,
                    padding:0
                  }}
                >
                  ›
                </button>
              )}
            </div>
            {/* Dots */}
            <div style={{ display:'flex', justifyContent:'center', gap:8 }}>
              {images.map((_, i) => (
                <button key={i} onClick={() => setSlide(i)} style={{ width:8, height:8, borderRadius:'50%', background: i===slide ? '#201713' : '#ccc', border:'none', cursor:'pointer', padding:0 }} />
              ))}
            </div>
          </div>

          {/* Info */}
          <div>
            <p style={{ fontSize:'0.7rem', fontWeight:800, letterSpacing:'0.18em', textTransform:'uppercase', color:'#8d5b37', marginBottom:'0.6rem' }}>Curated Eyewear</p>
            <h1 style={{ fontFamily:"'Noto Serif KR',serif", fontSize: isMobile ? '2rem' : '2.8rem', fontWeight:700, letterSpacing:'-0.05em', lineHeight:1.12, color:'#201713', marginBottom:'0.35rem' }}>{p.model}</h1>
            <p style={{ fontSize:'1rem', color:'#6d6158', marginBottom:'1.2rem' }}>{p.brand}</p>
            <div style={{ marginBottom:'1rem' }}>
              <span style={{
                display:'inline-flex',
                alignItems:'center',
                padding:'0.4rem 0.75rem',
                borderRadius:999,
                background: p.isSoldOut ? 'rgba(160,63,45,0.12)' : 'rgba(141,91,55,0.12)',
                color: p.isSoldOut ? '#8d3526' : '#201713',
                fontSize:'0.82rem',
                fontWeight:800
              }}>
                {p.isSoldOut ? '품절' : '판매중'}
              </span>
            </div>

            <div style={{ display:'grid', gap:'0.28rem', marginBottom:'1.2rem' }}>
              {p.originalPrice && (
                <span style={{ fontSize:'0.86rem', color:'#8b847d', textDecoration:'line-through', textDecorationThickness:'1px' }}>
                  {p.originalPrice}
                </span>
              )}
              <div style={{ display:'flex', alignItems:'baseline', gap:'0.7rem' }}>
                {p.discount && <span style={{ fontSize:'1.2rem', fontWeight:900, color:'#2f7f93' }}>{p.discount}</span>}
                <span style={{ fontSize:'1.8rem', fontWeight:900, letterSpacing:'-0.04em', color:'#201713' }}>{p.price}</span>
              </div>
            </div>

            {/* Tags */}
            <div style={{ display:'flex', gap:6, flexWrap:'wrap', marginBottom:'1.5rem' }}>
              {p.tags.map(t => <span key={t} style={{ fontSize:'0.82rem', fontWeight:700, color:'#3b2418', background:'rgba(141,91,55,0.09)', border:'1px solid rgba(66,43,29,0.10)', padding:'0.45rem 0.75rem', borderRadius:4 }}>{t}</span>)}
            </div>

            {p.description && (
              <div style={{
                marginBottom:'1.5rem'
              }}>
                <p style={{
                  margin:0,
                  color:'#6d6158',
                  fontSize:'0.92rem',
                  lineHeight:1.8,
                  whiteSpace:'pre-line'
                }}>
                  {p.description}
                </p>
              </div>
            )}

            {/* CTAs only */}
            <div style={{ display:'grid', gap:'0.65rem' }}>
              <a href="https://naver.me/FkLzXOKu" target="_blank" style={{ display:'block', padding:'0.95rem', textAlign:'center', background:'#201713', color:'#fff9f2', borderRadius:4, fontSize:'0.95rem', fontWeight:800 }}>
                방문 문의하기
              </a>
              <a href="tel:0515015010" style={{ display:'block', padding:'0.95rem', textAlign:'center', border:'1px solid rgba(66,43,29,0.20)', color:'#201713', borderRadius:4, fontSize:'0.95rem', fontWeight:700 }}>
                전화 상담하기
              </a>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}

/* ─── BRAND PAGE ─── */
function BrandPage() {
  const W = window.innerWidth;
  const isMobile = W < 768;

  return (
    <div style={{ background:'#f5f4f2', display:'flex', flexDirection:'column', flex:1 }}>
      <div style={{ maxWidth:1100, margin:'0 auto', padding: isMobile ? '2rem 1.25rem' : '3rem 1.25rem' }}>
        <p style={{ fontSize:'0.7rem', fontWeight:800, letterSpacing:'0.18em', textTransform:'uppercase', color:'#8d5b37', marginBottom:'0.6rem' }}>Store Story</p>
        <h1 style={{ fontFamily:"'Noto Serif KR',serif", fontSize: isMobile ? '2rem' : '3rem', fontWeight:700, lineHeight:1.15, letterSpacing:'-0.05em', color:'#201713', marginBottom:'1.2rem' }}>
          으뜸안경본데이<br />법조타운점
        </h1>
        <p style={{ fontSize:'0.96rem', color:'#6d6158', lineHeight:1.85, maxWidth:600, marginBottom:'2rem' }}>
          데일리 안경부터 선글라스, 누진다초점 상담까지 한 자리에서 도와드립니다.
        </p>

        {/* Features */}
        <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2,1fr)', gap:'1rem', marginBottom:'2.5rem' }}>
          {[['01','매일 쓰기 좋은 프레임','가볍고 편한 기본 안경부터 분위기를 살려주는 포인트 프레임까지 직접 비교해 보실 수 있습니다.'],
            ['02','누진다초점 맞춤 상담','처음 맞추는 분도 부담 없도록, 생활 패턴과 보는 거리를 먼저 듣고 차근차근 안내해 드립니다.']
          ].map(([n,title,desc]) => (
            <div key={n} style={{ background:'#fff', border:'1px solid rgba(66,43,29,0.08)', borderRadius:8, padding:'1.4rem' }}>
              <div style={{ fontSize:'0.7rem', fontWeight:800, letterSpacing:'0.14em', color:'#8d5b37', marginBottom:'0.8rem' }}>{n}</div>
              <h3 style={{ fontSize:'1rem', fontWeight:900, color:'#201713', marginBottom:'0.6rem' }}>{title}</h3>
              <p style={{ fontSize:'0.88rem', color:'#6d6158', lineHeight:1.75 }}>{desc}</p>
            </div>
          ))}
        </div>

        {/* Map + contact */}
        <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap:'1.5rem', alignItems:'center' }}>
          <div style={{ borderRadius:8, overflow:'hidden' }}>
            <img src={`${ASSETS}map_image.png`} alt="지도" style={{ width:'calc(100% + 8px)', height: isMobile ? 208 : 288, margin:'-4px', objectFit:'cover', objectPosition:'center' }} />
          </div>
          <div>
            <div style={{ display:'grid', gap:'0.7rem', marginBottom:'1.2rem' }}>
              {[['주소','부산광역시 연제구 월드컵대로 229 (거제동, 1층)'],['운영','10:00 ~ 20:00 / 매주 일요일 휴무'],['전화','051-501-5010']].map(([k,v]) => (
                <div key={k} style={{ display:'grid', gridTemplateColumns:'60px 1fr', gap:'0.5rem', fontSize:'0.9rem' }}>
                  <span style={{ fontWeight:800, color:'#8d5b37', fontSize:'0.72rem', letterSpacing:'0.1em', textTransform:'uppercase' }}>{k}</span>
                  <span style={{ color:'#201713', lineHeight:1.6 }}>{v}</span>
                </div>
              ))}
            </div>
            <div style={{ display:'flex', gap:'0.7rem', flexWrap:'wrap' }}>
              <a href="https://naver.me/FkLzXOKu" target="_blank" style={{ padding:'0.75rem 1.3rem', background:'#201713', color:'#fff9f2', borderRadius:4, fontSize:'0.88rem', fontWeight:800 }}>지도로 보기</a>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}

/* ─── APP SHELL ─── */
function LoadingPage({ error }) {
  return (
    <div style={{ background:'#f5f4f2', display:'grid', placeItems:'center', padding:'2rem', flex:1 }}>
      <div style={{ textAlign:'center', maxWidth:420 }}>
        <p style={{ fontSize:'0.7rem', fontWeight:800, letterSpacing:'0.18em', textTransform:'uppercase', color:'#8d5b37', marginBottom:'0.9rem' }}>Bonday</p>
        <h1 style={{ fontFamily:"'Noto Serif KR',serif", fontSize:'2rem', color:'#201713', margin:'0 0 0.85rem' }}>
          {error ? '상품 정보를 불러오지 못했습니다.' : '상품 정보를 불러오는 중입니다.'}
        </h1>
        <p style={{ color:'#6d6158', lineHeight:1.7, margin:0 }}>
          {error ? '잠시 후 다시 시도해 주세요.' : '공개 상품 데이터를 서버에서 받아오고 있습니다.'}
        </p>
      </div>
    </div>
  );
}

function App() {
  const [ready, setReady] = React.useState(Boolean(window.BONDAY_DATA_READY));
  const [error, setError] = React.useState(window.BONDAY_DATA_ERROR || null);
  const page = window.BONDAY_PAGE || 'landing';
  const CATALOG_PAGES = ['glasses','sunglasses','progressive','contact','special','events'];
  const isCatalog = CATALOG_PAGES.includes(page);
  const detailProduct = page === 'detail'
    ? getProductByModel(new URLSearchParams(window.location.search).get('model'))
    : null;
  const activeHeaderPage = page === 'detail' && detailProduct ? detailProduct.category : page;

  React.useEffect(() => {
    function handleReady() {
      setError(null);
      setReady(true);
    }

    function handleError() {
      setError(window.BONDAY_DATA_ERROR || new Error('상품 데이터를 불러오지 못했습니다.'));
      setReady(false);
    }

    window.addEventListener('bonday:data-ready', handleReady);
    window.addEventListener('bonday:data-error', handleError);

    if (window.BONDAY_DATA_PROMISE) {
      window.BONDAY_DATA_PROMISE.then(handleReady).catch(handleError);
    }

    return () => {
      window.removeEventListener('bonday:data-ready', handleReady);
      window.removeEventListener('bonday:data-error', handleError);
    };
  }, []);

  React.useEffect(() => {
    document.title = getPageTitle(page, detailProduct);
  }, [page, detailProduct]);

  if (!ready) {
    return <LoadingPage error={error} />;
  }

  return (
    <div style={{ minHeight:'100vh', display:'flex', flexDirection:'column', background:'#f5f4f2' }}>
      <Header page={activeHeaderPage} />
      {page === 'landing' && <LandingPage />}
      {isCatalog && <CatalogPage category={page} />}
      {page === 'detail' && <DetailPage />}
      {page === 'brand' && <BrandPage />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
