// Home screen — slim app header, category pills, mood subfilter, uniform grid.

const HomeScreen = ({
  density = "comfy",
  onOpen,
  favorites,
  toggleFavorite,
  dataSaver,
  wallpapers,
  categories,
  moods,
}) => {
  const [category, setCategory] = React.useState("All");
  const [mood, setMood] = React.useState(null);
  const [showMoods, setShowMoods] = React.useState(false);
  const scrollRef = React.useRef(null);

  const filtered = wallpapers.filter((w) => {
    if (category === "Favorites") {
      if (!favorites.includes(w.id)) return false;
    } else if (category !== "All" && w.category !== category) {
      return false;
    }
    if (mood && !w.mood.includes(mood)) return false;
    return true;
  });

  const cols = density === "cozy" ? 4 : density === "comfy" ? 3 : 2;
  const gap = density === "cozy" ? 6 : density === "comfy" ? 10 : 16;

  return (
    <div
      ref={scrollRef}
      className="no-sb"
      style={{
        position: "absolute",
        inset: 0,
        overflowY: "auto",
        scrollbarWidth: "none",
      }}
    >
      <style>{`.no-sb::-webkit-scrollbar{display:none}`}</style>

      <header
        style={{
          position: "sticky",
          top: 0,
          zIndex: 20,
          background: "color-mix(in oklab, var(--bg) 88%, transparent)",
          backdropFilter: "blur(20px) saturate(140%)",
          WebkitBackdropFilter: "blur(20px) saturate(140%)",
          borderBottom: "1px solid var(--line)",
        }}
      >
        <div
          style={{
            padding: "14px 18px",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
            <img
              src="favicon.png"
              alt=""
              width={26}
              height={26}
              style={{ borderRadius: 7, display: "block" }}
            />
            <Wordmark size={18} />
          </div>
          <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
            <span
              style={{
                fontFamily: "var(--font-ui)",
                fontSize: 11,
                color: "var(--muted)",
                letterSpacing: "0.04em",
              }}
            >
              {filtered.length} of {wallpapers.length}
            </span>
            <button
              className={`icon-btn ${showMoods ? "active" : ""}`}
              onClick={() => setShowMoods((v) => !v)}
              aria-label="Filter by mood"
            >
              <Icon name="filter" size={16} />
            </button>
          </div>
        </div>

        <div
          className="no-sb"
          style={{
            display: "flex",
            gap: 6,
            overflowX: "auto",
            padding: "0 18px 12px",
          }}
        >
          {(() => {
            const active = category === "Favorites";
            return (
              <button
                key="__favorites"
                onClick={() => setCategory(active ? "All" : "Favorites")}
                title="Favorites"
                style={{
                  appearance: "none",
                  border: "1px solid " + (active ? "var(--accent)" : "var(--line)"),
                  background: active ? "var(--accent)" : "transparent",
                  color: active ? "white" : "var(--accent)",
                  padding: "6px 12px",
                  borderRadius: 999,
                  fontFamily: "var(--font-ui)",
                  fontSize: 13,
                  fontWeight: 500,
                  cursor: "pointer",
                  whiteSpace: "nowrap",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 6,
                  transition: "all 160ms ease",
                  flexShrink: 0,
                }}
              >
                Favs
                {favorites.length > 0 && (
                  <span
                    style={{
                      fontSize: 11,
                      opacity: 0.85,
                      padding: "0 6px",
                      borderRadius: 999,
                      background: active
                        ? "rgba(255,255,255,0.22)"
                        : "color-mix(in oklab, var(--accent) 14%, transparent)",
                    }}
                  >
                    {favorites.length}
                  </span>
                )}
              </button>
            );
          })()}
          {categories.map((c) => {
            const active = category === c;
            return (
              <button
                key={c}
                onClick={() => setCategory(c)}
                style={{
                  appearance: "none",
                  border: "1px solid " + (active ? "var(--fg)" : "var(--line)"),
                  background: active ? "var(--fg)" : "transparent",
                  color: active ? "var(--bg)" : "var(--fg)",
                  padding: "6px 14px",
                  borderRadius: 999,
                  fontFamily: "var(--font-ui)",
                  fontSize: 13,
                  fontWeight: 500,
                  cursor: "pointer",
                  whiteSpace: "nowrap",
                  transition: "all 160ms ease",
                }}
              >
                {c}
              </button>
            );
          })}
        </div>

        {showMoods && (
          <div
            className="no-sb"
            style={{
              display: "flex",
              gap: 6,
              overflowX: "auto",
              padding: "0 18px 12px",
              borderTop: "1px solid var(--line)",
              paddingTop: 12,
              animation: "fadeIn 200ms ease",
            }}
          >
            {moods.map((m) => {
              const active = mood === m;
              return (
                <button
                  key={m}
                  onClick={() => setMood(active ? null : m)}
                  style={{
                    appearance: "none",
                    border: "none",
                    background: active ? "var(--accent)" : "var(--surface)",
                    color: active ? "white" : "var(--fg)",
                    padding: "5px 11px",
                    borderRadius: 999,
                    fontFamily: "var(--font-ui)",
                    fontSize: 12,
                    cursor: "pointer",
                    whiteSpace: "nowrap",
                  }}
                >
                  {m}
                </button>
              );
            })}
          </div>
        )}
      </header>

      <div
        style={{
          padding: gap,
          paddingBottom: 100,
          display: "grid",
          gridTemplateColumns: `repeat(${cols}, 1fr)`,
          gap: gap,
        }}
      >
        {filtered.map((w, i) => (
          <WallTile
            key={w.id}
            w={w}
            onOpen={onOpen}
            favorited={favorites.includes(w.id)}
            toggleFavorite={toggleFavorite}
            dataSaver={dataSaver}
            index={i}
          />
        ))}
      </div>

      {filtered.length === 0 && (
        <div
          style={{
            padding: "60px 28px",
            textAlign: "center",
            fontFamily: "var(--font-ui)",
            fontSize: 14,
            color: "var(--muted)",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            gap: 10,
          }}
        >
          {category === "Favorites" ? (
            <React.Fragment>
              <div style={{ color: "var(--accent)" }}>
                <Icon name="heart" size={28} />
              </div>
              <div style={{ color: "var(--fg)", fontSize: 15, fontWeight: 500 }}>
                No favorites yet
              </div>
              <div>Tap the heart on any wallpaper to keep it here.</div>
            </React.Fragment>
          ) : (
            <div>No wallpapers match these filters.</div>
          )}
        </div>
      )}
    </div>
  );
};

const WallTile = ({ w, onOpen, favorited, toggleFavorite, dataSaver, index }) => {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => onOpen(w.id)}
      style={{
        position: "relative",
        aspectRatio: "9/16",
        background: w.palette[0] || "#1a1a1a",
        backgroundImage: `url("${w.thumbnail}")`,
        backgroundSize: "cover",
        backgroundPosition: "center",
        borderRadius: 14,
        overflow: "hidden",
        cursor: "pointer",
        opacity: 1,
        animation: `riseIn 360ms ${Math.min(index * 18, 400)}ms cubic-bezier(0.2, 0.7, 0.2, 1)`,
        transition: "transform 280ms cubic-bezier(0.2, 0.7, 0.2, 1)",
        transform: hover ? "scale(1.015)" : "scale(1)",
        filter: dataSaver ? "blur(0.6px) saturate(0.92)" : "none",
        boxShadow: "0 1px 0 rgba(255,255,255,0.04) inset",
      }}
    >
      <button
        onClick={(e) => {
          e.stopPropagation();
          toggleFavorite(w.id);
        }}
        aria-label="Favorite"
        style={{
          position: "absolute",
          top: 8,
          right: 8,
          width: 32,
          height: 32,
          borderRadius: "50%",
          border: "none",
          background: "rgba(0,0,0,0.4)",
          backdropFilter: "blur(10px)",
          WebkitBackdropFilter: "blur(10px)",
          color: favorited ? "var(--accent)" : "white",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          cursor: "pointer",
          opacity: hover || favorited ? 1 : 0,
          transform: hover || favorited ? "scale(1)" : "scale(0.8)",
          transition: "all 200ms ease",
          zIndex: 2,
        }}
      >
        <Icon name={favorited ? "heart-fill" : "heart"} size={15} />
      </button>

      <div
        style={{
          position: "absolute",
          inset: 0,
          background:
            "linear-gradient(180deg, transparent 60%, rgba(0,0,0,0.55) 100%)",
          opacity: hover ? 1 : 0,
          transition: "opacity 200ms ease",
        }}
      />

      <div
        style={{
          position: "absolute",
          left: 12,
          right: 12,
          bottom: 10,
          color: "white",
          fontFamily: "var(--font-ui)",
          fontSize: 12,
          fontWeight: 500,
          opacity: hover ? 1 : 0,
          transform: hover ? "translateY(0)" : "translateY(4px)",
          transition: "all 200ms ease",
          textShadow: "0 1px 4px rgba(0,0,0,0.55)",
        }}
      >
        {w.title}
        <div style={{ fontSize: 10, opacity: 0.75, marginTop: 1 }}>
          {w.category}
        </div>
      </div>
    </div>
  );
};

window.HomeScreen = HomeScreen;
