// Search screen — text search across name/author/category/mood + color search
// that re-ranks results by palette distance to the picked color.

const SearchScreen = ({ onOpen, dataSaver, wallpapers }) => {
  const [q, setQ] = React.useState("");
  const [color, setColor] = React.useState(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    inputRef.current?.focus();
  }, []);

  const colors = [
    "#ff5b1f",
    "#f5a524",
    "#1f6feb",
    "#7a3aff",
    "#0e6a8c",
    "#5a6e3f",
    "#c2185b",
    "#eae6dd",
    "#0a0a0a",
  ];

  const recents = ["Glitch", "Minimal", "Dark", "Gradients"];
  const trending = ["AMOLED", "Constellation", "Patterns", "Vivid"];

  const dist = (a, b) => {
    const ah = (a.match(/\w\w/g) || []).map((x) => parseInt(x, 16));
    const bh = (b.match(/\w\w/g) || []).map((x) => parseInt(x, 16));
    if (ah.length < 3 || bh.length < 3) return 9999;
    return Math.sqrt(ah.slice(0, 3).reduce((s, _, i) => s + (ah[i] - bh[i]) ** 2, 0));
  };

  const filtered = wallpapers.filter((w) => {
    if (q) {
      const ql = q.toLowerCase();
      if (
        !w.title.toLowerCase().includes(ql) &&
        !(w.author || "").toLowerCase().includes(ql) &&
        !w.category.toLowerCase().includes(ql) &&
        !(w.collections || "").toLowerCase().includes(ql) &&
        !w.mood.some((m) => m.toLowerCase().includes(ql))
      )
        return false;
    }
    return true;
  });

  let sorted = filtered;
  if (color) {
    sorted = [...filtered].sort((a, b) => {
      const da = Math.min(...a.palette.map((c) => dist(c, color)));
      const db = Math.min(...b.palette.map((c) => dist(c, color)));
      return da - db;
    });
  }

  const showResults = q || color;

  return (
    <div
      style={{ position: "absolute", inset: 0, overflowY: "auto", scrollbarWidth: "none" }}
      className="no-sb"
    >
      <div
        style={{
          position: "sticky",
          top: 0,
          zIndex: 10,
          padding: "14px 18px",
          background: "color-mix(in oklab, var(--bg) 88%, transparent)",
          backdropFilter: "blur(20px)",
          WebkitBackdropFilter: "blur(20px)",
          borderBottom: "1px solid var(--line)",
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 10,
            background: "var(--surface)",
            border: "1px solid var(--line)",
            borderRadius: 12,
            padding: "10px 14px",
          }}
        >
          <Icon name="search" size={18} />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search wallpapers, moods, authors…"
            style={{
              flex: 1,
              minWidth: 0,
              background: "transparent",
              border: "none",
              outline: "none",
              color: "var(--fg)",
              fontFamily: "var(--font-ui)",
              fontSize: 15,
              padding: 0,
            }}
          />
          {q && (
            <button
              onClick={() => setQ("")}
              aria-label="Clear"
              style={{
                appearance: "none",
                border: "none",
                background: "transparent",
                color: "var(--muted)",
                cursor: "pointer",
                padding: 0,
                display: "flex",
              }}
            >
              <Icon name="close" size={16} />
            </button>
          )}
        </div>
      </div>

      <div style={{ padding: "20px 18px 100px" }}>
        <SectionLabel>By color</SectionLabel>
        <div style={{ display: "flex", gap: 10, marginTop: 12, flexWrap: "wrap", alignItems: "center" }}>
          {colors.map((c) => {
            const active = color === c;
            return (
              <button
                key={c}
                onClick={() => setColor(active ? null : c)}
                aria-label={c}
                style={{
                  width: 32,
                  height: 32,
                  borderRadius: "50%",
                  background: c,
                  border: active ? "2px solid var(--fg)" : "1px solid var(--line)",
                  cursor: "pointer",
                  transform: active ? "scale(1.08)" : "scale(1)",
                  transition: "all 200ms ease",
                  boxShadow: active ? "0 0 0 3px var(--bg), 0 0 0 4px var(--fg)" : "none",
                }}
              />
            );
          })}
          {color && (
            <button
              onClick={() => setColor(null)}
              style={{
                marginLeft: 4,
                background: "transparent",
                border: "none",
                color: "var(--muted)",
                fontFamily: "var(--font-ui)",
                fontSize: 12,
                cursor: "pointer",
              }}
            >
              Clear
            </button>
          )}
        </div>

        {!showResults && (
          <React.Fragment>
            <div style={{ marginTop: 26 }}>
              <SectionLabel>Recent</SectionLabel>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 12 }}>
                {recents.map((r) => (
                  <Chip key={r} onClick={() => setQ(r)} label={r} />
                ))}
              </div>
            </div>
            <div style={{ marginTop: 22 }}>
              <SectionLabel>Trending</SectionLabel>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 12 }}>
                {trending.map((r) => (
                  <Chip key={r} onClick={() => setQ(r)} label={r} accent />
                ))}
              </div>
            </div>
          </React.Fragment>
        )}

        <div style={{ marginTop: 24 }}>
          {showResults && (
            <div
              style={{
                fontFamily: "var(--font-ui)",
                fontSize: 13,
                color: "var(--muted)",
                marginBottom: 12,
              }}
            >
              {sorted.length} {sorted.length === 1 ? "result" : "results"}
              {color && ` near ${color.toUpperCase()}`}
              {q && ` for "${q}"`}
            </div>
          )}
          {!showResults && (
            <div style={{ marginTop: 4 }}>
              <SectionLabel>Suggested</SectionLabel>
            </div>
          )}
          <div
            style={{
              marginTop: 12,
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: 10,
            }}
          >
            {sorted.slice(0, showResults ? 60 : 12).map((w) => (
              <div
                key={w.id}
                onClick={() => onOpen(w.id)}
                style={{
                  cursor: "pointer",
                  aspectRatio: "9/16",
                  background: w.palette[0] || "#1a1a1a",
                  backgroundImage: `url("${w.thumbnail}")`,
                  backgroundSize: "cover",
                  backgroundPosition: "center",
                  borderRadius: 12,
                  filter: dataSaver ? "blur(0.6px)" : "none",
                  transition: "transform 220ms ease",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.transform = "scale(1.02)")}
                onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}
              />
            ))}
          </div>
          {showResults && sorted.length === 0 && (
            <div
              style={{
                padding: "60px 20px",
                textAlign: "center",
                fontFamily: "var(--font-ui)",
                fontSize: 14,
                color: "var(--muted)",
              }}
            >
              Nothing matches — try a different word or color.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const Chip = ({ label, onClick, accent }) => (
  <button
    onClick={onClick}
    style={{
      appearance: "none",
      border: "1px solid var(--line)",
      background: accent ? "var(--surface)" : "transparent",
      color: "var(--fg)",
      padding: "7px 14px",
      borderRadius: 999,
      fontFamily: "var(--font-ui)",
      fontSize: 13,
      cursor: "pointer",
    }}
  >
    {label}
  </button>
);

window.SearchScreen = SearchScreen;
