/* ColdStartRoadmap — 신규/콜드스타트 브랜드(실측 0, 자체몰만) 초기 로드맵.

   원칙(CLAUDE.md):
   · 실측 0 → applyToResult(tier A) 금지. 표본은 reference(tier C 렌즈)로만.
   · 로드맵 축은 달력이 아니라 "데이터 성숙도 / 학습 모수". 추정→실측 수렴이 본질.
   · 비중은 고정 정답 없음 → 퍼널(prior)+브랜드핏+일예산 매핑한 *추천값 + 신뢰구간*.
   · 추정을 측정처럼 단정하지 않는다 — 각 단계에 "지금 할 수 있는 것 / 다음 단계 조건" 명시.

   분석 객체(analysis)에서 페르소나(tier별)·confidence·referenceProfile·archetype을 읽어
   3단계(시딩 → 수렴 → 스케일) 카드로 재구성. 별도 엔진 변경 없이 기존 산출물을 합성.
*/

const { useState: useCSRState } = React;

// 퍼널·브랜드핏·예산을 매핑한 구매의도 추천 비중 (TargetingLever 로직과 동일 계열)
function csrRecoShare(funnel, fitAdj, budgetTier) {
  const base = funnel === 'action' ? 70 : funnel === 'awareness' ? 30 : 50;
  const budgetAdj = budgetTier === 'low' ? 15 : budgetTier === 'high' ? -15 : 0;
  return Math.max(10, Math.min(90, Math.round(base + fitAdj + budgetAdj)));
}

function ColdStartRoadmap({ analysis }) {
  const [openPhase, setOpenPhase] = useCSRState(0);
  const personas = analysis.personas || [];
  const ref = analysis.referenceProfile || null;
  const conf = analysis.confidence || 0;
  const fmtN = window.SimEngine?.fmtN || (x => String(x));

  // 페르소나를 tier별로 — 단계별 권장 타겟에 연결
  const byTier = {
    intent:   personas.find(p => p.tier === 'intent'),
    mixed:    personas.find(p => p.tier === 'mixed'),
    interest: personas.find(p => p.tier === 'interest'),
    mobile:   personas.find(p => p.tier === 'mobile'),
  };
  // fit 보정: 표본 렌즈가 있으면 구매자 윤곽이 조금 더 또렷 → +5 (실측 아님)
  const fitAdj = ref ? 5 : 0;
  const fitLabel = ref ? '표본 참고' : '기본(추정)';
  const aov = ref && ref.aov ? ref.aov : null;

  // 신뢰구간 폭 — 콜드스타트는 넓게 시작, 단계가 진행될수록(=실측 누적) 좁아진다고 표기
  const bands = [16, 10, 7];

  const phases = [
    {
      key: 0, tag: 'PHASE 0', label: '시딩 · 학습',
      maturity: '실측 0 — 지금',
      goal: 'GFA 학습 모수 + 스토어 전환 신호 적재',
      why: '매출보다 데이터 적재가 우선. 자동입찰이 학습을 끝내야 이후 단계의 모든 추정이 실측으로 수렴한다.',
      funnel: 'action', funnelLabel: '전환',
      budgetTier: 'low', budgetLabel: '저예산 (정밀)',
      persona: byTier.intent || byTier.mixed || personas[0],
      personaWhy: '낭비를 줄이려 구매의도 정밀 타겟 단일에 집중',
      kpi: '전환수 최대화 (학습 모수 확보) — CPA보다 누적 전환 수',
      trigger: 'GFA 학습 종료 · 최근 1주 40전환 달성 · 스토어 픽셀 모수 확보',
      tone: 'signal',
      band: bands[0],
    },
    {
      key: 1, tag: 'PHASE 1', label: '신호 수렴',
      maturity: '실측 소량 — 1st-party 적재 시작',
      goal: '성과 leaf 검증·확장, 관심사↔구매의도 최적점 탐색',
      why: '성별·연령·시간대 실측이 쌓이며 카테고리 prior 분산이 좁혀짐 → 추정 강도 상향.',
      funnel: 'traffic', funnelLabel: '트래픽·균형',
      budgetTier: 'mid', budgetLabel: '중예산 (확장 테스트)',
      persona: byTier.mixed || byTier.interest || byTier.intent,
      personaWhy: '풀퍼널 결합으로 확장 + A/B 비중 테스트 병행',
      kpi: 'CPA 안정 + ROAS 관측 시작 · 성과 leaf 가지치기',
      trigger: '실측 인구·시간대 수렴 → categoryPriors 분산 감소 · ROAS 손익분기 상회',
      tone: 'cyan',
      band: bands[1],
    },
    {
      key: 2, tag: 'PHASE 2', label: '스케일',
      maturity: '실측 확립 — tier-A 승격',
      goal: '광역 도달 확장 · 자체 실측 hard-apply · 룩어라이크',
      why: '자체 데이터가 tier-A로 승격되면 비로소 applyToResult로 실측 override. 예산 상향 → 관심사 광역 여유.',
      funnel: 'awareness', funnelLabel: '인지·광역',
      budgetTier: 'high', budgetLabel: '고예산 (스케일)',
      persona: byTier.interest || byTier.mobile || byTier.mixed,
      personaWhy: '관심사 광역 + 모바일 신규 카테고리 선점 + 룩어라이크',
      kpi: '규모 매출 + 효율 동시 · 신규 카테고리 점유',
      trigger: '— (실측 누적분을 정식 브랜드 프로파일로 적재 → 본 도구 tier-A 분석 전환)',
      tone: 'plant',
      band: bands[2],
    },
  ];

  return (
    <div className="csr">
      <div className="csr-head">
        <div className="csr-titlewrap">
          <div className="csr-eyebrow">신규 브랜드 초기 로드맵</div>
          <h3 className="csr-title">데이터 성숙도 기준 3단계 — 추정에서 실측으로</h3>
        </div>
        <div className="csr-diag">
          <span className="csr-tierpill csr-t-a is-off">tier A 실측 0</span>
          <span className="csr-arrow">→</span>
          <span className={'csr-tierpill csr-t-c' + (ref ? '' : ' is-off')}>{ref ? 'tier C 표본 렌즈' : 'tier C 표본 없음'}</span>
          <span className="csr-arrow">+</span>
          <span className="csr-tierpill csr-t-d">tier B/D 카테고리 추정</span>
        </div>
      </div>

      <div className="csr-coldnote">
        <b>콜드스타트 진단</b> — {analysis.label}은(는) 자체 측정 데이터가 없습니다.
        그래서 실측 override는 쓰지 않고, {ref
          ? <>동일 카테고리 표본(<b>{(ref.sampleBrands || []).join(', ')}</b>)을 <b>참고 렌즈(tier C)</b>로만 사용합니다. 같은 카테고리라도 구매자는 다르므로 그대로 찍지 않습니다.</>
          : <>카테고리 통계(leaf-stats) 기반 <b>추정</b>으로 출발합니다.</>}
        {' '}집행이 시작되면 1st-party가 쌓여 단계가 올라갑니다.
      </div>

      <div className="csr-track">
        {phases.map((ph, i) => {
          const share = csrRecoShare(ph.funnel, fitAdj, ph.budgetTier);
          const isOpen = openPhase === ph.key;
          const r = ph.persona && ph.persona.result;
          return (
            <div
              key={ph.key}
              className={'csr-card csr-tone-' + ph.tone + (isOpen ? ' is-open' : '')}
              onClick={() => setOpenPhase(ph.key)}
            >
              <div className="csr-card-top">
                <span className="csr-phase-tag">{ph.tag}</span>
                <span className="csr-maturity">{ph.maturity}</span>
              </div>
              <div className="csr-card-label">{ph.label}</div>
              <div className="csr-goal">{ph.goal}</div>

              {/* 추천 비중 + 신뢰구간 */}
              <div className="csr-mixwrap">
                <div className="csr-mix-hl">
                  <span>추천 구매의도 비중</span>
                  <span className="csr-mix-val">{share}<small>%</small> <span className="csr-band">±{ph.band}</span></span>
                </div>
                <div className="csr-mixbar">
                  <div className="csr-mixbar-band" style={{ left: Math.max(0, share - ph.band) + '%', width: Math.min(100, 2 * ph.band) + '%' }} />
                  <div className="csr-mixbar-fill" style={{ width: share + '%' }} />
                  <div className="csr-mixbar-mark" style={{ left: share + '%' }} />
                </div>
                <div className="csr-mixlegend">
                  <span>관심사 {100 - share}%</span>
                  <span>구매의도 {share}%</span>
                </div>
              </div>

              <dl className="csr-rows">
                <div className="csr-row">
                  <dt>목표</dt><dd>{ph.why}</dd>
                </div>
                <div className="csr-row">
                  <dt>권장 타겟</dt>
                  <dd>
                    {ph.persona ? <b>{ph.persona.name}</b> : '—'}
                    <span className="csr-pwhy"> · {ph.personaWhy}</span>
                    {r && (
                      <span className="csr-reach">
                        예상 도달 {fmtN(r.finalReach)}명
                        {r.reachLo != null && r.reachHi != null && (
                          <em> ({fmtN(r.reachLo)}–{fmtN(r.reachHi)})</em>
                        )}
                      </span>
                    )}
                  </dd>
                </div>
                <div className="csr-row">
                  <dt>핵심 KPI</dt><dd>{ph.kpi}</dd>
                </div>
                <div className="csr-row csr-row-trigger">
                  <dt>다음 단계 조건</dt><dd>{ph.trigger}</dd>
                </div>
              </dl>

              <div className="csr-chips">
                <span className="csr-chip">{ph.funnelLabel}</span>
                <span className="csr-chip">{ph.budgetLabel}</span>
                <span className="csr-chip csr-chip-fit">핏 {fitLabel}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div className="csr-foot">
        <span className="csr-foot-dot" />
        비중은 고정 정답이 아니라 <b>퍼널·브랜드핏·일예산을 매핑한 추천값 + 신뢰구간</b>입니다(레버로 수정 가능).
        실측이 쌓일수록 신뢰구간(±)이 좁아지고 추정 강도를 높입니다.
        {aov && <> 표본 AOV 참고 ₩{aov.toLocaleString()} <em>(렌즈 — 본 브랜드 측정값 아님)</em>.</>}
        <span className="csr-foot-conf">현재 분석 신뢰도 {conf}점</span>
      </div>

      <style>{`
        .csr {
          margin: 18px 0 6px;
          border: 1px solid var(--border-strong);
          border-radius: 6px;
          background:
            radial-gradient(120% 80% at 0% 0%, oklch(0.80 0.15 72 / 0.06), transparent 60%),
            var(--ink-100, oklch(0.13 0.02 240));
          overflow: hidden;
        }
        .csr-head {
          display: flex; align-items: flex-start; justify-content: space-between;
          gap: 16px; flex-wrap: wrap;
          padding: 16px 18px 12px;
          border-bottom: 1px solid var(--border);
        }
        .csr-eyebrow {
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em;
          text-transform: uppercase; color: var(--signal);
        }
        .csr-title {
          margin: 4px 0 0; font-size: 16px; font-weight: 700; color: var(--text);
          letter-spacing: -0.01em;
        }
        .csr-diag { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
        .csr-tierpill {
          font-family: var(--font-mono); font-size: 10px; font-weight: 600;
          padding: 3px 8px; border-radius: 3px; border: 1px solid var(--border-strong);
          letter-spacing: 0.02em;
        }
        .csr-t-a { color: var(--text); border-color: var(--border-strong); }
        .csr-t-c { color: var(--cyan); border-color: var(--cyan); background: var(--cyan-soft); }
        .csr-t-d { color: var(--text-dim); }
        .csr-tierpill.is-off { color: var(--text-mute); opacity: 0.6; text-decoration: line-through; }
        .csr-tierpill.csr-t-c.is-off { text-decoration: none; background: transparent; border-color: var(--border-strong); }
        .csr-arrow { color: var(--text-mute); font-family: var(--font-mono); font-size: 11px; }

        .csr-coldnote {
          padding: 11px 18px; font-size: 12px; line-height: 1.6; color: var(--text-dim);
          background: oklch(0.68 0.21 22 / 0.05);
          border-bottom: 1px solid var(--border);
        }
        .csr-coldnote b { color: var(--text); font-weight: 600; }

        .csr-track {
          display: flex; align-items: stretch; gap: 1px;
          background: var(--border);
        }
        @media (max-width: 900px) { .csr-track { flex-direction: column; } }
        .csr-card {
          flex: 1 1 0; min-width: 0;
          background: var(--ink-050, oklch(0.11 0.015 240));
          padding: 16px 16px 14px;
          cursor: pointer;
          border-top: 2px solid transparent;
        }
        .csr-card:hover { background: oklch(0.14 0.02 240); }
        .csr-tone-signal.is-open { border-top-color: var(--signal); background: oklch(0.80 0.15 72 / 0.05); }
        .csr-tone-cyan.is-open   { border-top-color: var(--cyan);   background: var(--cyan-soft); }
        .csr-tone-plant.is-open  { border-top-color: var(--plant);  background: var(--plant-soft); }

        .csr-card-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
        .csr-phase-tag {
          font-family: var(--font-mono); font-size: 10px; font-weight: 700; letter-spacing: 0.1em;
        }
        .csr-tone-signal .csr-phase-tag { color: var(--signal); }
        .csr-tone-cyan .csr-phase-tag   { color: var(--cyan); }
        .csr-tone-plant .csr-phase-tag  { color: var(--plant); }
        .csr-maturity { font-family: var(--font-mono); font-size: 9.5px; color: var(--text-mute); text-align: right; }
        .csr-card-label { font-size: 18px; font-weight: 800; color: var(--text); margin: 8px 0 4px; letter-spacing: -0.02em; }
        .csr-goal { font-size: 12px; color: var(--text-dim); line-height: 1.45; min-height: 34px; }

        .csr-mixwrap { margin: 12px 0; padding: 10px; border: 1px solid var(--border); border-radius: 4px; background: rgba(0,0,0,0.18); }
        .csr-mix-hl { display: flex; align-items: baseline; justify-content: space-between; font-size: 11px; color: var(--text-mute); }
        .csr-mix-val { font-family: var(--font-mono); font-size: 20px; font-weight: 700; color: var(--text); }
        .csr-mix-val small { font-size: 11px; color: var(--text-mute); }
        .csr-band { font-family: var(--font-mono); font-size: 11px; color: var(--text-mute); font-weight: 500; }
        .csr-mixbar { position: relative; height: 8px; margin: 9px 0 5px; border-radius: 4px; background: oklch(0.78 0.12 220 / 0.18); overflow: hidden; }
        .csr-mixbar-band { position: absolute; top: 0; bottom: 0; background: rgba(255,255,255,0.10); }
        .csr-mixbar-fill { position: absolute; top: 0; bottom: 0; left: 0; background: var(--signal); opacity: 0.55; }
        .csr-mixbar-mark { position: absolute; top: -2px; bottom: -2px; width: 2px; background: var(--text); transform: translateX(-1px); }
        .csr-mixlegend { display: flex; justify-content: space-between; font-family: var(--font-mono); font-size: 9.5px; color: var(--text-mute); }

        .csr-rows { margin: 0; display: flex; flex-direction: column; gap: 9px; }
        .csr-row { display: grid; grid-template-columns: 70px 1fr; gap: 8px; }
        .csr-row dt { font-size: 10px; font-weight: 600; color: var(--text-mute); font-family: var(--font-mono); letter-spacing: 0.02em; padding-top: 1px; }
        .csr-row dd { margin: 0; font-size: 11.5px; line-height: 1.5; color: var(--text-dim); }
        .csr-row dd b { color: var(--text); font-weight: 600; }
        .csr-pwhy { color: var(--text-mute); }
        .csr-reach { display: block; margin-top: 3px; font-family: var(--font-mono); font-size: 10.5px; color: var(--cyan); }
        .csr-reach em { color: var(--text-mute); font-style: normal; }
        .csr-row-trigger dd { color: var(--text-mute); }
        .csr-tone-plant .csr-row-trigger dd { color: var(--plant); opacity: 0.85; }

        .csr-chips { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 12px; }
        .csr-chip {
          font-family: var(--font-mono); font-size: 9.5px; font-weight: 500;
          padding: 2px 7px; border-radius: 3px; border: 1px solid var(--border-strong);
          color: var(--text-dim); background: rgba(0,0,0,0.2);
        }
        .csr-chip-fit { color: var(--cyan); border-color: var(--cyan-dim); }

        .csr-foot {
          padding: 11px 18px; font-size: 11px; line-height: 1.6; color: var(--text-mute);
          border-top: 1px solid var(--border); display: flex; flex-wrap: wrap; align-items: center; gap: 5px;
        }
        .csr-foot b { color: var(--text-dim); font-weight: 600; }
        .csr-foot em { font-style: normal; color: var(--text-mute); opacity: 0.8; }
        .csr-foot-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--signal); box-shadow: 0 0 8px var(--signal); flex-shrink: 0; }
        .csr-foot-conf { margin-left: auto; font-family: var(--font-mono); color: var(--text-dim); }
      `}</style>
    </div>
  );
}

Object.assign(window, { ColdStartRoadmap });
