/* pml-profiler-panel.jsx — 오디언스 프로파일링 패널 (자체 Persona Feature 엔진 + HPO) · PRD §13/§14
 *
 *  익스텐션 모드 신규 탭. 무중단 가산 — 기존 탭/위저드 변경 없음.
 *  바이올렛 오로라 유지: 실측(A)=plant solid / 추론(B)=cyan / 추론(C)=amber / dormant=점선 ghost.
 *  의존: window.PML, window.HpoEngine, window.BrandProfiles.
 */
(function () {
  var useState = React.useState, useMemo = React.useMemo;

  var TONES = {
    amber: ['#3a2a12', '#f0b46a'], cyan: ['#11303a', '#5fc7e0'], plant: ['#13301f', '#5fcf94'],
    mute: ['#23262d', '#9aa0aa'], red: ['#3a1b1b', '#e08a8a'], violet: ['#241338', '#b98cf0'],
  };
  function Badge(props) {
    var c = TONES[props.tone || 'mute'];
    return React.createElement('span', { style: {
      display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 7px', borderRadius: 4,
      fontSize: 10.5, fontFamily: 'var(--font-mono)', fontWeight: 600, background: c[0], color: c[1], whiteSpace: 'nowrap',
    } }, props.children);
  }
  function tierTone(d) {
    if (!d) return 'mute';
    if (d.tier === 'measured') return 'plant';
    if (d.tier === 'inference') return d.sameCat ? 'cyan' : 'amber';
    return 'mute';
  }
  function tierLabel(d) {
    if (!d) return '표본 없음';
    if (d.tier === 'measured') return '실측 A';
    if (d.tier === 'inference') return d.sameCat ? '추론 B·동일' : '추론 C·교차';
    return '—';
  }
  function won(v) { return '₩' + Math.round(v).toLocaleString(); }
  function pct(v) { return Math.round(v * 100) + '%'; }

  function SectionHead(props) {
    return React.createElement('h4', { style: {
      margin: props.first ? '0 0 10px' : '26px 0 10px', fontSize: 12, letterSpacing: '0.04em',
      color: 'var(--ink-400)', textTransform: 'uppercase', fontFamily: 'var(--font-mono)',
    } }, props.children);
  }
  var card = { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8 };
  var cardPad = Object.assign({ padding: '13px 15px' }, card);

  /* ── 1. 파이프라인 다이어그램 ── */
  function Pipeline() {
    var diag = window.PML.diagnose();
    return React.createElement('div', { style: Object.assign({ marginTop: 12, padding: '14px 16px' }, card) },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 10 } },
        React.createElement('strong', { style: { fontSize: 12.5 } }, '행동 → 시그널 → 오디언스 파이프라인'),
        React.createElement(Badge, { tone: diag.ready ? 'plant' : 'cyan' }, diag.ready ? '외부 모델 연결' : '외부 모델 미연결'),
        React.createElement(Badge, { tone: 'violet' }, '자체엔진 상시 작동')
      ),
      React.createElement('div', { style: { display: 'flex', alignItems: 'stretch', gap: 6, flexWrap: 'wrap' } },
        diag.steps.map(function (s, i) {
          return React.createElement('div', { key: s.id, style: { display: 'flex', alignItems: 'center', gap: 6 } },
            React.createElement('div', { style: {
              padding: '7px 11px', borderRadius: 6, fontSize: 11.5, fontFamily: 'var(--font-mono)',
              border: '1px ' + (s.done ? 'solid' : 'dashed') + ' ' + (s.done ? '#5fcf94' : 'var(--border)'),
              background: s.done ? '#13301f' : 'transparent', color: s.done ? '#9fe7bf' : 'var(--ink-300)',
            } }, s.label.replace(/\s*\(.*\)/, '')),
            i < diag.steps.length - 1 ? React.createElement('span', { style: { color: 'var(--ink-400)' } }, '→') : null
          );
        })
      ),
      React.createElement('p', { style: { margin: '10px 0 0', fontSize: 11.5, lineHeight: 1.6, color: 'var(--ink-300)' } }, diag.note),
      !diag.ready ? React.createElement('details', { style: { marginTop: 8 } },
        React.createElement('summary', { style: { cursor: 'pointer', fontSize: 11.5, color: 'var(--ink-400)' } }, '▸ 외부 오디언스 모델(optional) 연결 입력 양식'),
        React.createElement('div', { style: { marginTop: 8 } },
          window.PML.requestForm().fields.map(function (f) {
            return React.createElement('div', { key: f.key, style: { display: 'flex', gap: 10, padding: '4px 0', fontSize: 11.5, borderBottom: '1px solid var(--border)' } },
              React.createElement('code', { style: { fontFamily: 'var(--font-mono)', color: '#b98cf0', minWidth: 168 } }, f.key),
              React.createElement('span', { style: { color: 'var(--ink-400)' } }, f.desc));
          }),
          React.createElement('p', { style: { margin: '8px 0 0', fontSize: 11, color: 'var(--ink-400)' } }, window.PML.requestForm().note)
        )
      ) : null
    );
  }

  /* ── 2. 우선순위 지정 ── */
  function PrioritySelector(props) {
    var order = props.order;
    return React.createElement('div', { style: Object.assign({ marginTop: 12, padding: '13px 15px' }, card) },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 9, flexWrap: 'wrap' } },
        React.createElement('strong', { style: { fontSize: 12.5 } }, '정밀도 우선순위 지정'),
        React.createElement('span', { style: { fontSize: 11, color: 'var(--ink-400)' } }, '클릭 = 1순위로 올림. Feature 차원가중·출력 강조에 반영.')),
      React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
        order.map(function (k, i) {
          var on = i === 0;
          return React.createElement('button', { key: k, onClick: function () { props.onPromote(k); }, style: {
            display: 'flex', alignItems: 'center', gap: 8, padding: '8px 13px', borderRadius: 7, cursor: 'pointer',
            border: '1px solid ' + (on ? '#b98cf0' : 'var(--border)'), background: on ? '#241338' : 'transparent',
            color: on ? '#d9c2f7' : 'var(--ink-200)', fontFamily: 'var(--font-sans)', fontSize: 12.5, fontWeight: on ? 700 : 500,
          } },
            React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: 11, opacity: 0.7 } }, (i + 1)),
            window.PML.LABELS[k],
            React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: 10.5, opacity: 0.6 } }, 'w=' + window.PML.groupWeights()[k]));
        }))
    );
  }

  /* ── 3. 오디언스 추론 ── */
  function DimRow(props) {
    var d = props.d, label = props.label, fmt = props.fmt;
    if (!d) return React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--border)' } },
      React.createElement('span', { style: { color: 'var(--ink-300)' } }, label),
      React.createElement(Badge, { tone: 'mute' }, '표본 없음'));
    var ci = d.ci ? (' [' + fmt(d.ci[0]) + ' ~ ' + fmt(d.ci[1]) + ']') : '';
    return React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--border)' } },
      React.createElement('span', { style: { color: 'var(--ink-200)', fontSize: 13 } }, label),
      React.createElement('span', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
        React.createElement('strong', { style: { fontFamily: 'var(--font-mono)', fontSize: 13 } }, fmt(d.value)),
        d.tier === 'inference' ? React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-400)' } }, ci) : null,
        React.createElement(Badge, { tone: tierTone(d) }, tierLabel(d))));
  }
  function ShoppingIntent(props) {
    var si = props.si;
    if (!si) return null;
    var mix = si.mixRecommend;
    return React.createElement('div', null,
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(300px,1fr))', gap: 12 } },
        // demo
        React.createElement('div', { style: cardPad },
          React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 } },
            React.createElement('strong', { style: { fontSize: 13 } }, '유사 사용자 추론 · 성·연령'),
            React.createElement(Badge, { tone: si.measured ? 'plant' : 'cyan' }, si.measured ? '브랜드 실측' : 'lookalike 추론')),
          React.createElement(DimRow, { d: si.dims.femaleSkew, label: '여성 비중', fmt: pct }),
          React.createElement(DimRow, { d: si.dims.mobilePct, label: '모바일 비중', fmt: function (v) { return Math.round(v) + '%'; } }),
          React.createElement(DimRow, { d: si.dims.aov, label: '예상 AOV', fmt: won }),
          si.ageDist ? React.createElement('div', { style: { marginTop: 10 } },
            React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 } },
              React.createElement('span', { style: { fontSize: 11.5, color: 'var(--ink-400)' } }, '연령 분포'),
              React.createElement(Badge, { tone: si.ageDist.tier === 'measured' ? 'plant' : 'amber' }, si.ageDist.tier === 'measured' ? '실측' : '표본 참고')),
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
              si.ageDist.bars.slice(0, 8).map(function (b, i) {
                return React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 11 } },
                  React.createElement('span', { style: { width: 52, color: 'var(--ink-400)', fontFamily: 'var(--font-mono)' } }, b.label),
                  React.createElement('span', { style: { flex: 1, height: 8, background: 'var(--bg)', borderRadius: 3, overflow: 'hidden' } },
                    React.createElement('span', { style: { display: 'block', height: '100%', width: Math.min(100, b.pct * 3) + '%', background: 'linear-gradient(90deg,#6f4bd8,#b98cf0)' } })),
                  React.createElement('span', { style: { width: 38, textAlign: 'right', fontFamily: 'var(--font-mono)', color: 'var(--ink-300)' } }, b.pct + '%'));
              }))) : null),
        // mix recommend
        React.createElement('div', { style: cardPad },
          React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
            React.createElement('strong', { style: { fontSize: 13 } }, '비중 추천 · 관심사 : 구매의도'),
            React.createElement(Badge, { tone: 'cyan' }, '예측 추천')),
          React.createElement('div', { style: { display: 'flex', height: 30, borderRadius: 6, overflow: 'hidden', border: '1px solid var(--border)' } },
            React.createElement('div', { style: { width: mix.interestPct + '%', background: 'linear-gradient(90deg,#6f4bd8,#9a6ef0)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11.5, fontWeight: 700, color: '#fff', fontFamily: 'var(--font-mono)' } }, '관심사 ' + mix.interestPct + '%'),
            React.createElement('div', { style: { width: mix.intentPct + '%', background: 'linear-gradient(90deg,#d8704b,#f0a06e)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11.5, fontWeight: 700, color: '#fff', fontFamily: 'var(--font-mono)' } }, '구매의도 ' + mix.intentPct + '%')),
          React.createElement('p', { style: { margin: '8px 0 0', fontSize: 11, color: 'var(--ink-400)' } }, '± ' + mix.ci + 'p 신뢰구간 · ' + mix.rationale)),
      ),
      // expanded cats
      React.createElement(SectionHead, null, '카테고리 확장 · 결합분포 lift'),
      si.expandedCats.length ? React.createElement('div', { style: Object.assign({ overflow: 'hidden' }, card) },
        React.createElement('table', { style: { width: '100%', borderCollapse: 'collapse', fontSize: 12.5 } },
          React.createElement('thead', null, React.createElement('tr', { style: { background: 'var(--bg)', color: 'var(--ink-400)', textAlign: 'left' } },
            React.createElement('th', { style: { padding: '7px 12px', fontWeight: 600 } }, '확장 카테고리'),
            React.createElement('th', { style: { padding: '7px 12px', fontWeight: 600, fontFamily: 'var(--font-mono)' } }, 'lift'),
            React.createElement('th', { style: { padding: '7px 12px', fontWeight: 600 } }, '근거'),
            React.createElement('th', { style: { padding: '7px 12px', fontWeight: 600 } }, 'tier'))),
          React.createElement('tbody', null, si.expandedCats.map(function (c, i) {
            return React.createElement('tr', { key: i, style: { borderTop: '1px solid var(--border)' } },
              React.createElement('td', { style: { padding: '7px 12px' } }, c.cat),
              React.createElement('td', { style: { padding: '7px 12px', fontFamily: 'var(--font-mono)', color: c.lift >= 1.3 ? '#5fcf94' : 'var(--ink-300)' } }, c.lift != null ? c.lift.toFixed(2) + '×' : '—'),
              React.createElement('td', { style: { padding: '7px 12px', color: 'var(--ink-400)', fontSize: 11.5 } }, c.via),
              React.createElement('td', { style: { padding: '7px 12px' } }, React.createElement(Badge, { tone: 'amber' }, 'C 참고')));
          }))) ) : React.createElement('p', { style: { fontSize: 12, color: 'var(--ink-400)' } }, '확장 표본 부족 — 전체 참고 데이터 적재 시 활성(거짓정밀 금지).'),
      // GFA mapping
      React.createElement(SectionHead, null, 'GFA 매핑 · 노출 ON · 예산 비중'),
      React.createElement('div', { style: cardPad },
        React.createElement('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap' } },
          si.gfaMapping.segments.map(function (s, i) {
            return React.createElement('span', { key: i, style: { display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 14, border: '1px solid #2c6e8c', background: '#0f2630', fontSize: 11.5 } },
              React.createElement('span', { style: { width: 6, height: 6, borderRadius: '50%', background: '#5fc7e0' } }),
              s.cat, React.createElement('span', { style: { fontFamily: 'var(--font-mono)', color: '#5fc7e0' } }, s.budgetSharePct + '%'));
          })),
        React.createElement('p', { style: { margin: '9px 0 0', fontSize: 11, color: 'var(--ink-400)', lineHeight: 1.6 } },
          '✓ ' + si.gfaMapping.note, React.createElement('br'), '↔ ' + si.gfaMapping.saNote))
    );
  }

  /* ── 4. 키워드 시그널 ── */
  function CustomAttributes(props) {
    var rows = props.rows;
    if (!rows || !rows.length) return React.createElement('p', { style: { fontSize: 12, color: 'var(--ink-400)' } }, '키워드를 입력하면 시드 Feature와의 유사도 순위를 표시합니다.');
    var max = Math.max.apply(null, rows.map(function (r) { return r.similarity || 0; })) || 1;
    return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 5 } },
      rows.map(function (r, i) {
        return React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', borderBottom: '1px solid var(--border)' } },
          React.createElement('span', { style: { width: 150, fontSize: 12.5, color: 'var(--ink-100)' } }, r.keyword),
          React.createElement('span', { style: { flex: 1, height: 9, background: 'var(--bg)', borderRadius: 4, overflow: 'hidden' } },
            React.createElement('span', { style: { display: 'block', height: '100%', width: ((r.similarity || 0) / max * 100) + '%', background: 'linear-gradient(90deg,#11303a,#5fc7e0)' } })),
          React.createElement('span', { style: { width: 48, textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 12, color: '#5fc7e0' } }, r.similarity != null ? r.similarity.toFixed(2) : '—'),
          React.createElement('span', { style: { width: 120, fontSize: 10.5, color: 'var(--ink-400)', fontFamily: 'var(--font-mono)' } }, (r.matchedCats || []).slice(0, 2).join('·') || '—'));
      }),
      React.createElement('p', { style: { margin: '8px 0 0', fontSize: 11, color: 'var(--ink-400)' } }, '상대 유사도 순위(절대 확률 아님). 키워드 시그널 (착안: 외부 모델) — 키워드 엔진 산출의 역방향 검증.'));
  }

  /* ── 5. HPO ── */
  function HpoSection() {
    var H = window.HpoEngine;
    var stored = H.current();
    var st = useState(null), res = st[0], setRes = st[1];
    var ap = useState(!!stored), applied = ap[0], setApplied = ap[1];
    var bz = useState(false), busy = bz[0], setBusy = bz[1];

    function run() {
      setBusy(true);
      setTimeout(function () { try { setRes(H.search({ method: 'tpe', nTrials: 80 })); } catch (e) { setRes({ status: 'error', note: String(e) }); } setBusy(false); }, 30);
    }
    function applyBest() { if (res && res.best) { H.apply(res.best); setApplied(true); } }
    function resetW() { H.reset(); setApplied(false); }

    var foldInfo = H.folds();
    return React.createElement('div', null,
      React.createElement('div', { style: Object.assign({ padding: '13px 15px' }, card) },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 8 } },
          React.createElement('strong', { style: { fontSize: 13 } }, 'HPO · 엔진 가중치 자동 튜닝'),
          React.createElement(Badge, { tone: 'violet' }, 'LOBO 교차검증'),
          applied ? React.createElement(Badge, { tone: 'plant' }, '튜닝 가중치 적용중') : React.createElement(Badge, { tone: 'mute' }, '하드코딩 기본값')),
        React.createElement('p', { style: { margin: '0 0 10px', fontSize: 11.5, lineHeight: 1.6, color: 'var(--ink-300)' } },
          '하드코딩 가중치를 brand 실측 대비 검증오차 최소화로 탐색. 딥러닝 학습 아님 — 투명 통계엔진 가중치 튜닝. 표본↑ 시 CI 수렴(북극성).'),
        // search space
        React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(230px,1fr))', gap: 8, marginBottom: 10 } },
          H.SEARCH_SPACE.map(function (s) {
            return React.createElement('div', { key: s.key, style: { padding: '8px 10px', background: 'var(--bg)', borderRadius: 6, border: '1px solid var(--border)' } },
              React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between' } },
                React.createElement('code', { style: { fontFamily: 'var(--font-mono)', fontSize: 11.5, color: '#b98cf0' } }, s.key),
                React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-400)' } }, '[' + s.min + ',' + s.max + ']' + (s.scale === 'log' ? ' log' : ''))),
              React.createElement('p', { style: { margin: '4px 0 0', fontSize: 10.5, color: 'var(--ink-400)', lineHeight: 1.4 } }, s.target));
          })),
        // fold honesty
        React.createElement('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 10 } },
          H.DIMS.map(function (d) {
            var n = (foldInfo[d.dim] || []).length;
            return React.createElement(Badge, { key: d.dim, tone: n >= 2 ? 'cyan' : 'mute' }, d.dim + ' 폴드 ' + n);
          })),
        React.createElement('button', { onClick: run, disabled: busy, style: {
          padding: '9px 16px', borderRadius: 7, border: 'none', cursor: busy ? 'wait' : 'pointer',
          background: '#6f4bd8', color: '#fff', fontWeight: 700, fontSize: 13, fontFamily: 'var(--font-sans)',
        } }, busy ? '탐색 중…' : '튜닝 실행 (Random→TPE, 멀티시드)')
      ),
      res ? React.createElement('div', { style: Object.assign({ marginTop: 12, padding: '13px 15px' }, card) },
        res.status === 'dormant' ? React.createElement('div', null,
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 } }, React.createElement(Badge, { tone: 'cyan' }, '휴면'), React.createElement('strong', { style: { fontSize: 13 } }, '표본 부족 — 튜닝 비활성')),
          React.createElement('p', { style: { margin: 0, fontSize: 12, color: 'var(--ink-300)', lineHeight: 1.6 } }, res.reason)
        ) : res.status === 'error' ? React.createElement('p', { style: { color: '#e08a8a', fontSize: 12 } }, res.note) :
        React.createElement('div', null,
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 10 } },
            React.createElement(Badge, { tone: res.status === 'ok' ? 'plant' : 'amber' }, res.status === 'ok' ? '신뢰 가능' : '잠정(표본 얇음)'),
            React.createElement('span', { style: { fontSize: 12, color: 'var(--ink-300)' } }, 'CV 손실 '),
            React.createElement('strong', { style: { fontFamily: 'var(--font-mono)', fontSize: 13 } }, res.cvLoss),
            React.createElement('span', { style: { fontSize: 11, color: 'var(--ink-400)', fontFamily: 'var(--font-mono)' } }, '[' + res.ci[0] + '~' + res.ci[1] + ']'),
            React.createElement('span', { style: { fontSize: 11.5, color: res.improvePct > 0 ? '#5fcf94' : 'var(--ink-400)' } }, '기본값 대비 ' + (res.improvePct > 0 ? '−' : '+') + Math.abs(res.improvePct) + '% 오차')),
          React.createElement('p', { style: { margin: '0 0 10px', fontSize: 11, color: 'var(--ink-400)', lineHeight: 1.5 } }, res.note),
          // best params + importance
          React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 } },
            React.createElement('div', null, React.createElement('div', { style: { fontSize: 11, color: 'var(--ink-400)', marginBottom: 5, fontFamily: 'var(--font-mono)' } }, '최적 가중치'),
              Object.keys(res.best || {}).map(function (k) {
                return React.createElement('div', { key: k, style: { display: 'flex', justifyContent: 'space-between', fontSize: 11.5, padding: '3px 0', borderBottom: '1px solid var(--border)' } },
                  React.createElement('code', { style: { fontFamily: 'var(--font-mono)', color: '#b98cf0' } }, k),
                  React.createElement('span', { style: { fontFamily: 'var(--font-mono)' } }, res.best[k]));
              })),
            React.createElement('div', null, React.createElement('div', { style: { fontSize: 11, color: 'var(--ink-400)', marginBottom: 5, fontFamily: 'var(--font-mono)' } }, '파라미터 중요도'),
              (res.importance || []).map(function (im) {
                var mx = (res.importance[0] && res.importance[0].sensitivity) || 1;
                return React.createElement('div', { key: im.key, style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, padding: '2px 0' } },
                  React.createElement('span', { style: { width: 96, fontFamily: 'var(--font-mono)', color: 'var(--ink-300)' } }, im.key),
                  React.createElement('span', { style: { flex: 1, height: 7, background: 'var(--bg)', borderRadius: 3, overflow: 'hidden' } },
                    React.createElement('span', { style: { display: 'block', height: '100%', width: (im.sensitivity / mx * 100) + '%', background: '#6f4bd8' } })),
                  React.createElement('span', { style: { width: 44, textAlign: 'right', fontFamily: 'var(--font-mono)', color: 'var(--ink-400)' } }, im.sensitivity));
              }))),
          React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 12 } },
            React.createElement('button', { onClick: applyBest, disabled: applied, style: {
              padding: '8px 14px', borderRadius: 7, border: '1px solid #5fcf94', cursor: applied ? 'default' : 'pointer',
              background: applied ? '#13301f' : 'transparent', color: '#5fcf94', fontWeight: 700, fontSize: 12.5,
            } }, applied ? '✓ 적용됨' : '이 가중치 적용'),
            applied ? React.createElement('button', { onClick: resetW, style: {
              padding: '8px 14px', borderRadius: 7, border: '1px solid var(--border)', cursor: 'pointer',
              background: 'transparent', color: 'var(--ink-300)', fontSize: 12.5,
            } }, '기본값으로 리셋') : null)
        )
      ) : null
    );
  }

  /* ── 메인 패널 ── */
  function PMLProfilerPanel() {
    if (!window.PML || !window.HpoEngine) return React.createElement('div', { style: { padding: 24, color: 'var(--ink-400)' } }, 'PML/HpoEngine 미로드.');
    var brands = (window.BrandProfiles && window.BrandProfiles.list()) || [];
    var sd = useState(brands[0] || ''), seed = sd[0], setSeed = sd[1];
    var po = useState(window.PML.getPriority()), order = po[0], setOrder = po[1];
    function promote(k) { var n = [k].concat(order.filter(function (x) { return x !== k; })); window.PML.setPriority(n); setOrder(n); }

    var prof = useMemo(function () { return seed && window.BrandProfiles ? window.BrandProfiles.match(seed) : null; }, [seed]);
    var defKw = (prof && prof.signatureKeywords) ? prof.signatureKeywords.join(', ') : '';
    var kw = useState(defKw), kwText = kw[0], setKwText = kw[1];
    React.useEffect(function () { setKwText(defKw); }, [seed]);

    var si = useMemo(function () { try { return window.PML.shoppingIntent({ brand: seed, category: prof && prof.meta.categoryLabel, keywords: defKw }); } catch (e) { return null; } }, [seed, order]);
    var ca = useMemo(function () {
      var list = kwText.split(',').map(function (s) { return s.trim(); }).filter(Boolean);
      try { return window.PML.customAttributes(list, seed); } catch (e) { return []; }
    }, [kwText, seed, order]);
    var prov = window.PML.provenance;

    return React.createElement('div', { style: { padding: '18px 20px', maxWidth: 1100, margin: '0 auto' } },
      // header
      React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', gap: 14, flexWrap: 'wrap', padding: '14px 16px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8 } },
        React.createElement('div', { style: { flex: '1 1 420px' } },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
            React.createElement('strong', { style: { fontFamily: 'var(--font-display)', fontSize: 16 } }, '오디언스 프로파일링 · 자체 Feature 엔진 (Persona Matrix LAB)'),
            React.createElement(Badge, { tone: 'violet' }, 'self-hosted'),
            React.createElement(Badge, { tone: 'cyan' }, '외부 모델 optional')),
          React.createElement('p', { style: { margin: '8px 0 0', fontSize: 12, lineHeight: 1.55, color: 'var(--ink-300)' } },
            prov.paradigm + ' — ' + prov.kind + '. ' + prov.note),
          React.createElement('p', { style: { margin: '4px 0 0', fontSize: 11, color: 'var(--ink-400)', lineHeight: 1.5 } },
            '정직한 갭(외부 대규모 행동모델 대비 미달): ' + prov.gaps.join(' · ')))),
      Pipeline(),
      React.createElement(PrioritySelector, { order: order, onPromote: promote }),
      // seed selector
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, flexWrap: 'wrap' } },
        React.createElement(SectionHead, { first: true }, '오디언스 추론 · 시드 → 유사 사용자'),
        React.createElement('select', { value: seed, onChange: function (e) { setSeed(e.target.value); }, style: {
          padding: '6px 10px', borderRadius: 6, background: 'var(--surface)', color: 'var(--ink-100)',
          border: '1px solid var(--border)', fontSize: 12.5, fontFamily: 'var(--font-sans)',
        } }, brands.map(function (b) { return React.createElement('option', { key: b, value: b }, b); }))),
      React.createElement(ShoppingIntent, { si: si }),
      // custom attributes
      React.createElement(SectionHead, null, '키워드 시그널 · 키워드 유사도'),
      React.createElement('textarea', { value: kwText, onChange: function (e) { setKwText(e.target.value); }, rows: 2,
        placeholder: '키워드 콤마 구분 입력 (예: 골전도이어폰, 러닝, 수영)', style: {
          width: '100%', padding: '9px 12px', borderRadius: 7, background: 'var(--surface)', color: 'var(--ink-100)',
          border: '1px solid var(--border)', fontSize: 12.5, fontFamily: 'var(--font-sans)', resize: 'vertical', boxSizing: 'border-box', marginBottom: 10,
        } }),
      React.createElement(CustomAttributes, { rows: ca }),
      // HPO
      React.createElement(SectionHead, null, 'HPO · 예측 정확도 튜닝'),
      React.createElement(HpoSection, null)
    );
  }

  Object.assign(window, { PMLProfilerPanel: PMLProfilerPanel });
})();
