// Dashboard/PlatformSearch.jsx
function PlatformSearch({ dataSources = {}, onSelect }) {
  // dataSources: { courses: [], certificates: [], profile: {...}, other: [...] }
  const [q, setQ] = React.useState("");
  const [results, setResults] = React.useState([]);
  const [loading, setLoading] = React.useState(false);

  // простой debounce
  React.useEffect(() => {
    if (!q) {
      setResults([]);
      return;
    }
    setLoading(true);
    const id = setTimeout(() => {
      const query = q.trim().toLowerCase();

      const matches = [];

      // Поиск по курсам
      (dataSources.courses || []).forEach((c) => {
        if ((c.title || "").toLowerCase().includes(query) || (c.sub || "").toLowerCase().includes(query)) {
          matches.push({ type: "course", item: c });
        }
      });

      // Поиск по сертификатам
      (dataSources.certificates || []).forEach((c) => {
        if ((c.title || "").toLowerCase().includes(query)) {
          matches.push({ type: "certificate", item: c });
        }
      });

      // Поиск по профилю (имя, email, специализация)
      const profile = dataSources.profile || {};
      ["name", "email", "specialization", "license"].forEach((k) => {
        if ((profile[k] || "").toLowerCase().includes(query)) {
          matches.push({ type: "profile", item: profile, field: k });
        }
      });

      // Дополнительные источники (опционально)
      (dataSources.other || []).forEach((o) => {
        if ((o.title || "").toLowerCase().includes(query) || (o.text || "").toLowerCase().includes(query)) {
          matches.push({ type: "other", item: o });
        }
      });

      setResults(matches);
      setLoading(false);
    }, 300);

    return () => clearTimeout(id);
  }, [q, dataSources]);

  function highlight(text = "", q) {
    if (!q) return text;
    const idx = text.toLowerCase().indexOf(q.toLowerCase());
    if (idx === -1) return text;
    return (
      <>
        {text.slice(0, idx)}
        <mark>{text.slice(idx, idx + q.length)}</mark>
        {text.slice(idx + q.length)}
      </>
    );
  }

  return (
    <div className="platform-search">
      <label className="search-label">Поиск по платформе</label>
      <div className="search-row">
        <input
          className="search-input"
          placeholder="Искать курсы, сертификаты, профиль..."
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Escape") setQ("");
          }}
        />
        <button className="btn ghost" onClick={() => setQ("")}>Очистить</button>
      </div>

      <div className="search-results">
        {loading && <div className="muted">Поиск...</div>}
        {!loading && q && results.length === 0 && <div className="muted">Ничего не найдено</div>}

        <ul>
          {results.map((r, i) => (
            <li key={i} className="search-item" onClick={() => onSelect && onSelect(r)}>
              <div className="item-type">{r.type}</div>
              <div className="item-main">
                {r.type === "course" && (
                  <>
                    <div className="item-title">{highlight(r.item.title, q)}</div>
                    <div className="item-sub muted">{r.item.sub}</div>
                  </>
                )}

                {r.type === "certificate" && (
                  <>
                    <div className="item-title">{highlight(r.item.title, q)}</div>
                    <div className="item-sub muted">Получен: {r.item.date}</div>
                  </>
                )}

                {r.type === "profile" && (
                  <>
                    <div className="item-title">{highlight(r.item.name || r.item.email, q)}</div>
                    <div className="item-sub muted">Поле: {r.field}</div>
                  </>
                )}

                {r.type === "other" && (
                  <>
                    <div className="item-title">{highlight(r.item.title || r.item.text, q)}</div>
                  </>
                )}
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
