
const SVG = {
  Init: `<svg viewBox="0 0 24 24" fill="none" width="100%" height="100%"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`,
  Doc: `<svg viewBox="0 0 24 24" fill="none" width="100%" height="100%"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>`,
  Database: `<svg viewBox="0 0 24 24" fill="none" width="100%" height="100%"><ellipse cx="12" cy="5" rx="9" ry="3" stroke="currentColor" stroke-width="1.6"/><path d="M21 12c0 1.66-4.03 3-9 3s-9-1.34-9-3" stroke="currentColor" stroke-width="1.6"/><path d="M3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5" stroke="currentColor" stroke-width="1.6"/></svg>`,
  Score: `<svg viewBox="0 0 24 24" fill="none" width="100%" height="100%"><path d="M22 12h-4l-3 9L9 3l-3 9H2" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></svg>`,
  Filter: `<svg viewBox="0 0 24 24" fill="none" width="100%" height="100%"><path d="M3 6h18M7 12h10M11 18h2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>`,
  Check: `<svg viewBox="0 0 24 24" fill="none" width="100%" height="100%"><path d="M22 11.08V12a10 10 0 11-5.93-9.14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><path d="M22 4L12 14.01l-3-3" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>`
};

const NODES = [
  { id:"init", step:"01", label:"Khởi động AI Engine", brief:"Chuẩn bị pipeline phối đồ", icon:"Init", color:"#a78bfa" },
  { id:"fetch_product", step:"02", label:"Phân tích SP Gốc", brief:"Nạp metadata, mã màu, type", icon:"Doc", color:"#38bdf8" },
  { id:"fetch_rules", step:"03", label:"Kéo luật phối DB", brief:"Truy vấn chatbot_fashion_rules", icon:"Database", color:"#facc15" },
  { id:"scoring", step:"04", label:"Scoring Engine", brief:"Tính Color Synergy, Material, Occasion", icon:"Score", color:"#fb923c" },
  { id:"dedup", step:"05", label:"Deduplication & Mở rộng", brief:"Lọc trùng, SQL Classifications", icon:"Filter", color:"#f87171" },
  { id:"complete", step:"06", label:"Hoàn tất", brief:"Đóng gói JSON trả frontend", icon:"Check", color:"#34d399" }
];

// Setup Nodes UI
function renderNodes() {
  const wrap = document.getElementById('flowNodes');
  let html = '';
  NODES.forEach((n, idx) => {
    html += \`<div id="node-\${n.id}" class="mf-node" style="border-color:\${n.color}55">
      <div class="mf-node-icon" style="color:\${n.color};background:\${n.color}15">\${SVG[n.icon]}</div>
      <div style="flex:1">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:2px">
          <span class="mf-node-step" style="color:\${n.color}">\${n.step}</span>
          <span class="mf-node-title">\${n.label}</span>
        </div>
        <div class="mf-node-brief">\${n.brief}</div>
      </div>
    </div>\`;
    if (idx < NODES.length - 1) {
      html += \`<div id="conn-\${n.id}" class="mf-connector"><div class="mf-connector-line"></div></div>\`;
    }
  });
  wrap.innerHTML = html;
}

renderNodes();

// Search Input Logic
let searchTimeout = null;
const searchInput = document.getElementById('searchInput');
const searchResults = document.getElementById('searchResults');
let eventSource = null;

searchInput.addEventListener('input', (e) => {
  const q = e.target.value.trim();
  if (q.length < 2) {
    searchResults.style.display = 'none';
    return;
  }
  
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(async () => {
    try {
      const res = await fetch(\`/api/fashion-matches/simulator/search?q=\${encodeURIComponent(q)}\`);
      const data = await res.json();
      
      if (data.ok && data.data.length > 0) {
        let html = '';
        data.data.forEach(item => {
          html += \`
            <div class="search-item" onclick="startSimulation('\${item.code}')">
              <img src="\${item.image || ''}" class="search-item-img" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNlMmU4ZjAiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiLz48L3N2Zz4='">
              <div class="search-item-info">
                <div class="search-item-name">\${item.name}</div>
                <div class="search-item-code">\${item.code} • \${item.color}</div>
              </div>
            </div>
          \`;
        });
        searchResults.innerHTML = html;
        searchResults.style.display = 'block';
      } else {
        searchResults.innerHTML = '<div style="padding: 16px; font-size: 11px; color:#94a3b8; text-align:center;">Không tìm thấy sản phẩm...</div>';
        searchResults.style.display = 'block';
      }
    } catch (err) {
      console.error(err);
    }
  }, 300);
});

document.addEventListener('click', (e) => {
  if (!e.target.closest('.search-box')) {
    searchResults.style.display = 'none';
  }
});

searchInput.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') {
    e.preventDefault();
    const firstResult = searchResults.querySelector('.search-item');
    if (firstResult && searchResults.style.display !== 'none') {
      firstResult.click();
    } else {
      const q = e.target.value.trim();
      if (q) startSimulation(q);
    }
  }
});
// Logger
const term = document.getElementById('logTerminal');
function logTerminal(msg, type = 'normal') {
  const time = new Date().toLocaleTimeString('vi-VN', {hour12: false});
  const div = document.createElement('div');
  div.className = \`log-line \${type}\`;
  div.innerHTML = \`<span class="log-time">[\${time}]</span> \${msg}\`;
  term.appendChild(div);
  term.scrollTop = term.scrollHeight;
}

// Reset UI
function resetUI() {
  document.querySelectorAll('.mf-node').forEach(el => {
    el.classList.remove('active', 'done');
  });
  document.querySelectorAll('.mf-connector').forEach(el => {
    el.classList.remove('active');
  });
  term.innerHTML = '';
  document.getElementById('finalResult').classList.remove('show');
  document.getElementById('outfitGrid').innerHTML = '';
}

// Start Stream
function startSimulation(code) {
  searchResults.style.display = 'none';
  searchInput.value = code;
  
  if (eventSource) {
    eventSource.close();
  }
  
  resetUI();
  logTerminal(\`Starting simulator for \${code}...\`);

  eventSource = new EventSource(\`/api/fashion-matches/simulator/stream?code=\${encodeURIComponent(code)}\`);
  
  eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    
    if (data.error) {
      logTerminal(data.status, 'error');
      eventSource.close();
      return;
    }

    // Un-activate all nodes, mark previous as done
    document.querySelectorAll('.mf-node').forEach(el => {
      if (el.classList.contains('active')) {
        el.classList.remove('active');
        el.classList.add('done');
      }
    });

    const currentNode = document.getElementById(\`node-\${data.node}\`);
    if (currentNode) {
      currentNode.classList.add('active');
    }
    
    // Line connector active
    if (data.step > 1) {
      const prevId = NODES[data.step - 2].id;
      const conn = document.getElementById(\`conn-\${prevId}\`);
      if (conn) conn.classList.add('active');
    }

    // Log terminal
    let logType = 'normal';
    if (data.step === 6) logType = 'success';
    logTerminal(data.status, logType);

    // Render payload if step 6
    if (data.step === 6 && data.payload && data.payload.ai_matches) {
      renderFinalResults(data.payload.ai_matches);
      eventSource.close();
    }
  };
  
  eventSource.onerror = (err) => {
    logTerminal("Connection closed or error", "error");
    eventSource.close();
  };
}

function renderFinalResults(matches) {
  const grid = document.getElementById('outfitGrid');
  let html = '';
  
  for (const [role, items] of Object.entries(matches)) {
    if (!items || items.length === 0) continue;
    
    html += \`<div class="outfit-card">
      <div class="outfit-role">Phối với \${role}</div>
      <div class="product-combo">\`;
      
    items.forEach(p => {
      html += \`
        <div class="product-mini">
          <img src="\${p.image_url || ''}" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNlMmU4ZjAiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiLz48L3N2Zz4='">
          <div class="product-mini-name">\${p.name || 'Không có tên'}</div>
          <div class="product-mini-code">\${p.sku || p.code || ''}</div>
          <div class="product-mini-code" style="color:var(--primary);margin-top:4px">Điểm: \${(p.score || 0).toFixed(1)}</div>
        </div>
      \`;
    });
    
    html += \`</div></div>\`;
  }
  
  grid.innerHTML = html;
  document.getElementById('finalResult').classList.add('show');
}
