/* =====================================================================
 * Afflix Thumbnail · T01_A (가성비 비교 · BEST 3)
 * ---------------------------------------------------------------------
 * 디팀 v1.0.0 · 2026-05-07
 * SSOT: v12/thumb-slots.json  (templates.T01_A)
 * 개발팀장 흡수 가이드:
 *   - 이 컴포넌트는 600×600 기준으로 그리고, 1200 retina는 size=1200 prop
 *   - 모든 시각 규격은 SSOT.style_rules 와 1:1 일치
 *   - validators는 SSOT.templates.T01_A.validators 동일 — 검증은 발행 전
 *   - HTML→PNG 렌더는 자동화 영역 (puppeteer/playwright/satori 등)
 * 입력 슬롯:
 *   props.slots = {
 *     post_id, template_id, char_id, theme_color,
 *     title_main, title_sub, badge_text, highlight_price,
 *     product_image_1, product_image_2, product_image_3,
 *     product_label_1, product_label_2, product_label_3, brand_mark
 *   }
 * ===================================================================== */

const { useMemo: uMt } = React;

/* SSOT 와 1:1 — 사이즈별 px 스케일 */
const T01A_STYLE = {
  600: {
    title_main: 56, title_sub: 22, badge: 18, price: 30, label: 17, brand: 14,
    pad: 24, gap: 14, card_radius: 16, badge_radius: 6, price_radius: 8,
    header_h: 188, products_h: 296, footer_h: 92,
    big_w: 256, small_w: 160, image_pad: 12,
  },
  1200: {
    title_main: 112, title_sub: 44, badge: 36, price: 60, label: 34, brand: 28,
    pad: 48, gap: 28, card_radius: 32, badge_radius: 12, price_radius: 16,
    header_h: 376, products_h: 592, footer_h: 184,
    big_w: 512, small_w: 320, image_pad: 24,
  },
};

/* 폴백 룰 — SSOT.fallback_rules */
function _truncate(text, max, useEllipsis = true) {
  if (!text) return '';
  if (text.length <= max) return text;
  return useEllipsis ? text.slice(0, max - 1) + '…' : text.slice(0, max);
}

/* 색상 darken (theme_color → theme_color_700) — 자동 그라디언트용 */
function _darken(hex, amt = 0.18) {
  const m = /^#([0-9A-Fa-f]{6})$/.exec(hex || '');
  if (!m) return hex;
  const n = parseInt(m[1], 16);
  let r = (n >> 16) & 0xff, g = (n >> 8) & 0xff, b = n & 0xff;
  r = Math.max(0, Math.round(r * (1 - amt)));
  g = Math.max(0, Math.round(g * (1 - amt)));
  b = Math.max(0, Math.round(b * (1 - amt)));
  return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('');
}

/* SSOT validators 와 동일 — 발행 전 검증 가능 */
window.validateThumbT01A = function(slots) {
  const errs = [];
  if (!slots) return ['slots_missing'];
  if (!slots.title_main) errs.push('title_main_required');
  else if (slots.title_main.length > 22) errs.push('title_main_overflow');
  if (slots.title_sub && slots.title_sub.length > 18) errs.push('title_sub_overflow');
  if (slots.badge_text && slots.badge_text.length > 6) errs.push('badge_overflow');
  if (!slots.highlight_price) errs.push('highlight_price_required');
  else if (slots.highlight_price.length > 10) errs.push('highlight_price_overflow');
  if (!slots.product_image_1) errs.push('product_image_1_missing');
  if (!slots.product_image_2) errs.push('product_image_2_missing');
  if (!slots.product_image_3) errs.push('product_image_3_missing');
  if (!slots.theme_color || !/^#[0-9A-Fa-f]{6}$/.test(slots.theme_color)) errs.push('theme_color_invalid');
  if (!slots.char_id || !/^C\d{2}$/.test(slots.char_id)) errs.push('char_id_invalid');
  return errs;
};

/* ============== T01_A 컴포넌트 ============== */
window.ThumbT01A = function ThumbT01A({ slots, size = 600 }) {
  const s = T01A_STYLE[size] || T01A_STYLE[600];
  const v = useMemo_t(() => slots || {}, [slots]);

  /* 폴백 적용 */
  const titleMain  = _truncate(v.title_main || '', 22);
  const titleSub   = _truncate(v.title_sub || '', 18);
  const badgeText  = (v.badge_text && v.badge_text.length <= 6) ? v.badge_text : '';
  const price      = _truncate(v.highlight_price || '', 10);
  const themeColor = (/^#[0-9A-Fa-f]{6}$/.test(v.theme_color || '')) ? v.theme_color : '#D7263D';
  const themeDark  = _darken(themeColor, 0.22);
  const brandMark  = v.brand_mark || 'AFFLIX';
  const lbl1       = v.product_label_1 || 'BEST 1';
  const lbl2       = v.product_label_2 || 'BEST 2';
  const lbl3       = v.product_label_3 || 'BEST 3';

  return (
    <div
      data-thumb-template={v.template_id || 'T01_A'}
      data-thumb-post-id={v.post_id || ''}
      data-thumb-char-id={v.char_id || ''}
      data-thumb-size={size}
      style={{
        width: size, height: size,
        background: `linear-gradient(135deg, ${themeColor} 0%, ${themeDark} 100%)`,
        position: 'relative',
        fontFamily: '"Noto Sans KR", system-ui, sans-serif',
        color: '#fff',
        overflow: 'hidden',
        boxSizing: 'border-box',
      }}
    >
      {/* 배경 데코 — 우상단 큰 원 */}
      <div style={{
        position: 'absolute', right: -size * 0.2, top: -size * 0.2,
        width: size * 0.7, height: size * 0.7, borderRadius: '50%',
        background: 'rgba(255,255,255,0.06)',
      }}/>
      <div style={{
        position: 'absolute', left: -size * 0.15, bottom: -size * 0.25,
        width: size * 0.5, height: size * 0.5, borderRadius: '50%',
        background: 'rgba(0,0,0,0.08)',
      }}/>

      {/* HEADER — 제목 영역 */}
      <div data-slot-zone="header" style={{
        padding: `${s.pad}px ${s.pad}px ${s.gap}px`,
        position: 'relative', zIndex: 2,
      }}>
        {badgeText && (
          <div data-slot="thumb.badge_text" style={{
            display: 'inline-block',
            background: '#fff', color: themeColor,
            fontSize: s.badge, fontWeight: 800,
            padding: `${s.badge*0.18}px ${s.badge*0.6}px`,
            borderRadius: s.badge_radius,
            letterSpacing: '0.04em',
            marginBottom: s.gap * 0.6,
          }}>{badgeText}</div>
        )}
        <div data-slot="thumb.title_main" style={{
          fontSize: s.title_main, fontWeight: 800,
          lineHeight: 1.12, letterSpacing: '-0.02em',
          color: '#fff', textShadow: '0 2px 8px rgba(0,0,0,0.18)',
          wordBreak: 'keep-all',
        }}>{titleMain}</div>
        {titleSub && (
          <div data-slot="thumb.title_sub" style={{
            fontSize: s.title_sub, fontWeight: 500,
            color: 'rgba(255,255,255,0.92)',
            marginTop: s.gap * 0.4,
            letterSpacing: '-0.01em',
          }}>{titleSub}</div>
        )}
      </div>

      {/* PRODUCTS — 3개 슬롯 (BEST1 큰 / BEST2·3 작은) */}
      <div data-slot-zone="products" style={{
        padding: `0 ${s.pad}px`,
        display: 'flex', gap: s.gap,
        position: 'relative', zIndex: 2,
        height: s.products_h,
        alignItems: 'center',
      }}>
        {/* BEST 1 — 큰 카드 */}
        <_ProductCard
          slot="thumb.product_image_1"
          label={lbl1}
          src={v.product_image_1}
          width={s.big_w}
          height={s.products_h - s.gap}
          radius={s.card_radius}
          pad={s.image_pad}
          labelSize={s.label}
          labelColor={themeColor}
          isPrimary={true}
        />
        {/* BEST 2·3 — 작은 카드 세로 스택 */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: s.gap, height: s.products_h - s.gap }}>
          <_ProductCard
            slot="thumb.product_image_2"
            label={lbl2}
            src={v.product_image_2}
            width="100%"
            height="50%"
            radius={s.card_radius * 0.75}
            pad={s.image_pad * 0.7}
            labelSize={s.label * 0.88}
            labelColor={themeColor}
            isPrimary={false}
          />
          <_ProductCard
            slot="thumb.product_image_3"
            label={lbl3}
            src={v.product_image_3}
            width="100%"
            height="50%"
            radius={s.card_radius * 0.75}
            pad={s.image_pad * 0.7}
            labelSize={s.label * 0.88}
            labelColor={themeColor}
            isPrimary={false}
          />
        </div>
      </div>

      {/* FOOTER — 가격 + 브랜드 */}
      <div data-slot-zone="footer" style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        padding: `${s.gap}px ${s.pad}px ${s.pad}px`,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        zIndex: 2,
      }}>
        <div data-slot="thumb.highlight_price" style={{
          background: 'rgba(0,0,0,0.22)',
          color: '#fff',
          fontSize: s.price, fontWeight: 800,
          padding: `${s.price*0.14}px ${s.price*0.5}px`,
          borderRadius: s.price_radius,
          letterSpacing: '-0.01em',
          backdropFilter: 'blur(4px)',
        }}>{price}</div>
        <div data-slot="thumb.brand_mark" style={{
          fontSize: s.brand, fontWeight: 700,
          color: 'rgba(255,255,255,0.85)',
          letterSpacing: '0.12em',
        }}>{brandMark}</div>
      </div>
    </div>
  );
};

/* 상품 카드 (내부) */
function _ProductCard({ slot, label, src, width, height, radius, pad, labelSize, labelColor, isPrimary }) {
  return (
    <div style={{
      width, height,
      background: '#fff', borderRadius: radius,
      boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
      padding: pad,
      display: 'flex', flexDirection: 'column',
      position: 'relative',
      boxSizing: 'border-box',
    }}>
      <div style={{
        position: 'absolute', top: pad * 0.7, left: pad * 0.7,
        background: labelColor, color: '#fff',
        fontSize: labelSize, fontWeight: 800,
        padding: `${labelSize*0.15}px ${labelSize*0.5}px`,
        borderRadius: labelSize * 0.35,
        letterSpacing: '0.04em',
        zIndex: 2,
      }}>{label}</div>
      <div data-slot={slot} style={{
        flex: 1,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        {src ? (
          <img src={src} alt="" style={{
            maxWidth: '100%', maxHeight: '100%',
            objectFit: 'contain',
          }}/>
        ) : (
          <div style={{
            width: '60%', aspectRatio: '1/1',
            background: '#F0F0F0', borderRadius: radius * 0.5,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#999', fontSize: labelSize * 0.9,
          }}>이미지</div>
        )}
      </div>
    </div>
  );
}

/* React 17/18 양쪽 호환을 위한 useMemo 별칭 */
function useMemo_t(fn, deps) { return React.useMemo(fn, deps); }
