// Detail view — full-bleed real image, lock/home/full preview, palette,
// download (blob), share (Web Share API + clipboard fallback).

const DetailView = ({
  wallpaper,
  onClose,
  onOpen,
  favorites,
  toggleFavorite,
  wallpapers,
  dataSaver,
}) => {
  const [mode, setMode] = React.useState("home");
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(null);
  const [downloading, setDownloading] = React.useState(false);
  const [shared, setShared] = React.useState(false);
  const w = wallpaper;
  if (!w) return null;
  const fav = favorites.includes(w.id);
  const palette = w.palette;

  const sourceUrl = dataSaver ? w.thumbnail : w.url;

  const related = (w.suggestions || [])
    .map((id) => wallpapers.find((x) => x.id === id))
    .filter(Boolean)
    .slice(0, 8);
  if (!related.length) {
    const fallback = wallpapers
      .filter((x) => x.id !== w.id && (x.category === w.category || x.mood.some((m) => w.mood.includes(m))))
      .slice(0, 8);
    related.push(...fallback);
  }

  const copy = (c) => {
    navigator.clipboard?.writeText(c).catch(() => {});
    setCopied(c);
    setTimeout(() => setCopied(null), 1200);
  };

  const triggerDownload = async () => {
    if (downloading) return;
    setDownloading(true);
    try {
      const res = await fetch(w.url, { mode: "cors" });
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      const ext = (w.url.match(/\.[a-z0-9]+(?:$|\?)/i) || [".png"])[0].replace(/\?$/, "");
      a.download = `${w.title.replace(/[^\w\- ]+/g, "")}${ext}`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (e) {
      // Cross-origin direct download blocked — open in new tab so the user can long-press save.
      window.open(w.url, "_blank", "noopener,noreferrer");
    } finally {
      setDownloading(false);
    }
  };

  const triggerShare = async () => {
    const shareData = {
      title: `Wallpeppers — ${w.title}`,
      text: `${w.title} by ${w.author}`,
      url: w.url,
    };
    try {
      if (navigator.share) {
        await navigator.share(shareData);
      } else if (navigator.clipboard) {
        await navigator.clipboard.writeText(w.url);
        setShared(true);
        setTimeout(() => setShared(false), 1500);
      }
    } catch (e) {
      // user cancelled
    }
  };

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 100,
        background: "#000",
        animation: "fadeIn 240ms ease",
        overflow: "hidden",
      }}
    >
      {/* Ambient blurred backdrop — always present so the screen edges
          are colored and the contained Full-fit foreground has something
          to sit against on wide viewports. */}
      <div
        aria-hidden="true"
        style={{
          position: "absolute",
          inset: 0,
          backgroundColor: w.palette[0] || "#0a0a0a",
          backgroundImage: `url("${sourceUrl}")`,
          backgroundSize: "cover",
          backgroundPosition: "center",
          filter: "blur(40px) saturate(1.1)",
          transform: "scale(1.15)",
        }}
      />

      {/* Vignette darken — only when the phone mock is on top, to keep
          ambient color from blowing out the bezel. */}
      {mode !== "flat" && (
        <div
          aria-hidden="true"
          style={{
            position: "absolute",
            inset: 0,
            background:
              "radial-gradient(80% 60% at 50% 40%, transparent 0%, rgba(0,0,0,0.55) 100%)",
            transition: "background 320ms ease",
          }}
        />
      )}

      {/* Foreground image — contained for Full so the whole wallpaper is
          visible on any viewport without cropping. */}
      {mode === "flat" && (
        <div
          style={{
            position: "absolute",
            inset: 0,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            pointerEvents: "none",
            padding: "84px 18px 96px",
            animation: "fadeIn 240ms ease",
          }}
        >
          <img
            src={sourceUrl}
            alt={w.title}
            style={{
              maxWidth: "100%",
              maxHeight: "100%",
              objectFit: "contain",
              borderRadius: 14,
              boxShadow: "0 30px 80px -20px rgba(0,0,0,0.6)",
            }}
          />
        </div>
      )}

      {mode !== "flat" && (
        <div
          style={{
            position: "absolute",
            inset: 0,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            pointerEvents: "none",
            animation: "fadeIn 320ms ease",
          }}
        >
          <PhoneMock wallpaper={w} mode={mode} sourceUrl={sourceUrl} />
        </div>
      )}

      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          padding: "16px 18px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          zIndex: 5,
          background: "linear-gradient(180deg, rgba(0,0,0,0.45) 0%, transparent 100%)",
        }}
      >
        <button className="float-btn" onClick={onClose} aria-label="Close">
          <Icon name="close" size={18} />
        </button>
        <div
          style={{
            color: "white",
            fontFamily: "var(--font-ui)",
            fontSize: 13,
            fontWeight: 500,
            textShadow: "0 1px 6px rgba(0,0,0,0.4)",
            maxWidth: "60%",
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {w.title}
        </div>
        <button
          className="float-btn"
          onClick={() => setSheetOpen((v) => !v)}
          aria-label="Wallpaper details"
          title="Details"
        >
          <Icon name="info" size={18} />
        </button>
      </div>

      <div
        style={{
          position: "absolute",
          top: 64,
          left: "50%",
          transform: "translateX(-50%)",
          zIndex: 5,
          display: "flex",
          padding: 3,
          background: "rgba(0,0,0,0.4)",
          backdropFilter: "blur(14px)",
          WebkitBackdropFilter: "blur(14px)",
          border: "1px solid rgba(255,255,255,0.14)",
          borderRadius: 999,
        }}
      >
        {[
          { id: "home", label: "Home" },
          { id: "lock", label: "Lock" },
          { id: "flat", label: "Full" },
        ].map((opt) => {
          const active = mode === opt.id;
          return (
            <button
              key={opt.id}
              onClick={() => setMode(opt.id)}
              style={{
                appearance: "none",
                border: "none",
                background: active ? "white" : "transparent",
                color: active ? "black" : "white",
                padding: "6px 14px",
                borderRadius: 999,
                fontFamily: "var(--font-ui)",
                fontSize: 12,
                fontWeight: 500,
                cursor: "pointer",
                transition: "all 180ms ease",
              }}
            >
              {opt.label}
            </button>
          );
        })}
      </div>

      <div
        style={{
          position: "absolute",
          bottom: 0,
          left: 0,
          right: 0,
          padding: "60px 18px 22px",
          background: "linear-gradient(0deg, rgba(0,0,0,0.55) 0%, transparent 100%)",
          display: "flex",
          alignItems: "center",
          gap: 10,
          zIndex: 5,
        }}
      >
        <button
          className="float-btn"
          onClick={() => toggleFavorite(w.id)}
          aria-label="Favorite"
          style={{ color: fav ? "var(--accent)" : "white" }}
        >
          <Icon name={fav ? "heart-fill" : "heart"} size={18} />
        </button>
        <button className="float-btn" onClick={triggerShare} aria-label="Share">
          <Icon name="share" size={18} />
        </button>
        {shared && (
          <span
            style={{
              fontFamily: "var(--font-ui)",
              fontSize: 11,
              color: "white",
              background: "rgba(0,0,0,0.5)",
              padding: "4px 10px",
              borderRadius: 999,
              animation: "fadeIn 160ms ease",
            }}
          >
            Link copied
          </span>
        )}
        <div style={{ flex: 1 }} />
        <button
          onClick={triggerDownload}
          disabled={downloading}
          style={{
            appearance: "none",
            border: "none",
            background: "white",
            color: "black",
            padding: "12px 22px",
            borderRadius: 999,
            fontFamily: "var(--font-ui)",
            fontSize: 14,
            fontWeight: 600,
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            cursor: downloading ? "wait" : "pointer",
            opacity: downloading ? 0.7 : 1,
          }}
        >
          <Icon name="download" size={16} />
          {downloading ? "Saving…" : "Set wallpaper"}
        </button>
      </div>

      <DetailsDrawer
        open={sheetOpen}
        onOpenChange={setSheetOpen}
        wallpaper={w}
        palette={palette}
        copied={copied}
        copy={copy}
        related={related}
        onOpen={onOpen}
      />
    </div>
  );
};

const DetailsDrawer = ({ open, onOpenChange, wallpaper, palette, copied, copy, related, onOpen }) => {
  const Drawer = (window.Vaul && window.Vaul.Drawer) || null;
  const w = wallpaper;
  if (!Drawer) return null;
  return (
    <Drawer.Root open={open} onOpenChange={onOpenChange} shouldScaleBackground={false}>
      <Drawer.Portal>
        <Drawer.Overlay
          style={{
            position: "fixed",
            inset: 0,
            background: "rgba(0,0,0,0.55)",
            zIndex: 200,
          }}
        />
        <Drawer.Content
          aria-describedby={undefined}
          style={{
            position: "fixed",
            left: 0,
            right: 0,
            bottom: 0,
            zIndex: 201,
            display: "flex",
            justifyContent: "center",
            outline: "none",
            background: "transparent",
          }}
        >
          <div
            className="no-sb"
            style={{
              width: "100%",
              maxWidth: 980,
              maxHeight: "85vh",
              background: "var(--bg)",
              color: "var(--fg)",
              borderTopLeftRadius: 20,
              borderTopRightRadius: 20,
              boxShadow: "0 -20px 50px rgba(0,0,0,0.4)",
              overflowY: "auto",
              scrollbarWidth: "none",
            }}
          >
            <div
              style={{
                position: "sticky",
                top: 0,
                padding: "10px 0 0",
                display: "flex",
                justifyContent: "center",
                background: "var(--bg)",
                zIndex: 2,
              }}
            >
              <div
                aria-hidden="true"
                style={{
                  width: 40,
                  height: 5,
                  borderRadius: 999,
                  background: "var(--line)",
                }}
              />
            </div>
            <div style={{ padding: "16px 22px 32px" }}>
              <Drawer.Title
                style={{
                  fontFamily: "var(--font-ui)",
                  fontSize: 22,
                  fontWeight: 600,
                  letterSpacing: "-0.01em",
                  margin: 0,
                  color: "var(--fg)",
                }}
              >
                {w.title}
              </Drawer.Title>
              <Drawer.Description
                style={{
                  marginTop: 4,
                  fontFamily: "var(--font-ui)",
                  fontSize: 13,
                  color: "var(--muted)",
                }}
              >
                by {w.author} · {w.category}
              </Drawer.Description>

              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 14 }}>
                {w.mood.map((m) => (
                  <span
                    key={m}
                    style={{
                      fontFamily: "var(--font-ui)",
                      fontSize: 11,
                      padding: "4px 10px",
                      borderRadius: 999,
                      background: "var(--surface)",
                      border: "1px solid var(--line)",
                      color: "var(--muted)",
                    }}
                  >
                    {m}
                  </span>
                ))}
              </div>

              <div style={{ marginTop: 22 }}>
                <SectionLabel>Palette · tap to copy</SectionLabel>
                <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
                  {palette.map((c, i) => (
                    <button
                      key={`${c}-${i}`}
                      onClick={() => copy(c)}
                      style={{
                        flex: 1,
                        appearance: "none",
                        border: "1px solid var(--line)",
                        background: "transparent",
                        padding: 0,
                        borderRadius: 8,
                        overflow: "hidden",
                        cursor: "pointer",
                        color: "var(--fg)",
                      }}
                    >
                      <div style={{ height: 36, background: c }} />
                      <div
                        style={{
                          padding: "6px 4px",
                          fontFamily: "var(--font-mono)",
                          fontSize: 10,
                          letterSpacing: "0.04em",
                          color: copied === c ? "var(--accent)" : "var(--muted)",
                        }}
                      >
                        {copied === c ? "Copied" : c.toUpperCase()}
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              <div style={{ marginTop: 22 }}>
                <SectionLabel>Specs</SectionLabel>
                <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <Spec k="Collection" v={w.collections || w.category} />
                  <Spec k="Format" v={(w.url.match(/\.([a-z0-9]+)(?:$|\?)/i) || [, "PNG"])[1].toUpperCase()} />
                  <Spec k="Source" v="raw.githubusercontent" />
                  <Spec k="License" v="Free · Personal" />
                </div>
              </div>

              <div style={{ marginTop: 26 }}>
                <SectionLabel>You might also like</SectionLabel>
                <div
                  className="no-sb"
                  style={{
                    marginTop: 12,
                    display: "flex",
                    gap: 8,
                    overflowX: "auto",
                    paddingBottom: 6,
                  }}
                >
                  {related.map((r) => (
                    <div
                      key={r.id}
                      onClick={() => {
                        onOpen(r.id);
                        onOpenChange(false);
                      }}
                      style={{
                        flex: "0 0 110px",
                        aspectRatio: "9/16",
                        backgroundColor: r.palette[0] || "#1a1a1a",
                        backgroundImage: `url("${r.thumbnail}")`,
                        backgroundSize: "cover",
                        backgroundPosition: "center",
                        borderRadius: 10,
                        cursor: "pointer",
                      }}
                    />
                  ))}
                </div>
              </div>
            </div>
          </div>
        </Drawer.Content>
      </Drawer.Portal>
    </Drawer.Root>
  );
};

const SectionLabel = ({ children }) => (
  <div
    style={{
      fontFamily: "var(--font-ui)",
      fontSize: 11,
      letterSpacing: "0.14em",
      textTransform: "uppercase",
      color: "var(--muted)",
      fontWeight: 500,
    }}
  >
    {children}
  </div>
);

const Spec = ({ k, v }) => (
  <div
    style={{
      padding: "10px 12px",
      background: "var(--surface)",
      borderRadius: 8,
      border: "1px solid var(--line)",
      overflow: "hidden",
    }}
  >
    <div
      style={{
        fontFamily: "var(--font-ui)",
        fontSize: 10,
        textTransform: "uppercase",
        letterSpacing: "0.12em",
        color: "var(--muted)",
      }}
    >
      {k}
    </div>
    <div
      style={{
        marginTop: 3,
        fontFamily: "var(--font-ui)",
        fontSize: 13,
        fontWeight: 500,
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
      }}
    >
      {v}
    </div>
  </div>
);

const PhoneMock = ({ wallpaper, mode, sourceUrl }) => {
  const w = 220;
  const h = 460;
  const url = sourceUrl || wallpaper.thumbnail;
  return (
    <div
      style={{
        width: w,
        height: h,
        borderRadius: 38,
        background: "#0a0a0a",
        padding: 8,
        boxShadow:
          "0 30px 60px -10px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.08) inset",
        animation: "phoneIn 380ms cubic-bezier(0.2, 0.7, 0.2, 1)",
      }}
    >
      <div
        style={{
          width: "100%",
          height: "100%",
          borderRadius: 30,
          overflow: "hidden",
          position: "relative",
          backgroundColor: wallpaper.palette[0] || "#1a1a1a",
          backgroundImage: `url("${url}")`,
          backgroundSize: "cover",
          backgroundPosition: "center",
        }}
      >
        <div
          style={{
            position: "absolute",
            top: 9,
            left: "50%",
            transform: "translateX(-50%)",
            width: 70,
            height: 22,
            background: "black",
            borderRadius: 999,
            zIndex: 5,
          }}
        />
        <div
          style={{
            position: "absolute",
            top: 11,
            left: 0,
            right: 0,
            display: "flex",
            justifyContent: "space-between",
            padding: "0 22px",
            color: "white",
            fontFamily: "var(--font-ui)",
            fontSize: 11,
            fontWeight: 600,
            zIndex: 4,
            textShadow: "0 1px 2px rgba(0,0,0,0.5)",
          }}
        >
          <span>9:41</span>
          <span style={{ opacity: 0.9 }}>● ●●</span>
        </div>

        {mode === "lock" && (
          <div
            style={{
              position: "absolute",
              inset: 0,
              color: "white",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              padding: "70px 0 30px",
              textShadow: "0 1px 6px rgba(0,0,0,0.4)",
            }}
          >
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 14, opacity: 0.85 }}>
              {new Date().toLocaleDateString(undefined, { weekday: "long", month: "long", day: "numeric" })}
            </div>
            <div
              style={{
                fontFamily: "var(--font-ui)",
                fontSize: 78,
                fontWeight: 300,
                letterSpacing: "-0.04em",
                lineHeight: 1,
                marginTop: 4,
              }}
            >
              {new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }).replace(/\s?[AP]M/i, "")}
            </div>
            <div style={{ flex: 1 }} />
            <div style={{ display: "flex", gap: 90 }}>
              <span style={{ width: 36, height: 36, borderRadius: "50%", background: "rgba(255,255,255,0.2)" }} />
              <span style={{ width: 36, height: 36, borderRadius: "50%", background: "rgba(255,255,255,0.2)" }} />
            </div>
          </div>
        )}

        {mode === "home" && (
          <div
            style={{
              position: "absolute",
              inset: 0,
              padding: "48px 18px 16px",
              display: "flex",
              flexDirection: "column",
            }}
          >
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(4, 1fr)",
                gap: 14,
                alignContent: "start",
              }}
            >
              {Array.from({ length: 16 }).map((_, i) => (
                <div
                  key={i}
                  style={{
                    aspectRatio: "1 / 1",
                    background: "rgba(255,255,255,0.2)",
                    backdropFilter: "blur(10px)",
                    WebkitBackdropFilter: "blur(10px)",
                    borderRadius: 10,
                    border: "1px solid rgba(255,255,255,0.18)",
                  }}
                />
              ))}
            </div>
            <div
              style={{
                marginTop: "auto",
                background: "rgba(255,255,255,0.24)",
                backdropFilter: "blur(12px)",
                WebkitBackdropFilter: "blur(12px)",
                borderRadius: 20,
                height: 60,
                border: "1px solid rgba(255,255,255,0.2)",
              }}
            />
          </div>
        )}
      </div>
    </div>
  );
};

window.DetailView = DetailView;
