// Dashboard/WebSearch.jsx
function WebSearch({ engine = "google" }) {
  const [q, setQ] = React.useState("");
  const [openInNewTab, setOpenInNewTab] = React.useState(true);

  function submitSearch(e) {
    e && e.preventDefault();
    const query = (q || "").trim();
    if (!query) return;

    // Быстрый вариант: открыть поисковик в новой вкладке (обходит CORS)
    const engines = {
      google: `https://www.google.com/search?q=${encodeURIComponent(query)}`,
      bing: `https://www.bing.com/search?q=${encodeURIComponent(query)}`,
      duckduckgo: `https://duckduckgo.com/?q=${encodeURIComponent(query)}`
    };

    const url = engines[engine] || engines.google;

    if (openInNewTab) {
      window.open(url, "_blank", "noopener");
    } else {
      window.location.href = url;
    }
  }

  return (
    <div className="web-search">
      <label className="search-label">Поиск в интернете</label>
      <form className="search-row" onSubmit={submitSearch}>
        <input
          className="search-input"
          placeholder="Искать в интернете (Google/Bing)..."
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <button className="btn primary" type="submit">Найти</button>
        <button
          type="button"
          className="btn ghost"
          onClick={() => {
            setQ("");
          }}
        >
          Очистить
        </button>
      </form>

      <div style={{ marginTop: 8 }}>
        <label style={{ fontSize: 13, color: "#94a3b8" }}>
          Открывать в новой вкладке
          <input
            type="checkbox"
            checked={openInNewTab}
            onChange={(e) => setOpenInNewTab(e.target.checked)}
            style={{ marginLeft: 8 }}
          />
        </label>
      </div>

      <div className="muted" style={{ marginTop: 8 }}>
      </div>
    </div>
  );
}
