/* Brand Studio — brand info → AI persona generation → dedicated simulator
   Persists brands to localStorage.
*/

const { useState: useBSState, useMemo: useBSMemo, useEffect: useBSEffect } = React;

const BRAND_KEY = 'gfa-pm-brands-v1';

function loadBrands() {
  try { return JSON.parse(localStorage.getItem(BRAND_KEY) || '[]'); }
  catch { return []; }
}
function persistBrands(b) {
  try { localStorage.setItem(BRAND_KEY, JSON.stringify(b)); } catch {}
}

// Score a brand against every taxonomy leaf using simple keyword match
function rankLeaves(brand, taxonomy) {
  const allLeaves = window.SimEngine.collectLeaves(taxonomy);
  const tokens = (brand.name + ' ' + brand.category + ' ' + brand.keywords + ' ' + brand.description)
    .toLowerCase()
    .split(/[\s,·\/]+/)
    .filter(t => t.length >= 2);

  const scored = allLeaves.map(path => {
    let score = 0;
    for (const t of tokens) {
      if (path.toLowerCase().includes(t)) score += 1;
    }
    // bonus: category match in path
    if (brand.category && path.includes(brand.category.split(/[\s/]/)[0])) score += 2;
    return { path, score };
  });
  return scored.filter(x => x.score > 0).sort((a, b) => b.score - a.score);
}

function generatePersonas(brand, taxonomy) {
  // Prefer the high-fidelity PrecisionEngine if loaded.
  if (window.PrecisionEngine?.generatePersonasV2) {
    return window.PrecisionEngine.generatePersonasV2(brand, taxonomy).personas;
  }
  // Fallback: legacy keyword rank
  const ranked = rankLeaves(brand, taxonomy);
  if (ranked.length === 0) return [];

  // Bucketize by tier
  const interest = ranked.filter(x => x.path.startsWith('관심사')).slice(0, 8);
  const intent   = ranked.filter(x => x.path.startsWith('구매의도')).slice(0, 8);
  const mobile   = ranked.filter(x => x.path.startsWith('모바일')).slice(0, 8);

  const personas = [];

  // ① 핵심 도달 페르소나
  if (interest.length) {
    personas.push({
      id: 'p1-' + Date.now(),
      name: `${brand.name} 핵심 관심층`,
      angle: '관심사 기반 도달 확장',
      query: [{ op: 'OR', leaves: interest.slice(0, 4).map(x => x.path) }],
      tier: 'interest',
    });
  }
  // ② 전환 의도층
  if (intent.length) {
    personas.push({
      id: 'p2-' + Date.now(),
      name: `${brand.name} 구매 의도층`,
      angle: '즉시 전환 타겟',
      query: [{ op: 'OR', leaves: intent.slice(0, 3).map(x => x.path) }],
      tier: 'intent',
    });
  }
  // ③ 풀퍼널 정밀 결합
  if (interest.length && intent.length) {
    personas.push({
      id: 'p3-' + Date.now(),
      name: `${brand.name} 풀퍼널 결합`,
      angle: '관심사 ∩ 구매의도',
      query: [
        { op: 'OR', leaves: interest.slice(0, 2).map(x => x.path) },
        { op: 'OR', leaves: intent.slice(0, 2).map(x => x.path) },
      ],
      tier: 'mixed',
    });
  }
  // ④ 모바일 신규 카테고리
  if (mobile.length) {
    personas.push({
      id: 'p4-' + Date.now(),
      name: `${brand.name} 신규 모바일 카테고리`,
      angle: '신규 카테고리 선점',
      query: [{ op: 'OR', leaves: mobile.slice(0, 3).map(x => x.path) }],
      tier: 'mobile',
    });
  }
  // Run simulation on each
  for (const p of personas) {
    p.result = window.SimEngine.evalQuery(p.query);
  }
  return personas;
}

Object.assign(window, { loadBrands, persistBrands, generatePersonas });
