/* Reactive Intelligence layer
   Live commentary on the current query — warnings, insights, opportunities.
   Computed from result + correlation + archetype ranks.
*/

const { useMemo: useRIMemo } = React;

function ReactiveIntelligence({ query, result, correlation, archetypes }) {
  const insights = useRIMemo(
    () => deriveInsights(query, result, correlation, archetypes),
    [query, result, correlation, archetypes]
  );

  return (
    <div className="ri-strip">
      <div className="ri-head">
        <span className="ri-eye">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5">
            <circle cx="12" cy="12" r="3" />
            <path d="M2 12 C5 6, 12 4, 12 4 S 19 6, 22 12 C19 18, 12 20, 12 20 S5 18, 2 12 Z" />
          </svg>
        </span>
        <span className="label" style={{ letterSpacing: '0.12em' }}>REACTIVE INTELLIGENCE</span>
        <span className="mono mute" style={{ fontSize: 9 }}>
          {insights.length} signal{insights.length === 1 ? '' : 's'} · 갱신 LIVE
        </span>
        <span style={{ flex: 1 }} />
        <span className="mono mute" style={{ fontSize: 9 }}>
          confidence {result ? Math.round((result.validity / 100) * 88 + 12) : 0}%
        </span>
      </div>
      <div className="ri-list">
        {insights.length === 0 ? (
          <div className="ri-empty">쿼리를 구성하면 매트릭스가 실시간으로 진단을 제공합니다.</div>
        ) : (
          insights.map((ins, i) => <InsightChip key={i} ins={ins} />)
        )}
      </div>
      <style>{`
        .ri-strip {
          background: linear-gradient(180deg, oklch(0.16 0.03 70 / 0.7), oklch(0.10 0.02 220 / 0.5));
          border: 1px solid var(--border-strong);
          border-left: 2px solid var(--signal);
          margin: 0 18px;
          padding: 8px 12px;
          backdrop-filter: blur(8px);
          position: relative;
          overflow: hidden;
        }
        .ri-strip::before {
          content: '';
          position: absolute;
          inset: 0;
          background: radial-gradient(circle at 20% 50%, oklch(0.80 0.14 72 / 0.06), transparent 50%);
          pointer-events: none;
        }
        .ri-head {
          display: flex; align-items: center; gap: 8px;
          color: var(--text-dim);
          margin-bottom: 6px;
          position: relative;
        }
        .ri-eye {
          color: var(--signal);
          animation: blink 3.4s ease-in-out infinite;
        }
        @keyframes blink {
          0%, 92%, 100% { opacity: 1; }
          95% { opacity: 0.2; }
        }
        .ri-list {
          display: flex; gap: 6px; flex-wrap: wrap;
          position: relative;
        }
        .ri-empty {
          font-size: 11px;
          color: var(--text-mute);
          font-family: var(--font-mono);
        }
      `}</style>
    </div>
  );
}

function InsightChip({ ins }) {
  return (
    <div className={'ri-chip tone-' + ins.tone} title={ins.detail}>
      <span className="ri-chip-icon">{ins.icon}</span>
      <span className="ri-chip-text">{ins.text}</span>
      {ins.metric && <span className="ri-chip-metric">{ins.metric}</span>}
      <style>{`
        .ri-chip {
          display: inline-flex; align-items: center; gap: 6px;
          padding: 4px 8px;
          background: var(--ink-200);
          border: 1px solid var(--border);
          font-size: 11px;
          color: var(--text-dim);
          font-family: var(--font-sans);
          animation: ri-pop 0.36s cubic-bezier(.2,.9,.3,1.2);
        }
        @keyframes ri-pop {
          from { opacity: 0; transform: translateY(4px) scale(0.95); }
          to   { opacity: 1; transform: translateY(0) scale(1); }
        }
        .ri-chip.tone-good   { border-color: var(--plant);  color: var(--plant); }
        .ri-chip.tone-warn   { border-color: var(--signal); color: var(--signal); }
        .ri-chip.tone-alert  { border-color: var(--alert);  color: var(--alert); }
        .ri-chip.tone-info   { border-color: var(--cyan);   color: var(--cyan); }
        .ri-chip-icon { font-family: var(--font-mono); font-size: 10px; }
        .ri-chip-metric {
          font-family: var(--font-mono); font-size: 10px;
          padding: 1px 5px;
          background: rgba(0,0,0,0.3);
          color: var(--text);
        }
      `}</style>
    </div>
  );
}

function deriveInsights(query, result, correlation, archetypes) {
  const out = [];
  if (!result) return out;

  // 1. Reach assessment
  if (result.finalReach < 80_000) {
    out.push({ icon: '◢', tone: 'alert', text: '도달 인원이 협소합니다. 조건을 완화하거나 OR 추가 권장.', metric: window.SimEngine.fmtN(result.finalReach), detail: '추정 도달 < 80K' });
  } else if (result.finalReach > 2_500_000) {
    out.push({ icon: '◢', tone: 'warn',  text: '타겟이 광범위합니다. 정밀도 향상 위해 AND 결합 검토.', metric: window.SimEngine.fmtN(result.finalReach), detail: '추정 도달 > 2.5M' });
  } else {
    out.push({ icon: '✓', tone: 'good',  text: '도달 규모 양호.', metric: window.SimEngine.fmtN(result.finalReach), detail: '권장 범위 200K–2M' });
  }

  // 2. Validity
  if (result.validity < 45) {
    out.push({ icon: '!', tone: 'alert', text: '유효성 낮음 — 연령 분산 불균형 가능성.', metric: result.validity });
  } else if (result.validity >= 70) {
    out.push({ icon: '✓', tone: 'good', text: '유효성 우수 — 입찰 효율 양호.', metric: result.validity });
  }

  // 3. Competition
  if (result.compete > 75) {
    out.push({ icon: '▲', tone: 'warn', text: 'CPM 상승 압력 — 경합 카테고리 다수.', metric: result.compete });
  }

  // 4. Overlap detection
  if (correlation && correlation.paths.length >= 2) {
    let maxOff = 0, pair = null;
    for (let i = 0; i < correlation.paths.length; i++) {
      for (let j = i+1; j < correlation.paths.length; j++) {
        const v = correlation.matrix[i][j];
        if (v > maxOff) { maxOff = v; pair = [correlation.paths[i], correlation.paths[j]]; }
      }
    }
    if (maxOff > 0.85 && pair) {
      out.push({
        icon: '↻',
        tone: 'warn',
        text: `상호 베타 ↑ — 중복도 ${(maxOff*100).toFixed(0)}% (${shortP(pair[0])} ↔ ${shortP(pair[1])})`,
        detail: '동일 인구 반복 노출 위험 → 빈도 캡 권장'
      });
    } else if (maxOff < 0.55) {
      out.push({
        icon: '✦',
        tone: 'info',
        text: '카테고리 간 보완성 강함 — 노출 다양성 확보.',
        metric: `${(maxOff*100).toFixed(0)}%`,
      });
    }
  }

  // 5. Archetype hint
  if (archetypes && archetypes.length) {
    const top = archetypes[0];
    if (top.match >= 55) {
      out.push({
        icon: '◉',
        tone: 'info',
        text: `'${top.name}' 페르소나와 정합도 ${top.match}점.`,
        detail: top.desc,
      });
    }
  }

  // 6. Conversion strength
  if (result.conv > 0.55) {
    out.push({ icon: '$', tone: 'good', text: 'CVR 강세 — 구매의도 결합 효과.', metric: result.conv + '%' });
  }

  // 7. Gender skew
  const sk = result.skew;
  if (sk > 0.75) out.push({ icon: '♀', tone: 'info', text: '여성 스큐 강함', metric: `${Math.round(sk*100)}%` });
  if (sk < 0.25) out.push({ icon: '♂', tone: 'info', text: '남성 스큐 강함', metric: `${Math.round((1-sk)*100)}%` });

  // 8. Time concentration
  const tmax = Math.max(...result.timeDist);
  const tConc = tmax / (result.timeDist.reduce((a, b) => a + b, 0) / 4);
  if (tConc > 1.6) {
    const idx = result.timeDist.indexOf(tmax);
    const labels = window.SimEngine.TIME_BINS.map(t => t.label);
    out.push({ icon: '⏱', tone: 'info', text: `${labels[idx]} 시간대 집중 노출 우세`, metric: `${(tmax*100).toFixed(0)}%` });
  }

  return out;
}
function shortP(p) {
  const parts = p.split(' > ');
  return parts[parts.length - 1];
}

Object.assign(window, { ReactiveIntelligence });
