/* tier-polish.jsx — v3 의사결정 폴리시 (무중단 가산)
 * 기존 컴포넌트/기능을 일절 제거·대체하지 않음. window 전역으로 노출만 하고,
 * workflow.jsx(스탠다드 Step3)·easy-mode.jsx(이지 결과) 기존 자리에 "끼워넣기"만 한다.
 * 기존 토큰(--text/--text-dim/--font-mono)·관습(p.tier, analysis 플래그) 재사용.
 * 원칙(CLAUDE.md): 측정=tier A, 표본=tier C 추정. 비중은 고정정답 아님 → 퍼널·신뢰구간 동반(DP-3/5).
 */
(function () {
  'use strict';
  const e = React.createElement;

  // ── 등급 판정: 기존 analysis 플래그만 사용(없으면 null → 뱃지 미표시, 거짓정밀 금지) ──
  function gradeOf(analysis) {
    if (!analysis) return null;
    if (analysis.measuredProfile) return 'A';
    if (analysis.salesProfile) return 'B';
    if (analysis.referenceProfile) return 'C';
    if (analysis.brandMetaProfile) return 'D';
    return null;
  }

  const GRADE = {
    A: { label: '실측', title: '측정값 직접 적용 (tier A)' },
    B: { label: '부분실측', title: '부분 실측 / 공식 메타 (tier B)' },
    C: { label: '표본추정', title: '표본 참고 prior — 신뢰구간 명시 (tier C)' },
    D: { label: '웹추정', title: '웹 추정 — 측정값 아님 (tier D)' },
  };
  function TierBadge({ grade, compact }) {
    if (!grade || !GRADE[grade]) return null;
    const g = GRADE[grade];
    return e('span', { className: 'tpf-badge', 'data-grade': grade, title: g.title },
      e('span', { className: 'tpf-badge-dot' }), g.label + (compact ? '' : ' ' + grade));
  }

  function ConfInterval({ interval, conf = 2, unit = '' }) {
    if (interval == null && conf == null) return null;
    const bars = [0, 1, 2, 3].map(i => e('i', { key: i, className: 'tpf-cbar' + (i < conf ? ' on' : '') }));
    return e('span', { className: 'tpf-ci' },
      interval != null ? e('span', { className: 'tpf-ci-iv' }, '±' + interval + unit) : null,
      e('span', { className: 'tpf-cbars' }, bars));
  }

  // ── 퍼널 반응형 비중 추천 (DP-5: 추천값 + 신뢰구간, 고정정답 아님) ──
  function recommend(stage, fit) {
    const base = { awareness: 65, interest: 50, conversion: 40 }[stage] ?? 50;
    let interest = base; const why = [];
    if (stage === 'awareness') why.push('퍼널(인지) → 관심사 광역 가중 ↑');
    else if (stage === 'conversion') why.push('퍼널(전환) → 구매의도 가중 ↑');
    else why.push('퍼널(관심) → 관심사·의도 균형');
    const hasMeasured = fit && typeof fit.repurchase === 'number';
    if (hasMeasured && fit.repurchase > 0.04) { interest -= 6; why.push('실측 재구매 높음 → 의도 효율 우위(prior)'); }
    if (fit && typeof fit.intentBias === 'number') interest -= Math.round(fit.intentBias * 6);
    const band = (fit && fit.budgetBand) || 'mid';
    if (band === 'low') { interest -= 6; why.push('저예산 → 구매의도 정밀'); }
    else if (band === 'high') { interest += 6; why.push('고예산 → 관심사 광역 여유'); }
    else why.push('가용 예산 중간 → 정밀·광역 균형');
    interest = Math.max(20, Math.min(80, Math.round(interest)));
    return { interest, intent: 100 - interest, iv: hasMeasured ? 8 : 12, conf: hasMeasured ? 3 : 2, why };
  }

  function FunnelWeighting({ fit, defaultStage = 'conversion' }) {
    const [stage, setStage] = React.useState(defaultStage);
    const r = recommend(stage, fit);
    const stages = [['awareness', '인지'], ['interest', '관심'], ['conversion', '전환']];
    return e('div', { className: 'tpf-fw' },
      e('div', { className: 'tpf-fw-head' },
        e('span', { className: 'tpf-fw-title' }, '관심사 : 구매의도 비중'),
        e(TierBadge, { grade: 'C', compact: true }),
        e('span', { className: 'tpf-fw-pred' }, '예측 추천')),
      e('div', { className: 'tpf-fw-toggle' }, stages.map(([k, lab]) =>
        e('button', { key: k, className: stage === k ? 'on' : '', onClick: () => setStage(k) }, lab))),
      e('div', { className: 'tpf-fw-nums' },
        e('div', { className: 'tpf-fw-s int' }, e('span', { className: 'l' }, '관심사'), e('span', { className: 'v' }, r.interest)),
        e('div', { className: 'tpf-fw-s buy' }, e('span', { className: 'l' }, '구매의도'), e('span', { className: 'v' }, r.intent))),
      e('div', { className: 'tpf-fw-bar' },
        e('div', { className: 'i', style: { width: r.interest + '%' } }),
        e('div', { className: 'b', style: { width: r.intent + '%' } })),
      e('div', { className: 'tpf-fw-meta' },
        e('span', null, '신뢰구간 ', e('b', null, '±' + r.iv)), e(ConfInterval, { conf: r.conf })),
      e('div', { className: 'tpf-fw-why' }, r.why.map((t, i) => e('div', { key: i, className: 'tpf-fw-chip' }, t))));
  }

  // ── 의사결정 3카드 (스탠다드 Step3 상단에 얹는 "결정 먼저" 밴드) ──
  function DecisionBand({ analysis, chosen }) {
    if (!analysis || !chosen) return null;
    const grade = gradeOf(analysis);
    const leaves = (() => {
      try { return chosen.query.flatMap(g => g.leaves).slice(0, 3).map(l => l.split(' > ').pop()); }
      catch (_) { return []; }
    })();
    const r = chosen.result || {};
    const fit = { repurchase: analysis.measuredProfile && analysis.measuredProfile.repurchase, budgetBand: 'mid' };
    const reach = window.SimEngine && r.finalReach ? window.SimEngine.fmtN(r.finalReach) : null;
    const tierIsIntent = chosen.tier === 'intent';
    return e('div', { className: 'tpf-band no-print' },
      e('div', { className: 'tpf-band-label' }, '의사결정',
        e('span', { className: 'tpf-band-hint' }, '먼저 답, 근거는 아래 — 결정에 필요한 3가지')),
      e('div', { className: 'tpf-band-grid' },
        // 1) 타겟
        e('div', { className: 'tpf-dc target' },
          e('h4', null, '핵심 타겟', e(TierBadge, { grade, compact: true })),
          e('div', { className: 'tpf-dc-big' }, chosen.name),
          chosen.angle ? e('div', { className: 'tpf-dc-sub' }, chosen.angle) : null,
          leaves.length ? e('div', { className: 'tpf-leafrow' }, leaves.map((l, i) =>
            e('span', { key: i, className: 'tpf-leaf' }, l))) : null,
          reach ? e('div', { className: 'tpf-dc-rat' }, '예상 도달 ' + reach + '명' + (r.validity ? ' · 정확도 ' + r.validity : '')) : null),
        // 2) 비중
        e('div', { className: 'tpf-dc intent' },
          e('h4', null, '관심사 : 구매의도 비중'),
          e(FunnelWeighting, { fit })),
        // 3) 액션
        e('div', { className: 'tpf-dc action' },
          e('h4', null, '첫 액션', e('span', { className: 'tpf-prio' }, '우선순위')),
          e('div', { className: 'tpf-stepn' }, 'STEP 01 / 집행'),
          e('div', { className: 'tpf-dc-big sm' },
            tierIsIntent
              ? '구매의도 ‘' + (leaves[0] || chosen.name) + '’ 세그먼트에 예산을 우선 배치, 입찰 정밀 모드.'
              : '관심사 ‘' + (leaves[0] || chosen.name) + '’ 광역 도달부터 시작, 전환 모수 축적 후 정밀화.'),
          e('div', { className: 'tpf-dc-rat' }, '3일 후 CVR 보고 비중 재조정(신뢰구간 내)'))));
  }

  // ── 이지 모드 "결정 먼저" 히어로 (이지 결과 상단에 얹기) ──
  function EasyDecision({ analysis, name, topAge, gender, leaves }) {
    const grade = gradeOf(analysis);
    const tail = (leaves && leaves[0]) || '핵심 카테고리';
    return e('div', { className: 'tpf-ed' },
      e('div', { className: 'tpf-ed-lab' }, '이렇게 설정하세요', e(TierBadge, { grade, compact: true })),
      e('div', { className: 'tpf-ed-answer' },
        e('b', null, name),
        ' 타겟에 ',
        e('span', { className: 'tpf-coral' }, '‘' + tail + '’ 구매의도'),
        ' 비중을 높여 집행하세요.'),
      e('div', { className: 'tpf-ed-meta' },
        topAge ? e('span', { className: 'tpf-pill' }, '핵심 연령 ', e('b', null, topAge)) : null,
        gender ? e('span', { className: 'tpf-pill' }, '성별 ', e('b', null, gender)) : null,
        e('span', { className: 'tpf-pill' }, '비중 추천 ', e('b', null, '관심사 40 : 구매의도 60'))));
  }

  if (!document.getElementById('tpf-styles')) {
    const s = document.createElement('style');
    s.id = 'tpf-styles';
    s.textContent = `
    :root{--tpf-violet:oklch(0.66 0.17 300);--tpf-violet-br:oklch(0.80 0.13 300);--tpf-violet-soft:oklch(0.66 0.17 300/.16);
      --tpf-coral:oklch(0.72 0.15 38);--tpf-coral-br:oklch(0.82 0.12 45);--tpf-coral-soft:oklch(0.72 0.15 38/.16);
      --tpf-line:oklch(0.72 0.10 300/.14);--tpf-line2:oklch(0.72 0.10 300/.24);--tpf-panel:oklch(0.15 0.02 290/.5)}
    .tpf-badge{font-family:var(--font-mono);font-size:10px;letter-spacing:.02em;padding:2px 7px;border-radius:5px;display:inline-flex;align-items:center;gap:5px;white-space:nowrap;vertical-align:middle}
    .tpf-badge-dot{width:5px;height:5px;border-radius:50%}
    .tpf-badge[data-grade="A"]{color:var(--tpf-violet-br);background:var(--tpf-violet-soft);border:1px solid var(--tpf-line2)}
    .tpf-badge[data-grade="A"] .tpf-badge-dot{background:var(--tpf-violet);box-shadow:0 0 6px var(--tpf-violet)}
    .tpf-badge[data-grade="B"]{color:oklch(0.82 0.13 200);background:oklch(0.70 0.12 200/.14);border:1px solid oklch(0.72 0.10 200/.28)}
    .tpf-badge[data-grade="B"] .tpf-badge-dot{background:oklch(0.72 0.12 200)}
    .tpf-badge[data-grade="C"]{color:var(--text-dim);border:1px dashed oklch(0.62 0.02 290/.55)}
    .tpf-badge[data-grade="C"] .tpf-badge-dot{background:var(--text-dim)}
    .tpf-badge[data-grade="D"]{color:var(--text-mute,var(--text-dim));border:1px dotted oklch(0.55 0.02 290/.5)}
    .tpf-badge[data-grade="D"] .tpf-badge-dot{display:none}
    .tpf-ci{display:inline-flex;align-items:center;gap:8px;vertical-align:middle}
    .tpf-ci-iv{font-family:var(--font-mono);font-size:11px;color:var(--text-dim)}
    .tpf-cbars{display:inline-flex;gap:2px}
    .tpf-cbar{width:4px;height:11px;border-radius:1px;background:oklch(0.40 0.02 290)}
    .tpf-cbar.on{background:var(--tpf-violet)}
    .tpf-fw{display:flex;flex-direction:column;gap:9px}
    .tpf-fw-head{display:flex;align-items:center;gap:8px}
    .tpf-fw-title{font-size:13px;font-weight:600;letter-spacing:-.01em;color:var(--text)}
    .tpf-fw-pred{margin-left:auto;font-family:var(--font-mono);font-size:10px;color:var(--text-dim);padding:2px 7px;border:1px dashed oklch(0.62 0.02 290/.5);border-radius:5px}
    .tpf-fw-toggle{display:inline-flex;gap:3px;background:oklch(0.10 0.02 290/.6);padding:3px;border-radius:9px;border:1px solid var(--tpf-line);align-self:flex-start}
    .tpf-fw-toggle button{font:inherit;font-size:12px;color:var(--text-dim);background:none;border:none;padding:5px 13px;border-radius:6px;cursor:pointer;transition:.15s}
    .tpf-fw-toggle button.on{color:var(--text);background:var(--tpf-violet-soft);box-shadow:inset 0 0 0 1px var(--tpf-line2)}
    .tpf-fw-nums{display:flex;justify-content:space-between;align-items:flex-end}
    .tpf-fw-s{display:flex;flex-direction:column;gap:1px}
    .tpf-fw-s.buy{text-align:right}
    .tpf-fw-s .l{font-family:var(--font-mono);font-size:10px;letter-spacing:.04em;text-transform:uppercase}
    .tpf-fw-s.int .l{color:var(--tpf-violet-br)} .tpf-fw-s.buy .l{color:var(--tpf-coral-br)}
    .tpf-fw-s .v{font-size:28px;font-weight:700;letter-spacing:-.02em;color:var(--text)}
    .tpf-fw-bar{height:12px;border-radius:7px;overflow:hidden;display:flex;border:1px solid var(--tpf-line)}
    .tpf-fw-bar .i{background:linear-gradient(90deg,var(--tpf-violet),var(--tpf-violet-br));transition:width .45s cubic-bezier(.4,0,.2,1)}
    .tpf-fw-bar .b{background:linear-gradient(90deg,var(--tpf-coral-br),var(--tpf-coral));transition:width .45s cubic-bezier(.4,0,.2,1)}
    .tpf-fw-meta{display:flex;align-items:center;justify-content:space-between;font-family:var(--font-mono);font-size:11px;color:var(--text-dim)}
    .tpf-fw-meta b{color:var(--text);font-weight:600}
    .tpf-fw-why{display:flex;flex-direction:column;gap:5px;margin-top:2px}
    .tpf-fw-chip{font-size:11.5px;color:var(--text-dim);display:flex;align-items:flex-start;gap:7px;line-height:1.4}
    .tpf-fw-chip::before{content:"";width:5px;height:5px;border-radius:50%;flex:none;margin-top:5px;background:oklch(0.70 0.16 300/.7)}
    /* decision band */
    .tpf-band{margin:4px 0 2px}
    .tpf-band-label{display:flex;align-items:center;gap:9px;margin-bottom:11px;font-family:var(--font-mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--text-dim)}
    .tpf-band-label::before{content:"";width:5px;height:5px;border-radius:50%;background:var(--tpf-violet);box-shadow:0 0 8px var(--tpf-violet)}
    .tpf-band-hint{margin-left:auto;text-transform:none;letter-spacing:0;font-size:11px;color:var(--text-mute)}
    .tpf-band-grid{display:grid;grid-template-columns:1.05fr 1.35fr 1fr;gap:12px}
    .tpf-dc{position:relative;background:var(--tpf-panel);border:1px solid var(--tpf-line);border-radius:14px;padding:17px 18px;display:flex;flex-direction:column;gap:10px;overflow:hidden}
    .tpf-dc::before{content:"";position:absolute;inset:0 0 auto 0;height:2px;background:linear-gradient(90deg,var(--tpf-violet),transparent 70%)}
    .tpf-dc.intent::before{background:linear-gradient(90deg,var(--tpf-coral),transparent 70%)}
    .tpf-dc h4{font-family:var(--font-mono);font-size:11px;letter-spacing:.05em;color:var(--text-dim);text-transform:uppercase;font-weight:500;display:flex;align-items:center;gap:8px;margin:0}
    .tpf-dc-big{font-size:21px;font-weight:700;letter-spacing:-.02em;line-height:1.18;color:var(--text)}
    .tpf-dc-big.sm{font-size:15px;font-weight:600;line-height:1.4}
    .tpf-dc-sub{font-size:12.5px;color:var(--text-dim);line-height:1.5}
    .tpf-leafrow{display:flex;gap:6px;flex-wrap:wrap}
    .tpf-leaf{font-family:var(--font-mono);font-size:11px;color:var(--text-dim);background:oklch(0.18 0.02 290/.5);border:1px solid var(--tpf-line);padding:3px 8px;border-radius:6px}
    .tpf-dc-rat{font-size:11.5px;color:var(--text-dim);line-height:1.45;margin-top:auto}
    .tpf-prio{margin-left:auto;font-family:var(--font-mono);font-size:10px;color:var(--tpf-violet-br);background:var(--tpf-violet-soft);border:1px solid var(--tpf-line2);padding:2px 7px;border-radius:5px}
    .tpf-stepn{font-family:var(--font-mono);font-size:10px;color:var(--tpf-coral-br);letter-spacing:.08em}
    /* easy decision hero */
    .tpf-ed{position:relative;margin-top:14px;background:linear-gradient(135deg,var(--tpf-violet-soft),oklch(0.66 0.16 30/.08));border:1px solid var(--tpf-line2);border-radius:16px;padding:20px 22px;overflow:hidden}
    .tpf-ed::before{content:"";position:absolute;inset:0 auto 0 0;width:3px;background:linear-gradient(var(--tpf-violet),var(--tpf-coral))}
    .tpf-ed-lab{font-family:var(--font-mono);font-size:11px;color:var(--text-dim);letter-spacing:.04em;display:flex;align-items:center;gap:8px}
    .tpf-ed-answer{font-size:19px;font-weight:700;letter-spacing:-.02em;line-height:1.45;margin-top:10px;color:var(--text)}
    .tpf-ed-answer b{color:var(--tpf-violet-br)} .tpf-coral{color:var(--tpf-coral-br)}
    .tpf-ed-meta{display:flex;gap:8px;flex-wrap:wrap;margin-top:13px}
    .tpf-pill{font-family:var(--font-mono);font-size:11px;color:var(--text-dim);background:oklch(0.12 0.02 290/.6);border:1px solid var(--tpf-line);padding:4px 10px;border-radius:999px}
    .tpf-pill b{color:var(--text);font-weight:600}
    @media(max-width:900px){.tpf-band-grid{grid-template-columns:1fr}}
    `;
    document.head.appendChild(s);
  }

  Object.assign(window, { TierBadge, ConfInterval, FunnelWeighting, DecisionBand, EasyDecision, tierGradeOf: gradeOf, tierRecommend: recommend });
})();
